Commit Graph
25 Commits
Author SHA1 Message Date
Anees Iqbal 9d629a3e9f Reflect the image the module binds, not the one the type name implies
`ShaderReflection::texture_shape` is what a consumer feeds into
`VkImageViewCreateInfo`, and Vulkan requires the created view's type to match the
`Dim` and `Arrayed` of the image variable the descriptor is read through. The
shape was decoded from the AIR type name, and the emitter does not always bind the
image that name implies: SPIR-V has no cube texel fetch, so `resources::discovery`
binds a `texturecube` that is only ever texel-read as a `Dim2D` ARRAY image with
the face in the layer slot. Reflection kept saying `Cube`, so a consumer following
it created a `VK_IMAGE_VIEW_TYPE_CUBE` view for a 2D-array image variable and the
dispatch was invalid.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:34:36 +03:00
Anees Iqbal 42a7998514 Name each reflected resource once
`ShaderReflection::bindings` is a work list: a consumer walks it and acts once per
entry, allocating a descriptor, writing it, and sizing per-resource budgets from
the length. `from_fragment` called `append_embedded_resources` twice with the same
arguments, so every fragment entry with an `air.indirect_buffer` argument listed
each of its argument-buffer residents twice and asked for that work twice.

Nothing in the emitted module records the repeat -- the decorations it duplicates
are already there once -- so `reflection_covers_declared_bindings.rs`, which asks
whether reflection covers what the module declares, cannot see it. Measured over
2880 corpus sources: 405 fully-identical duplicate entries across 19 modules, all
fragment `EmbeddedArgBufferTexture` and `EmbeddedArgBufferBuffer`. After: 0.

To keep the class from returning silently, `validate_descriptor_abi` -- which both
`reflect_sanitized` and the reflected translation path run -- now rejects two
entries that agree in every field. Equality is the right test rather than the
`(set, binding)` pair, which raw-word alias buffers legitimately share and which
this check deliberately still allows; genuinely distinct resources always differ
somewhere, in the Metal index, the entry-parameter index, or an argument-buffer
resident's field offset.

New `tests/reflection_describes_each_resource_once.rs` with an authored fragment
fixture: one `air.indirect_buffer` holding a writable texture and a nested device
buffer. Verified as a detector -- with the second append restored the fixture test
and the gate test both fail. It also sweeps every public fixture and pins the gate
itself, so deleting the check cannot make the other two pass by not looking.

`REFLECTION_VERSION` 31 -> 32: a cached v31 reflection for such a fragment carries
entries a consumer would act on twice. `docs/REFLECTION.md` follows.

Verified: 2880 corpus sources, SPIR-V bytes identical and the failure count
unchanged at 204; 19 modules differ in reflection only, the same 19 the duplicate
scan named.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:09:09 +03:00
Anees Iqbal ca14b5b544 Report an imageblock plane wherever the module asks for one
The interface pass materializes a descriptor-backed render-target plane wherever
it lowers an `air.load/store.implicit_imageblock.*` call, and the detector that
finds those calls scans the module body -- it never looks at the stage. Reflection
did look at the stage: `KernMeta` carried the detected attachments and `from_kernel`
reported them, while `from_fragment` and `from_vertex` hardcoded an empty list.

A fragment entry that reads its render target back through the implicit imageblock
therefore emitted `OpDecorate %n Binding 200` and reflected nothing, so a consumer
building its `VkDescriptorSetLayout` from `ShaderReflection` produced a layout that
did not cover the shader. Verified on the authored fixture: before this change the
module declared Binding 200 with `implicit_imageblock_attachments: []`; now it
reports the plane at that binding.

`FragMeta` and `VertMeta` now carry the field, filled by the same stage-agnostic
detector, and one `implicit_imageblock_planes` helper does the meta-to-reflection
mapping for all three constructors instead of the one copy `from_kernel` had.

Scope of the evidence: all five corpus users of those intrinsics are kernels, so
this is not a claim about how common fragment imageblock read-back is in real AIR.
It is the module and its description disagreeing, which is a defect whether or not
a shipped shader has hit it.

`REFLECTION_VERSION` 30 -> 31, since a cached reflection from v30 is missing a
binding its module declares. `docs/REFLECTION.md` said 29 and now says 31.

Verified: 2880 corpus sources byte-identical (this changes reflection, not
emission).

The sweep in `tests/reflection_covers_declared_bindings.rs` stays at each fixture's
declared stage. Translating a module at a stage its AIR does not declare leaves the
stage parse with no source at all, so the reflection is a stub regardless of what
the module contains; that is a different question from this one.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 22:46:04 +03:00
Anees Iqbal c470af1290 Describe the nesting reconstruction step in the architecture guide
The CFG structurization section still described reconstruction as the bounded
relooper alone. Record that nesting runs first for reducible functions, what a
staged edge is, and why the pass checks its own value flow before adopting a
nesting.
2026-08-31 12:17:22 +03:00
Anees Iqbal 7154e84d2c Lower the per-translation wall-clock ceiling from 30s to 20s
The hard end-to-end ceiling per translation attempt is now 20 seconds,
in the corpus-triage worker guard that enforces it and in the AGENTS.md
and docs/VALIDATION.md statements of the contract. The 500-MiB memory
budget is unchanged.

Verified: corpus-triage unit tests (15) pass; fmt clean.
2026-08-31 10:26:25 +03:00
Anees Iqbal 52c961b4de Tighten owned numeric conversion contracts
Split ConversionClass so each width-changing conversion carries its own
shape contract instead of sharing IntegerToInteger and FloatToFloat
buckets. OpUConvert, OpSConvert, and OpFConvert now require the source and
result component widths to differ: a same-width conversion is not a no-op,
it is an invalid instruction. OpUConvert additionally requires an unsigned
result type, since it names a zero extension or truncation.

Reject OpSatConvertSToU and OpSatConvertUToS as a shape class before they
reach a numeric contract that does not describe them; the saturating OpenCL
conversions require the Kernel capability and have no Vulkan environment.

Switch the conversion checks from scalar_type_shape to numeric_type_shape
so component width is available alongside opcode and lane count.

Cover each rejected and accepted shape with a test that pairs the owned
verdict against the independent spirv-val verdict, so the construction-time
rule stays a restatement of the Vulkan rule rather than a local invention.

Verified: cargo clippy --all-targets (clean). Per request, the cargo doc
check and workspace test run were skipped.

Claude-Session: https://claude.ai/code/session_015sJUGShcKseDFnk4WvaJU2
2026-08-31 09:50:44 +03:00
Anees Iqbal 08970cacd2 Consolidate translation, linkage, and validation work
Squash 147 commits (2026-08-20 through 2026-08-31) into one change on top
of the exact-kernel-grid work. Covers native lowering and pointer/layout
construction, AIR intrinsic and funnel-shift coverage, BDA address
preservation across aggregate calls, CFG structurization, function-constant
and visible-function specialization, the 30-second translation ceiling, the
authored-case corpus and linkage validation suite, and refreshed byte-exact
MoltenVK evidence.

The kernel-grid lowering in this tree supersedes the 324-line variant in
the parent commit; that file is reduced to its current 139-line form here.

Resulting tree is identical to 7174c7b. Prior history remains reachable at
tag pre-squash-backup and branch backup/pre-squash-7174c7b.

Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS
2026-08-31 09:03:42 +03:00
Anees Iqbal 9ff250502c Make exact kernel grids safe by default
Model kernel dispatch geometry as a typed contract shared by lowering, reflection, validation, and the CLI. Cull surplus dispatchThreads invocations using fixed or reflected push-constant grid bounds, make that safe dynamic-grid path the default, and require an explicit whole-workgroup assertion to omit it.

Reject unsafe source-barrier kernels before every product emission facade by following the selected AIR entry graph, including quoted LLVM symbols. Exercise the same default contract in authored candidate validation and document the host ABI.

Keep corpus audit parent concurrency bounded by feeding isolated translation workers from scratch-backed stdin files instead of creating one feeder thread per row. This removes the scoped-thread exhaustion that aborted late full censuses while retaining child decoding inside the time and memory watchdog.

Verified with format checking, warnings-denied workspace clippy and Rustdoc, validation tests at concurrency 16, the unchanged downstream repro, a forced 88,819-row audit completing in one invocation at jobs 16, failure retries, and a zero-read warm pass.
2026-08-22 02:16:13 +03:00
Anees Iqbal 8e95e84d0c Close specialization and descriptor audit gaps
Distinguish image descriptors from texel buffers, scope synthesized binding occupancy by descriptor set, and decouple the Metal texture source limit from configurable descriptor ranges. Centralize retry finalization and runtime sampler projection so layout and specialization contracts cannot drift across paths. Refresh consumer documentation and add adversarial descriptor tests.
2026-08-20 08:31:42 +03:00
Anees Iqbal 12abadb798 Add caller-selected descriptor layouts
Thread a versioned, validated descriptor layout through emission, reflection, synthesized resources, retry-created address tables, and Vulkan validation. Preserve the existing ABI as the explicit default and cover cross-stage separation, static samplers, embedded textures, raw aliases, invalid ranges, and default byte identity.
2026-08-20 07:52:35 +03:00
Anees Iqbal c37cd41b29 Align storage image reflection refusals
Enforce runtime storage-image component compatibility at the metadata-only reflection boundary as well as executable translation. Update every matching reflected storage binding, cover the authored embedded-texture checker path, and advance reflection and executor fingerprints to prevent stale reuse.\n\nVerified with cargo fmt, warnings-denied workspace clippy and Rustdoc, 1364 serial product tests, and 144 serial validation tests.
2026-08-20 07:05:05 +03:00
Anees Iqbal f3e376361b Specialize embedded runtime storage images
Route writable argument-buffer textures, including fixed descriptor arrays, through the runtime storage-image format and capability contract. Reflect their applied state by synthetic resource index and teach authored validation to resolve structural owner/offset identities through reflection before candidate translation. Bump reflection and executor fingerprints so stale outputs are not reused.\n\nVerified with cargo fmt, warnings-denied workspace clippy and Rustdoc, 1364 serial product tests, and 144 serial validation tests.
2026-08-20 07:00:10 +03:00
Anees Iqbal 547a59d99b Specialize runtime storage image formats
Accept runtime storage surface formats and host feature facts by Metal texture index, specialize image types before interface creation, and reflect the exact explicit or formatless contract. Track runtime origins through arrays and image aliases so every read, write, imageblock write, emulated fetch, and atomic operation checks the required capability or refuses honestly.\n\nWire authored validation resources into the same product options, bump the reflection and candidate executor contracts, document consumer use, and cover type splitting, dependent loads, exact formatless capabilities, atomics, incompatibility, missing bindings, imageblock writes, and pixel-gather storage reads.\n\nVerified with workspace clippy -D warnings, warnings-denied all-features Rustdoc, serial product and validation suites, both packaged AIR reproductions plus spirv-val Vulkan 1.3, and release measurements under 0.5 seconds / 23 MiB RSS.
2026-08-20 06:47:22 +03:00
Anees Iqbal f263d8a195 Reject lost runtime sampler specialization
Propagate exact sampler state through bounded sampler-typed SSA aliases and mark mixed joins ambiguous. Refuse pointer-selected runtime samplers instead of silently substituting the default sampler and returning to native sampling.\n\nAdd a selected-sampler regression and clarify the consumer contract.
2026-08-20 06:07:22 +03:00
Anees Iqbal 04666b0f44 Specialize runtime sampler state structurally
Accept bounded pipeline sampler state by Metal index, attach it to the emitted runtime sampler SSA value, and reuse the static sampler lowering seam for pixel-coordinate sampling, addressing, depth, comparison, and LOD refusals. Reflect only applied sampler states and make the validation executor consume that synchronized contract.\n\nCover normalized/pixel switching, fragment and kernel indices, all supported address modes, offsets, depth comparisons, serde, validation plumbing, and honest unsupported-state refusals.
2026-08-20 05:59:50 +03:00
Anees Iqbal 7cf240e05a Fix descriptor binding band collisions
Replace overlapping resource bases with checked sampled-texture, sampler, color, imageblock, storage-texture, and synthetic descriptor bands shared by emission and reflection. Reject unknown or cross-class descriptor layouts at the final module boundary, keep constexpr/default allocation inside its band, and bump reflection ABI version 22.

Also resolve kernel function-constant resource locations consistently, coalesce compatible aliases in the Vulkan validation consumer, and cover high/last indices plus sampled/storage aliases end to end.

Verified with serial product and validation tests, warnings-denied workspace clippy and Rustdoc, the packaged descriptor collision repro, a 500-row current-fingerprint translation checkpoint, and release translation at 0.02s / 22,216,704-byte max RSS.
2026-08-20 05:14:56 +03:00
Anees Iqbal adb19e2c2c Make AIR vector layout authoritative
Preserve and parse the source datalayout, use allocation strides through aggregate byte walkers, and correctly map uchar vectors from AIR struct metadata. Record typed mapping outcomes so authoritative metadata cannot disappear silently.\n\nCover scalar families, custom vector alignment, raw and inline lowering, retry emission, metadata matching, and path-based translation.
2026-08-20 03:58:18 +03:00
Anees Iqbal 8b78eaca3b Expand macOS 26 AIR translation coverage
Overhaul the validation workflow around sharded authored cases, dependency-exact observations, incremental indexed corpus audits, bounded parallel translation, and native Metal/Vulkan comparison.\n\nExpand native AIR lowering, reflection, linked-function specialization, resource and stage-interface support, and structural CFG/pointer repair across the harvested macOS 26 corpus. Add exact intrinsic inventory, distributed 16x16x16 matrix lowering, explicit opaque tensor linkage, and regression coverage for the newly supported feature classes.\n\nThe final corpus verification accounts for all 88,819 indexed AIR modules under the current product fingerprint: 65,355 translate and validate directly, 23,464 require exact authored linkage, and zero fail or remain unresolved.
2026-08-13 21:46:27 +02:00
Anees Iqbal 1b013834bc Improve translation correctness and oracle safety
Add structural lowering fixes for function constants, byte aggregates, texture arrays, sampling, and SIMD operations. Harden corpus oracle planning and quarantine unsafe or non-comparable rows without GPU resubmission. Reject reused SPIR-V merge ownership and fast-fallback oversized systematic CFG failures so broken AIR returns promptly instead of emitting invalid bytes after lengthy retries.
2026-08-10 16:54:26 +02:00
Anees Iqbal 3fbe8e516b Harden AIR translation and consumer validation
Expand structural image, buffer, control-flow, and passthrough lowering, including driver-safe relooper limits and regression coverage.\n\nExpose buffer extent, type, and refined access in reflection v4 for downstream consumers.\n\nHarden corpus oracle planning and loop safety, quarantine non-semantic rows, and refresh the affected translation and execution ledgers.\n\nVerified with cargo fmt --all, workspace clippy with warnings denied, and serial product and validation test suites.
2026-08-10 11:44:46 +02:00
Anees Iqbal 53b627809c Expand AIR translation and validation coverage 2026-07-26 00:43:57 +03:00
Anees Iqbal 3338acecb5 Reflect AIR constexpr sampler state
Reserve translator-owned constexpr samplers inside the sampler descriptor\nband instead of allowing framebuffer-fetch bindings to push them into the\ncolor-input range. Decode the full two-word AIR sampler state and expose it\nthrough reflection schema version 3 so Vulkan consumers can create the exact\nimmutable sampler rather than guessing from the emitted descriptor.

Keep emission and reflection ordering aligned by the stable AIR sampler\nglobal suffix, and cover the pipe25 shape with runtime sampler, two static\nsamplers, and a framebuffer-fetch color input.

Verified with:\n- cargo test --workspace --all-features -- --test-threads=1\n- cargo clippy --workspace --all-targets --all-features -- -D warnings
2026-07-24 02:23:35 +03:00
Anees Iqbal 6a14365536 Rework validation corpus workflow around ledgers
Replace the old drift/harvest scripts and generated corpus-test path with
Rust validation binaries that use JSONL ledgers as the durable corpus and
execution record.

- Move translate banking from validation/corpus/drift-ledger.jsonl to
  validation/corpus/metal2vulkan-ledger.jsonl, and seed tracked Metal and
  MoltenVK execution ledgers with hash-identified rows and output_b64
  payloads.
- Add corpus-harvest, corpus-mint, corpus-remint, corpus-why, corpus-triage,
  and corpus-run-{metal,vulkan,moltenvk} binaries for shard harvesting,
  additive/remint translate banking, single-case fallback inspection,
  status triage, and backend execution.
- Rework corpus runners to infer execution plans from shard-backed AIR at run
  time, merge per-run deltas into sorted ledgers, support focused reruns, and
  keep Metal oracle coverage available for translate FALLBACK rows while SPIR-V
  backends remain gated on translate status=ok.
- Bound control-parameter seeding and add loop-budget instrumentation,
  quarantine handling, subprocess timeouts, Ctrl-C worker cleanup, slow-case
  logging, panic backtraces, and MoltenVK/Homebrew Vulkan discovery for safer
  offline execution.
- Consolidate validation helpers for AIR stage/entry parsing, corpus source and
  shard resolution, hashing, JSONL I/O, texture shape policy, translate-ledger
  rows, runner status rows, and triage summaries.
- Remove obsolete Python drift/harvest scripts, generated corpus stubs,
  broken/tolerances sidecars, TOOLCHAIN.lock, and unused validation harness
  modules from the repo surface.
- Update validation, corpus, A/B, architecture, contributing, and agent docs,
  plus gitignore rules, to describe the shard-backed ledger workflow and its
  expected generated artifacts.
2026-07-23 20:01:24 +03:00
Anees Iqbal 3007485352 🆕 Open Source metal2vulkan 2026-07-22 13:15:24 +03:00