Commit Graph
510 Commits
Author SHA1 Message Date
Anees Iqbal 888dbbbf2f Refuse each constants-block record outside the typed model by LLVM's name
What: `Feature::Constant { code: u32 }` becomes
`Feature::Constant { record: ConstantRecord }`, in the front end and the
translator, which re-exports the new `ConstantRecord`. ConstantRecord is
non-exhaustive, one variant per LLVM name:
- Select, ExtractElement, InsertElement, Compare;
- ShuffleVector (CE_SHUFFLEVEC and CE_SHUFVEC_EX);
- BlockAddress, UnaryOp, DsoLocalEquivalent, NoCfi, GepWithInrange;
- PtrAuth (PTRAUTH and PTRAUTH2), Byte (BYTE and WIDE_BYTE);
- PtrToAddr: a CE_CAST of `CAST_PTRTOADDR`.
Each record is matched from its code (`codes::cst_unsupported`). A code
LLVM does not define stays `UnknownRecord`.

A refusal now reads `Constant { record: Select }` where it read
`Constant { code: 13 }`. The names and codes come from
`LLVMBitCodes.h` of the local LLVM 21.1.8 and 23.1.4 toolchains
(`ConstantsCodes`, `CastOpcodes`).

WIDE_INTEGER stays malformed, on purpose, with a comment that says why.
LLVM writes it only for an integer wider than 64 bits. The type table
already refuses those types (`Feature::Type`). So a WIDE_INTEGER that
reaches the constants block has a type of at most 64 bits, which LLVM
never writes.

Why: a refusal should name what it refuses. The inline assembly record
(code 30) reached a consumer as a bare `Constant { code: 30 }`; it now
decodes, and this names the rest of the class.

Verified (debug):
- metal2vulkan-air suite passes, including `constant_errors_are_typed`:
  - each of the 15 refused codes yields its name;
  - CE_CAST opcode 13 yields PtrToAddr, opcode 14 is malformed;
  - WIDE_INTEGER of an i32 is malformed;
  - code 60 is UnknownRecord.
  At the base the test does not compile (no ConstantRecord), and the
  refusal there was the bare code.
- The translator's api_surface, api_signatures (blessed: the new enum,
  its variants, the changed variant) and refusal_surface tests pass.
- clippy -D warnings, workspace, all targets, plain and --cfg m2v_gpu.
- docs/REFUSALS.md regenerated (the row's doc text).

The census changes no outcome: no private-corpus row was refused with a
constants-block code at d3e66f9415 or after the bit-manipulation change
(nvidia-rtx5080-laptop and moltenvk-m3).

SEMANTICS_VERSION 1954 -> 1956 (a refusal's class changes): the lane's
value plus one after f19e887e4a takes 1955.

Golden tables: none move (no fixture holds such a record).

(cherry picked from commit 2af3e7891ee1ce7893107ff69f32ea879a06a56c)
(cherry picked from commit 94412279d2b277a2b9cfc11a83fc1e231ef91ecb)
(cherry picked from commit 3f5560c3fd7da0edab9a10d6b951986d8fcc6f80)
2026-11-03 02:25:30 -08:00
Anees Iqbal a1ee191fd1 Filter a 3D mipmap chain by compute where the driver's blits do not filter a volume
the_device_s_blit_chain_filters_each_level_and_is_announced failed on the
Apple M3 Max through MoltenVK 1.4.2 for its 3D textures only. Measured there:
vkCmdBlitImage with VK_FILTER_LINEAR from level 0 of an 8 x 8 x 4
R8G8B8A8_UNORM image into level 1 does not answer Vulkan's linear filter, the
average of the eight texels around each destination centre. Of the level's
128 bytes, 4 lie within a code of it, 67 within a code of source slice
2z + 1's four texels alone, and 2 of slice 2z's alone. 2D, 2D-array and cube
blits filter as Vulkan states. NVIDIA 615.71.09 on the RTX 5080 Laptop GPU
filters the same 3D image correctly, and the test passes there. So this is a
driver difference, and FAST-PATHS row 73's claim of the blit chain "where its
blits filter the format" did not hold for a volume on MoltenVK.

Following the runtime's driver-defect pattern:
- New RuntimeDriverDefect::VolumeBlitsUnfiltered, with Affected { MOLTENVK,
  clean: &[] } in driver_defects.rs, keyed by driver as the other defects are,
  never by the release. Its doc holds the measurement.
- `plan_mipmaps` takes the driver's defects. A 3D texture on such a driver
  takes the compute filter (MipmapPlan::Filter) where the filter computes the
  format. Elsewhere the blit chain stays, announced as before
  (device-filtered-mipmaps). Nothing is refused, and no note is added.
- blit_texture.rs passes the device's defects. The mipmap_plan unit tests pass
  them too.
- New unit test a_volume_takes_the_compute_filter_where_the_driver_s_blits_do_not_filter_it.
  It fails without the change.
- tests/driver_defects.rs lists the defect for MoltenVK.
- api_signatures.tsv has the new variant, and FAST-PATHS row 73 names the
  defect. REFUSALS.md regenerated with no change.
- mipmap_chains expects the compute filter for 3D textures where the device
  has the defect, each level still within a code of the filter. Its diagnostic
  print is removed.

Verified: cargo nextest run -p metal2vulkan-runtime for the mipmap_plan and
driver_defects tests passes, and the new test fails without the change. The
lane test's M3 rerun follows.

(cherry picked from commit a160bb01e43d7e5f4916b700012663a4020cf2a7)
(cherry picked from commit 7e77515beeb4d938a67de4b659ad31b8bed3394f)
2026-11-03 02:03:18 -08:00
Anees Iqbal 822263b1b7 Hold the precise trig at NaN operands to what its stage records
The owned fixture precise-trigonometric-functions-at-nan-operands-under-fast-math
calls precise sin, cos, tan and sincos in a fast-math entry. MoltenVK compiles
an entry in one math mode, so those precise calls take their fast forms. On
the Apple M3 Max through MoltenVK 1.4.2, sin, cos and sincos of a NaN answer 0
(and other words keep payloads such as ffc00000 or 7fc12345) where Metal
answers 7fc00000. The live stage already records
PrecisionNote::DeviceTranscendentals and NativeNanEncoding, and the runtime
announces both. Apple states no answer at a NaN operand under fast math. The
test, though, held every NaN word to Metal's canonical NaN on a profile with
MetalCanonicalNans.

What changed:
- owned_float_fixtures_answer_metal takes the case's notes. A NaN word's bits
  are the device's where the stage records NativeNanEncoding. A function's
  answer word (not the operand word, DFL_TRIG_OPERAND) may be a number where
  it records DeviceTranscendentals.
- Each note the answers needed must be recorded. Every recorded note must be
  announced, checked once over the test's notices, so a once-per-device
  announcement is not lost between cases.
- DeviceTranscendentals' doc (pipeline/artifact.rs) and its docs/API.md entry
  now say that a NaN operand may answer a number in such an entry.

No note is added: the stage recorded both before the change.

Verified: runtime_lane::driver_deviations::owned_float_fixtures_answer_metal
passes on the Apple M3 Max through MoltenVK 1.4.2 (--cfg m2v_gpu), together
with the next commit's minimum rows.

(cherry picked from commit 91f122b133c93af4b155a258d088e0001ff55a72)
(cherry picked from commit 54a9b15a1fe0a27e8bf9d2a3a236813b9c117347)
2026-11-03 02:03:16 -08:00
Anees Iqbal 78f6377e4a FAST-PATHS: an empty command buffer is not submitted, so drop its old commit-to-completion number
The commit-to-completion entry measured an empty command buffer against a bare barrier (51.6 µs
against 45.1 µs on a Radeon 780M). Empty command buffers make no vkQueueSubmit now; the submit
path's bench measured commit and wait at 2.6 µs on the RTX 5080 and 1.8 µs on the M3 (p50). The
timestamp cost on MoltenVK and its switch are unchanged.

(cherry picked from commit f7abac8bbb7971b7bb9fd2c8638af94d7f96f51e)
(cherry picked from commit bef265b91124cc376bbeda1fead475bd87ebf805)
2026-11-03 01:40:30 -08:00
Anees Iqbal 36f5029870 commit_and_submit: the committing thread submits for itself
A runtime extension. CommandBuffer::commit_and_submit commits as commit
does, with the same checks and refusals. Then, where no submission pass is
under way, the calling thread becomes the passer (Scheduler::
submit_at_commit, Inbox::pass_once_then). It takes in the inbox and submits
the ready heads committed first, in commit order, up to PASS_SUBMISSIONS,
while each needs no host step, no submission check, no group, no storage-
form switch and no rebind (plain_ready with Passer::Committing:
submits_without_the_program's handler exclusion dropped, the rest kept).

Still counted as the passer and outside the state lock, it runs their
submission handlers, then lets go of what the pass held; a last reference
goes through let_go_elsewhere. It then counts out, wakes the scheduler's
thread where it left work or a commit was handed to it meanwhile, and makes
an owed completion turn. The commit is posted with no mark and no wake
(Inbox::post_quietly, Hand::Pass), so the scheduler's thread is not woken
for work the committer takes. A plain transition to Scheduled runs inline
as its batch is published; one with scheduled or submission handlers goes
to its queue's context as before. Called from the runtime's own threads (a
handler on the scheduler's thread or a waiter) it commits as commit does.
Plain commit is unchanged: Metal's commit returns before scheduling.

Submission handlers keep submission order whichever thread runs them.
Each pass that takes batches with submission handlers takes a ticket
under the scheduler's lock, in pass order (State::handler_ticket), and
runs them once every earlier ticket's ran (Turns). This departs from
the design's "handlers then count out": the scheduler's own pass counts
out before running its handlers, so a counted committer alone cannot
keep them in order. The new order test showed it: without the turns its
handlers ran out of commit order in 4 runs of 4.

Counted: WorkCounts::scheduler_passes_at_commit,
batches_submitted_at_commit (the conformance cost's scheduler_ and
batches_ prefixes already cover them). Docs: the method, the scheduler
and inbox module docs, add_submission_handler's thread bullet, the
runtime README's extensions, RUNTIME-PORTING, and FAST-PATHS's "commit
returns at once". api_signatures blessed (3 added); REFUSALS regenerated,
unchanged.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu:
- tests::commit_and_submit, 6 runs:
  - the submission handler ran on the caller inside the call, reading
    Committed, 40 of 40, with the scheduled handler on a handler thread;
  - 1000 command buffers from 2 threads alternating commit and
    commit_and_submit: handlers in commit order, 362 to 449 of them on a
    committing thread;
  - a checked head and the one behind it were left to the scheduler's
    thread, with 0 batches at commit.
- Negative control: Turns::wait made to return at once failed the order
  test 4 of 4 (e.g. 238, 239, 240, 255, 256, 241).
- The runtime suite: 1512 passed.
- clippy -D warnings with and without --cfg m2v_gpu, and rustdoc
  -D warnings, clean.

RUNTIME_VERSION and the runtime-sources pin follow at hand-over, on the
lane tip.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(cherry picked from commit 266f7cd26327e408d9cd1f0d6ea5ba33e49e10b3)
2026-11-02 16:41:46 -08:00
Anees Iqbal a00edd042e Measure what extended_range_blits = Canonical costs against Kept
The ledger's extended_range_blits row said "Not measured". It now gives the
cost of Canonical against Kept on two hosts. The consumer will make
Canonical its default only if it costs nothing measurable, and it does cost
something on both hosts.

Method: a scratch release bench, not committed. It opens two devices in one
process whose DevicePolicy differs in extended_range_blits alone, uses
Private BGRA10_XR textures that Metal keeps compressed (ShaderRead only,
allowGPUOptimizedContents) at 256x256 and 2048x2048, and runs one
whole-texture blit per command buffer, the two values interleaved: 20
warm-up blits, then 300 timed. Three processes per host. Kinds: buffer into
texture (Private and Shared buffer), texture into buffer (Private and
Shared), texture into texture.

- RTX 5080 Laptop, NVIDIA 615.71.09: calibrated GPUStartTime/GPUEndTime.
  Run under msi's gpu-locks.sh with SCHED_OTHER.
- M3 Max, MoltenVK 1.4.2: GPU times come from the host clock there, so the
  ledger cites 16 blits per command buffer, per blit.

Evidence the pass ran:
- Shared-texture byte checks: Canonical wrote Metal's encoding in all three
  directions; Kept kept the bytes.
- Work counts: one vkCmdDispatch per blit under Canonical, none under Kept.
- ExtendedRangeBitsKept was announced only under Kept.

Verified: cargo fmt; nextest -p metal2vulkan -E 'test(fast_paths)', 17
passed.

(cherry picked from commit e8eb63b8acd94897718c8e5784e715dbe6e89b9b)
2026-11-02 13:50:17 -08:00
Anees Iqbal 66d39ceb8e Regenerate the refusal surface for buffer_into_texture's sites
What: docs/REFUSALS.md regenerated (python3 scripts/refusal-surface/refusal_surface.py). Three
refusals' sites (OverlappingSurfaceRows, MultisampledBufferCopy, Copy) now name
blit_texture.rs's buffer_into_texture, where the previous commit moved
copy_from_buffer_to_texture's body so a fill's row copies share it.

Why: the generated surface names each refusal's building function; no refusal, RuntimeGap or
basis changed (0 variants without a reach mark, 0 without a basis).

(cherry picked from commit ead4b73a198ad597b502de5f20b246c64c9424c2)
2026-11-02 13:13:18 -08:00
Anees Iqbal 4b194d24af Write Metal's encoding through compressed BGRA10_XR blits under an exact-answers switch
What: a new DevicePolicy switch, `extended_range_blits` (ExtendedRangeBlitPolicy::Kept, the
default, and ::Canonical, which `exact_answers()` selects). Under Canonical a blit or fill through a
BGRA10_XR or BGRA10_XR_sRGB texture Metal keeps losslessly compressed writes Metal's canonical
encoding: each 16-bit field's low six bits cleared and, for a blit, the alpha code clamped to
[384, 894].
- bind::extended_canonical_module, a compute kernel that rewrites a texel range's words in place
  (bind/extended_canonical.rs, with extended_range_canonical as its reference and interpreter
  tests); the runtime owns it as OwnedModule::ExtendedCanonical.
- The runtime (extended_canonical.rs): after a blit into such a texture, or out of one into another
  texture of the format, the written regions go out to a scratch buffer, one dispatch per region
  rewrites them, and they go back; after a blit out of one into a buffer, or into a texture over a
  buffer's bytes, one dispatch rewrites the words in place at the layout's rows. A fill's texel is
  encoded before it is written (fills clear the low bits alone: Metal's fill keeps alpha codes 4
  and 1023 on the M3 Max under 27.0.1). A buffer the device cannot bind (offset or pitch off 4,
  past maxStorageBufferRange) or a texture over a buffer whose rows share bytes keeps the bytes and
  announces extended-range-bits-kept, as under Kept. Under Canonical the note is not announced for
  the blits it makes exact.
- copy_from_buffer_to_texture's body moved into buffer_into_texture, which a fill's row copies call
  with Writer::Fill (so a fill announces its own wording and is never rewritten as a blit).

Why: Metal's GPU blits through the compression rewrite these bits (measured on the M3 Max under
macOS 27.0.1, plain Metal, xr_matrix: compression iff allowGPUOptimizedContents, shorter side >= 16,
neither ShaderWrite nor PixelFormatView usage; every storage mode alike; CPU copies keep the bytes;
fills clear the low six bits only). The device's copy keeps the bytes. It is the runtime's choice,
not a native answer (no device arithmetic is involved: a copy's bytes), so per rule 1 the fast form
stays the default and the exact form is the switch.

Ledger: FAST-PATHS row (fast defaults), API.md section 1 bullet and the extended-range-bits-kept
catalogue entry, the Degradation doc, the conformance Policy doc. Known gaps: the 28 rows of
compressed-blits-bgra10xr and -srgb (7 sites x 2 formats x Apple M3 Max and llvmpipe) dropped:
under the suite's exact policy those sites now hold Metal's bytes.
RUNTIME_VERSION 1728 -> 1731 (a run under the exact policy writes other bytes).

Also fixes forward a clippy needless borrow in engine_arith's pack test (7a99b93af2).

Verified (M3 Max, macOS 27.0.1, MoltenVK 1.4.2; and lavapipe in scripts/linux-gate, arm64,
LLVM 21.1.8 128 bits):
- runtime_lane::compressed_blits on MoltenVK: both tests pass; the new
  extended_range_blits_write_metal_s_encoding_under_the_canonical_policy checks every direction,
  level 3 into padded rows, Shared CPU/blit mixes, texture to texture both ways, a fill of a
  compressed and a plain texture, and a copy into a texture over a buffer with padded rows, under
  both values (Canonical: Metal's bytes and no notice; Kept: the bytes and the notice once).
- conformance replay of the four compressed-blits cases on MoltenVK: exit 0, the ledger as
  edited (bgra10xr and -srgb `announced` only for staged-texture-copy/shadowed-texture).
- the full `conformance replay --cpu` on lavapipe at 68074019a3 and at this change: the only
  difference is the 14 llvmpipe sites of the two XR cases, which no longer diverge (divergent
  244 -> 242, exact 458 -> 460); the 265 other ledger mismatches of that arm64 venue are the same
  at both (it is not CI's amd64 lavapipe).
- 154 touched validation lanes on MoltenVK (blits, fills, extended-range, NaN, pack, padded,
  rotated, no-copy, two-plane heap): 143 passed, 10 failed, 1 ignored; the same 10 fail with the
  same messages and the same differing texels at 68074019a3 (pre-existing).

(cherry picked from commit 612ff50b86bc29515b158d9b2596b14a45431467)
2026-11-02 13:13:17 -08:00
Anees Iqbal 452c17aa2c Carve MoltenVK on the M3 Max's identity out of DevicePackConversion for the measured forms
reims-vgpu treats precision notes as fatal on Apple GPUs. On the M3 Max (MoltenVK 1.4.2, macOS
27.0.1) the module's air.pack/air.unpack of rgb565 in float, and in half of unorm4x8, snorm4x8,
unorm.rgb10a2 and unorm.rgb565 (both ways) and unorm2x16 and snorm2x16 (packed), answer Metal's
words, so DevicePackConversion was recorded where nothing differs.

What: DriverDeviation::MetalPackConversions (VkProperty::MetalPackConversions), taken by the
APPLE9 MoltenVK row alone. Where taken, select_pack records no note for a form
lower::arith::pack::measured names and the module requires the property
(ArithPlan::metal_packs). The lowering is unchanged on every profile. Kept noted, with the inputs
that differ (probe over the same inputs, fast and precise math): the sRGB format (85,511 of
3,083,776 float packs, 3,286 of 65,536 half packs, every unpack), unorm.rgb10a2 in float (9,163
of 131,072 unpacked words, 1,257 packed floats), the half unpacks of unorm2x16/snorm2x16 (8
lanes: our float quotient rounded twice), and snorm.rgb10a2 (unmeasured).

Docs: Metal's float rgb565 measured to round the product to float first (the exact-product model
misses 55 of the tie set) and to unpack by the float reciprocal; the artifact rustdoc and API.md
said Metal rounds the exact product and divides correctly rounded for every format, now
qualified for rgb565 in float.

Verified (all on this M3 Max):
- Plain Metal running runtime_lane::pack_conversions' own AIR (12 kernels: every code of every
  field, every half in every channel, 68,672 float words incl. 33 around each 5/6-bit tie):
  the lane's model matches Metal in every word.
- runtime_lane::pack_conversions on MoltenVK: no kernel records the note, 0 inputs differ.
- tests::engine_arith::pack_conversions_are_metals_where_measured: all 32 normalized forms on
  lavapipe and moltenvk-m3 (note and property per form); it fails without the deviation row
  (its takes == moltenvk-m3 assertion) and without the select_pack change (the note).
- Focused core run (engine_arith, driver_facts, fast_paths, golden, api_signatures, pack,
  engine_tile, engine_texture): 197 passed.

Also: drops an unused binding the NaN-moves commit left in engine_native_half. The NaN-moves
commit's message gives SEMANTICS_VERSION 1946; since the rebase onto 68074019a3 it is 1948
(ARTIFACT_FORMAT_VERSION 483), which covers this commit too. FAST-PATHS row for air.pack updated.
api_signatures blessed (two variants); golden hashes re-blessed (the moltenvk-m3 profile).

(cherry picked from commit b344f5e515e5b1c586877ca45fedead512ea0ad2)
2026-11-02 13:13:17 -08:00
Anees Iqbal 3e28f68331 Carve MoltenVK on the M3 Max's identity out of NativeNanEncoding for NaN moves
reims-vgpu treats precision notes as fatal on Apple GPUs; NativeNanEncoding was its largest
group of Mac-only failures. Measured on the M3 Max (MoltenVK 1.4.2, macOS 27.0.1), the device's
widening of a half to float, its narrowing back, and float fneg/fabs and half fabs answer
Metal's NaN bits, so the note was recorded where nothing differs.

What: a new DriverDeviation::MetalNanMoves (VkProperty::MetalNanMoves), taken by the APPLE9
MoltenVK row alone. Where taken:
- a float fneg or fabs records no NativeNanEncoding and the module requires the property
  (SPIRV-Cross writes -x and abs(x), Metal's own operators on the same operand);
- a half's widening to float (fpext, air.convert) and a half fabs, and a module's reads and
  encodes of a half's bits, record no note and require the property, but only where the module
  moves its halves through the registers as measured. narrow::moves_unfolded keeps the note
  where a widened half is stored anywhere but a buffer, workgroup memory or a function's float
  variable, passes through a call, return, group, atomic or image operation, has its bits read
  (a bitcast that is not stored, frexp/modf/ldexp: the frexp routines stay noted), or where the
  module holds a float NaN constant other than 0x7fc00000.
- A half fneg stays noted on every profile: the measured shapes matched only because the
  driver's compiler moved the negation onto the half.

By construction: MoltenVK's MSL writes float(as_type<half>(x)) and half(f); Metal's compiler
folds half(float(h)) across selects, phis and a function's local float variable, so moved
halves keep their bits as Metal's do.

Verified (all runs on this M3 Max):
- Plain Metal running the lane's own AIR (8 kernels; every one of the 65,536 half patterns,
  98,368 float words including 65,536 structured NaNs) matches the lane's model in every word.
- runtime_lane::nan_moves on MoltenVK: the note is absent from every kernel but the half fneg,
  and 0 lanes differ from Metal in all 8 kernels.
- Earlier MSL probe, fast and precise math: the same equalities over 262,144 float words.
- New core tests: half_moves_are_metals_only_where_the_device_folds_them (a payload NaN
  constant keeps the note), the frexp negative control in engine_metal_routines,
  float_sign_operations and the class C/D NaN tests with a moves argument, and the driver-facts
  lists.
- Core nextest (metal2vulkan, air, runtime, devtools, --all-features): 4,989 passed.

Docs: API.md (native-nan-encoding exemption), HOWTO.md, the PrecisionNote and deviation rustdoc.
SEMANTICS_VERSION 1946, ARTIFACT_FORMAT_VERSION 483 (a new VkProperty in the codec); these
bumps cover the rest of this branch. api_signatures blessed (two variants); the moltenvk-m3
profile's golden hash re-blessed.

(cherry picked from commit 93ae66b6ddb46b4d0d3db1944a4b043c40911592)
(Note on the development copy: this message names SEMANTICS_VERSION 1946; the commit sets 1948, after a rebase.)
2026-11-02 13:13:17 -08:00
Anees Iqbal 9613166920 Document the video plumbing; regenerate the refusal surface and the signatures table
- crates/metal2vulkan-runtime/README.md: the extra_queues option, the feature structures the
  listed video extensions take, DeviceHandles' extra queues and the sharing rule for them, the
  shared event's semaphore (signal-index counter, vk_wait, reserve_vk_signal), plane textures
  over the consumer's VkImage and their refusal, and Buffer::vk_host_memory.
- docs/REFUSALS.md regenerated (python3 scripts/refusal-surface/refusal_surface.py) for
  RuntimeGap::VkImagePlaneCopy and WrappedImageProblem::{Plane, PlaneFormat}; reach.tsv marks
  the gap `none` (a runtime extension's path). 0 variants without a reach mark or a basis.
- crates/metal2vulkan/tests/api_signatures.tsv blessed: 28 added records (ExtraQueue,
  VkEventWait, VkEventSignal, VkHostMemory, the new fields, methods and variants), none removed
  or changed.
- The extra-queue device test prints the video features enabled through the runtime's own
  query (listed_structures, listed_reported) and asserts each required one is on where its
  extension is enabled.

docs/METAL-COVERAGE.md and docs/CONFORMANCE-COVERAGE.md check current.

(cherry picked from commit bb2a4c2c6101458026253461402ac463c1bcb323)
2026-11-02 12:32:05 -08:00
Anees Iqbal b0bed82331 Record a pixel sample's centre denormals only where its centre can run
ed08da17f6's pixel-sampler fix recorded PrecisionNote::DeviceDenormals
unconditionally for every texel-centre position, TexelBySpec and
TexelByWord included. Those two are the runtime slot's and the argument
buffer's samples, whose centre `floor(x) + 0.5` sits behind the
NearestPixelSampler specialization or the table word's test: code that
no normalized state reaches. So every stage that samples through a
runtime or argument-buffer sampler, normalized ones included, gained an
unconditional DeviceDenormals at making, which a host that refuses any
precision note on an Apple GPU dies of (cubic stages died of it before
reaching their own BicubicFilterArithmetic, which is unchanged).

The note is real where the centre runs. Measured on the M3 Max with a
21x13 texture and clamp-to-zero and white-border states, at x = -2^-149,
-2^-140 and -2^-127: Metal's nearest pixel sampler reads texel -1 (the
border), MoltenVK's `floor` flushes the subnormal to -0 and reads texel
0. It shows through every centre form: a constexpr nearest sample with
an offset (UnnormalizedTexel), a constexpr edge fetch with an offset, a
constexpr nearest array sample (Texel), a runtime slot under a nearest
pixel state (TexelBySpec) and an argument buffer under one
(TexelByWord). The shader keeps the device's floor (owner's rule 1).

centre_denormals now gives the note per form:
- a constexpr sampler's Texel or UnnormalizedTexel centre, and a fetch
  under an offset: unconditional, as before;
- a runtime slot's TexelBySpec: only under NearestPixelSampler == 1,
  which is 0 for every normalized state; a runtime slot's Texel (an
  integer texture): only where its word has the pixel bit;
- an argument buffer's TexelByWord: none of its own;
  ArgumentPixelSamplerScaling, which the runtime announces only while a
  pixel state lives, records it (its doc now says so).

Tests:
- tests::engine_sampler::normalized_and_cubic_stages_record_no_note_
  their_states_cannot_run (moltenvk-m3) holds the unconditional notes of
  the sampling, handle, argument-buffer, pixel-argument and cubic
  fixtures (plain and the cubic variant under normalized and pixel
  words) to 9f5776bf31's, and checks every specialized DeviceDenormals
  clause tests the nearest-pixel constant or the pixel bit. It fails on
  ed08da17f6's select.rs (DeviceDenormals among the unconditional notes).
- runtime_pixel_accesses_hand_the_device_the_scaled_coordinate now
  checks the nearest kernels' one specialized DeviceDenormals entry and
  that the gather has none.
- runtime_lane::pixel_edges::normalized_states_announce_no_pixel_note
  dispatches the slot and argument-buffer kernels under normalized
  nearest and linear states and asserts no DeviceDenormals or pixel
  note, then a nearest pixel state and asserts DeviceDenormals (slot)
  and ArgumentPixelSamplerScaling (argument buffer). On ed08da17f6 it
  fails on the Apple M3 Max with DeviceDenormals under normalized states.

docs/API.md (device-denormals, argument-pixel-sampler-scaling) and the
DeviceDenormals row of docs/FAST-PATHS.md state the per-form rule and
the measurement. SEMANTICS_VERSION 1947: an artifact's notes changed.

Verified before this commit on MoltenVK (M3 Max, under maclock and
memcap): runtime_lane::pixel_samplers, pixel_edges (the new test
included) and pixel_downscales, 8 of 8; sampler translator tests 121.
The full checks follow on this tree.

(cherry picked from commit 382e940c470becee8cfdf560f2f1284ce2844599)
2026-11-02 11:36:44 -08:00
Anees Iqbal bd264821bf Regenerate REFUSALS.md for the draw-shape sites
The per-draw changes moved RenderState's scissor check from set_scissors
to scissor_rects, and the cross-encoder shape memo's layout view now
builds TileAtSampleCount too. refusal_surface.py --check passed with the
old site lists (it does not compare them), so the table went stale.
Regenerated with python3 scripts/refusal-surface/refusal_surface.py; the
diff is the six site-list lines alone.

(cherry picked from commit ed08da17f6ca8d1f7714f76e02053c8ae68d6583)
2026-11-02 10:03:18 -08:00
Anees Iqbal ec9e0546eb Hold a constexpr linear pixel sample to Metal's answer, not the normalized control, off MoltenVK
A constexpr linear pixel sampler now reads through the device's own linear filter in unnormalized
coordinates. On lavapipe that path's arithmetic is its own rather than the normalized filter's at
a moved coordinate: 79 to 107 of 800 cells of clamp to zero and to the border differ from the
normalized control in their last bits (none of clamp to edge), so
`pixel_samplers_answer_metal_s_texels` failed its control rule there. Such a configuration is
the device's native filter (`device-sampling`): where the device's sampler is not Metal's it is
printed and no longer held to the control; on a device with Metal's own sampler it must still
answer Metal's hash, as every constexpr and nearest configuration must.

docs/FAST-PATHS.md's pixel row scopes its nearest claim to the edge probes and says what a
constexpr linear sample is on lavapipe.

Verified: the pixel lanes (pixel_samplers, pixel_edges, pixel_downscales; 7 tests) pass on arm64
lavapipe in linux-gate under --cfg m2v_cpu_icd, where pixel_samplers failed before this change,
and on the M3 Max under MoltenVK; no nearest cell off Metal's rule was printed on either
(`PIXEL-EDGE-DEVICE`). The fast_paths ledger tests pass.

(cherry picked from commit 427ed1fa9dd6fc2ca7a9f8b12bd60a8bfa23d93a)
2026-11-02 10:03:18 -08:00
Anees Iqbal 575ac2b103 Read a pixel-coordinate sample's texel as Metal's sampler does
A `coord::pixel` sampler handed the device the coordinate divided by the texture's size. At a
texel edge whose quotient is inexact the device's normalized sampler read the texel before it:
on the consumer's 258x258 matrix 28 of 1042 nearest clamp-to-zero and clamp-to-border cells on
MoltenVK and up to 500 on an RTX 5080. Metal reads `floor(x)` for nearest and quantizes `x - 0.5`
to its 1/256 grid for linear filters and gathers.

Now, decided from the sampler's state and the access's structure:

- A constexpr pixel sampler that Vulkan's unnormalized sampler can state (one filter, no mip
  filter or anisotropy, clamp to edge, zero or border; a 1D or 2D non-array image, no comparison,
  no status read) samples and gathers through the device's own unnormalized sampler at the
  coordinate itself, on a view of level 0 (`CombinedSampler::unnormalized`,
  `SamplerDesc::unnormalized`). A linear sample's or gather's constant offset folds into the
  coordinate; a nearest sample's offset is applied to its texel's centre (`floor(x) + 0.5 + k`).
- A constexpr nearest pixel sampler the unnormalized form cannot take (an array, a mirror mode)
  samples at its texel's centre over the size, `(floor(x) + 0.5) / N`, which the device's
  normalized sampler reads as that texel exactly.
- A runtime slot's sampler takes the centre where a new pipeline constant,
  `SpecKey::NearestPixelSampler`, says the bound state is a nearest pixel sampler (1 only for
  those, so normalized states make no new pipeline); an argument buffer's sampler tests its word
  (`SamplerWord::nearest_pixel`, which replaces `exact_fetch`).
- Linear samples and gathers through runtime or argument-buffer samplers, arrays and 3D,
  comparisons, level queries and status reads keep the scaled coordinate and its note: their
  state is unknown where the shader is made, or Vulkan's unnormalized sampler forbids them.

`PixelSamplerScaling` is now recorded only where a scaled form remains; `DeviceDenormals` where
a centre's `floor` may read a subnormal coordinate as the device does. The pixel_samplers lane
also asserts Metal's answer for every constexpr and nearest configuration on MetalSampler devices.
The conformance case declares `pixel-sampler-scaling` for its linear cases alone, and the
llvmpipe ledger rows follow the run: two `rgba16f-nearest-mirror` rows are gone (Metal's answer
now), seven take the new digests. `SEMANTICS_VERSION` 1945, `ARTIFACT_FORMAT_VERSION` 482. No
`RUNTIME_VERSION` bump: an unchanged artifact (no unnormalized sampler, no new constant) binds and
runs as before.

The new fixture `px_edges` (own MSL, through regen-air-fixtures) samples every form at texel and
block edges, quarter offsets and each border colour on three NPOT sizes, and the new
`runtime_lane::pixel_edges` holds each nearest cell to the CPU's `floor` rule on every device and
every probe to Metal's digests on MetalSampler devices. Fixture comments in `sampling` and
`sampling_completion` no longer say the coordinate is scaled (their AIR bodies are unchanged).

Verified on the M3 Max under MoltenVK 1.4.2: the consumer's matrix compared with Metal's
results, 0 differing cells on every kernel and size (28 of 1042 before on three kernels);
lavapipe 0 before and after; `runtime_lane::pixel_edges`, `pixel_samplers` and `pixel_downscales`
pass; conformance replay of the 23 pixel cases holds the ledger on MoltenVK; on arm64 lavapipe
the whole set's replay departs from the parent's ledger, beyond what the parent's own replay
does, at exactly the nine rows edited here (the answers are the report's own). Core suite 4988
passed; validation suite under `--cfg m2v_gpu` passes the new and pixel tests, its other failures
fail the same on the parent commit; conformance 1007 passed; goldens, hashes and inventory
blessed. Release translation of every px_edges and px_samplers kernel on four profiles: slowest
0.08 s, largest peak 6 MB.

(cherry picked from commit 888ad9bae9f0aaaf769360740e1dd16817245ca4)
2026-11-02 10:03:17 -08:00
Anees Iqbal ddccbfac5a Bump RUNTIME_VERSION to 1722 for ASTC passes, storage slots and 4x2 and 8x4 footprints
What: RUNTIME_VERSION 1721 -> 1722; the runtime-sources pin recomputed on this tree
(3314ddbb...); api_signatures.tsv blessed (Degradation::AstcStorageNeutral and
PlanDiagnostic::AstcStorageNeutral added); docs/CONFORMANCE-COVERAGE.md regenerated (one ledger
row fewer, one more module declaring a notice); `cargo fmt` of the footprint case's allowance.

Why: a run of an unchanged artifact and plan now does something else: a pass over an ASTC
attachment drops it instead of refusing, a storage slot over an ASTC texture binds a neutral and
announces `astc-storage-neutral`, and the 4x2 and 8x4 footprints make textures. docs/REFUSALS.md
and docs/METAL-COVERAGE.md regenerate unchanged.

Verified: `signatures.py --bless`, `refusal_surface.py`, `metal-coverage/coverage.py --check`,
`conformance-coverage/coverage.py` on this tree (rebased onto fbc086020f).

(cherry picked from commit a37ab781870cf9d3c1e9672026f9773f3f6dfdf2)
2026-11-02 02:17:10 -08:00
Anees Iqbal 253dedccc3 Drop ASTC attachments from passes and bind a neutral at ASTC storage slots
What: on every device and for every ASTC form (LDR, sRGB, HDR, every footprint, in its own block
or in a carrier):
- a render pass drops an ASTC color attachment that resolves nothing (`render_pass::layout`): it
  loads, clears and stores nothing into it, its level's extent still bounds the pass, and the
  pass's other attachments run as they would. No notice: that is Metal's answer.
- a draw or dispatch binding an ASTC texture at a storage slot binds the slot's neutral
  (`PlanDiagnostic::AstcStorageNeutral`): its writes leave the blocks as they were, its reads
  answer zero. The runtime announces the new `astc-storage-neutral` (precision) once, catalogued
  in docs/API.md, its lane site `ASTC_STORAGE`.
A render pipeline of an ASTC color attachment stays refused (Metal ends the process), as do a
resolve of an ASTC attachment (unmeasured), 1D and multisampled textures and another footprint's
view.

Why: the runtime answers plain Metal, not its validation layer. Plain Metal (an M3 Max under
macOS 27.0.1, probe `astc_passes_writes_footprints`) completes such a pass for every load and
store action, with a draw and without, leaving the blocks unchanged and the other attachment as
without it; it completes a kernel's `write` and `read_write` and stores bytes no format defines
into the blocks (`read_write` reads their decode). No Vulkan format of a block is an attachment's
or a storage image's, so the pass drop is exact and the neutral differs, announced.

Tests that fail before: the translator's `a_stand_in_compile_is_the_compile_of_its_formats_bind_
and_no_other` (every ASTC format at a storage slot plans the neutral with the diagnostic); the
runtime's `degradation_sites` closure (a lane site for the kind); the lane's
`runtime_lane::astc_passes_and_writes`: every one of the 48 ASTC formats at color 0 of four
passes (clear and store, load and draw, dontcare both and draw, clear and draw) with an RGBA8
color 1: the blocks unchanged and color 1 the pass's without the attachment (192 passes); a
pipeline of an ASTC attachment refused; every format bound to `write` and `read_write` kernels:
blocks and texels unchanged, `astc-storage-neutral` announced once.

Verified: MoltenVK lane on the M3 Max, `runtime_lane::astc*` 9 of 9 (192 passes, 96 dispatches);
runtime touched tests.

(cherry picked from commit 68a296589040b208634abd7b8dfa6ce938cf8c96)
2026-11-02 02:17:10 -08:00
Anees Iqbal e972337dd8 Hold ASTC's 4x2 and 8x4 footprints in a carrier with a decoded twin
What: the six ASTC formats of Apple's 4x2 and 8x4 footprints (LDR, sRGB, HDR), which no Vulkan
format holds, are made on every device as the other ASTC formats are on a device without ASTC:
their blocks in the 16-byte carrier (BC7, BC3, BC2, BC5, ETC2 or EAC; one ASTC block over 4 x 4
carrier texels whatever its footprint), their reads through a decoded twin of 8-bit codes (LDR,
sRGB) or halves (HDR). `AstcDecode::of` takes every footprint from `metal::format::block_extent`;
the format table maps them decoded-only (no direct format); the footprint module answers 26
formats now, and the heap size query takes the modelled ASTC block layout for them. Copies map
regions in blocks (`copy_plan::block_bytes`), a partial last block as Metal rounds it.

Why: plain Metal makes every such texture (2D, 2D array, cube, 3D; Shared and Private; read,
write, render-target usage) and copies them in whole blocks, the last ending at the level's edge
(probe `astc_passes_writes_footprints`). The orchestrator's brief suggested an uncompressed
16-byte-texel carrier; the existing compressed carrier already holds any 16-byte block per 4 x 4
carrier texels, so it serves every footprint with the decode passes, CPU decodes, second twins
and copy paths the other ASTC formats use, with no new image kind.

Tests that fail before: the translator's format tests (`astc_4x2_and_8x4_are_named_and_read_
through_their_twin`, counts and twins), the decode digests of 4x2 and 8x4 against Metal's
(`astc_decode` tests, HDR coverage), the runtime's image-plan, heap and pixel-format tests, and
the lane: `runtime_lane::astc_textures` and `astc_hdr_textures` now take every footprint (32 LDR
and sRGB, 16 HDR), the round trip at every level and slice 4x2 and 8x4 (partial blocks at 37x23
and 29), the colour-space views 4x2 and 8x4. The conformance case
`format-footprints-astc-4x2-and-8x4` now makes and round-trips them: its ledger row (the refusal)
is gone and it declares the three notices the carrier announces.

Verified: translator and runtime touched suites; MoltenVK lane (`runtime_lane::astc*`, 9 of 9 on
the M3 Max); conformance replay on MoltenVK of the footprint case and the ASTC cases, compliant
(the footprint case announced, every byte Metal's); lavapipe replay: every byte Metal's, the
notices undeclared before this commit's declaration.

(cherry picked from commit 2a8dd25c6b9d4cc62ff79816fa61d984969b3c22)
2026-11-02 02:17:10 -08:00
Anees Iqbal 1210972f03 Hold multisampled word-format textures in their word's format
Metal makes 2- and 4-sample textures of R8Unorm_sRGB (11), A1BGR5Unorm
(41), ABGR4Unorm (42) and RGB9E5Float (93) for every usage, memoryless
included (our probe msaa_word_formats.m, M3 Max, macOS 27.0.1). The RTX
5080 samples these formats but renders none, so Vulkan states one
sample for their images and the runtime refused each at creation
(TextureSampleCount, FramebufferColorSampleCount(4)).

What changes:
- image_plan::word_samples: where the device samples the format, renders
  it at no count and renders the word's format (R8_UINT, R16_UINT,
  R32_UINT), a multisampled texture's image is the word's format,
  mutable to the format's sampled view (and an 8-bit sRGB format's UNORM
  twin, for its resolve). Every sample holds Metal's word by
  construction: the existing word lowering writes it, clears write
  Metal's clear word, reads decode through the format's view, copies are
  bitwise. Shader writes stay unavailable (Metal writes no multisampled
  texture from a function). A device that renders the format keeps its
  native image.
- The resolve of such an attachment is the crate-owned one: Metal's for
  RGB9E5Float and 8-bit sRGB, a near-equivalent within one code for the
  packed formats, announced as the new Degradation::WordResolve
  (word-resolve). The NotImplemented(Format) refusal of word resolves in
  resolve.rs is gone; an attachment that takes neither input attachment
  usage nor the copy is still refused.
- DeviceOptions::withheld_attachment_formats (doc hidden, a test hook):
  a device made with formats' color attachments withheld, so the word
  path runs on MoltenVK, which renders all four.
- RUNTIME_VERSION 1721. Docs: API.md (word bullets, the multisampled
  word paragraph, the word-resolve catalogue entry), FAST-PATHS known
  gaps (word resolves no longer refused), word.rs, image_plan.rs and
  resolve.rs module docs; runtime-sources pin recomputed.

Routes over the committed profiles (tests::word_samples, pinned): the
word for all four formats at 2 and 4 on NVIDIA's three profiles, for
R8Unorm_sRGB and RGB9E5Float on ANV's four, and RGB9E5Float at 4 on the
gate's lavapipe; native on MoltenVK and RADV; refused where the word's
format renders one sample or the textures take no such count
(swiftshader, lavapipe's profile, the floors).

Verified:
- cargo nextest run -p metal2vulkan-runtime --all-features: 1188 pass
  (the three word_samples planning tests among them).
- Device lane runtime_lane::word_samples_msaa on the M3 Max through
  MoltenVK (--cfg m2v_gpu, maclock), new owned fixture wsm_samples: the
  device as it is (each format natively) and with the four attachments
  withheld (each held in its word, printed per format). On the word path
  every stored sample is Metal's word (all 32 or 64 per shape), reads
  decode them, the sRGB and RGB9E5 resolves are Metal's in every pixel,
  the packed resolves within a code (7-9 of 16 pixels exact after a
  draw, 13-16 after a load), a packed blend's words Metal's in every
  sample. word-resolve and shader-resolve announced. Negative control:
  with word_samples disabled the lane fails.
- clippy -D warnings (default and --cfg m2v_gpu), rustdoc -D warnings,
  private intra-doc links at their ceilings, refusal_surface --check,
  api_signatures --bless (DeviceOptions field, Degradation::WordResolve
  added), METAL-COVERAGE and CONFORMANCE-COVERAGE --check current.

Not in this change: the golden tables for the new fixture
(golden_hashes, the engine inventory, the air_input printout) are
re-blessed on development. Blends of an 8-bit sRGB or RGB9E5Float word
stay refused as the device lacking the format, as they are at one
sample.

(cherry picked from commit ad8b94cd840f3d0bf4bb9552904fbdf2f253b9af)
2026-11-02 01:32:20 -08:00
Anees Iqbal 7130d5d6e7 Make ASTC HDR textures where Metal makes them: native, else a carrier with a twin of halves
Metal on an M3 Max (macOS 27.0.1) makes every 2D ASTC HDR texture
(MTLPixelFormat 222-236) with read, write and render-target usage; the
runtime refused them on every device without the Vulkan SFLOAT block
(the RTX 5080 among them) as a format it cannot hold.

- Translator: bind::AstcDecode decodes the HDR profile, written from
  the Khronos Data Format Specification's ASTC chapter (new hdr.rs):
  HDR endpoint modes 2, 3, 7, 11, 14 and 15, the LNS-to-half mapping,
  LDR modes and void-extent blocks in an HDR texture, and the HDR
  void extent, on the CPU and in the GPU decode kernel (kernel/hdr.rs).
  Where the probe showed Metal's own answer it is the one taken: an
  LDR channel in the HDR profile is C/65536 truncated to a half (1 for
  65535); a void extent's NaN halves read as the quiet NaN; an error
  block reads NaN in every channel. Public API: AstcDecode gains `hdr`,
  AstcTexels gains `Half` (R16G16B16A16_SFLOAT), AstcDecode::form picks
  a profile's compact form, and AstcDecode::texel_bytes is now a method
  (a consumer calling AstcDecode::texel_bytes(texels) writes
  decode.texel_bytes(texels)); api_signatures.tsv blessed.
- Format table: each ASTC HDR format takes its ASTC_*_SFLOAT_BLOCK
  where the device holds it (the device's decode, rule 1), else
  FormatEmulation::Decoded over R16G16B16A16_SFLOAT.
- Runtime: such a texture is the existing carrier (its 16-byte blocks,
  which copies and getBytes move unchanged) and a decoded twin of
  Metal's halves, exact, kept in step by the same GPU and CPU decodes;
  a new texture's twin starts at the error block's NaN. Notices:
  carried-decoded-twin and cpu-block-decode, as for ASTC LDR; no
  decoded-texel-precision (the halves are Metal's). A view in another
  profile (an HDR texture's LDR or sRGB view, or the reverse) is
  refused on a carrier (Feature::TextureView, as another footprint
  is); render passes into one and kernel writes of one stay refused
  typed (the Vulkan formats take neither), where Metal's validation
  stops each.
- Docs: API.md's carried-decoded-twin entry, FAST-PATHS known gaps,
  module docs of bind::astc_decode, astc.rs and decoded_twin.rs.
- Conformance: the 42 ASTC cases now name the twin notices for HDR rows
  too, and the decoder cross-check holds Metal's recorded HDR reads.

Versions: RUNTIME_VERSION 1720 (an HDR texture is now made and read
where it was refused). No SEMANTICS_VERSION or ARTIFACT_FORMAT_VERSION
bump: translation output is unchanged (the Decoded candidate admits
sampling usages only, so no pipeline's format answer moves) and no
encoded artifact carries AstcDecode. Runtime-sources pin recomputed.

Verified:
- CPU decode bit-exact against Metal for 2048 seeded blocks of each of
  the fourteen footprints (every endpoint mode, partitions, dual plane,
  void extents, error blocks), as float and half reads and nearest
  samples (probe `reads`), checked by per-footprint digests and a
  66-block fixture of Metal's float bits (bind::astc_decode::tests::hdr);
  the GPU kernel equals the CPU decode on every texel; the kernels are
  valid on every committed profile; the conformance suite's recorded
  astc-*-hdr reads equal the decoder's.
- Plans: moltenvk-m3 native for all 14; nvidia-rtx5080-laptop,
  lavapipe, amd-780m-radv and intel-arl-anv in a carrier
  (runtime tests::image_plan).
- conformance replay of the 42 ASTC cases on lavapipe (linux-gate,
  --cpu): the 14 HDR rows `announced` (texels exact, carried-decoded-
  twin and cpu-block-decode fired), exit 0; on MoltenVK the 14 HDR rows
  `exact` with no notice.
- Touched tests in metal2vulkan, metal2vulkan-runtime,
  metal2vulkan-conformance; clippy (plain and --cfg m2v_gpu);
  refusal_surface --check, both coverage docs current; private
  intra-doc link loop at its ceilings.

(cherry picked from commit eb6828adddde978fab87dc7d05ea1a2a55738008)
2026-11-02 01:09:01 -08:00
Anees Iqbal 81441ca877 Regenerate the surfaces for pull-model interpolation
- RUNTIME_VERSION 1719: the runtime answers supportsPullModelInterpolation
  and refuses a draw reading an interpolant at a sample at custom positions.
- scripts/metal-coverage/coverage.tsv: supportsPullModelInterpolation
  implemented (DeviceProperties::supports_pull_model_interpolation);
  docs/METAL-COVERAGE.md and docs/CONFORMANCE-COVERAGE.md regenerated.
- docs/REFUSALS.md regenerated: feature::PullModelInterpolation and
  gap::InterpolateAtSampleWithPositions (reach rows in reach.tsv).
- crates/metal2vulkan/tests/api_signatures.tsv blessed: additions only but
  Query::ALL's length (8 to 9) and value.
- crates/metal2vulkan-runtime/README.md: the query and what differs.
- runtime-sources pin recomputed (pin-compute.py).

Verified: refusal_surface.py --check, signatures.py --check,
metal-coverage --check and conformance-coverage --check all current.

(cherry picked from commit 2dcbbf39b6e5caeb3e87079d7f2f36540ceb0dd0)
2026-11-01 23:38:39 -08:00
Anees Iqbal ef7a8d6f08 Lower Metal's pull-model interpolation (interpolant inputs)
A fragment function reading an `interpolant<T, P>` input through
interpolate_at_center, _centroid, _sample or _offset was refused as invalid
input (the AIR key air.interpolation_function was unknown), so a guest whose
device answers supportsPullModelInterpolation could not run one.

AIR: the key marks a fragment input `Sampling::Interpolant`, a device-space
handle (`AbiHandle::Interpolant`); `air.interpolate_{center,centroid,sample,
offset}_{perspective,no_perspective}.{f16,f32 x1..4}` parse as
`AirIntrinsic::Interpolate`, decided from the intrinsic family and the
metadata ABI, never names.

Lowering: the interpolant is a float Input variable of its form (NoPerspective
where not perspective), read only through its calls:
- center: as a center varying is read (its pixel-center form at more than
  one sample where the device has one);
- centroid / sample / offset: GLSL.std.450 InterpolateAtCentroid,
  InterpolateAtSample (index & (SampleCount - 1), Metal's i mod n) and
  InterpolateAtOffset (offset moved to the device's origin and NClamped to
  [minInterpolationOffset, maxInterpolationOffset], which Vulkan requires).
  These need sampleRateShading (and MoltenVK's portability member): without
  them the function is refused Unsupported(PullModelInterpolation).
- MoltenVK's SPIRV-Cross hands InterpolateAtOffset(v) to Metal as
  interpolate_at_offset(v + 7/16): such a device gets the new
  VkProperty::InterpolateAtOffsetFromSevenSixteenths and the module moves
  the offset by 7/16 (a module annotation picks the property).
- An interpolant used any other way (a select of two) stays
  NotImplemented(PullModelInterpolation); on RADV
  (InterpolationNeedsTheWholeQuad) a sample or offset read after a discard
  or outside the first block is refused; lavapipe refuses a multisampled
  centroid read as it refuses a centroid varying.
- GraphicsState::interpolates_at_sample states a fragment stage that reads
  at a sample (Vulkan takes no InterpolateAtSample with custom sample
  locations); Sampling::Interpolant carries center/centroid/sample.

Metal measured on the M3 Max, macOS 27.0.1, with the new probe
probes/pull_model_interpolation.m over the owned fixture
pull_model_interpolants (cases origin, grid, samples, centroid, lane): an
offset is read from the pixel's corner as given, no range, no grid, NaN for
a non-finite one; sample i reads i mod n at Vulkan's standard positions;
centroid is the center when the pixel is covered whole, else the lowest
covered sample. The offset's range and grid are the device's:
PrecisionNote::DeviceInterpolationOffset (validation: Recorded), in
docs/API.md's catalogue and FAST-PATHS.md's device gaps; a centroid read
notes MultisamplePosition as a centroid varying does.

Verified: tests::engine_pull_model (309 pipelines over every committed
profile at 1 and 4 samples: instructions, mask's planned SampleCount,
origin, NClamp, note, property, L3; refusals on vk12-floor, RADV after a
discard, lavapipe centroid at 4x; pm_selected refused everywhere),
engine_multisample, engine_fragment, engine_coverage_loop, fast_paths,
api_tests, codec and cache tests, metal2vulkan-air abi/intrinsics tests and
api_surface; runtime degradation and catalogue tests; clippy all features.
Before: every pull_model_interpolants function failed InvalidInput
(Abi(UnknownKey)). Goldens: only new rows and the moltenvk-m3 profile hash
moved (its new property); inventory 24 new rows, 0 moved cells.

SEMANTICS_VERSION 1941 (refusals became translations), ARTIFACT_FORMAT_VERSION
481 (IoSampling, PrecisionNote, VkProperty and GraphicsState encodings).

(cherry picked from commit 70e01b4bd6f8a0d1421ae07ed710714fb4ce985b)
2026-11-01 23:38:39 -08:00
Anees Iqbal ceb666187a Answer Metal's supports32BitMSAA from the device's own textures
The runtime had no answer for supports32BitMSAA (METAL-COVERAGE listed it
missing), so the consumer passed None through. Metal's answer promises a
multisample texture of each 32-bit integer format and the resolve of
each 32-bit float one; the M3 Max, a Radeon Pro 5300M and a UHD 630 all
answer 1.

What the runtime did before was read first: a multisample texture of each
of the nine formats is planned as any texture is (image_plan), within the
device's limits for the image (vkGetPhysicalDeviceImageFormatProperties2),
and refused as a count its format lacks; draws and texture2d_ms reads of
it, the float formats' AVERAGE resolves (Metal's own on MoltenVK,
device-rounded-resolve elsewhere) and the refusal of an integer resolve
(ResolveFormat, as Metal stops it) were all in place. The render
pipeline, sample planes and interleave all take a format's own counts
beside framebufferIntegerColorSampleCounts. Nothing was wrong; the
query was missing.

Device::supports_32bit_msaa answers yes where the device makes every
texture and resolve the answer promises, each probed exactly as
pixel_format_capabilities probes a capability (the probe closure of
families::formats::answers is now a function both share): the texture
sample counts hold 4, a 2D multisample RenderTarget|ShaderRead texture of
each of the nine formats is made at every count above 1 the textures take,
and each float format resolves (its Resolve capability). A device method,
as supports_family is, because it reads the device's per-format limits:
Vulkan floors an integer format at framebufferIntegerColorSampleCounts,
one sample on RADV and lavapipe, while their 32-bit integer formats each
take 1 to 8 (1, 4, 8 on lavapipe), as the venue profiles' captured
per-format counts state.

Tests:
- runtime tests::msaa_32bit: every committed profile pinned, with the
  limits it states (a venue profile's own per-format color attachment
  counts, else Vulkan's floors). Yes on every venue (moltenvk-m3, both
  780M RADV, both gate lavapipe, the ANV and NVIDIA ones) and on the
  Intel and NVIDIA profiles whose floors cover the counts; no on
  amd-rdna2/rdna3-radv, lavapipe, lunarg-desktop-baseline-2023,
  swiftshader and vk12-floor (R32Uint at the lowest count, naming
  FramebufferIntegerColorSampleCount), and roadmap-2022 (no 4 samples).
  A yes agrees with each format's Msaa and float Resolve capabilities;
  the rule needs 4 and every count, and a missing resolve texture says
  so. A negative control that probes 4 samples alone fails two of them.
- validation runtime_lane::msaa_32bit (--cfg m2v_gpu): the answer is what
  the device makes; R32Uint and RGBA32Uint targets at 2 and 4 drawn at
  sample rate hold every bit, read back through texture2d_ms<uint>
  (Metal: every channel as written); an RG32Float 4-sample target keeps
  its samples and resolves to the probe's Metal texels, exact where the
  driver's average is Metal's; an RGBA32Uint resolve is refused.

Verified: runtime tests msaa_32bit, families and capabilities, the
metal_coverage and runtime-sources pin tests; on the M3 Max (MoltenVK
1.4.2, macOS 27.0.1) through the Mac GPU lock, runtime_lane msaa_32bit,
families and capabilities 7/7: supports32BitMSAA true, counts [2, 4],
nothing refused, 0 integer channels differ, 32 of 32 resolved channels
as Metal's, device-rounded-resolve not announced. clippy with all
features and with --cfg m2v_gpu, rustdoc -D warnings, refusal_surface
--check (no refusal moved), api-signatures (one method added),
METAL-COVERAGE and CONFORMANCE-COVERAGE regenerated (the item now
implemented, not yet exercised by the suite).

RUNTIME_VERSION 1718 (a new answer); runtime sources re-pinned.

(cherry picked from commit 2376157b3bf7bf99221579f42a795ef351b8144c)
2026-11-01 22:35:40 -08:00
Anees Iqbal 6f8ec46671 Draw a draw whose own band the translator refuses at the nearest width
A draw whose own band variant the translator refuses where the state's
first band compiled (a varying or push data the draw's variant adds, such
as a shader-side depth test's window depth and depth range, past
maxTessellationEvaluationOutputComponents or maxPushConstantsSize) was
refused with the translator's Unsupported(WideLines). Only its later
draws took the nearest width. That breaks the owner's rule that an
accuracy note is logged and never fatal: the draw can run at the nearest
width.

The draw now takes the nearest width, announced as a state's refusal is
(lines-at-nearest-width, the translator's refusal the reason). The
refusal is still kept per state and primitive (GraphicsState::refuse_band,
two answers a state). A draw's variant key follows from its bind shape,
and its route sets that shape, so a per-key memo would need the shape
before the route. Recording a draw factors what its lines' route decides
(the route, provoking vertex, listed strip, private form, settings) into
RenderLowering::routed_draw and a RoutedDraw. draw_resident settles in a
loop. Where the settle answers the translator's refusal of the draw's band
(LineRoute::refused), it marks the state's primitive refused and routes
the draw again. Routed again it draws no band of the primitive, so it
settles once more at most. settle_draw hands that refusal back to the
caller before its snapshot and shadow retries, as before.

Docs: line_width.rs, the runtime README, FAST-PATHS's known gap, API.md's
and degradation.rs's lines-at-nearest-width (no refusal named any more).
REFUSALS.md does not move (refusal_surface --check passes): the
translator's refusal stays. RUNTIME_VERSION 1717 (a refusal became an
announced draw); runtime sources re-pinned.

Verified: the new pure test
a_draw_whose_band_the_translator_refuses_takes_the_nearest_width covers
every committed profile under both policies, lines and edges, widths 0 to
16. Each band route takes either refusal (not implemented, and the
evaluation-output limit) as its primitive's. Routed again, it is the
nearest width with the refusal as the reason, or the device's lines, and
never a band. A non-WideLines refusal or a runtime gap stands. It does
not compile against be2d725fdb, which had no such decision. A negative
control that drops the decision for lines fails it ("amd-780m-radv,
Device, Lines at 0: left None, right Some(Lines)"). Runtime line_width
tests 4/4 pass. Also clean: clippy with all features and with
--cfg m2v_gpu, refusal_surface --check, the runtime-sources pin test.
Not run: the GPU lane. No draw on MoltenVK reaches this cheaply: the base
key's band and a draw's differ only by shader-side tests' additions or
push data. The orchestrator's gate covers the restructured draw path.

(Carried to development from steelbrain/reims-graphics-kext 06f08298fd.)
2026-11-01 21:26:24 -08:00
Anees Iqbal b3d483fd72 Draw triangles' wide edges as bands, and refused bands at the nearest width
Metal draws a triangle in fill mode Lines at a width other than 1 as its
three edges, each the line parallelogram, facing as the triangle does and
culled by it, its flat inputs from the provoking vertex (the probe's
`edges` case, committed with the lane before this). The runtime drew
those edges with the device's lines, at the nearest width they draw (1
pixel on MoltenVK), announced.

Translator: the band variant takes a primitive (`BandPrimitive`, in
`VariantKey::line_band`, `LineBandState::primitive`, `BindState` and
`BindShape::line_band`). A triangle's patch is its three vertices in the
quad domain at outer levels (11, 1, 6, 1) and inner levels (3, 2): the
inner ring degenerates to a segment, so the spec's deterministic fans
from its two vertices cover the u = 0 and u = 1 edges, and the
evaluation stage places those fans' vertices at the corners of the
edges' parallelograms (from the vertex of the largest w, which never
moves at the near plane), every other triangle degenerate. The band
faces as the triangle (the sign of its homogeneous determinant, a
zero-area one back) by turning the minor axis, so the draw's own cull
mode, front face and depth bias apply. `LineBandState::PATCH_CONTROL_POINTS`
gives way to `BandPrimitive::patch_control_points`. A pure test checks
the fan tables against the spec's triangulation: every triangle is
degenerate or one of the nine that cover the parallelograms once, and
each winds as a line's band, turned by the facing.

Runtime: a triangle's edges (lists, strips, fans, Metal's private
triangle types) route as lines do: the device's lines where they draw
the width, else the band, on every device with tessellationShader;
strips are listed, the last provoking vertex read from the list led by
it. The band's depth bias is the device's per band triangle: announced
(new `Degradation::WideEdgeDepthBias`) under a slope factor or a
constant over a float depth. A pipeline state whose band variant the
translator refuses (barycentric weights, a selected slice or viewport,
synthesized geometry, multiview, too many outputs) now draws its lines
and edges at the nearest width, announced with the refusal as the
reason, instead of failing the draw: the state's first band compiles
the variant of its base key and remembers a refusal per primitive
(`Unrouted::Refused`). Mesh draws and tessellated patches keep the
nearest width. Docs: line_width.rs, band.rs, the runtime README,
FAST-PATHS (row and known gap), API.md (band variant, catalogue),
REFUSALS.md regenerated; api_signatures blessed (BandPrimitive added,
LineBandState::PATCH_CONTROL_POINTS removed, the three line_band fields
now carry the primitive). SEMANTICS_VERSION 1940, RUNTIME_VERSION 1716;
runtime sources re-pinned.

Verified (M3 Max, MoltenVK, --cfg m2v_gpu, maclock and memcap):
runtime_lane::line_widths 7/7 pass under both policies; 148 cases, 145
drawn as Metal's pixel for pixel, 28 of the 31 wide edge cases (facing,
culling, zero-area, strips, flat IDs and primitive IDs at both provoking
modes, depth across an edge, 4 samples), the other 3 the depth-bias edge
cases, announced (two differ from Metal, by slope and by exponent; the
uniform-depth one matches); 93 draws as bands, 0 at the nearest width.
Before this commit the same lane failed 4 of 7 (31 edge cases at the
nearest width, refused bands refused). Also: engine_line_band and the
band's fan tests, golden_hashes_match_the_table and the engine inventory
parts unchanged (no bless), runtime line_width tests (the route table
for lines and edges on every profile under both policies, refused rows),
api_surface, api_signatures, refusal_surface --check, clippy with all
features and with --cfg m2v_gpu, rustdoc with -D warnings.

(Carried to development from steelbrain/reims-graphics-kext be2d725fdb.)
2026-11-01 21:26:24 -08:00
Anees Iqbal b5e18d8fb3 Document the nearest-width line route; name its cause in the notice
Follows the previous commit, which drew at the nearest width what neither
line route draws. Its nearest width is Metal's drawn width: w', and 1/16
at w' = 0 (Metal draws 0 as 1/16, the width-0 commit this rebased onto),
clamped into lineWidthRange where the device enables wideLines, else 1.

- line_width.rs: module docs for the Nearest route and what still
  refuses (a strip's band whose segment list cannot be drawn; the band
  variant's forms the translator does not build). The
  lines-at-nearest-width notice's object names the edges or lines drawn,
  its reason the width drawn, lineWidthRange (or no wideLines) and the
  cause.
- The runtime README's line widths, FAST-PATHS.md's wide_lines row
  (counter nearest_width_line_draws) and its known gap (what is drawn at
  the nearest width, announced, instead of refused), RUNTIME-PORTING's
  SetLineWidth row.
- refusal_surface reach.tsv: gap WideLines now reaches only a strip's
  band list; feature WideLines only the translator's band forms.
  REFUSALS.md regenerated (gap::WideLines sites 5 -> 1, the runtime's
  Unsupported(WideLines) site gone).
- api_signatures blessed: Degradation::LinesAtNearestWidth,
  WorkCounts::nearest_width_line_draws.
- RUNTIME_VERSION 1715 (a refusal became a run, a new announcement);
  runtime-sources pin recomputed on this tree (pin-compute.py, which
  reproduces 9ada26c9fa's pin on that tree).

Verified: refusal_surface.py --check exit 0; cargo nextest run -p
metal2vulkan-runtime -p metal2vulkan --all-features -E
'test(/line_width|degradation|api_signatures|api_surface|refusal_surface|apple_only|error_kinds|draw_shape|call_checks/)'
27 passed; cargo clippy --workspace --all-targets --all-features -D
warnings clean.

(Carried to development from steelbrain/reims-graphics-kext 7aed54b621.)
2026-11-01 21:26:23 -08:00
Anees Iqbal 9ccc90d246 Draw at the nearest width what neither line route draws; draw nothing for no primitive
The consumer (reims-vgpu, whose guest process ends at any refusal) measured
two problems with setLineWidth: on an M3 Max over MoltenVK:

1. A draw of no complete primitive was refused. After setLineWidth 2 in fill
   mode Lines, Triangle or TriangleStrip draws of 1 or 2 vertices or indices
   returned NotImplemented(WideLines), where Metal draws nothing. drawn()
   ignored the draw's count. It now takes whether the draw may draw a
   primitive (line_width::draws_primitives: a direct draw whose vertices or
   indices complete none of its type's primitives, RewriteProgram::capacity,
   draws none; an indirect draw's count is the GPU's and keeps its route, as
   do patch and mesh draws), and such a draw is Plain. The shape memo keys
   on it beside the assembly, so a later whole draw does not reuse its
   settings.

2. Every remaining refusal refused a draw that can run. LineRoute gains
   Nearest { width, why }: the device's own lines at the width nearest
   Metal's they draw (w' clamped into lineWidthRange where the device
   enables wideLines, else 1), announced once per device (unless
   announce_each) as the new Degradation::LinesAtNearestWidth
   (lines-at-nearest-width, precision), whose reason names why and both
   widths, and counted in WorkCounts::nearest_width_line_draws. It takes a
   triangle's edges in fill mode Lines and mesh lines the device's lines do
   not draw (Unbanded), lines on a device without tessellationShader
   (Untessellated, formerly Unsupported needing it), an amplified band
   (Amplified), and every wide line in a rate-mapped pass (RateMapped) or of
   an execution's command (Executed: ShapeInputs::executes, the replay's
   lowering), whose width Metal's answer is not measured for. route() is
   infallible now; Device carries whether it differs. The replay's and the
   commit precompile's refusals go: an execution's command draws the
   nearest width and the precompile makes its pipeline; the GPU form still
   leaves such a pass to the host step, which draws and announces it.

RuntimeGap::WideLines stays for the one refusal left: a strip's band whose
list of segments the runtime cannot draw (ListGap::WideLines, as for the
provoking vertex's lists). The band variant's own refusals in the
translator (pipeline::link::band) are unchanged.

Not a speed-for-accuracy switch: the fallback for capability not built, so
no DevicePolicy switch.

Verified: cargo nextest run -p metal2vulkan-runtime -E 'test(/line_width/)'
(3 passed): each_device_routes_each_width_as_its_lines_allow now expects
the nearest width (checked against lineWidthRange) in every former refusal
cell, and rate-mapped and executed draws at the nearest width; the new
a_draw_of_no_complete_primitive_draws_nothing covers every line, triangle
and private type, direct and indexed, 1 and 3 instances, both fill modes,
on four profiles under both policies. Negative control: with drawn()
ignoring the count it fails (left: Lines, right: Nothing).

(Carried to development from steelbrain/reims-graphics-kext 5eecc33ca1.)
2026-11-01 21:26:23 -08:00
Anees Iqbal 815c8af707 Re-pin the runtime sources at the branch tip
The previous commit changed runtime-sources inputs (the runtime's pipeline
sources), so the committed digest no longer described the sources and
`the_runtime_sources_are_the_committed_ones` would fail. Recomputed over the
same inputs with pin-compute.py on the tree rebased onto 7cf79c50ed.

REFUSALS.md regenerated on the same tree: beside nothing of this branch, it
picks up the base's rename of `line_width.rs`'s `line_route` to `route`, which
the base left out of the generated document.

(Carried to development from steelbrain/reims-graphics-kext 6fd1ce74b1.)
2026-11-01 21:26:22 -08:00
Anees Iqbal b2bbc86339 Answer linked binary functions as plain Metal does
Measured on this M3 Max under macOS 27.0.1 (binary_function_linking.m, plain
and with MTL_DEBUG_LAYER=1, source libraries and metallibs alike), the runtime
now answers what plain Metal answers rather than what its validation layer
stops:

- One name in `functions` and `binary_functions`, or twice in
  `binary_functions`, one function or two: made, where the runtime refused
  `Invalid(DuplicateLinkedFunction)`. `duplicate_linked_name` keeps only a name
  `functions` repeats, which plain Metal's creation fails ("error: duplicated
  symbol", code 3). With the previous commit, a call calls the `functions` one
  and a table holds each.
- A function only `binary_functions` holds that a stage calls directly:
  `Compile(NeedsInput(LinkedFunction))`, as Metal fails with code 3, where the
  runtime linked it (previous commit).
- A function not compiled to a binary in a stage's `binary_functions`: plain
  Metal fails the creation once the stage links, code 2 ("Internal error
  during compute pipeline creation", "... tile pipeline creation", an empty
  description for render and mesh-fragment stages), after a reference it
  leaves unresolved (code 3 first). The runtime answered
  `Invalid(BinaryFunctions(NotPrecompiled))` before the compile; it now
  answers `Error::MetalError` with that problem, the M3 Max's domain and
  Metal's code and text, right after the compile (`additions::check_precompiled`).
  Added to a made state's stage: `MetalError` code 1 ("Failed to allocate a new
  pipeline"). Added to a stage the state lacks: taken, as plain Metal makes it
  (it was refused).
- A mesh pipeline's object or mesh stage linking binary functions ends plain
  Metal's process ("Binary linked functions are not supported for object and
  mesh shaders"): `Invalid(BinaryFunctions(ObjectOrMeshStage))`, a new problem,
  where the runtime made the state.

The module docs of `pipeline/additions.rs` record the measurements, the error
and README docs follow, REFUSALS.md and the API signatures are regenerated.
RUNTIME_VERSION 1713: creation answers change class.

Verified on this Mac (MoltenVK, --cfg m2v_gpu, under maclock and memcap):
runtime_lane::tests::a_kernel_runs_the_functions_its_descriptor_links and
runtime_lane::function_tables::{binary_functions_link_as_plain_metal_links_them,
binary_functions_and_required_threads_answer_as_metal_s_do,
functions_added_to_a_stage_a_drawing_state_lacks_are_left_out} pass; each
asserts an answer the previous runtime gave otherwise. The runtime unit test of
`duplicate_linked_name` passes.

(Carried to development from steelbrain/reims-graphics-kext 580daa4338.)
2026-11-01 21:26:21 -08:00
Anees Iqbal 3c1f56b63b Resolve no visible-function reference against binary functions
Metal resolves a visible-function reference against MTLLinkedFunctions'
`functions` and `privateFunctions`, never `binaryFunctions`, whose functions
only a visible-function table reaches: on this M3 Max under macOS 27.0.1
(binary_function_linking.m) a direct call to a function only binaryFunctions
holds fails the creation, plain and under validation ("unresolved visible
function reference"), from the stage's function and from a linked function
alike, while a table calls it. Two different functions of one name, one in
each list, are made: the call calls the one of `functions`, and a table holds
both, each handle calling its own definition.

The compile layer resolved references against every list, so it linked what
Metal refuses and saw two such functions as ambiguous. Now
`LinkedList::resolves_references` is `functions` and `private_functions`;
`linked_modules` reaches a table's functions by key rather than by name, and
each `LinkedName` says whether a reference resolves to it
(`resolves_references`, a new field of metal2vulkan-air's public struct), which
canonicalization's stub resolution reads. A reference only a binary function
names is `NeedsInput(LinkedFunction)`, the answer for any unresolved one.

The owned fixture `linked_other_functions` (compiled by
scripts/regen-air-fixtures) defines `linked_scale` and `table_add` with other
bodies, for the two-of-one-name shapes. SEMANTICS_VERSION 1937: the same key
now compiles otherwise (a binary-only reference refuses).

Verified: the AIR link tests, `engine_linking::a_reference_resolves_to_no_
binary_function` (interpreter: the call calls the `functions` one from either
module; a binary-only call and a binary-only nested call refuse) and
`engine_tables::a_table_holds_a_binary_function_of_another_s_name`
(interpreter: alternating own and other `table_add` through one table) pass;
with the stub filter removed, the link test and the engine_linking test fail.
API signatures blessed (one new field).

(Carried to development from steelbrain/reims-graphics-kext 64bd644d0b.)
2026-11-01 21:26:21 -08:00
Anees Iqbal eb41a55e82 Draw every width Apple's setLineWidth: takes, as Metal draws it
RenderCommandEncoder::set_line_width refused every width but 1
(AppleOnly::LineWidth). Measured on the Apple M3 Max under macOS 27.0.1
(probes/line_widths.m): each encoder starts at 1 and the width holds
across draws and pipeline states; Metal draws w' = floor(16 w) / 16
clamped to [0, 16] (NaN and negatives as 0, infinity as 16); at w' = 1
its ordinary diamond-exit lines; at every other w' Vulkan's non-strict
parallelogram (major axis the larger extent, x on a tie; minor-axis
edges through the endpoints, w' long and centred; ends not extended;
centres inside, top-left ties; the width not rounded); at 0 exactly the
pixel centres on the segment; one parallelogram per strip segment with
no joins; triangles in fill mode Lines draw their edges so; at 4
samples every width is the parallelogram at the sample positions.

The runtime (render/line_width.rs) keeps the quantized width in the
encoder state and routes each draw at w' != 1:
- the device's own lines (lineWidth w', no Bresenham mode) where it
  enables wideLines and w' lies in lineWidthRange above 0: exact where
  strictLines is unset, nonStrictWideLinesUseParallelogram set, w' > 1
  and on lineWidthGranularity; elsewhere announced device-wide-lines
  under the default DevicePolicy::wide_lines = WideLinePolicy::Device,
  and the band under WideLinePolicy::Exact (exact_answers() selects it);
- the pipeline's band variant otherwise (no wideLines, MoltenVK among
  them; w' outside the range; w' = 0 at half a width of
  2^-subPixelPrecisionBits): cull none, the band's front face, fill
  mode, a PATCH_LIST of two points, viewport 0's half extent pushed
  with the half width; strips and loops listed as their segments
  (ListGap::WideLines), flat inputs under the last provoking vertex
  read from the list led by the last vertex, which covers the same
  pixels.
Refused: Unsupported(WideLines) needing tessellationShader where neither
route draws a line; NotImplemented(RuntimeGap::WideLines) for a
triangle's edges or a mesh draw's lines the device's lines do not draw,
an amplified band, a rate-mapped pass and an execution's commands.
Counted: WorkCounts::device_wide_line_draws, line_band_draws.

The lane test runtime_lane::line_widths draws the probe's cases through
owned fixtures and compares every pixel with Metal's answers
(line_widths_m3_max.txt, the probe's output), checks each wide draw took
a route, and that every fragment is front-facing; its site WIDE_LINES
holds the new kind in the lane's degrade-notice closure.

Docs: FAST-PATHS.md's row for wide_lines and a known-gap bullet (edges
and mesh lines on devices without wideLines, near-plane cuts, band
fragments' inputs uncompared, width 1 on multisampled targets off
MoltenVK); API.md's policy bullet and degrade catalogue; the runtime
README's Line widths; RUNTIME-PORTING's row; REFUSALS.md regenerated
(reach rows for feature and gap WideLines, apple LineWidth gone).
Validation: the line limits the device description gained describe
execution and are not compared in a profile's subset check; the
generator's CORE_PROPERTIES and roadmap-2022's m2v_layer_presentation
state them at the reader's absent values; opened_chains reblessed (one
member more, wide_lines, on every device with it); golden_hashes'
profile fingerprints reblessed (no output cell moved); api_signatures
and api_surface name WideLinePolicy and LineBandState.

RUNTIME_VERSION 1712; the runtime-sources pin rewritten.

Verified on the M3 Max under MoltenVK 1.4.2 through maclock with the
validation layer: runtime_lane::line_widths, 4 tests pass. Default and
exact policies each: 102 cases, 100 matched pixel for pixel, 2 refused
(the two fill-mode Lines cases at width 4, NotImplemented(WideLines)),
0 announced; 46 draws took the band, 0 the device's lines (MoltenVK has
no wideLines). a_band_needs_tessellation (tessellationShader withheld:
width 0 refused needing it, width 2 refused, width 1 matches) and
the_lane_s_maps_tell_the_widths_apart pass. Negative control: the band
widened by 1/16 of a pixel fails both runs at LANE lines 0.5. Also
cargo clippy --workspace --all-targets --all-features -D warnings, plain
and with --cfg m2v_gpu; nextest of metal2vulkan, -air, -runtime and
-devtools (4954 run, the one failure the missing lane site, now
declared), of metal2vulkan-validation (the failures the profile rules,
chains and pin fixed here, rerun green) and of metal2vulkan-conformance
(1007 pass). Not run: lavapipe, RADV, ANV and NVIDIA lanes, which take
the device route.

(Carried to development from steelbrain/reims-graphics-kext b16d03150c.)
2026-11-01 21:26:20 -08:00
Anees Iqbal 14dc4c5f2e Draw a line wider than the device's lines as a band of two triangles
Metal draws a line under Apple's setLineWidth: at a width other than 1 as
the parallelogram Vulkan's non-strict wide lines may be (major axis the
larger framebuffer extent, minor-axis edges through the endpoints, centred,
w long). Devices without wideLines (MoltenVK among them) or whose wide
lines are strict or not parallelograms cannot draw it with their own lines.

A render pipeline's band variant (VariantKey::line_band) adds two
synthesized stages after the vertex stage (pipeline::link::band): a
tessellation control stage that copies each of a line's two vertices and
writes every level 1 in the quad domain, and an evaluation stage that
places each corner at its endpoint moved across the segment by half the
width in framebuffer pixels along the minor axis, taken to clip space
through Vulkan viewport 0's half extent, which the draw pushes
(PushField::LineBand, BindState::line_band, its own 16-byte aligned push
range). Ends behind w = 2^-20 are clipped first; smooth varyings and clip
distances follow their endpoint, flat and integer ones take the first
control point's. GraphicsState::line_band (LineBandState) states the
consumer's contract: PATCH_LIST of two control points, no culling, its
front face, the push offset.

The device description gains what chooses the route: VkFeature::WideLines,
and the limits lineWidthRange, lineWidthGranularity, strictLines,
nonStrictWideLinesUseParallelogram (VK_KHR_maintenance5) and
subPixelPrecisionBits, read from Khronos profile JSON and from ash. The
verifier and requirement rules take the per-vertex arrays of tessellation
control inputs and outputs and evaluation inputs, and TessLevelOuter and
TessLevelInner as arrays. ARTIFACT_FORMAT_VERSION 480 for the new encoded
fields (VariantKey, GraphicsState, LineBandState, PushField, VkFeature).

Verified: cargo build --workspace --all-features --all-targets; nextest
tests::engine_line_band (the band variant on every committed profile with
tessellationShader validates in spirv-val and requirements, draws
PATCH_LIST with its own push range; flat varyings take the first control
point; without tessellationShader it is refused needing it; barycentric
reads are not implemented) and the tessellation push_offset tests pass.

(Carried to development from steelbrain/reims-graphics-kext 19814d7bb3.)
2026-11-01 21:26:20 -08:00
Anees Iqbal 59209afdf7 Link stitched functions: read a linked module's signature as the entry's
A pipeline linking a function Metal's stitcher made was refused,
`Unsupported { feature: Linking, needs: NotImplemented }` at the call
(stitch_caller, block 0, instruction 5, symbol "fused"), because
link::plan refused every linked module that carries an !air.signature.
Each module of a stitched library carries one, of kind
air.stitching_modules_signature: it records the graph the function was
made from and the stitchable modules' digests, while the module's own
code (the graph's nodes inlined into the stitched function) is what
runs. The entry side already read a signature that way and refused only
a linked-constants module that still declares function constants, which
has no reading.

The rule is now one function, canon::unread_signature, which both the
entry's specialization and the linked module's plan use: a stitched
module and a linked-constants module that declares no constant link like
any other module; a linked-constants module that still declares one is
refused at the surviving call as before. The dynamic-library export
check, which blocks any signature, is unchanged: a stitched library is
an executable library and cannot be a dynamic one.

Verified: link_tests::a_linked_module_s_signature_is_read_as_the_entry_s
(replacing the test that held the old refusal) passes, and fails with
the old gate restored. Against the stitched library the probe dumped on
the M3 (not committed), the old gate reproduces the consumer's refusal
exactly, and with this change both stitched functions link, privately
or not, and compute 20 and 25 on the SPIR-V interpreter.

(Carried to development from steelbrain/reims-graphics-kext 3ebc1a708a.)
2026-11-01 21:26:19 -08:00
Anees Iqbal e54a2c12aa Refuse a pipeline of an unspecialized function that declares constants
Since functions whose constants are left undefined compile (a2e34a9d2f),
the runtime made a pipeline state of a function made by
newFunctionWithName: whose function declares function constants. Plain
Metal ends its process there, at every creator's descriptor validation
(probes/undefined_function_constant_values.m, new cases <how>:<shape>,
on the M3 Max under macOS 27.0.1, MTL_DEBUG_LAYER unset, exit 134):
"Compute Pipeline Descriptor Validation / function ko cannot be used to
build a pipeline state. Use newFunctionWithName:constantValues:... to get
the specialized function"; the render and mesh creators name
vertexFunction, fragmentFunction, objectFunction and meshFunction, and
the tile creator says "without setting constant values first". It does
so for an optional constant read only where is_function_constant_defined
says (ko) and for a constant that only gates arguments (kg). Made: a
function made by name that declares none (kn, plain, tile-plain,
mesh-plain), and every shape made with constant values that hold none or
by newFunctionWithDescriptor: without them (each then answers an empty
functionConstantsDictionary; ko stored 7, kn 9).

- metal2vulkan: FunctionDescriptor gains `specialized` (false by default,
  a function made by name; a descriptor with constant values is
  specialized whatever it says) and with_specialized, and
  needs_specialization(budget, entries) answers whether Metal makes no
  state of the stage: not specialized and a non-empty
  functionConstantsDictionary. A module function's constants are read
  through the StageEntries' module decodes (constants_dictionary_with),
  which the stage's compile copies, so the check decodes nothing the
  compile does not. The compile itself is unchanged.
- metal2vulkan-runtime: Function::function_descriptor marks the stage
  specialized where the function was made with constant values or by
  descriptor. pipeline/unspecialized.rs refuses before anything is
  compiled, Invalid with the new Problem::UnspecializedFunction { stage,
  name }: compute and tile states (of_kernel), render states (vertex,
  fragment) and mesh states (object, mesh, fragment). A linked function
  keeps its own rule (LinkProblem::UnresolvedConstant).
- Pipeline records carry the stage's specialized flag, RECORD_FORMAT 3:
  without it every specialized stage's record read back unspecialized
  and went unrecorded.
- The owned fixture engine/unspecialized_stage_functions (the probe's
  shapes at every stage); its golden rows, inventory and printout are
  new rows only (11 functions by 2 forms in each table).
- docs/API.md ("Function constants"), the FunctionConstantValues and
  creators' docs, the runtime README, docs/REFUSALS.md regenerated, the
  signatures blessed (FunctionDescriptor.specialized, with_specialized,
  needs_specialization, Problem::UnspecializedFunction).

Verified:
- metal2vulkan tests::engine_unspecialized 2/2 (every declaring function
  of the fixture needs specialization made by name, no free one does,
  and the eleven answers read one module decode, (1, 10); specialized or
  valued, none does, decoding nothing).
- On MoltenVK (M3 Max) through maclock, --cfg m2v_gpu:
  runtime_lane::unspecialized_functions 3/3 (by name: guarded and gate
  kernels, vertex, fragment, tile, mesh and object refused; free kernel
  stores 9; plain render state made; empty-valued and descriptor-made
  guarded kernels store 7, gate kernels made, render states made; tile
  and mesh states of them not refused as unspecialized) and
  runtime_lane::linked_functions 2/2.
- metal2vulkan-runtime suite 1177/1177; tests::warm_record 4/4.
- metal2vulkan and metal2vulkan-air: 3748 of 3753 before blessing, the 5
  failures the new fixture's table rows; after blessing they and the
  signature and surface tests pass.
- Negative controls: needs_specialization answering false fails
  engine_unspecialized's by-name test; function_descriptor without the
  specialized flag fails all three lane tests (the empty-valued and
  descriptor-made functions refused); the stage flag removed from the
  record's writes and reads fails the four warm_record tests.

(Carried to development from steelbrain/reims-graphics-kext 116efd0dfe.)
2026-11-01 21:26:18 -08:00
Anees Iqbal 6a41f826c8 Document linked-function names and constants; lane test on the device
docs/API.md section 3 states the rule: a reference resolves by
LinkedFunction::name (the specialized name, else the function's own), a
linked module with constants is specialized with the function's values, a
specialized function reads an unvalued constant as undefined, and an
unspecialized one (newFunctionWithName:) that reaches a constant is refused
with LinkProblem::UnresolvedConstant. Section 10 adds the zero read of a
linked function's unvalued constant to the accepted differences. The runtime
README says how a stage links visible functions and by which name.

The probe's header records its 19 cases as measured on the M3 Max under macOS
27.0.1 (26A434), MTL_DEBUG_LAYER unset, one case a process through maclock:
the four of the brief (specialized 16, plain and other unresolved custom_fn,
both 16) and the constant shapes (newFunctionWithName: reaching the constant,
guarded or not, fails "cannot lower module with unresolved function
constants"; plain_fn links; every specialized form links, unvalued reads
storing nothing).

runtime_lane::linked_functions runs both through the runtime: names answered,
16 at word 0 with every word 3x + 1, plain and another_fn needing custom_fn,
both 16; derived 6x, guarded 3x and x - 1, plain_fn x + 2, base_fn unvalued 1;
by name: base_fn and guarded_fn refused UnresolvedConstant, plain_fn 7,
constantValues 3 16, empty values and a descriptor without values link.
tests::pipeline gains the duplicate-name check by link name: one function
under its own and a specialized name is no repeat, two under one specialized
name are.

Verified: on this M3 Max, MoltenVK, through maclock and memcap (6 GiB),
RUSTFLAGS='--cfg m2v_gpu' cargo nextest run -p metal2vulkan-validation
--all-features -E 'test(/runtime_lane::linked_functions::/)': 2/2 passed.
cargo nextest run -p metal2vulkan-runtime --all-features -E
'test(/tests::pipeline::/)': 5/5 passed.

(Carried to development from steelbrain/reims-graphics-kext 228cf1424c.)
2026-11-01 21:26:17 -08:00
Anees Iqbal b4a3540c9d Keep a Core Image kernel library's HASH as read instead of verifying it
Core Image's own kernel libraries (ci_stdlib, ci_filters, ci_raw: file
type 1, extern functions over one module) were refused as
Container(HashMismatch), so Library::from_metallib, the runtime's
new_library_with_data and the command line ("FALLBACK (input not read)")
refused what Metal reads, in every process that uses Core Image. The
function table, metadata, extended header (HDYN, UUID) and shared module
were all in the shape the reader already takes; only the HASH check
failed.

What the HASH is, measured with libraries written from scratch under
Xcode 27.2's toolchain (metal -fcikernel, metallib -cikernel) on an M3
Max under macOS 27.0.1:
- metallib -cikernel writes one HASH for every function. For some modules
  it is the SHA-256 of the module it writes (the two-kernel library the
  file-type-1 support was first measured with, kernels with short
  loops); for others it is not, e.g. one kernel with a three-iteration
  loop of sin and cos. Not the digest of the input .air, of the stream
  without the wrapper, of the module without its zero padding or with
  other padding, or of the module round-tripped through metal-opt.
  metallib is deterministic, and feeding the written module back through
  it gives the same module and the same HASH. What it is a digest of is
  not known, so it is not interpreted.
- Metal checks no HASH: the new probe
  (crates/metal2vulkan-conformance/probes/metallib_function_hashes.m)
  loads an executable library and a Core Image kernel library with one
  bit of every HASH flipped exactly as written (the kernel's pipeline
  stores 1,4,7,10 both ways), and the Core Image library whose HASH is
  not its module's digest as well.

So a Core Image kernel library's HASH is read as 32 bytes, once, present
(as before), kept as read in LibraryFunction::raw_tags, and each
function's content key (LibraryFunction::hash, FunctionInfo::air_hash)
is its module's SHA-256, computed once for the shared range. Every other
library's HASH stays verified (HashMismatch), which is stricter than
Metal; docs/API.md says so.

The same probe found that Metal's externFunctionNames order is not the
reverse of the table's in general: a two-kernel library (tint, shift)
answers it, but a four-kernel library written from scratch, libraries of
10 to 200 kernels and Core Image's own answer the same names in an order
that is neither the table's, its reverse, nor sorted. The runtime keeps
the reverse; Library::extern_function_names' doc now says the order
differs from Metal's (doc only).

No cache version moves: a type-1 library whose HASH matched keeps the
same content key, and one whose HASH did not was refused before. No
translation output changes. The runtime-sources pin moves for the doc
comment in the runtime's library.rs (no behaviour): re-pinned to
d000eb23746160492052af4ff3e62bb81ab598b44fc8684b3cf36105d2c67026.

Verified (M3 Max, macOS 27.0.1):
- New test container::tests::a_core_image_library_hash_is_kept_as_read:
  a synthetic type-1 library of three extern functions over one module
  whose HASH is not the module's SHA-256 parses, each function's hash is
  the module's digest and its HASH is kept raw; one whose HASH is the
  digest reads the same; a missing, duplicate or 31-byte HASH is still
  MissingTag, DuplicateTag, BadTag; the same table as a dynamic library
  is HashMismatch. Negative control: with the exception disabled
  (every library verified) the test fails (HashMismatch at parse), the
  other 18 container tests pass.
- cargo nextest -p metal2vulkan-air --all-features: 482 passed.
- Locally only, nothing of it committed: Core Image's ci_stdlib,
  ci_filters, ci_raw (and ci_stdlib_h) now read through the command line
  and through the runtime on MoltenVK: each lists only extern functions
  (as many as its table holds), function_names empty, every name made by
  new_extern_function_with_name and new_function_with_name with
  FunctionType::Extern, a sample of six per library refused as a compute
  pipeline (Compile, EntryNotFound), as Metal answers; Metal's own answers
  for the same files through the probe agree (type executable, no
  function names, the same count of extern names, functionType 4 for
  each).
- metal2vulkan core_image_libraries and api_signatures (3), the
  validation runtime-sources guard after the re-pin: pass. clippy
  --workspace --all-targets --all-features -D warnings, plain and under
  --cfg m2v_gpu (own target): clean. rustdoc -D warnings for the three
  published crates: clean.
- Not run: the other suites, the device tests, golden tables (no
  translation output changes), a corpus census. Core Image's link of
  these extern functions into ciKernelMain was not reached locally:
  rendering ten built-in filters did not go through Metal's image-filter
  link calls on this Mac.

(Carried to development from steelbrain/reims-graphics-kext 2d3259adbf.)
2026-11-01 21:26:16 -08:00
Anees Iqbal 9c80a4957b Compile functions whose function constants are left undefined
A function constant the request leaves unset no longer refuses the pipeline
with NeedsInput(FunctionConstant). Metal makes that pipeline, optional or
required: is_function_constant_defined is false, arguments gated on the
constant (negated or not) are absent, and its reads vary from read to read
(probes/undefined_function_constant_values.m on the M3 Max, macOS 27.0.1:
u + 3 read 0, u * 7 + 1 read 1, u == 0 ? 111 : 222 read 222, b ? 5 : 6 read
5). WindowServer's QuartzCore pipelines leave optional constants unset
(fixed_vert_lpf_gen without constant 53), so the desktop could not draw.

SCCP's lattice is now flat, the undefined value one more value beside the
constants:
- a value computed from an undefined constant alone stays undefined, and a
  pure instruction computing one becomes its type's zero (an address keeps
  naming the constant's global);
- a branch on one takes its false way (a rewrite only where no other way
  was opened), and a select its false arm;
- an and with zero, an or with all ones and a mul by zero are that
  constant whatever the undefined operand holds, in SCCP and in the static
  initializer, so QuartzCore's generic || (...) is true with generic set;
- an operation that also reads a run's value, and a PHI (an undefined
  entry merges as overdefined), keep what the run computes, so a defined
  way keeps its value and a loop counting from the constant still counts.
The entry-block refusal and its inliner gate are gone. Entry gains
undefined_reads, the undefined constants the specialized body reads,
which validation's case checker uses where it used the refusal to prove
an omitted constant unread.

Removed: MissingInput::FunctionConstant (metal2vulkan-air),
RuntimeInput::FunctionConstant (metal2vulkan), the command line's
--constant hint. docs/API.md lists the reads under accepted differences.
SEMANTICS_VERSION 1932. The golden tables and the engine inventory move
only the 532 cells (28 rows by 19 profiles) that were the refusal; each is
now ok.

Verified: metal2vulkan-air 481/481, with negative controls (absorbing rule
off: the two new and/or tests fail; the PHI mapping off: the loop test
fails); the core suites; clippy (all features, --cfg m2v_gpu); the
command line on the M3's QuartzCore library: fixed_vert_lpf_gen with
reims's values (0 and 1 true, 3 = 0) and the whole pipeline with
fixed_frag_lpf_cpf translate and pass spirv-val on moltenvk-m3,
nvidia-rtx5080-laptop and intel-uhd770-rpls-anv, with generic true
keeping the texture-matrix path (521 lines of SPIR-V against 290); every
fixed_* pair and backdrop_capture_compute_tile_* with no constants
translates but the _spc vertex functions, which ask for a vertex
descriptor.
2026-10-31 05:34:42 +02:00
Anees Iqbal bf3ce3813c Read Core Image kernel libraries and split whole aggregate accesses
A Core Image kernel library (metal -fcikernel, metallib -cikernel) is a
metallib of file type 1 whose kernels (!air.ci) are listed as function
TYPE 5 over one shared module. The container refused the file type
(Unsupported LibraryKind(1)), so newLibraryWithData: failed where Metal
succeeds; the consumer's graphics-kext lane hit it on Core Image's own
helper library in a macOS 26 guest, so every Core Image path stopped
there.

What Metal answers, measured with kernels written from scratch on an M3
Max under macOS 27.0.1 (probe programs over Metal's API and objc's message
log of a CIColorKernel render):
- newLibraryWithData: takes it as MTLLibraryTypeExecutable; functionNames
  is empty; the private externFunctionNames lists the kernels in the
  reverse of the table's order (libraries of two and four kernels);
- newFunctionWithName:, newFunctionWithDescriptor: and the private
  newExternFunctionWithName: make each kernel with functionType 4 (no SDK
  enumerator; its description prints "Unknown"); newExternFunctionWithName:
  answers as newFunctionWithName: for any library, a kernel of an
  executable one included, and nil for a missing name;
- a compute pipeline made from an extern function fails ("Function tint
  was not found in the module");
- Core Image fetches each kernel and its own helpers with
  newExternFunctionWithName: and links them on the CPU, in Metal.framework's
  base device class, into an ordinary executable library holding one
  kernel, ciKernelMain, of which it builds a plain compute pipeline.

So now:
- container: file type 1 is read (executable; its functions may share one
  bitcode range, hashed once, as a dynamic library's); TYPE 5 is the new
  FunctionStage::Extern, no stage: the ABI cross-check refuses it as a
  mismatch, Library::Function compiles it as no entry (EntryNotFound,
  available 0). Unobserved file types stay LibraryKind refusals.
- FunctionType gains the private enumerator Extern = 4
  (regen-metal-enums PRIVATE); reflection maps Extern to it.
- runtime Library: function_names leaves extern functions out;
  extern_function_names (reverse table order) and
  new_extern_function_with_name are new.

ciKernelMain itself was refused next: Lowering(Arith) at its first
load, `load [4 x <4 x float>], ptr addrspace(2)`, a whole array loaded
from the constant buffer and passed by value to a helper. Lowering reads
and writes buffer and threadgroup memory a scalar or vector at a time.
The new canon pass `aggregates` (after SCCP, beside the other expansions)
replaces each non-volatile, non-atomic load or store of a pointer-free
array or struct in device, constant or threadgroup memory by its members'
accesses in layout order (a getelementptr i8 at the member's distance, the
access's alignment lowered to what the distance allows, joined by
insertvalue or split by extractvalue), at most 256 members, 8 deep.
Thread memory, pointer-holding aggregates (handles), volatile accesses
and larger types stay whole as before. The same-type pointer bitcast
beside the load was never the problem (verified alone).

Public surface: metal2vulkan-air FunctionStage::Extern; metal2vulkan
FunctionStage::Extern and FunctionType::Extern; runtime
Library::extern_function_names and new_extern_function_with_name
(api_signatures blessed: 5 added, none changed or removed). devtools
gains core_image_metallib. The metal-enum generation now records the
macOS 27.2 SDK (the host's Xcode); no SDK value changed, only Extern was
added. LibraryKind's doc and reach note name what it refuses now.

No cache version moves: file type 1 and aggregate accesses outside thread
memory were refused before, so no key reached them, and
golden_hashes_match_the_table passes unchanged (every public fixture
assembled: this Mac's Xcode 27.2 now has its Metal toolchain). The
runtime-sources pin moves (runtime library.rs): re-pinned here to
23766690fd75227c5333e976bfc1fdfafa6ff78f43e0c5ba8fa5183574cd9371.

Verified (M3 Max, macOS 27.0.1):
- Metal versus this tree's runtime on MoltenVK: Core Image's linked
  ciKernelMain for a tint color kernel and for a sampler kernel (both
  from-scratch CI kernels; the linked libraries captured from Metal in
  scratch and deleted after), same constant buffer, source texture and
  sampler, 4x4 RGBA32Float target: byte-identical texels, the early-out
  column untouched on both. The parent tree answers FALLBACK (Lowering
  Arith) for both. Release CLI: 0.01-0.03 s, 11 MiB each.
- Release CLI, parent vs this tree, largest public fixtures
  (hfb_filter_bank render pair, tns_mm_flags), three runs each:
  0.12-0.13 s vs 0.12-0.16 s and 0.05-0.06 s vs 0.04-0.05 s, 27 MiB both
  (runs beside a test suite; the same within noise).
- New tests: canon aggregates (split loads, stores with nested arrays and
  lowered alignments, threadgroup; volatile, pointer-holding and
  300-element aggregates stay whole), an engine test running a
  ciKernelMain-shaped kernel on the CPU interpreter on three profiles,
  core_image_libraries (container types, stages, shared hash, functionType
  4, EntryNotFound), and a runtime device test on MoltenVK (names, extern
  names, both lookups, pipeline refusal, an executable library's kernel
  through the extern lookup). Negative controls: the split and execution
  tests fail with the pass disabled; the library tests fail with file
  type 1 refused.
- cargo nextest -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime
  -p metal2vulkan-devtools --all-features: 4927 passed (golden hashes and
  the metal-as fixture parts included); -p metal2vulkan-validation
  -p metal2vulkan-conformance: 2369, all passed after the re-pin; doctests
  ok; clippy --workspace --all-targets --all-features -D warnings and the
  runtime's under --cfg m2v_gpu: clean; rustdoc -D warnings and
  scripts/api-docs: clean; REFUSALS, METAL-COVERAGE and
  CONFORMANCE-COVERAGE re-derived (MTLFunctionTypeExtern is listed as not
  yet compared by a conformance case). Not run: a corpus translation
  census, and the device suites beyond the new runtime test.
2026-10-31 03:39:16 +02:00