Skip to main content

fuel_dispatch/fkc/
lower.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Lowering: parsed FKC schema (strings) → typed dispatch records
3//! (adoption plan §2, §2.1 / §2.2 mapping tables, §2.3 cost AST, §6 caps).
4//!
5//! This slice converts a parsed [`FkcKernel`] into a [`ResolvedPrimitive`]
6//! or [`ResolvedFused`] — typed records ready for the NEXT slice (the
7//! trampoline / global cost-table / `register_into`). It stops at typed
8//! records + a **parsed** cost AST; it does NOT build a `CostFn`
9//! fn-pointer.
10//!
11//! Every string → typed conversion is an **explicit, exhaustive `match`**
12//! (NOT `FromStr`-by-discriminant) so that adding a new source variant
13//! (a new `OpKind`, a new `DType`) forces a compile error here to extend
14//! the table — the table cannot silently drift behind the type. The one
15//! exception is `fused_op`, whose name table is **generated** from
16//! `fuel-graph`'s `default_registry()` so it cannot drift from the graph's
17//! single source of truth.
18
19use fuel_graph::registry::{FusedOpId, FusedOps};
20use fuel_ir::DType;
21use fuel_ir::dispatch::OpKind;
22use fuel_ir::probe::BackendId;
23use smallvec::SmallVec;
24
25use crate::fkc::caps_map::{self, ResolvedLayout};
26use crate::fkc::cost_expr::{self, CompiledCostExpr};
27use crate::fkc::error::FkcError;
28use crate::fkc::precision;
29use crate::fkc::revhash;
30use crate::fkc::schema::{CostBlock, FkcKernel};
31use crate::fused::{KernelRevisionHash, PrecisionGuarantee};
32use crate::kernel::{CostFn, KernelCaps, KernelDTypes, KernelRef};
33
34// ===========================================================================
35// LinkRegistry — entry_point symbol → KernelRef (P9, §12.6)
36// ===========================================================================
37
38/// Resolve a contract's `entry_point` symbol string into a concrete
39/// [`KernelRef`] function pointer. Each provider crate implements this
40/// over its exported `&'static [(&str, KernelRef)]` table (FKC §12.6); a
41/// test stub maps every symbol to a dummy kernel.
42///
43/// The importer never fabricates a function pointer — it looks the symbol
44/// up and errors ([`FkcError::UnknownEntryPoint`]) if absent. This keeps
45/// P9 (serializable contracts, no pointers in the file) honest.
46pub trait LinkRegistry {
47    /// Resolve a primitive (`op_kind`) kernel's entry point.
48    fn resolve_primitive(&self, symbol: &str) -> Option<KernelRef>;
49    /// Resolve a fused (`fused_op`) kernel's entry point.
50    fn resolve_fused(&self, symbol: &str) -> Option<KernelRef>;
51
52    /// Resolve a contract's `cost.cost_fn` NAME into a concrete [`CostFn`]
53    /// pointer — the cost-model analogue of [`Self::resolve_primitive`] (§4.4
54    /// cost-fn trampoline, Task-F). A provider that pins real cost fns exports
55    /// its own `&'static [(&str, CostFn)]` table and overrides this over it
56    /// (exactly as it exports its `entry_point` table); the built-in default
57    /// is `None` (no cost-fn table), so every existing `LinkRegistry` impl and
58    /// test stub compiles unchanged and a section that names no cost fn is
59    /// unaffected. The importer never fabricates a pointer: an unresolved name
60    /// is a typed [`FkcError::UnknownCostFn`], never a silent `unknown_cost`
61    /// fallback (P9 — the resolved cost model is a real registered fn, not a
62    /// serialized pointer).
63    fn resolve_cost_fn(&self, _name: &str) -> Option<CostFn> {
64        None
65    }
66}
67
68// ===========================================================================
69// Resolved records
70// ===========================================================================
71
72/// A fully-lowered primitive (`op_kind`) contract — typed dispatch record
73/// ready for the register slice. The cost is held as a parsed AST
74/// ([`CompiledCostExpr`]), NOT a `CostFn` fn-pointer (the trampoline is the
75/// next slice).
76#[derive(Debug, Clone)]
77pub struct ResolvedPrimitive {
78    /// The dispatch op (key.0).
79    pub op: OpKind,
80    /// Per-operand dtypes, inputs in order then outputs (key.1).
81    pub dtypes: KernelDTypes,
82    /// The backend (key.2).
83    pub backend: BackendId,
84    /// Projected layout capabilities (§6) — one bool today, every parsed
85    /// flag retained on `layouts`.
86    pub caps: KernelCaps,
87    /// Per-operand parsed five-flag layout sets (retained for forward use;
88    /// §6 [consumer-ahead]).
89    pub layouts: Vec<ResolvedLayout>,
90    /// Lowered precision guarantee.
91    pub precision: PrecisionGuarantee,
92    /// Parsed cost AST (capacity-eval next slice; `Unknown` ⇒ `unknown_cost`).
93    pub cost: CompiledCostExpr,
94    /// A CONTRACT-PINNED [`CostFn`] resolved from `cost.cost_fn` through the
95    /// `LinkRegistry` (§4.4 cost-fn trampoline, Task-F). `Some(fn)` ⇒ the
96    /// register slice stamps THIS `CostFn` on the binding, which SURVIVES the
97    /// `fill_unset_cost_for_backend` pass (that pass only replaces the
98    /// `unknown_cost` sentinel); `None` ⇒ the imported `unknown_cost` sentinel
99    /// (the fill pass upgrades it to the op/backend default). This is how the
100    /// CUDA `flash_decoding` contract keeps its static infeasibility-gate cost.
101    pub cost_fn: Option<CostFn>,
102    /// The resolved kernel function pointer.
103    pub kernel: KernelRef,
104    /// The `kernel_source` tag (`BindingEntry.kernel_source`).
105    pub kernel_source: String,
106    /// The kernel revision hash (§4.7).
107    pub revision: KernelRevisionHash,
108    /// OPAQUE specialization-variant tag (contract `variant:`), retained
109    /// verbatim from [`crate::fkc::schema::FkcKernel::variant`] so it survives
110    /// to where records / `ImplId` construction (the emission step) will read
111    /// it. Never parsed or validated here; the entry point remains the true
112    /// kernel identity.
113    pub variant: Option<String>,
114}
115
116/// A fully-lowered fused (`fused_op`) contract — analogous to
117/// [`ResolvedPrimitive`] but targeting the `FusedKernelRegistry`
118/// (`FusedOpId` instead of `OpKind`; the fused cost target).
119#[derive(Debug, Clone)]
120pub struct ResolvedFused {
121    /// The fused op id (registry key, from `default_registry()`).
122    pub id: FusedOpId,
123    /// Per-operand dtypes, inputs in order then outputs.
124    pub dtypes: KernelDTypes,
125    /// The backend (registry key).
126    pub backend: BackendId,
127    /// Projected layout capabilities (§6).
128    pub caps: KernelCaps,
129    /// Per-operand parsed five-flag layout sets (retained; §6).
130    pub layouts: Vec<ResolvedLayout>,
131    /// Lowered precision guarantee.
132    pub precision: PrecisionGuarantee,
133    /// Parsed cost AST (the fused cost target; `Unknown` ⇒ `unknown_cost`).
134    pub cost: CompiledCostExpr,
135    /// The resolved kernel function pointer.
136    pub kernel: KernelRef,
137    /// The `kernel_source` tag.
138    pub kernel_source: String,
139    /// The kernel revision hash (§4.7; `BackendImpl.revision`).
140    pub revision: KernelRevisionHash,
141    /// OPAQUE specialization-variant tag (contract `variant:`), retained
142    /// verbatim from [`crate::fkc::schema::FkcKernel::variant`] (see
143    /// [`ResolvedPrimitive::variant`]).
144    pub variant: Option<String>,
145    /// §5.5 `return.bundle` slot names, in declared order (empty for a
146    /// single-output section). Populated by
147    /// `crate::fkc::return_check::bundle_slot_names` (Finding 5.4, Task
148    /// 3.6); `register_into` (`register.rs`) threads non-empty values into
149    /// `FusedKernelRegistry::record_bundle_slot_names`.
150    pub bundle_slot_names: Vec<String>,
151}
152
153/// The result of lowering one kernel section: a primitive xor a fused
154/// record (exactly one of `op_kind` / `fused_op`).
155#[derive(Debug, Clone)]
156pub enum Resolved {
157    /// An `op_kind` contract → the binding table.
158    Primitive(ResolvedPrimitive),
159    /// A `fused_op` contract → the fused registry.
160    Fused(ResolvedFused),
161}
162
163// ===========================================================================
164// op_kind String → OpKind (explicit exhaustive match; §2.1)
165// ===========================================================================
166
167/// Map an `op_kind` string to an [`OpKind`]. The `match` is exhaustive
168/// over `OpKind` so adding a new variant forces this table to grow
169/// (a compile error, not a silent miss). `UnknownOpKind` on a bad string.
170pub(crate) fn lower_op_kind(s: &str, section: &str) -> Result<OpKind, FkcError> {
171    // Helper so the match arms read as `name => Variant`. We round-trip
172    // through a known-exhaustive coverage check below.
173    let mapped = match s {
174        "MatMul" => Some(OpKind::MatMul),
175        "AddElementwise" => Some(OpKind::AddElementwise),
176        "SubElementwise" => Some(OpKind::SubElementwise),
177        "MulElementwise" => Some(OpKind::MulElementwise),
178        "DivElementwise" => Some(OpKind::DivElementwise),
179        "ReluElementwise" => Some(OpKind::ReluElementwise),
180        "NegElementwise" => Some(OpKind::NegElementwise),
181        "SqrElementwise" => Some(OpKind::SqrElementwise),
182        "SqrtElementwise" => Some(OpKind::SqrtElementwise),
183        "RecipElementwise" => Some(OpKind::RecipElementwise),
184        "AbsElementwise" => Some(OpKind::AbsElementwise),
185        "TanhElementwise" => Some(OpKind::TanhElementwise),
186        "ExpElementwise" => Some(OpKind::ExpElementwise),
187        "LogElementwise" => Some(OpKind::LogElementwise),
188        "SinElementwise" => Some(OpKind::SinElementwise),
189        "CosElementwise" => Some(OpKind::CosElementwise),
190        "SigmoidElementwise" => Some(OpKind::SigmoidElementwise),
191        "SiluElementwise" => Some(OpKind::SiluElementwise),
192        "GeluElementwise" => Some(OpKind::GeluTanhElementwise),
193        "StepElementwise" => Some(OpKind::StepElementwise),
194        "SumReduce" => Some(OpKind::SumReduce),
195        "MaxReduce" => Some(OpKind::MaxReduce),
196        "MinReduce" => Some(OpKind::MinReduce),
197        "MeanReduce" => Some(OpKind::MeanReduce),
198        "Cast" => Some(OpKind::Cast),
199        "Conv2D" => Some(OpKind::Conv2D),
200        "ConvTranspose2D" => Some(OpKind::ConvTranspose2D),
201        "ReduceSumTo" => Some(OpKind::ReduceSumTo),
202        "ReduceMaxTo" => Some(OpKind::ReduceMaxTo),
203        "FusedLinear" => Some(OpKind::FusedLinear),
204        "FlashAttn" => Some(OpKind::FlashAttn),
205        "FlashAttnBackwardQ" => Some(OpKind::FlashAttnBackwardQ),
206        "FlashAttnBackwardK" => Some(OpKind::FlashAttnBackwardK),
207        "FlashAttnBackwardV" => Some(OpKind::FlashAttnBackwardV),
208        "PagedAttn" => Some(OpKind::PagedAttn),
209        "Affine" => Some(OpKind::Affine),
210        "ClampElementwise" => Some(OpKind::ClampElementwise),
211        "PowIElementwise" => Some(OpKind::PowIElementwise),
212        "PowIElementwiseBackward" => Some(OpKind::PowIElementwiseBackward),
213        "MaximumElementwise" => Some(OpKind::MaximumElementwise),
214        "MinimumElementwise" => Some(OpKind::MinimumElementwise),
215        "EqualElementwise" => Some(OpKind::EqualElementwise),
216        "NotEqualElementwise" => Some(OpKind::NotEqualElementwise),
217        "LessElementwise" => Some(OpKind::LessElementwise),
218        "LessEqualElementwise" => Some(OpKind::LessEqualElementwise),
219        "GreaterElementwise" => Some(OpKind::GreaterElementwise),
220        "GreaterEqualElementwise" => Some(OpKind::GreaterEqualElementwise),
221        "Where" => Some(OpKind::Where),
222        "FloorElementwise" => Some(OpKind::FloorElementwise),
223        "CeilElementwise" => Some(OpKind::CeilElementwise),
224        "RoundElementwise" => Some(OpKind::RoundElementwise),
225        "SignElementwise" => Some(OpKind::SignElementwise),
226        "ErfElementwise" => Some(OpKind::ErfElementwise),
227        "GeluErfElementwise" => Some(OpKind::GeluElementwise),
228        "PowElementwise" => Some(OpKind::PowElementwise),
229        "RsqrtElementwise" => Some(OpKind::RsqrtElementwise),
230        "RemElementwise" => Some(OpKind::RemElementwise),
231        "Flip" => Some(OpKind::Flip),
232        "Roll" => Some(OpKind::Roll),
233        "CumSum" => Some(OpKind::CumSum),
234        "Pad" => Some(OpKind::Pad),
235        "Triu" => Some(OpKind::Triu),
236        "Tril" => Some(OpKind::Tril),
237        "LogSoftmaxLastDim" => Some(OpKind::LogSoftmaxLastDim),
238        "LogSoftmaxLastDimBackward" => Some(OpKind::LogSoftmaxLastDimBackward),
239        "MaskedFill" => Some(OpKind::MaskedFill),
240        "PadBackward" => Some(OpKind::PadBackward),
241        "Concat" => Some(OpKind::Concat),
242        "SoftmaxLastDim" => Some(OpKind::SoftmaxLastDim),
243        "SoftmaxLastDimBackward" => Some(OpKind::SoftmaxLastDimBackward),
244        "RmsNormLastDim" => Some(OpKind::RmsNormLastDim),
245        "RmsNormLastDimBackward" => Some(OpKind::RmsNormLastDimBackward),
246        "LayerNormLastDim" => Some(OpKind::LayerNormLastDim),
247        "LayerNormLastDimBackward" => Some(OpKind::LayerNormLastDimBackward),
248        "ReduceMaxToBackward" => Some(OpKind::ReduceMaxToBackward),
249        "IndexSelect" => Some(OpKind::IndexSelect),
250        "Gather" => Some(OpKind::Gather),
251        "Rope" => Some(OpKind::Rope),
252        "IndexAdd" => Some(OpKind::IndexAdd),
253        "ScatterAdd" => Some(OpKind::ScatterAdd),
254        "ArgMaxDim" => Some(OpKind::ArgMaxDim),
255        "ArgMinDim" => Some(OpKind::ArgMinDim),
256        "QMatMul" => Some(OpKind::QMatMul),
257        "WriteSlice" => Some(OpKind::WriteSlice),
258        "WriteSliceRotating" => Some(OpKind::WriteSliceRotating),
259        "WriteSliceDoff" => Some(OpKind::WriteSliceDoff),
260        "Copy" => Some(OpKind::Copy),
261        "ReluInplace" => Some(OpKind::ReluInplace),
262        "SiluInplace" => Some(OpKind::SiluInplace),
263        "GeluInplace" => Some(OpKind::GeluTanhInplace),
264        "TanhInplace" => Some(OpKind::TanhInplace),
265        "SigmoidInplace" => Some(OpKind::SigmoidInplace),
266        "NegInplace" => Some(OpKind::NegInplace),
267        "AbsInplace" => Some(OpKind::AbsInplace),
268        "SqrInplace" => Some(OpKind::SqrInplace),
269        "SqrtInplace" => Some(OpKind::SqrtInplace),
270        "RsqrtInplace" => Some(OpKind::RsqrtInplace),
271        "RecipInplace" => Some(OpKind::RecipInplace),
272        "ExpInplace" => Some(OpKind::ExpInplace),
273        "LogInplace" => Some(OpKind::LogInplace),
274        "SinInplace" => Some(OpKind::SinInplace),
275        "CosInplace" => Some(OpKind::CosInplace),
276        "SignInplace" => Some(OpKind::SignInplace),
277        "FloorInplace" => Some(OpKind::FloorInplace),
278        "CeilInplace" => Some(OpKind::CeilInplace),
279        "RoundInplace" => Some(OpKind::RoundInplace),
280        "ErfInplace" => Some(OpKind::ErfInplace),
281        "GeluErfInplace" => Some(OpKind::GeluInplace),
282        "ClampInplace" => Some(OpKind::ClampInplace),
283        "PowIInplace" => Some(OpKind::PowIInplace),
284        "InplaceAffine" => Some(OpKind::InplaceAffine),
285        "FusedSoftmaxCrossEntropy" => Some(OpKind::FusedSoftmaxCrossEntropy),
286        "CausalConv1d" => Some(OpKind::CausalConv1d),
287        "SelectiveScan" => Some(OpKind::SelectiveScan),
288        "SsdChunkScan" => Some(OpKind::SsdChunkScan),
289        "Nf4Matmul" => Some(OpKind::Nf4Matmul),
290        "AwqMatmul" => Some(OpKind::AwqMatmul),
291        _ => None,
292    };
293    // NOTE: `OpKind` is `#[non_exhaustive]` in `fuel-core-types`, so a
294    // wildcard-free exhaustiveness anchor is not possible across the crate
295    // boundary. The string table above is still explicit + audited (each
296    // `OpKind` variant has its own arm); a new upstream variant simply
297    // won't be reachable until a token is added here (an `UnknownOpKind`
298    // at runtime, not a compile error — the non_exhaustive contract).
299    match mapped {
300        Some(op) => Ok(op),
301        None => Err(FkcError::UnknownOpKind {
302            section: section.to_string(),
303            op_kind: s.to_string(),
304        }),
305    }
306}
307
308// ===========================================================================
309// fused_op String → FusedOpId (SCREAMING_SNAKE FusedOps constant table; §2.2)
310// ===========================================================================
311
312/// Map a `fused_op` token to its [`FusedOpId`].
313///
314/// **The spec/contracts use the `FusedOps` CONSTANT NAME** — SCREAMING_SNAKE,
315/// e.g. `SOFTMAX_LAST_DIM` / `FLASH_ATTN` / `QMATMUL` (FKC §3.1 token format,
316/// §3.7). This is NOT the registry entry's `name` field, which is PascalCase
317/// (`"SoftmaxLastDim"`). The earlier `default_registry().id_for_name(...)`
318/// resolver matched the PascalCase `name` and therefore always *missed* on a
319/// real contract token.
320///
321/// The mapping is an explicit `match` from each SCREAMING_SNAKE constant name
322/// to its `FusedOps::<NAME>` `FusedOpId` (`UnknownFusedOp` on a miss). It is
323/// kept honest by the [`tests::every_registry_id_is_reachable_through_table`]
324/// drift-guard: every `FusedOpId` present in `default_registry()` must be
325/// reachable through this table, so adding a new `FusedOps` const without a
326/// table entry fails that test.
327pub(crate) fn lower_fused_op(s: &str, section: &str) -> Result<FusedOpId, FkcError> {
328    fused_op_id_for_const_name(s).ok_or_else(|| FkcError::UnknownFusedOp {
329        section: section.to_string(),
330        fused_op: s.to_string(),
331    })
332}
333
334/// The SCREAMING_SNAKE `FusedOps::*` constant-name → [`FusedOpId`] table.
335/// Returns `None` for an unknown token. One arm per `FusedOps` associated
336/// const (`fuel-graph/src/registry.rs`); the drift-guard test asserts this
337/// covers every registered id.
338pub(crate) fn fused_op_id_for_const_name(s: &str) -> Option<FusedOpId> {
339    let id = match s {
340        "SOFTMAX_LAST_DIM" => FusedOps::SOFTMAX_LAST_DIM,
341        "FUSED_LINEAR" => FusedOps::FUSED_LINEAR,
342        "RMS_NORM_LAST_DIM" => FusedOps::RMS_NORM_LAST_DIM,
343        "LAYER_NORM_LAST_DIM" => FusedOps::LAYER_NORM_LAST_DIM,
344        "ROPE" => FusedOps::ROPE,
345        "CONV2D" => FusedOps::CONV2D,
346        "SOFTMAX_LAST_DIM_BACKWARD" => FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
347        "LAYER_NORM_LAST_DIM_BACKWARD" => FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
348        "RMS_NORM_LAST_DIM_BACKWARD" => FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
349        "REDUCE_MAX_TO_BACKWARD" => FusedOps::REDUCE_MAX_TO_BACKWARD,
350        "CONV_TRANSPOSE2D" => FusedOps::CONV_TRANSPOSE2D,
351        "FLASH_ATTN" => FusedOps::FLASH_ATTN,
352        "PAGED_ATTN" => FusedOps::PAGED_ATTN,
353        "QMATMUL" => FusedOps::QMATMUL,
354        "POWI_BACKWARD" => FusedOps::POWI_BACKWARD,
355        "INPLACE_AFFINE" => FusedOps::INPLACE_AFFINE,
356        "FUSED_SOFTMAX_CROSS_ENTROPY" => FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
357        "CAUSAL_CONV1D" => FusedOps::CAUSAL_CONV1D,
358        "SELECTIVE_SCAN" => FusedOps::SELECTIVE_SCAN,
359        "SSD_CHUNK_SCAN" => FusedOps::SSD_CHUNK_SCAN,
360        "NF4_MATMUL" => FusedOps::NF4_MATMUL,
361        "FLASH_ATTN_BACKWARD_Q" => FusedOps::FLASH_ATTN_BACKWARD_Q,
362        "FLASH_ATTN_BACKWARD_K" => FusedOps::FLASH_ATTN_BACKWARD_K,
363        "FLASH_ATTN_BACKWARD_V" => FusedOps::FLASH_ATTN_BACKWARD_V,
364        "AWQ_MATMUL" => FusedOps::AWQ_MATMUL,
365        _ => return None,
366    };
367    Some(id)
368}
369
370// ===========================================================================
371// dtype token / dtype_class String → DType (explicit match; §3.4)
372// ===========================================================================
373
374/// Map a single dtype token to a [`DType`]. Explicit exhaustive `match`
375/// (FDX codes are a different axis; this is NOT `FromStr`-by-discriminant).
376///
377/// Rejection is **two-way**: `ReservedScalarType` for a token KISS-CLASSIFY
378/// §6.1 reserves at this schema version, `BadScalarType` for anything else.
379/// Both are typed errors — what differs is which fact the contract author is
380/// told, and therefore what they should do about it (§6.1-0001).
381pub(crate) fn lower_dtype(token: &str, section: &str, operand: &str) -> Result<DType, FkcError> {
382    let mapped = match token {
383        "U8" => Some(DType::U8),
384        "I8" => Some(DType::I8),
385        "U32" => Some(DType::U32),
386        "I16" => Some(DType::I16),
387        "I32" => Some(DType::I32),
388        "I64" => Some(DType::I64),
389        "BF16" => Some(DType::BF16),
390        "F16" => Some(DType::F16),
391        "F32" => Some(DType::F32),
392        "F64" => Some(DType::F64),
393        "F8E4M3" => Some(DType::F8E4M3),
394        "F6E2M3" => Some(DType::F6E2M3),
395        "F6E3M2" => Some(DType::F6E3M2),
396        "F4" => Some(DType::F4),
397        "F8E8M0" => Some(DType::F8E8M0),
398        "F8E5M2" => Some(DType::F8E5M2),
399        "F8E6M2" => Some(DType::F8E6M2),
400        "BOOL" => Some(DType::Bool),
401        _ => None,
402    };
403    if let Some(dt) = mapped {
404        // Exhaustiveness anchor (no wildcard): a new DType variant breaks
405        // this match, forcing the token table above to grow.
406        match dt {
407            DType::U8
408            | DType::I8
409            | DType::U32
410            | DType::I16
411            | DType::I32
412            | DType::I64
413            | DType::BF16
414            | DType::F16
415            | DType::F32
416            | DType::F64
417            | DType::F8E4M3
418            | DType::F8E5M2
419            | DType::F6E2M3
420            | DType::F6E3M2
421            | DType::F4
422            | DType::F8E8M0
423            | DType::F8E6M2
424            | DType::Bool => (),
425        };
426        Ok(dt)
427    } else if fuel_ir::is_reserved_dtype_token(token) {
428        // Recognized-but-reserved is a DIFFERENT rejection from unknown, and a
429        // contract author must be able to tell them apart. (This is §6.1's
430        // reserved vocabulary applied to an ingest surface Fuel really has —
431        // NOT §6.1-0001 conformance, which binds a reader of a structure_key;
432        // Fuel has no such reader. See `fuel_ir::RESERVED_DTYPE_TOKENS`.)
433        //
434        // Order matches KISS's own reference impl: reserved is checked BEFORE
435        // unknown, because the reserved set is a SUBSET of the vocabulary and
436        // an unknown-first check would swallow it.
437        //
438        // The list lives in `fuel-ir` and is CONSULTED, not copied. Two
439        // hand-maintained lists is the drift pattern this repo keeps
440        // re-finding: the copy that stops being edited silently reverts to
441        // treating reserved tokens as unknown, and nothing fails.
442        //
443        // This does not contradict the module's "explicit table, never
444        // `FromStr`-by-discriminant" rule. The accept table above is still the
445        // exhaustive, compile-anchored `match`; what is shared here is the
446        // RESERVED-token list — a fact about the standard rather than about
447        // Fuel's as-built `DType` set, so it has no exhaustiveness anchor to
448        // lose, and every reserved token is by definition absent from `DType`.
449        //
450        // Order is load-bearing: this arm is only reached because the accept
451        // arms are exact literals and cannot capture a reserved token. That is
452        // asserted rather than assumed (see the tests below) — `F8E5M2` is a
453        // PREFIX of `F8E5M2FNUZ`, so any `starts_with`/`contains` classifier
454        // here would read the reserved token as the supported one and compute
455        // on `fnuz` bytes as if they were OCP: silent numerical corruption,
456        // not a loud failure.
457        Err(FkcError::ReservedScalarType {
458            section: section.to_string(),
459            operand: operand.to_string(),
460            token: token.to_string(),
461        })
462    } else {
463        Err(FkcError::BadScalarType {
464            section: section.to_string(),
465            operand: operand.to_string(),
466            token: token.to_string(),
467        })
468    }
469}
470
471/// Expand a `dtype_class` shorthand (§3.4) into its dtype list. `any`
472/// resolves to the operand's enumerated `dtypes` (passed in `enumerated`).
473///
474/// `pub(crate)`: also the single source of truth for
475/// `shape_constraint::first_probe_dtype`'s dtype-class fallback pick (its
476/// first element), so the §3.4 class -> dtype-list mapping is defined once.
477pub(crate) fn expand_dtype_class(
478    class: &str,
479    enumerated: &[DType],
480    section: &str,
481    operand: &str,
482) -> Result<Vec<DType>, FkcError> {
483    match class {
484        "float" => Ok(vec![DType::BF16, DType::F16, DType::F32, DType::F64]),
485        "int" => Ok(vec![DType::I8, DType::I16, DType::I32, DType::I64]),
486        "uint" => Ok(vec![DType::U8, DType::U32]),
487        "any" => Ok(enumerated.to_vec()),
488        other => Err(FkcError::BadScalarType {
489            section: section.to_string(),
490            operand: operand.to_string(),
491            token: format!("dtype_class={other}"),
492        }),
493    }
494}
495
496// ===========================================================================
497// backend String → BackendId (explicit match; §2.1)
498// ===========================================================================
499
500/// Map a `backend` string to a [`BackendId`]. Explicit exhaustive match.
501fn lower_backend(s: &str, section: &str) -> Result<BackendId, FkcError> {
502    let mapped = match s {
503        "Cpu" => Some(BackendId::Cpu),
504        "Cuda" => Some(BackendId::Cuda),
505        "Vulkan" => Some(BackendId::Vulkan),
506        "Metal" => Some(BackendId::Metal),
507        _ => None,
508    };
509    // `BackendId` is `#[non_exhaustive]`; same note as `lower_op_kind` —
510    // the explicit string table is the audit surface, not a compile gate.
511    match mapped {
512        Some(b) => Ok(b),
513        None => Err(FkcError::UnknownBackend {
514            section: section.to_string(),
515            backend: s.to_string(),
516        }),
517    }
518}
519
520// ===========================================================================
521// Per-operand dtype assembly → per-variant KernelDTypes (multi-dtype fan-out)
522// ===========================================================================
523
524/// One fanned variant of a section: its full binding key (`[in1, .., out]`)
525/// plus the fan dtype that produced it.
526#[derive(Debug, Clone)]
527pub(crate) struct DtypeVariant {
528    /// The binding-table key: input operand dtypes in order, then outputs.
529    pub(crate) dtypes: KernelDTypes,
530    /// The dtype the varying operands took for this variant. `Some(dt)` when
531    /// the section fans out (drives the `<entry_point>_<suffix>` resolution);
532    /// `None` for the single all-fixed variant (entry_point resolved as-is).
533    pub(crate) fan_dtype: Option<DType>,
534}
535
536/// The canonical `DType → FKC dtype suffix` spelling used to build a fanning
537/// section's per-variant `entry_point` symbol (`<base>_<suffix>`), e.g.
538/// `F32 → "f32"`, `BF16 → "bf16"`, `U8 → "u8"`, `F8E4M3 → "f8e4m3"`.
539///
540/// This is the **inverse** of [`lower_dtype`] and is deliberately the SAME
541/// spelling the byte-kernel `ep!` macro (`fkc/cpu_link.rs`) and the CPU
542/// backend's per-(op,dtype) thunks use — it reuses [`DType::as_str`] rather
543/// than hand-rolling a second table (the [`tests::dtype_suffix_is_the_inverse_of_lower_dtype`]
544/// drift-guard locks the round-trip).
545fn dtype_suffix(dt: DType) -> &'static str {
546    dt.as_str()
547}
548
549/// A resolved input operand: its role name + its enumerated dtype list
550/// (post `dtype_class` expansion; always ≥1) + whether it is OPTIONAL (§3.4).
551struct InputOperand {
552    name: String,
553    dtypes: Vec<DType>,
554    /// `optional: true` (§3.4): production registers the op BOTH with and
555    /// without this operand. Only the LAST input may be optional.
556    optional: bool,
557}
558
559/// Resolve one operand's enumerated dtype list (explicit `dtypes:` wins; a
560/// `dtype_class` shorthand only fills an empty explicit list; §3.4). Errors
561/// [`FkcError::BadScalarType`] on a bad token or an empty result.
562fn resolve_operand_dtypes(
563    d: &crate::fkc::schema::TensorDesc,
564    section: &str,
565    operand: &str,
566) -> Result<Vec<DType>, FkcError> {
567    let mut enumerated: Vec<DType> = Vec::new();
568    for tok in &d.dtypes {
569        enumerated.push(lower_dtype(tok, section, operand)?);
570    }
571    let resolved = if enumerated.is_empty() {
572        if let Some(class) = &d.dtype_class {
573            expand_dtype_class(class, &enumerated, section, operand)?
574        } else {
575            enumerated
576        }
577    } else {
578        // Explicit list present ⇒ it is the enumeration (a `dtype_class`, if
579        // also present, is descriptive only — the explicit list wins, §3.4).
580        enumerated
581    };
582    if resolved.is_empty() {
583        return Err(FkcError::BadScalarType {
584            section: section.to_string(),
585            operand: operand.to_string(),
586            token: "<no dtypes and no dtype_class>".to_string(),
587        });
588    }
589    Ok(resolved)
590}
591
592/// Assemble the per-variant binding-key dtype-lists for a section (§3.4
593/// **multi-dtype fan-out**) plus the shared per-operand layouts.
594///
595/// A section whose operands are all single-dtype (or a `dtype_class` that
596/// expands to exactly one) yields exactly ONE variant with `fan_dtype: None`
597/// — today's behavior, and what keeps the per-(op,dtype) binary / affine /
598/// cast families byte-identical. A section whose operand(s) **vary**
599/// (enumerate >1 dtype, or a `dtype_class` that expands to >1) fans out into
600/// N variants — one per fanned dtype.
601///
602/// Fan rules:
603/// - The fan-out dtype set is the enumerated list of the operand(s) that
604///   vary. ALL varying operands must enumerate the SAME list in the SAME
605///   order; a disagreement is [`FkcError::FanoutDtypeMismatch`] (never a
606///   silent pick).
607/// - Per fanned dtype `dt`, each INPUT operand contributes its dtype at this
608///   variant — a FIXED (single-enumerated) operand its one dtype (e.g.
609///   `where`'s `cond` = U8), a VARYING operand `dt`. Then OUTPUTS:
610///   `fixed(D)` → D; `passthrough(role)` → the dtype of the INPUT operand
611///   named `role` **at this variant** (so `where`'s `passthrough(a)` mirrors
612///   `a` = `dt`, NOT the first input `cond`). Key shape is inputs-then-outputs.
613///
614/// **Optional-operand fan-out (§3.4).** When the LAST input carries
615/// `optional: true` (e.g. conv's `bias`), EACH dtype variant fans into TWO
616/// keys — one OMITTING the optional operand (its dtype dropped from the input
617/// tail) and one INCLUDING it — so `variants = (dtype fan-out) × (optional
618/// {absent, present})`. Both keys resolve the SAME `entry_point`/kernel (the
619/// optional operand rides through op-params, not a distinct symbol). Rules:
620/// - Only the LAST input may be optional; an earlier optional operand would
621///   leave a hole mid-key and is [`FkcError::OptionalOperandNotLast`] (never a
622///   silent mis-key).
623/// - An output may NOT `passthrough(role)` the optional operand — absent, the
624///   two keys' output dtypes would disagree — that is
625///   [`FkcError::PassthroughNamesOptionalOperand`]. `passthrough` of any other
626///   (always-present) operand resolves identically for both keys.
627/// - A section with NO optional operand behaves EXACTLY as before (one key per
628///   dtype variant) — the already-migrated per-(op,dtype) families stay
629///   byte-identical.
630///
631/// The PRESENT (full-operand) key is emitted FIRST so the fused path's
632/// representative (first) variant is unchanged (`lower_fused` takes `.next()`).
633fn assemble_dtype_variants(
634    kernel: &FkcKernel,
635    section: &str,
636) -> Result<(Vec<DtypeVariant>, Vec<ResolvedLayout>), FkcError> {
637    let mut inputs: Vec<InputOperand> = Vec::new();
638    let mut layouts: Vec<ResolvedLayout> = Vec::new();
639
640    if let Some(accept) = &kernel.accept {
641        for d in &accept.inputs {
642            let operand = d.name.as_deref().unwrap_or("<input>");
643            let resolved = resolve_operand_dtypes(d, section, operand)?;
644            inputs.push(InputOperand {
645                name: operand.to_string(),
646                dtypes: resolved,
647                optional: d.optional,
648            });
649            layouts.push(caps_map::resolve_layout(
650                d.layout.as_ref(),
651                section,
652                operand,
653            )?);
654        }
655    }
656
657    // §3.4 optional-operand support: at most the LAST input may be `optional`.
658    // An earlier optional operand, when omitted, would leave a hole in the
659    // MIDDLE of the key and mis-align every following operand — a typed error,
660    // never a silent mis-key. `optional_last` drives the {absent, present} fan.
661    let optional_last = inputs.last().map(|op| op.optional).unwrap_or(false);
662    for (i, op) in inputs.iter().enumerate() {
663        if op.optional && i != inputs.len() - 1 {
664            return Err(FkcError::OptionalOperandNotLast {
665                section: section.to_string(),
666                operand: op.name.clone(),
667            });
668        }
669    }
670
671    // The fan-out dtype set = the enumerated list of the operand(s) that vary
672    // (enumerate >1). All varying operands must agree on the SAME list/order.
673    let mut fan_set: Option<&[DType]> = None;
674    for operand in &inputs {
675        if operand.dtypes.len() > 1 {
676            match fan_set {
677                None => fan_set = Some(&operand.dtypes),
678                Some(existing) => {
679                    if existing != operand.dtypes.as_slice() {
680                        return Err(FkcError::FanoutDtypeMismatch {
681                            section: section.to_string(),
682                            operand: operand.name.clone(),
683                            expected: format!("{existing:?}"),
684                            found: format!("{:?}", operand.dtypes),
685                        });
686                    }
687                }
688            }
689        }
690    }
691
692    // The list of fan dtypes: one all-fixed variant (None) when nothing
693    // varies, else one variant per fanned dtype.
694    let fan_dtypes: Vec<Option<DType>> = match fan_set {
695        None => vec![None],
696        Some(set) => set.iter().map(|dt| Some(*dt)).collect(),
697    };
698
699    // Capacity: one key per dtype variant, doubled when an optional operand
700    // fans each into {absent, present}.
701    let per_variant = if optional_last { 2 } else { 1 };
702    let mut variants: Vec<DtypeVariant> = Vec::with_capacity(fan_dtypes.len() * per_variant);
703    for fan in fan_dtypes {
704        // Each input operand contributes its dtype at THIS variant: a fixed
705        // operand its single dtype, a varying operand the fan dtype. Built with
706        // ALL inputs (incl. the optional last); the absent-key drops its tail.
707        let mut input_dtypes: KernelDTypes = SmallVec::new();
708        for operand in &inputs {
709            let dt = if operand.dtypes.len() > 1 {
710                // Varying: fan_dtype is Some by construction here.
711                fan.expect("a varying operand implies a fanned dtype")
712            } else {
713                operand.dtypes[0]
714            };
715            input_dtypes.push(dt);
716        }
717
718        // Outputs: `fixed(D)` → D; `passthrough(role)` → the role operand's
719        // dtype at this variant. Built ONCE and shared by BOTH the present and
720        // absent keys — an output may not `passthrough` the optional operand
721        // (checked below), so the output tail is identical for both. Best-
722        // effort otherwise: an output we cannot type (a passthrough naming no
723        // known input, no inputs at all) is omitted from the key tail rather
724        // than failing (full return validation is a separate slice).
725        let mut output_dtypes: KernelDTypes = SmallVec::new();
726        if let Some(ret) = &kernel.return_ {
727            for out in &ret.outputs {
728                let operand = out.name.as_deref().unwrap_or("<output>");
729                if let Some(rule) = out.dtype_rule.as_deref()
730                    && let Some(dt) = resolve_output_slot_dtype(
731                        rule,
732                        operand,
733                        &inputs,
734                        fan,
735                        optional_last,
736                        section,
737                    )?
738                {
739                    output_dtypes.push(dt);
740                }
741            }
742            // §5.5 multi-output bundle (Option C): a `return.bundle` packs
743            // several logical slots into ONE output buffer whose PRIMARY
744            // (first) slot's dtype tags the binding key — the multi-output
745            // contract on [`crate::kernel::KernelRef`] states the key
746            // "describes inputs + the bundle's primary dtype only". Derive that
747            // one slot dtype through the SAME `dtype_rule`/passthrough path as a
748            // regular output and append it to the key tail — so a 5-input scan
749            // with a `passthrough(u)` bundle keys `[T; 6]`, byte-for-byte the
750            // deleted hand-written reg. A section with NO bundle is unaffected
751            // (the migrated per-(op,dtype) families stay byte-identical).
752            if let Some(bundle) = &ret.bundle
753                && let Some((slot, rule)) = bundle_primary_dtype_rule(bundle)
754                && let Some(dt) =
755                    resolve_output_slot_dtype(&rule, &slot, &inputs, fan, optional_last, section)?
756            {
757                output_dtypes.push(dt);
758            }
759        }
760
761        if optional_last {
762            // PRESENT (full-operand) key FIRST so `lower_fused`'s representative
763            // (first) variant is unchanged: all inputs (incl. optional), outputs.
764            let mut present: KernelDTypes = input_dtypes.clone();
765            present.extend_from_slice(&output_dtypes);
766            variants.push(DtypeVariant {
767                dtypes: present,
768                fan_dtype: fan,
769            });
770            // ABSENT key: inputs MINUS the optional last, then outputs. Both
771            // resolve the SAME entry_point/kernel (same `fan_dtype`).
772            let mut absent: KernelDTypes = SmallVec::new();
773            absent.extend_from_slice(&input_dtypes[..input_dtypes.len() - 1]);
774            absent.extend_from_slice(&output_dtypes);
775            variants.push(DtypeVariant {
776                dtypes: absent,
777                fan_dtype: fan,
778            });
779        } else {
780            let mut dtypes: KernelDTypes = input_dtypes;
781            dtypes.extend_from_slice(&output_dtypes);
782            variants.push(DtypeVariant {
783                dtypes,
784                fan_dtype: fan,
785            });
786        }
787    }
788
789    Ok((variants, layouts))
790}
791
792/// Resolve `passthrough(role)` to the dtype of the input operand named
793/// `role` at this variant: a varying operand takes `fan`, a fixed operand
794/// its single dtype. Falls back to the first input's variant dtype when the
795/// role names no input (best-effort — the prior behavior for an untyped
796/// passthrough), and `None` when there are no inputs at all.
797fn passthrough_dtype(inputs: &[InputOperand], role: &str, fan: Option<DType>) -> Option<DType> {
798    let operand_dtype = |op: &InputOperand| -> DType {
799        if op.dtypes.len() > 1 {
800            fan.expect("a varying operand implies a fanned dtype")
801        } else {
802            op.dtypes[0]
803        }
804    };
805    if let Some(op) = inputs.iter().find(|op| op.name == role) {
806        Some(operand_dtype(op))
807    } else {
808        inputs.first().map(operand_dtype)
809    }
810}
811
812/// Resolve ONE output slot's key dtype from its `dtype_rule` at this variant —
813/// the single path shared by a regular `return.outputs` entry and a
814/// `return.bundle`'s primary slot (§5.5). `fixed(D)` → `D`;
815/// `passthrough(role)` → the role operand's dtype at this variant (best-effort
816/// untyped fallback per [`passthrough_dtype`]); an unrecognized rule → `None`
817/// (best-effort — the full return validation is a separate slice). A
818/// `passthrough` naming the OPTIONAL last operand is the typed
819/// [`FkcError::PassthroughNamesOptionalOperand`] (its dtype would disagree
820/// between the operand's present/absent keys, §3.4/§5.1).
821fn resolve_output_slot_dtype(
822    rule: &str,
823    operand: &str,
824    inputs: &[InputOperand],
825    fan: Option<DType>,
826    optional_last: bool,
827    section: &str,
828) -> Result<Option<DType>, FkcError> {
829    match parse_dtype_rule(rule, section, operand)? {
830        DtypeRule::Fixed(dt) => Ok(Some(dt)),
831        DtypeRule::Passthrough(role) => {
832            if optional_last && inputs.last().map(|o| o.name == role).unwrap_or(false) {
833                return Err(FkcError::PassthroughNamesOptionalOperand {
834                    section: section.to_string(),
835                    role,
836                });
837            }
838            Ok(passthrough_dtype(inputs, &role, fan))
839        }
840        DtypeRule::Other => Ok(None),
841    }
842}
843
844/// Extract the PRIMARY (first) slot's `(name, dtype_rule)` from a
845/// `return.bundle` value (§5.5 Option C multi-output). The bundle is carried
846/// opaquely in the schema — a `serde_yaml_ng::Value` sequence of
847/// `{ name, dtype_rule, shape_rule, … }` slot maps (its rank/name validation is
848/// a separate slice) — but the binding KEY only needs the first slot's
849/// `dtype_rule` string, which is then fed through the regular
850/// [`resolve_output_slot_dtype`] machinery exactly like a `return.outputs`
851/// entry. Returns `None` when the bundle is not a non-empty sequence of maps or
852/// the first slot declares no `dtype_rule` (best-effort — a malformed bundle is
853/// a validation concern, never a key that silently mirrors the wrong operand).
854fn bundle_primary_dtype_rule(bundle: &serde_yaml_ng::Value) -> Option<(String, String)> {
855    let serde_yaml_ng::Value::Sequence(slots) = bundle else {
856        return None;
857    };
858    let serde_yaml_ng::Value::Mapping(first) = slots.first()? else {
859        return None;
860    };
861    let rule = first
862        .get(serde_yaml_ng::Value::String("dtype_rule".into()))
863        .and_then(|v| v.as_str())?
864        .to_string();
865    let name = first
866        .get(serde_yaml_ng::Value::String("name".into()))
867        .and_then(|v| v.as_str())
868        .unwrap_or("<bundle>")
869        .to_string();
870    Some((name, rule))
871}
872
873/// A parsed `dtype_rule` (§5.1): `fixed(DType)`, `passthrough(role)`, or an
874/// unrecognized rule (typed later).
875enum DtypeRule {
876    Fixed(DType),
877    Passthrough(String),
878    Other,
879}
880
881/// Parse a `dtype_rule` string into a [`DtypeRule`]. `BadScalarType` only if
882/// `fixed(...)` names a bad dtype; `passthrough(role)` captures the role name.
883fn parse_dtype_rule(rule: &str, section: &str, operand: &str) -> Result<DtypeRule, FkcError> {
884    let rule = rule.trim();
885    if let Some(inner) = rule
886        .strip_prefix("fixed(")
887        .and_then(|s| s.strip_suffix(")"))
888    {
889        Ok(DtypeRule::Fixed(lower_dtype(
890            inner.trim(),
891            section,
892            operand,
893        )?))
894    } else if let Some(inner) = rule
895        .strip_prefix("passthrough(")
896        .and_then(|s| s.strip_suffix(")"))
897    {
898        Ok(DtypeRule::Passthrough(inner.trim().to_string()))
899    } else {
900        Ok(DtypeRule::Other)
901    }
902}
903
904// ===========================================================================
905// Cost block → CompiledCostExpr (primary: flops; §2.3 AST half)
906// ===========================================================================
907
908/// Compile a contract's cost block into a [`CompiledCostExpr`].
909///
910/// Strategy: this slice carries the AST. A cost block that is absent,
911/// `class`-only, or `judge_measured` with no coefficient expressions
912/// compiles to [`CompiledCostExpr::Unknown`] (the register slice maps
913/// that to `unknown_cost`). When expressions ARE present, the **`flops`**
914/// expression is compiled as the primary cost AST (the per-tier `memory`
915/// beyond device_bytes and the other coefficient fields are parsed for
916/// validation but the primary held expression is `flops`; a full
917/// multi-field cost vector is a register-slice concern).
918///
919/// Every present cost expression is parse-validated (V-FKC-8); a malformed
920/// one surfaces as [`FkcError::CostExprParse`] with the field name.
921fn compile_cost(block: Option<&CostBlock>, section: &str) -> Result<CompiledCostExpr, FkcError> {
922    let Some(cost) = block else {
923        return Ok(CompiledCostExpr::Unknown);
924    };
925
926    // Parse-validate every present coefficient expression (so a malformed
927    // bytes_moved is caught even though flops is the primary held AST).
928    let parse = |field: &str, src: Option<&str>| -> Result<CompiledCostExpr, FkcError> {
929        cost_expr::compile_field(src).map_err(|e| FkcError::CostExprParse {
930            section: section.to_string(),
931            field: field.to_string(),
932            expr: src.unwrap_or("").to_string(),
933            reason: e.to_string(),
934        })
935    };
936
937    let flops = parse("flops", cost.flops.as_deref())?;
938    let bytes_moved = parse("bytes_moved", cost.bytes_moved.as_deref())?;
939    // overhead_ns / memory.device_bytes are raw scalars (number or `~`);
940    // when they are an expression STRING they are parse-validated too.
941    if let Some(mem) = &cost.memory
942        && let Some(serde_yaml_ng::Value::String(s)) = &mem.device_bytes
943    {
944        let _ = parse("memory.device_bytes", Some(s))?;
945    }
946    // GAP-382: a declared `overhead_ns` reaches the estimate. A number is held
947    // as a literal, an expression STRING is compiled like flops/bytes, and an
948    // absent or `~` field declares none. Any other YAML type is a typed error,
949    // not a silent drop.
950    let overhead_ns = match &cost.overhead_ns {
951        None | Some(serde_yaml_ng::Value::Null) => None,
952        Some(serde_yaml_ng::Value::Number(n)) => n.as_f64().map(cost_expr::CostNode::Lit),
953        Some(serde_yaml_ng::Value::String(s)) => match parse("overhead_ns", Some(s))? {
954            CompiledCostExpr::Expr(n) => Some(n),
955            _ => None,
956        },
957        Some(other) => {
958            return Err(FkcError::CostExprParse {
959                section: section.to_string(),
960                field: "overhead_ns".to_string(),
961                expr: format!("{other:?}"),
962                reason: "expected a number, an expression string or `~`".to_string(),
963            });
964        }
965    };
966
967    // Hold BOTH expressions (GAP-376): a declared `bytes_moved` must reach
968    // the `CostEstimate`, and a bytes-only block must not have its bytes
969    // formula evaluated into `flops`. With no `bytes_moved` the flops-only
970    // `Expr` form is kept unchanged.
971    let node = |e: CompiledCostExpr| match e {
972        CompiledCostExpr::Expr(n) => Some(n),
973        _ => None,
974    };
975    match (node(flops), node(bytes_moved), overhead_ns) {
976        (None, None, None) => Ok(CompiledCostExpr::Unknown),
977        (Some(f), None, None) => Ok(CompiledCostExpr::Expr(f)),
978        (flops, bytes_moved, overhead_ns) => Ok(CompiledCostExpr::Declared {
979            flops,
980            bytes_moved,
981            overhead_ns,
982        }),
983    }
984}
985
986// ===========================================================================
987// The lowering entry points
988// ===========================================================================
989
990/// Resolve the effective `backend` / `kernel_source` / `entry_point` for a
991/// kernel, applying the front-matter fallbacks the caller passes in.
992struct Defaults<'a> {
993    backend: &'a str,
994    kernel_source: &'a str,
995    revision_base: &'a str,
996}
997
998/// Lower one parsed [`FkcKernel`] into its [`Resolved`] records, resolving
999/// each per-variant `entry_point` through `link`. Exactly one of `op_kind` /
1000/// `fused_op` must be present.
1001///
1002/// A primitive (`op_kind`) section **fans out** into one [`Resolved`] per
1003/// dtype variant (§3.4 multi-dtype fan-out); a section with no varying
1004/// operand yields exactly one. A fused (`fused_op`) section fans out the SAME
1005/// way — one [`Resolved::Fused`] per dtype variant (see [`lower_fused`]).
1006///
1007/// `defaults` carries the front-matter `backend` / `kernel_source` /
1008/// `revision_base` so a kernel that omits them inherits the provider's.
1009fn lower_kernel(
1010    kernel: &FkcKernel,
1011    defaults: &Defaults<'_>,
1012    link: &dyn LinkRegistry,
1013    warnings: &mut Vec<crate::fkc::ImportWarning>,
1014) -> Result<Vec<Resolved>, FkcError> {
1015    let section = kernel.kernel.as_str();
1016
1017    // Exactly one of op_kind / fused_op.
1018    match (kernel.op_kind.as_deref(), kernel.fused_op.as_deref()) {
1019        (Some(op_str), None) => {
1020            let op = lower_op_kind(op_str, section)?;
1021            // Phase 1 has no primitive-side warnings producer yet.
1022            Ok(lower_primitive(kernel, op, defaults, link)?
1023                .into_iter()
1024                .map(Resolved::Primitive)
1025                .collect())
1026        }
1027        (None, Some(fused_str)) => {
1028            let id = lower_fused_op(fused_str, section)?;
1029            Ok(lower_fused(kernel, id, defaults, link, warnings)?
1030                .into_iter()
1031                .map(Resolved::Fused)
1032                .collect())
1033        }
1034        (op, fused) => Err(FkcError::OpTargetAmbiguous {
1035            section: section.to_string(),
1036            op_kind: op.map(String::from),
1037            fused_op: fused.map(String::from),
1038        }),
1039    }
1040}
1041
1042/// Lower a primitive (`op_kind`) section into ONE [`ResolvedPrimitive`] per
1043/// dtype variant (§3.4 multi-dtype fan-out).
1044///
1045/// A section whose operand(s) vary fans out into N bindings — one per fanned
1046/// dtype, with the per-variant binding key rebuilt from
1047/// [`assemble_dtype_variants`]. Its declared `entry_point` is a **BASE**
1048/// symbol; each variant resolves `<base>_<dtype_suffix>` via `link`. A
1049/// non-fanning (single-variant) section keeps its specific `entry_point` and
1050/// resolves it AS-IS.
1051///
1052/// Everything except the per-variant `dtypes` + resolved `kernel` is
1053/// per-section (shared): backend, caps, layouts, precision, cost, and the
1054/// revision hash (which folds the declared BASE `entry_point`, so it is one
1055/// value for the whole section).
1056fn lower_primitive(
1057    kernel: &FkcKernel,
1058    op: OpKind,
1059    defaults: &Defaults<'_>,
1060    link: &dyn LinkRegistry,
1061) -> Result<Vec<ResolvedPrimitive>, FkcError> {
1062    let section = kernel.kernel.as_str();
1063    let backend_str = kernel.backend.as_deref().unwrap_or(defaults.backend);
1064    let backend = lower_backend(backend_str, section)?;
1065    let (variants, layouts) = assemble_dtype_variants(kernel, section)?;
1066    let caps = caps_map::project_kernel_caps(&layouts);
1067    let precision = precision::lower_precision(kernel.precision.as_ref(), section)?;
1068    let cost = compile_cost(kernel.cost.as_ref(), section)?;
1069    // §4.4 cost-fn trampoline (Task-F): a `cost.cost_fn` NAME pins a real,
1070    // shape-aware `CostFn` (per-section, shared by every dtype variant). Resolve
1071    // it ONCE through the LinkRegistry; an unresolved name is a typed error, not
1072    // a silent `unknown_cost` fallback. `None` ⇒ the register slice keeps the
1073    // imported `unknown_cost` sentinel (fill_unset then upgrades it).
1074    let cost_fn = match kernel.cost.as_ref().and_then(|c| c.cost_fn.as_deref()) {
1075        Some(name) => Some(
1076            link.resolve_cost_fn(name)
1077                .ok_or_else(|| FkcError::UnknownCostFn {
1078                    section: section.to_string(),
1079                    cost_fn: name.to_string(),
1080                })?,
1081        ),
1082        None => None,
1083    };
1084
1085    let base_entry_point =
1086        kernel
1087            .entry_point
1088            .as_deref()
1089            .ok_or_else(|| FkcError::MissingRequiredField {
1090                section: section.to_string(),
1091                field: "entry_point".to_string(),
1092            })?;
1093
1094    let kernel_source = kernel
1095        .kernel_source
1096        .as_deref()
1097        .unwrap_or(defaults.kernel_source)
1098        .to_string();
1099    // Per-section revision (same for all variants); folds the BASE entry_point
1100    // so it is byte-identical to the pre-fan-out single-binding revision.
1101    let revision = revhash::compute_revision(kernel, base_entry_point, defaults.revision_base)?;
1102
1103    let mut out = Vec::with_capacity(variants.len());
1104    for variant in variants {
1105        // Per-variant entry_point: a fanning section's declared entry_point is
1106        // a BASE symbol → resolve `<base>_<suffix>`; a non-fanning section
1107        // keeps its specific symbol and resolves AS-IS.
1108        let symbol: std::borrow::Cow<'_, str> = match variant.fan_dtype {
1109            Some(dt) => std::borrow::Cow::Owned(format!("{base_entry_point}_{}", dtype_suffix(dt))),
1110            None => std::borrow::Cow::Borrowed(base_entry_point),
1111        };
1112        let kernel_ref =
1113            link.resolve_primitive(&symbol)
1114                .ok_or_else(|| FkcError::UnknownEntryPoint {
1115                    section: section.to_string(),
1116                    entry_point: symbol.into_owned(),
1117                })?;
1118
1119        out.push(ResolvedPrimitive {
1120            op,
1121            dtypes: variant.dtypes,
1122            backend,
1123            caps,
1124            layouts: layouts.clone(),
1125            precision,
1126            cost: cost.clone(),
1127            cost_fn,
1128            kernel: kernel_ref,
1129            kernel_source: kernel_source.clone(),
1130            revision,
1131            // Retain the opaque `variant:` tag verbatim (per-section, shared by
1132            // every dtype variant) so it survives to the emission step.
1133            variant: kernel.variant.clone(),
1134        });
1135    }
1136    Ok(out)
1137}
1138
1139/// Lower a fused (`fused_op`) section into ONE [`ResolvedFused`] per dtype
1140/// variant (§3.4 multi-dtype fan-out — the fused analogue of
1141/// [`lower_primitive`]).
1142///
1143/// A section whose operand(s) vary fans out into N fused impls — one per fanned
1144/// dtype, with the per-variant binding key rebuilt from
1145/// [`assemble_dtype_variants`] (so a multi-dtype `SOFTMAX_LAST_DIM` section
1146/// registers a per-dtype impl for each of `[F32, F64, BF16, F16]`, 1:1 with the
1147/// hand-written `register_default_fused_kernels` seam it replaces). Its declared
1148/// `entry_point` is a **BASE** symbol; each variant resolves
1149/// `<base>_<dtype_suffix>` via `link` ([`crate::fkc::cpu_link`]'s
1150/// `CPU_FUSED_NORM_ENTRY_POINTS` maps those per-dtype symbols to the per-dtype
1151/// wrappers). A non-fanning (single-variant) section keeps its specific
1152/// `entry_point` and resolves it AS-IS, yielding exactly one record —
1153/// byte-identical to the pre-fan-out behavior.
1154///
1155/// Everything except the per-variant `dtypes` + resolved `kernel` is
1156/// per-section (shared): backend, caps, layouts, precision, cost, and the
1157/// revision hash (which folds the declared BASE `entry_point`, so it is one
1158/// value for the whole section — the primitive precedent).
1159fn lower_fused(
1160    kernel: &FkcKernel,
1161    id: FusedOpId,
1162    defaults: &Defaults<'_>,
1163    link: &dyn LinkRegistry,
1164    warnings: &mut Vec<crate::fkc::ImportWarning>,
1165) -> Result<Vec<ResolvedFused>, FkcError> {
1166    // §5 (Finding 5.1): cross-check the section's declared return rules
1167    // against the REAL registered FusedOpEntry fn BEFORE anything else lowers
1168    // — a disagreement fails the import (never silently drifts from the
1169    // graph's single source of truth). See `return_check::cross_check_fused_section`
1170    // for the never-panic guard + soft-catch-solver-errors invariants.
1171    crate::fkc::return_check::cross_check_fused_section(kernel, id, warnings)?;
1172    let section = kernel.kernel.as_str();
1173    let backend_str = kernel.backend.as_deref().unwrap_or(defaults.backend);
1174    let backend = lower_backend(backend_str, section)?;
1175    let (variants, layouts) = assemble_dtype_variants(kernel, section)?;
1176    let caps = caps_map::project_kernel_caps(&layouts);
1177    let precision = precision::lower_precision(kernel.precision.as_ref(), section)?;
1178    let cost = compile_cost(kernel.cost.as_ref(), section)?;
1179
1180    let base_entry_point =
1181        kernel
1182            .entry_point
1183            .as_deref()
1184            .ok_or_else(|| FkcError::MissingRequiredField {
1185                section: section.to_string(),
1186                field: "entry_point".to_string(),
1187            })?;
1188
1189    let kernel_source = kernel
1190        .kernel_source
1191        .as_deref()
1192        .unwrap_or(defaults.kernel_source)
1193        .to_string();
1194    // Per-section revision (same for all variants); folds the BASE entry_point
1195    // so it is byte-identical to the pre-fan-out single-binding revision.
1196    let revision = revhash::compute_revision(kernel, base_entry_point, defaults.revision_base)?;
1197
1198    let mut out = Vec::with_capacity(variants.len());
1199    for variant in variants {
1200        // Per-variant entry_point: a fanning section's declared entry_point is
1201        // a BASE symbol → resolve `<base>_<suffix>`; a non-fanning section
1202        // keeps its specific symbol and resolves AS-IS.
1203        let symbol: std::borrow::Cow<'_, str> = match variant.fan_dtype {
1204            Some(dt) => std::borrow::Cow::Owned(format!("{base_entry_point}_{}", dtype_suffix(dt))),
1205            None => std::borrow::Cow::Borrowed(base_entry_point),
1206        };
1207        let kernel_ref =
1208            link.resolve_fused(&symbol)
1209                .ok_or_else(|| FkcError::UnknownEntryPoint {
1210                    section: section.to_string(),
1211                    entry_point: symbol.into_owned(),
1212                })?;
1213
1214        out.push(ResolvedFused {
1215            id,
1216            dtypes: variant.dtypes,
1217            backend,
1218            caps,
1219            layouts: layouts.clone(),
1220            precision,
1221            cost: cost.clone(),
1222            kernel: kernel_ref,
1223            kernel_source: kernel_source.clone(),
1224            revision,
1225            // Retain the opaque `variant:` tag verbatim (per-section, shared by
1226            // every dtype variant) so it survives to the emission step.
1227            variant: kernel.variant.clone(),
1228            // Finding 5.4 (Task 3.6): the real §5.5 bundle-slot-name
1229            // extraction. Per-section (same for every dtype variant), so
1230            // this recomputes per variant — cheap (a handful of YAML-slot
1231            // reads), and keeps this call site a single self-contained
1232            // expression rather than hoisting a shared local above the loop.
1233            bundle_slot_names: crate::fkc::return_check::bundle_slot_names(&kernel.return_),
1234        });
1235    }
1236    Ok(out)
1237}
1238
1239/// Lower every kernel section of a parsed file into [`Resolved`] records,
1240/// using the file's front-matter for the backend / kernel_source /
1241/// revision_base defaults and resolving entry points through `link`.
1242///
1243/// **Describe-only sections (`registrable: false`, §3.10) are excluded** from
1244/// the lowered set: they are documentation, carry no dispatch target, and are
1245/// never registered — so they never become a [`Resolved`] record, never
1246/// resolve an `entry_point`, and never reach the binding table / fused
1247/// registry (§9.3, §12.5).
1248pub fn lower_file(
1249    file: &crate::fkc::schema::FkcFile,
1250    link: &dyn LinkRegistry,
1251    warnings: &mut Vec<crate::fkc::ImportWarning>,
1252) -> Result<Vec<Resolved>, FkcError> {
1253    let provider = &file.front_matter.provider;
1254    let defaults = Defaults {
1255        backend: provider.backend.as_str(),
1256        kernel_source: provider.kernel_source.as_str(),
1257        revision_base: provider.revision_base.as_deref().unwrap_or(""),
1258    };
1259    // Each registrable section lowers to ONE-OR-MORE Resolved records (a
1260    // primitive section fans out over its dtype variants, §3.4); flatten them
1261    // into the provider's flat list.
1262    let mut out = Vec::new();
1263    for kernel in file.kernels.iter().filter(|k| k.registrable) {
1264        // §3.10: describe-only documentation sections are skipped above.
1265        out.extend(lower_kernel(kernel, &defaults, link, warnings)?);
1266    }
1267    Ok(out)
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use super::*;
1273    use crate::fkc::parse_file;
1274    use std::sync::{Arc, RwLock};
1275
1276    const ELEMENTWISE_BINARY: &str =
1277        include_str!("../../kernel-contracts/cpu/elementwise-binary.fkc.md");
1278    const QUANT_MATMUL: &str = include_str!("../../kernel-contracts/cpu/quant-matmul.fkc.md");
1279    /// A real FUSED contract bundle whose `fused_op: SOFTMAX_LAST_DIM` etc.
1280    /// must now resolve through the SCREAMING_SNAKE constant table (Task 1).
1281    const FUSED_NORM_SOFTMAX: &str =
1282        include_str!("../../kernel-contracts/fused/norm-softmax.fkc.md");
1283
1284    // ---- KISS-CLASSIFY §6.1 reserved vocabulary: reserved != unknown ----
1285
1286    /// At the FKC parse site — a real ingest surface, since contract files are
1287    /// external and hand-authored — a reserved spelling declines **matchably
1288    /// differently** from an unknown one. Deleting the `ReservedScalarType`
1289    /// arm in `lower_dtype` makes this fail; that is the born-red evidence for
1290    /// this half of GAP-155.
1291    #[test]
1292    fn a_reserved_dtype_token_declines_distinctly_from_an_unknown_one() {
1293        let reserved = lower_dtype("F8E4M3FNUZ", "sec", "lhs").expect_err("must not lower");
1294        assert!(
1295            matches!(reserved, FkcError::ReservedScalarType { .. }),
1296            "a §6.1-reserved token must decline AS reserved, not as a bad token \
1297             — a contract author told 'bad dtype token' goes hunting for a typo \
1298             that does not exist; got {reserved:?}",
1299        );
1300
1301        // The other side. Without this, collapsing EVERYTHING into
1302        // ReservedScalarType would pass the assertion above.
1303        let unknown = lower_dtype("NOT_A_DTYPE", "sec", "lhs").expect_err("must not lower");
1304        assert!(
1305            matches!(unknown, FkcError::BadScalarType { .. }),
1306            "an unknown token must stay BadScalarType; got {unknown:?}",
1307        );
1308    }
1309
1310    /// Binds this site to `fuel-ir`'s list rather than to a copy of it. If
1311    /// someone adds a token to `RESERVED_DTYPE_TOKENS` and this site keeps a
1312    /// private list, the new token silently reverts to "unknown" here — a
1313    /// drift that no other test would notice.
1314    #[test]
1315    fn every_shared_reserved_token_declines_as_reserved_at_this_site() {
1316        for tok in fuel_ir::RESERVED_DTYPE_TOKENS {
1317            // FKC spells dtype tokens uppercase; the shared list is canonical
1318            // lowercase. That mismatch is exactly why the lookup is
1319            // case-insensitive, so exercise the FKC spelling here.
1320            let upper = tok.to_ascii_uppercase();
1321            let err = lower_dtype(&upper, "sec", "lhs")
1322                .expect_err("a reserved token must never lower to a DType");
1323            assert!(
1324                matches!(err, FkcError::ReservedScalarType { .. }),
1325                "{upper} is in RESERVED_DTYPE_TOKENS but declined as {err:?} — this \
1326                 site has drifted from the shared list",
1327            );
1328        }
1329        // Non-vacuity: an empty list would pass the loop above silently.
1330        assert!(!fuel_ir::RESERVED_DTYPE_TOKENS.is_empty());
1331    }
1332
1333    /// The delimiter trap. Every supported FP8 token is a PREFIX of a reserved
1334    /// one (`F8E5M2` / `F8E5M2FNUZ`), so a `starts_with`-style classifier would
1335    /// accept the reserved token AS the supported one. That failure is silent:
1336    /// `fnuz` uses a different exponent bias, so the same bytes decode to
1337    /// different numbers and the kernel returns wrong answers rather than an
1338    /// error.
1339    #[test]
1340    fn a_reserved_token_is_not_accepted_as_the_token_it_extends() {
1341        assert!(
1342            !matches!(lower_dtype("F8E5M2FNUZ", "sec", "lhs"), Ok(DType::F8E5M2)),
1343            "F8E5M2FNUZ must not lower to its OCP prefix F8E5M2",
1344        );
1345        assert!(
1346            !matches!(lower_dtype("F8E4M3FNUZ", "sec", "lhs"), Ok(DType::F8E4M3)),
1347            "F8E4M3FNUZ must not lower to its OCP prefix F8E4M3",
1348        );
1349        // Non-vacuity, both ways: the prefixes really are accepted tokens here
1350        // (so the pairs above are genuine traps), and the reserved forms really
1351        // do extend them.
1352        assert_eq!(lower_dtype("F8E5M2", "sec", "lhs").unwrap(), DType::F8E5M2);
1353        assert_eq!(lower_dtype("F8E4M3", "sec", "lhs").unwrap(), DType::F8E4M3);
1354        assert!(
1355            fuel_ir::RESERVED_DTYPE_TOKENS
1356                .iter()
1357                .any(|t| t.eq_ignore_ascii_case("F8E5M2FNUZ")),
1358        );
1359    }
1360
1361    // ---- A test LinkRegistry stub mapping every entry_point to a dummy ----
1362
1363    fn dummy_kernel(
1364        _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
1365        _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
1366        _layouts: &[fuel_ir::Layout],
1367        _params: &crate::kernel::OpParams,
1368    ) -> fuel_ir::Result<()> {
1369        Ok(())
1370    }
1371
1372    struct StubLink;
1373    impl LinkRegistry for StubLink {
1374        fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
1375            Some(dummy_kernel)
1376        }
1377        fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
1378            Some(dummy_kernel)
1379        }
1380    }
1381
1382    /// A stub that resolves nothing (for the UnknownEntryPoint negative).
1383    struct EmptyLink;
1384    impl LinkRegistry for EmptyLink {
1385        fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
1386            None
1387        }
1388        fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
1389            None
1390        }
1391    }
1392
1393    /// Lower every dtype variant of one section (a primitive fans out; a
1394    /// fused section yields one).
1395    fn lower_all(src: &str, kernel_name: &str) -> Result<Vec<Resolved>, FkcError> {
1396        let file = parse_file(src).expect("parses");
1397        let provider = &file.front_matter.provider;
1398        let defaults = Defaults {
1399            backend: provider.backend.as_str(),
1400            kernel_source: provider.kernel_source.as_str(),
1401            revision_base: provider.revision_base.as_deref().unwrap_or(""),
1402        };
1403        let kernel = file
1404            .kernels
1405            .iter()
1406            .find(|k| k.kernel == kernel_name)
1407            .unwrap_or_else(|| panic!("kernel {kernel_name} present"));
1408        lower_kernel(kernel, &defaults, &StubLink, &mut Vec::new())
1409    }
1410
1411    /// The first (representative) variant of a section — convenience for the
1412    /// single-variant positive tests.
1413    fn lower_one(src: &str, kernel_name: &str) -> Result<Resolved, FkcError> {
1414        Ok(lower_all(src, kernel_name)?
1415            .into_iter()
1416            .next()
1417            .expect("a section lowers to ≥1 variant"))
1418    }
1419
1420    // =====================================================================
1421    // POSITIVE: real contracts lower
1422    // =====================================================================
1423
1424    #[test]
1425    fn lowers_real_add_f32() {
1426        let r = lower_one(ELEMENTWISE_BINARY, "add_f32").expect("add_f32 lowers");
1427        let Resolved::Primitive(p) = r else {
1428            panic!("add_f32 is a primitive");
1429        };
1430        assert_eq!(p.op, OpKind::AddElementwise);
1431        // inputs lhs, rhs (F32, F32) then output (passthrough → F32).
1432        assert_eq!(p.dtypes.as_slice(), &[DType::F32, DType::F32, DType::F32]);
1433        assert_eq!(p.backend, BackendId::Cpu);
1434        // contiguous-only contract ⇒ strided_input false.
1435        assert!(!p.caps.strided_input);
1436        // precision mapped (bit-stable, ulp 0).
1437        assert!(p.precision.bit_stable_on_same_hardware);
1438        assert_eq!(p.precision.max_ulp, Some(0));
1439        // a non-null KernelRef.
1440        assert_eq!(
1441            p.kernel as *const () as usize,
1442            dummy_kernel as *const () as usize
1443        );
1444        // cost: flops = "n" parsed (not Unknown) AND the contract's declared
1445        // `bytes_moved` is held beside it (GAP-376), not dropped.
1446        assert!(matches!(
1447            p.cost,
1448            CompiledCostExpr::Declared {
1449                flops: Some(_),
1450                bytes_moved: Some(_),
1451                ..
1452            }
1453        ));
1454        assert_eq!(p.kernel_source, "portable-cpu");
1455    }
1456
1457    #[test]
1458    fn lowers_binary_chassis_section_fans_out_over_all_dtypes() {
1459        // The umbrella `binary` section has two operands both enumerating
1460        // [F32,F64,BF16,F16] (a UNIFORM multi-dtype section), so it FANS OUT
1461        // into one binding per dtype (§3.4) — not a single first-dtype
1462        // representative. `passthrough(lhs)` mirrors lhs at each variant.
1463        let all = lower_all(ELEMENTWISE_BINARY, "binary").expect("binary lowers");
1464        assert_eq!(all.len(), 4, "4 dtypes ⇒ 4 fanned variants");
1465        let keys: Vec<Vec<DType>> = all
1466            .iter()
1467            .map(|r| {
1468                let Resolved::Primitive(p) = r else {
1469                    panic!("binary is a primitive")
1470                };
1471                assert_eq!(p.op, OpKind::AddElementwise);
1472                p.dtypes.to_vec()
1473            })
1474            .collect();
1475        assert_eq!(
1476            keys,
1477            vec![
1478                vec![DType::F32, DType::F32, DType::F32],
1479                vec![DType::F64, DType::F64, DType::F64],
1480                vec![DType::BF16, DType::BF16, DType::BF16],
1481                vec![DType::F16, DType::F16, DType::F16],
1482            ],
1483            "each variant keys on [lhs, rhs, out(passthrough lhs)] at that dtype"
1484        );
1485    }
1486
1487    #[test]
1488    fn lowers_real_qmatmul_q4_0() {
1489        let r = lower_one(QUANT_MATMUL, "qmatmul_q4_0_f32").expect("q4_0 lowers");
1490        let Resolved::Primitive(p) = r else {
1491            panic!("QMatMul is a primitive")
1492        };
1493        assert_eq!(p.op, OpKind::QMatMul);
1494        // activations F32, weight U8, output fixed(F32).
1495        assert_eq!(p.dtypes.as_slice(), &[DType::F32, DType::U8, DType::F32]);
1496        assert_eq!(p.backend, BackendId::Cpu);
1497        // judge_measured with all-`~` coefficients ⇒ Unknown cost sentinel.
1498        assert_eq!(p.cost, CompiledCostExpr::Unknown);
1499        assert!(p.precision.bit_stable_on_same_hardware);
1500    }
1501
1502    #[test]
1503    fn lowers_real_nf4_matmul_f32() {
1504        // NF4 reaches the dedicated OpKind::Nf4Matmul path → it LOWERS in
1505        // this slice (the AFFINE_BLOCK / MxNotYetRegistrable gate is a
1506        // register-slice concern; lowering produces a typed record).
1507        let r = lower_one(QUANT_MATMUL, "nf4_matmul_f32").expect("nf4 lowers");
1508        let Resolved::Primitive(p) = r else { panic!() };
1509        assert_eq!(p.op, OpKind::Nf4Matmul);
1510        // activations F32, w_packed U8, absmax F32, output passthrough → F32.
1511        assert_eq!(
1512            p.dtypes.as_slice(),
1513            &[DType::F32, DType::U8, DType::F32, DType::F32]
1514        );
1515    }
1516
1517    #[test]
1518    fn lower_file_lowers_every_kernel() {
1519        let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
1520        let resolved = lower_file(&file, &StubLink, &mut Vec::new()).expect("all lower");
1521        // Every *registrable* section lowers; describe-only sections (§3.10,
1522        // e.g. the shared `binary` chassis umbrella) are filtered out first.
1523        let registrable = file.kernels.iter().filter(|k| k.registrable).count();
1524        assert_eq!(resolved.len(), registrable);
1525    }
1526
1527    #[test]
1528    fn cost_trampoline_evaluates_matmul_declared_flops() {
1529        // The matmul contract declares `flops: "2 * batch * m * n * k"`. Lower it
1530        // (StubLink resolves entry_points to dummies — we only need the parsed
1531        // cost AST), then run that AST through the cost trampoline for a
1532        // 2×(3×4×5) batched matmul → 2·2·3·4·5 = 240 flops. This is what FKC
1533        // import previously dropped in favor of the `unknown_cost` sentinel.
1534        const MATMUL: &str = include_str!("../../kernel-contracts/cpu/matmul.fkc.md");
1535        let file = parse_file(MATMUL).expect("matmul contract parses");
1536        let resolved =
1537            lower_file(&file, &StubLink, &mut Vec::new()).expect("matmul contract lowers");
1538        let prim = resolved
1539            .iter()
1540            .find_map(|r| match r {
1541                Resolved::Primitive(p) if p.op == OpKind::MatMul => Some(p),
1542                _ => None,
1543            })
1544            .expect("a MatMul primitive in the matmul contract");
1545        let params = crate::kernel::OpParams::Matmul {
1546            lhs_batch_dims: vec![2],
1547            rhs_batch_dims: vec![2],
1548            m: 3,
1549            n: 4,
1550            k: 5,
1551            m_compute: crate::kernel::MatmulM::All,
1552        };
1553        let est = crate::fkc::cost_estimate(
1554            &prim.cost,
1555            OpKind::MatMul,
1556            &[],
1557            &[DType::F32, DType::F32, DType::F32],
1558            &params,
1559        )
1560        .expect("declared matmul cost evaluates");
1561        assert_eq!(est.flops, 240, "2 * batch(2) * m(3) * n(4) * k(5) = 240");
1562    }
1563
1564    /// Task 1 end-to-end verification: a REAL fused contract from the corpus
1565    /// (`fused/norm-softmax.fkc.md`, `fused_op: SOFTMAX_LAST_DIM`) lowers via
1566    /// the stub link — proving the SCREAMING_SNAKE token now resolves.
1567    #[test]
1568    fn lowers_real_fused_softmax_last_dim() {
1569        let r = lower_one(FUSED_NORM_SOFTMAX, "softmax_last_dim")
1570            .expect("softmax_last_dim (fused) lowers");
1571        let Resolved::Fused(f) = r else {
1572            panic!("softmax_last_dim is a fused op");
1573        };
1574        assert_eq!(f.id, FusedOps::SOFTMAX_LAST_DIM);
1575        assert_eq!(f.backend, BackendId::Cpu);
1576        assert_eq!(f.kernel_source, "portable-cpu");
1577
1578        // The whole bundle lowers (every fused_op token resolves). Each of the
1579        // 8 `fused_op` sections enumerates `dtypes: [F32, F64, BF16, F16]` and
1580        // now FANS into one `ResolvedFused` per dtype (§3.4 fused dtype-fan), so
1581        // the lowered set is 8 sections × 4 dtypes = 32 (was 8 pre-fan, when
1582        // `lower_fused` took only the representative first variant).
1583        let file = parse_file(FUSED_NORM_SOFTMAX).expect("parses");
1584        let resolved =
1585            lower_file(&file, &StubLink, &mut Vec::new()).expect("all fused kernels lower");
1586        assert_eq!(
1587            resolved.len(),
1588            file.kernels.len() * 4,
1589            "each fused section fans over its 4 dtypes (8 sections × 4 = 32)",
1590        );
1591        assert!(resolved.iter().all(|r| matches!(r, Resolved::Fused(_))));
1592    }
1593
1594    // =====================================================================
1595    // FUSED dtype-fan (§3.4): a multi-dtype `fused_op` section fans into N
1596    // per-dtype ResolvedFused (mirroring the primitive fan-out), each keyed
1597    // on its own dtype tuple; a single-dtype fused section yields exactly one.
1598    // =====================================================================
1599
1600    /// A synthetic FUSED bundle exercising the fused dtype-fan. `fanned_softmax`
1601    /// declares `fused_op: SOFTMAX_LAST_DIM`, a BASE `entry_point`, and its input
1602    /// `x` enumerates `[F32, F64, BF16, F16]` — so it must fan into 4 per-dtype
1603    /// `ResolvedFused` (keys `[T, T]`), each resolving `<base>_<dt>`.
1604    /// `single_norm` is the backward-compat guard: a single-dtype (F32-only)
1605    /// section → EXACTLY ONE `ResolvedFused`, its declared symbol resolved AS-IS.
1606    const FUSED_FANOUT_SYNTH: &str = r#"---
1607fkc_version: 1
1608provider:
1609  name: test-provider
1610  backend: Cpu
1611  kernel_source: "test-cpu"
1612---
1613
1614# fused dtype-fan synthetic
1615
1616## fanned_softmax
1617
1618A blurb.
1619
1620```fkc
1621kernel: fanned_softmax
1622fused_op: SOFTMAX_LAST_DIM
1623blurb: "synthetic multi-dtype fused softmax"
1624entry_point: "x::softmax_cpu"
1625accept:
1626  inputs:
1627    - name: x
1628      dtypes: [F32, F64, BF16, F16]
1629return:
1630  outputs:
1631    - name: out
1632      dtype_rule: passthrough(x)
1633```
1634
1635## single_norm
1636
1637A blurb.
1638
1639```fkc
1640kernel: single_norm
1641fused_op: RMS_NORM_LAST_DIM
1642blurb: "synthetic single-dtype fused rms-norm"
1643entry_point: "x::rms_norm_f32_cpu"
1644accept:
1645  inputs:
1646    - name: x
1647      dtypes: [F32]
1648return:
1649  outputs:
1650    - name: out
1651      dtype_rule: passthrough(x)
1652```
1653"#;
1654
1655    #[test]
1656    fn fused_multi_dtype_section_fans_into_per_dtype_resolved_fused() {
1657        // BORN-RED → GREEN: `fanned_softmax` (input `x` over 4 dtypes, BASE
1658        // entry_point) must fan into 4 `ResolvedFused` — one per dtype — each
1659        // keyed `[dt, dt]`. Pre-change `lower_fused` took only the representative
1660        // (first) variant → 1 record (RED); the fan yields 4 (GREEN).
1661        let all = lower_all(FUSED_FANOUT_SYNTH, "fanned_softmax").expect("fanned_softmax lowers");
1662        assert_eq!(
1663            all.len(),
1664            4,
1665            "4 dtypes ⇒ 4 fanned ResolvedFused (pre-change: 1 representative only)",
1666        );
1667        let keys: Vec<Vec<DType>> = all
1668            .iter()
1669            .map(|r| {
1670                let Resolved::Fused(f) = r else {
1671                    panic!("fanned_softmax is a fused op")
1672                };
1673                assert_eq!(f.id, FusedOps::SOFTMAX_LAST_DIM);
1674                assert_eq!(f.backend, BackendId::Cpu);
1675                f.dtypes.to_vec()
1676            })
1677            .collect();
1678        assert_eq!(
1679            keys,
1680            vec![
1681                vec![DType::F32, DType::F32],
1682                vec![DType::F64, DType::F64],
1683                vec![DType::BF16, DType::BF16],
1684                vec![DType::F16, DType::F16],
1685            ],
1686            "each variant keys on [x, out(passthrough x)] at that dtype",
1687        );
1688    }
1689
1690    #[test]
1691    fn fused_single_dtype_section_yields_exactly_one_resolved_fused() {
1692        // Backward-compat hard gate: a single-dtype fused section produces
1693        // EXACTLY ONE `ResolvedFused`, byte-identical to today (its declared
1694        // `entry_point` resolves AS-IS — no `_<suffix>` appended).
1695        let all = lower_all(FUSED_FANOUT_SYNTH, "single_norm").expect("single_norm lowers");
1696        assert_eq!(
1697            all.len(),
1698            1,
1699            "single-dtype fused section ⇒ exactly one ResolvedFused"
1700        );
1701        let Resolved::Fused(f) = &all[0] else {
1702            panic!("single_norm is a fused op");
1703        };
1704        assert_eq!(f.id, FusedOps::RMS_NORM_LAST_DIM);
1705        assert_eq!(f.dtypes.as_slice(), &[DType::F32, DType::F32]);
1706    }
1707
1708    // =====================================================================
1709    // return.bundle key derivation (§5.5 Option C multi-output)
1710    // =====================================================================
1711
1712    /// A synthetic contract exercising the `return.bundle` key-derivation gap.
1713    /// `bundle_op` has TWO inputs (`a`, `b`) and a `return.bundle` (Option C
1714    /// multi-output: one packed buffer) whose PRIMARY slot mirrors input `a`
1715    /// (`passthrough(a)` → F32) and NO `return.outputs` — so its binding key
1716    /// must be `[a, b, out] = [F32; 3]` (N+1 slots). The importer previously
1717    /// read `return.outputs` ONLY, so a bundle-only section produced the N-slot
1718    /// short key `[F32, F32]` (missing the bundled output slot) — exactly why
1719    /// the `selective_scan_*` / `ssd_chunk_scan_*` families were deferred.
1720    /// `plain_op` is the no-bundle backward-compat guard: TWO inputs + a regular
1721    /// `return.outputs`, key `[F32, F32, F32]` (unchanged).
1722    /// A `dtype_rule: passthrough(<role>)` naming the LAST input when that
1723    /// input is OPTIONAL. Rejected: with the optional operand absent there is
1724    /// no operand to take a dtype from, so the output dtype would be
1725    /// unresolvable in exactly one arm of the {absent, present} fan.
1726    const PASSTHROUGH_OPTIONAL_SYNTH: &str = r#"---
1727fkc_version: 1
1728provider:
1729  name: test-provider
1730  backend: Cpu
1731  kernel_source: "test-cpu"
1732---
1733
1734# passthrough-names-optional synthetic
1735
1736## bad_passthrough
1737
1738A blurb.
1739
1740```fkc
1741kernel: bad_passthrough
1742op_kind: AddElementwise
1743blurb: "output passthrough names the optional last operand"
1744entry_point: "x::add_cpu"
1745accept:
1746  inputs:
1747    - name: x
1748      dtypes: [F32]
1749    - name: bias
1750      dtypes: [F32]
1751      optional: true
1752return:
1753  outputs:
1754    - name: out
1755      dtype_rule: passthrough(bias)
1756```
1757"#;
1758
1759    /// GAP-036: closes a clause that the derived clause->test coverage gate
1760    /// (`tests/fkc_clause_coverage.rs`) found unreachable by any test.
1761    ///
1762    /// `FkcError::PassthroughNamesOptionalOperand` was constructed on a live
1763    /// production path (`resolve_output_slot_dtype`) yet nothing proved that
1764    /// path was reachable — the "existence != enforcement" shape. The gate
1765    /// flagged it; this is the provoking test.
1766    ///
1767    /// The positive control is the `bias`-vs-`x` contrast: the SAME contract
1768    /// with `passthrough(x)` must lower cleanly. Without it this test would
1769    /// still pass if the contract were malformed for some unrelated reason and
1770    /// every lowering failed — it would be asserting "an error happened",
1771    /// not "THIS rule fired".
1772    #[test]
1773    fn passthrough_naming_the_optional_last_operand_is_rejected() {
1774        let err = lower_all(PASSTHROUGH_OPTIONAL_SYNTH, "bad_passthrough")
1775            .expect_err("passthrough(bias) names the optional last operand");
1776        match err {
1777            FkcError::PassthroughNamesOptionalOperand { ref role, .. } => {
1778                assert_eq!(role, "bias", "the rejected role is the optional operand");
1779            }
1780            other => panic!("expected PassthroughNamesOptionalOperand, got {other:?}"),
1781        }
1782
1783        // POSITIVE CONTROL: the identical contract passing through the REQUIRED
1784        // operand lowers. Proves the rejection above is caused by the operand
1785        // being optional, not by the fixture being broken.
1786        let ok = PASSTHROUGH_OPTIONAL_SYNTH.replace("passthrough(bias)", "passthrough(x)");
1787        lower_all(&ok, "bad_passthrough")
1788            .expect("passthrough(x) names a REQUIRED operand and must lower cleanly");
1789    }
1790
1791    const BUNDLE_SYNTH: &str = r#"---
1792fkc_version: 1
1793provider:
1794  name: test-provider
1795  backend: Cpu
1796  kernel_source: "test-cpu"
1797---
1798
1799# bundle key-derivation synthetic
1800
1801## bundle_op
1802
1803A blurb.
1804
1805```fkc
1806kernel: bundle_op
1807op_kind: SelectiveScan
1808blurb: "synthetic multi-output bundle op"
1809entry_point: "x::bundle_op"
1810accept:
1811  inputs:
1812    - name: a
1813      dtypes: [F32]
1814    - name: b
1815      dtypes: [F32]
1816return:
1817  bundle:
1818    - { name: y,  dtype_rule: passthrough(a), shape_rule: same_as(a), layout_guarantee: contiguous }
1819    - { name: st, dtype_rule: passthrough(a), shape_rule: same_as(a), layout_guarantee: contiguous }
1820```
1821
1822## plain_op
1823
1824A blurb.
1825
1826```fkc
1827kernel: plain_op
1828op_kind: AddElementwise
1829blurb: "synthetic no-bundle op"
1830entry_point: "x::plain_op"
1831accept:
1832  inputs:
1833    - name: a
1834      dtypes: [F32]
1835    - name: b
1836      dtypes: [F32]
1837return:
1838  outputs:
1839    - name: out
1840      dtype_rule: passthrough(a)
1841```
1842"#;
1843
1844    #[test]
1845    fn return_bundle_appends_primary_output_slot_to_key() {
1846        // A `return.bundle` (Option C multi-output, one packed buffer) must
1847        // contribute its PRIMARY slot's dtype to the binding key tail — so a
1848        // bundle-only section with N inputs keys `[in.., out] = N+1 slots`, NOT
1849        // the N-slot short key the importer built when it read `return.outputs`
1850        // only. The primary slot mirrors input `a` (`passthrough(a)` → F32).
1851        let r = lower_one(BUNDLE_SYNTH, "bundle_op").expect("bundle_op lowers");
1852        let Resolved::Primitive(p) = r else {
1853            panic!("bundle_op is a primitive");
1854        };
1855        assert_eq!(
1856            p.dtypes.as_slice(),
1857            &[DType::F32, DType::F32, DType::F32],
1858            "a `return.bundle` must append its primary output slot to the key \
1859             (2 inputs + 1 bundle out = 3); the importer previously built the \
1860             2-slot short key `[F32, F32]` from `return.outputs` only",
1861        );
1862    }
1863
1864    #[test]
1865    fn no_bundle_section_key_is_unchanged() {
1866        // Backward-compat guard: a section WITHOUT a `return.bundle` is
1867        // byte-identical to today — 2 inputs + 1 regular `passthrough(a)`
1868        // output = `[F32; 3]`, with NO phantom bundle slot appended.
1869        let r = lower_one(BUNDLE_SYNTH, "plain_op").expect("plain_op lowers");
1870        let Resolved::Primitive(p) = r else {
1871            panic!("plain_op is a primitive");
1872        };
1873        assert_eq!(
1874            p.dtypes.as_slice(),
1875            &[DType::F32, DType::F32, DType::F32],
1876            "a no-bundle section keys on inputs + regular outputs only",
1877        );
1878    }
1879
1880    // =====================================================================
1881    // variant: retained opaque tag (Baracuda `variant:`)
1882    // =====================================================================
1883
1884    /// A synthetic contract whose primitive section declares an opaque
1885    /// specialization `variant:` tag, plus a sibling section that omits it (the
1886    /// backward-compat `None` guard). The tag is a top-level per-kernel field
1887    /// (NOT `accept.op_params.variant`, which names the `OpParams` Rust
1888    /// variant) and must survive lowering onto `ResolvedPrimitive.variant`
1889    /// verbatim.
1890    const VARIANT_SYNTH: &str = r#"---
1891fkc_version: 1
1892provider:
1893  name: test-provider
1894  backend: Cpu
1895  kernel_source: "test-cpu"
1896---
1897
1898# variant retention synthetic
1899
1900## tagged_op
1901
1902A blurb.
1903
1904```fkc
1905kernel: tagged_op
1906op_kind: MatMul
1907blurb: "synthetic split-K partial variant"
1908entry_point: "x::tagged_op"
1909variant: "splitk_partial"
1910accept:
1911  inputs:
1912    - name: lhs
1913      dtypes: [F32]
1914    - name: rhs
1915      dtypes: [F32]
1916return:
1917  outputs:
1918    - name: out
1919      dtype_rule: fixed(F32)
1920```
1921
1922## untagged_op
1923
1924A blurb.
1925
1926```fkc
1927kernel: untagged_op
1928op_kind: MatMul
1929blurb: "synthetic no-variant op"
1930entry_point: "x::untagged_op"
1931accept:
1932  inputs:
1933    - name: lhs
1934      dtypes: [F32]
1935    - name: rhs
1936      dtypes: [F32]
1937return:
1938  outputs:
1939    - name: out
1940      dtype_rule: fixed(F32)
1941```
1942"#;
1943
1944    #[test]
1945    fn variant_tag_is_retained_on_resolved_primitive() {
1946        // A contract-declared `variant:` tag must ride verbatim onto the
1947        // lowered record so it can reach the (later) records / ImplId emission
1948        // step. RED before the wiring: the tag is dropped (retained `None`);
1949        // GREEN once `lower_primitive` clones `kernel.variant`.
1950        let r = lower_one(VARIANT_SYNTH, "tagged_op").expect("tagged_op lowers");
1951        let Resolved::Primitive(p) = r else {
1952            panic!("tagged_op is a primitive");
1953        };
1954        assert_eq!(
1955            p.variant.as_deref(),
1956            Some("splitk_partial"),
1957            "the opaque `variant:` tag must survive lowering onto \
1958             ResolvedPrimitive.variant (it was dropped)",
1959        );
1960    }
1961
1962    #[test]
1963    fn no_variant_section_retains_none() {
1964        // Backward-compat guard: a section that omits `variant:` lowers with
1965        // `variant: None` (every existing contract is unaffected, additive §11).
1966        let r = lower_one(VARIANT_SYNTH, "untagged_op").expect("untagged_op lowers");
1967        let Resolved::Primitive(p) = r else {
1968            panic!("untagged_op is a primitive");
1969        };
1970        assert_eq!(p.variant, None, "a section without `variant:` retains None");
1971    }
1972
1973    // =====================================================================
1974    // NEGATIVES
1975    // =====================================================================
1976
1977    #[test]
1978    fn bogus_op_kind_is_unknown_op_kind() {
1979        let err = lower_op_kind("NotARealOp", "k").expect_err("bogus op");
1980        assert!(matches!(err, FkcError::UnknownOpKind { .. }), "got {err:?}");
1981    }
1982
1983    #[test]
1984    fn bogus_dtype_is_bad_scalar_type() {
1985        let err = lower_dtype("F99", "k", "lhs").expect_err("bogus dtype");
1986        assert!(matches!(err, FkcError::BadScalarType { .. }), "got {err:?}");
1987    }
1988
1989    /// DRIFT GUARD (§3.4 fan-out): the `DType → FKC dtype suffix` spelling
1990    /// used to build a fanning section's `<entry_point>_<suffix>` symbol must
1991    /// stay the exact INVERSE of `lower_dtype` — i.e. uppercasing the suffix
1992    /// round-trips back to the same `DType`. This locks `dtype_suffix`
1993    /// (`DType::as_str`, the `ep!`/byte-kernel convention) to the token table
1994    /// so the two cannot drift into a second spelling.
1995    #[test]
1996    fn dtype_suffix_is_the_inverse_of_lower_dtype() {
1997        for dt in [
1998            DType::U8,
1999            DType::I8,
2000            DType::U32,
2001            DType::I16,
2002            DType::I32,
2003            DType::I64,
2004            DType::BF16,
2005            DType::F16,
2006            DType::F32,
2007            DType::F64,
2008            DType::F8E4M3,
2009            DType::F6E2M3,
2010            DType::F6E3M2,
2011            DType::F4,
2012            DType::F8E8M0,
2013            DType::F8E6M2,
2014        ] {
2015            let suffix = super::dtype_suffix(dt);
2016            let token = suffix.to_uppercase();
2017            assert_eq!(
2018                super::lower_dtype(&token, "k", "op").expect("round-trips"),
2019                dt,
2020                "suffix {suffix:?} (token {token:?}) must lower back to {dt:?}",
2021            );
2022        }
2023    }
2024
2025    #[test]
2026    fn bogus_fused_op_is_unknown_fused_op() {
2027        let err = lower_fused_op("NotAFusedOp", "k").expect_err("bogus fused");
2028        assert!(
2029            matches!(err, FkcError::UnknownFusedOp { .. }),
2030            "got {err:?}"
2031        );
2032    }
2033
2034    #[test]
2035    fn screaming_snake_const_name_resolves_not_pascalcase() {
2036        // The contract token is the SCREAMING_SNAKE FusedOps constant name.
2037        assert_eq!(
2038            lower_fused_op("SOFTMAX_LAST_DIM", "k").unwrap(),
2039            FusedOps::SOFTMAX_LAST_DIM
2040        );
2041        assert_eq!(
2042            lower_fused_op("FLASH_ATTN", "k").unwrap(),
2043            FusedOps::FLASH_ATTN
2044        );
2045        assert_eq!(lower_fused_op("QMATMUL", "k").unwrap(), FusedOps::QMATMUL);
2046        // The PascalCase registry `name` (what the OLD id_for_name resolver
2047        // matched) must NOT resolve — that was the bug.
2048        assert!(lower_fused_op("SoftmaxLastDim", "k").is_err());
2049        assert!(lower_fused_op("FlashAttn", "k").is_err());
2050    }
2051
2052    /// DRIFT GUARD (Task 1): every `FusedOpId` present in `default_registry()`
2053    /// must be reachable through the SCREAMING_SNAKE constant-name table — so
2054    /// adding a new `FusedOps` const + registry entry without a table arm
2055    /// fails this test (it would otherwise be silently unimportable).
2056    #[test]
2057    fn every_registry_id_is_reachable_through_table() {
2058        use std::collections::HashSet;
2059        // Every id the constant-name table can produce.
2060        let reachable: HashSet<FusedOpId> = [
2061            "SOFTMAX_LAST_DIM",
2062            "FUSED_LINEAR",
2063            "RMS_NORM_LAST_DIM",
2064            "LAYER_NORM_LAST_DIM",
2065            "ROPE",
2066            "CONV2D",
2067            "SOFTMAX_LAST_DIM_BACKWARD",
2068            "LAYER_NORM_LAST_DIM_BACKWARD",
2069            "RMS_NORM_LAST_DIM_BACKWARD",
2070            "REDUCE_MAX_TO_BACKWARD",
2071            "CONV_TRANSPOSE2D",
2072            "FLASH_ATTN",
2073            "PAGED_ATTN",
2074            "QMATMUL",
2075            "POWI_BACKWARD",
2076            "INPLACE_AFFINE",
2077            "FUSED_SOFTMAX_CROSS_ENTROPY",
2078            "CAUSAL_CONV1D",
2079            "SELECTIVE_SCAN",
2080            "SSD_CHUNK_SCAN",
2081            "NF4_MATMUL",
2082            "FLASH_ATTN_BACKWARD_Q",
2083            "FLASH_ATTN_BACKWARD_K",
2084            "FLASH_ATTN_BACKWARD_V",
2085            "AWQ_MATMUL",
2086        ]
2087        .iter()
2088        .map(|n| super::fused_op_id_for_const_name(n).expect("table arm exists"))
2089        .collect();
2090
2091        // Every registered id MUST be in `reachable`.
2092        for entry in fuel_graph::registry::default_registry().entries_iter() {
2093            assert!(
2094                reachable.contains(&entry.id),
2095                "FusedOpId {:?} (registry name {:?}) is registered but NOT reachable through the \
2096                 SCREAMING_SNAKE constant-name table — add a `fused_op_id_for_const_name` arm",
2097                entry.id,
2098                entry.name,
2099            );
2100        }
2101    }
2102
2103    #[test]
2104    fn bogus_backend_is_unknown_backend() {
2105        let err = lower_backend("Tpu", "k").expect_err("bogus backend");
2106        assert!(
2107            matches!(err, FkcError::UnknownBackend { .. }),
2108            "got {err:?}"
2109        );
2110    }
2111
2112    #[test]
2113    fn unknown_entry_point_errors() {
2114        let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
2115        let provider = &file.front_matter.provider;
2116        let defaults = Defaults {
2117            backend: provider.backend.as_str(),
2118            kernel_source: provider.kernel_source.as_str(),
2119            revision_base: provider.revision_base.as_deref().unwrap_or(""),
2120        };
2121        let kernel = file.kernels.iter().find(|k| k.kernel == "add_f32").unwrap();
2122        let err = lower_kernel(kernel, &defaults, &EmptyLink, &mut Vec::new())
2123            .expect_err("no entry point");
2124        assert!(
2125            matches!(err, FkcError::UnknownEntryPoint { .. }),
2126            "got {err:?}"
2127        );
2128    }
2129
2130    #[test]
2131    fn malformed_cost_expr_is_cost_expr_parse() {
2132        let mut block = CostBlock {
2133            provenance: Some("declared".into()),
2134            class: None,
2135            cost_fn: None,
2136            flops: Some("2 * * n".into()), // malformed
2137            bytes_moved: None,
2138            overhead_ns: None,
2139            memory: None,
2140        };
2141        let err = compile_cost(Some(&block), "k").expect_err("malformed flops");
2142        assert!(matches!(err, FkcError::CostExprParse { .. }), "got {err:?}");
2143
2144        // Also catch a malformed bytes_moved even when flops is fine.
2145        block.flops = Some("n".into());
2146        block.bytes_moved = Some("3 * n *".into());
2147        let err = compile_cost(Some(&block), "k").expect_err("malformed bytes_moved");
2148        assert!(matches!(err, FkcError::CostExprParse { field, .. } if field == "bytes_moved"));
2149    }
2150
2151    /// GAP-376: a declared `bytes_moved` must reach the `CostEstimate`.
2152    fn gap376_estimate(flops: Option<&str>, bytes: Option<&str>) -> crate::fused::CostEstimate {
2153        let block = CostBlock {
2154            provenance: Some("declared".into()),
2155            class: None,
2156            cost_fn: None,
2157            flops: flops.map(Into::into),
2158            bytes_moved: bytes.map(Into::into),
2159            overhead_ns: None,
2160            memory: None,
2161        };
2162        let expr = compile_cost(Some(&block), "k").expect("cost block compiles");
2163        let params = crate::kernel::OpParams::Matmul {
2164            lhs_batch_dims: vec![2],
2165            rhs_batch_dims: vec![2],
2166            m: 3,
2167            n: 4,
2168            k: 5,
2169            m_compute: crate::kernel::MatmulM::All,
2170        };
2171        crate::fkc::cost_estimate(
2172            &expr,
2173            OpKind::MatMul,
2174            &[],
2175            &[DType::F32, DType::F32, DType::F32],
2176            &params,
2177        )
2178        .expect("declared cost evaluates")
2179    }
2180
2181    #[test]
2182    fn declared_bytes_moved_reaches_the_cost_estimate() {
2183        // flops = 2 * n = 8; bytes_moved = 3 * n * dtype_bytes = 3 * 4 * 4 = 48.
2184        let est = gap376_estimate(Some("2 * n"), Some("3 * n * dtype_bytes"));
2185        assert_eq!(est.flops, 8, "flops expression still evaluates");
2186        assert_eq!(
2187            est.bytes_moved, 48,
2188            "GAP-376: declared bytes_moved was dropped"
2189        );
2190    }
2191
2192    #[test]
2193    fn bytes_only_block_does_not_read_bytes_as_flops() {
2194        // flops absent: the bytes formula must not be evaluated into `flops`.
2195        let est = gap376_estimate(None, Some("3 * n * dtype_bytes"));
2196        assert_eq!(est.flops, 0, "GAP-376: a bytes formula was read as flops");
2197        assert_eq!(est.bytes_moved, 48);
2198    }
2199
2200    #[test]
2201    fn flops_only_block_keeps_zero_bytes_moved() {
2202        // Sabotage sibling: absent bytes_moved stays 0, so the two tests
2203        // above cannot pass by filling bytes_moved unconditionally.
2204        let est = gap376_estimate(Some("2 * n"), None);
2205        assert_eq!(est.flops, 8);
2206        assert_eq!(est.bytes_moved, 0);
2207    }
2208
2209    /// GAP-382: a declared `overhead_ns` must reach the `CostEstimate`.
2210    fn gap382_estimate(
2211        flops: Option<&str>,
2212        bytes: Option<&str>,
2213        overhead: Option<serde_yaml_ng::Value>,
2214    ) -> crate::fused::CostEstimate {
2215        let block = CostBlock {
2216            provenance: Some("declared".into()),
2217            class: None,
2218            cost_fn: None,
2219            flops: flops.map(Into::into),
2220            bytes_moved: bytes.map(Into::into),
2221            overhead_ns: overhead,
2222            memory: None,
2223        };
2224        let expr = compile_cost(Some(&block), "k").expect("cost block compiles");
2225        let params = crate::kernel::OpParams::Matmul {
2226            lhs_batch_dims: vec![2],
2227            rhs_batch_dims: vec![2],
2228            m: 3,
2229            n: 4,
2230            k: 5,
2231            m_compute: crate::kernel::MatmulM::All,
2232        };
2233        crate::fkc::cost_estimate(
2234            &expr,
2235            OpKind::MatMul,
2236            &[],
2237            &[DType::F32, DType::F32, DType::F32],
2238            &params,
2239        )
2240        .expect("declared cost evaluates")
2241    }
2242
2243    fn num(v: u64) -> Option<serde_yaml_ng::Value> {
2244        Some(serde_yaml_ng::Value::Number(v.into()))
2245    }
2246
2247    #[test]
2248    fn declared_overhead_ns_number_reaches_the_cost_estimate() {
2249        // `overhead_ns: 40` beside flops "2 * n" (n = 4 -> 8).
2250        let est = gap382_estimate(Some("2 * n"), None, num(40));
2251        assert_eq!(est.flops, 8, "flops expression still evaluates");
2252        assert_eq!(
2253            est.kernel_overhead_ns, 40,
2254            "GAP-382: a declared overhead_ns was dropped"
2255        );
2256    }
2257
2258    #[test]
2259    fn overhead_only_block_reaches_the_cost_estimate() {
2260        // No flops, no bytes_moved: the block must not collapse to Unknown.
2261        let est = gap382_estimate(None, None, num(40));
2262        assert_eq!(
2263            est.kernel_overhead_ns, 40,
2264            "GAP-382: overhead-only block dropped"
2265        );
2266        assert_eq!(est.flops, 0);
2267        assert_eq!(est.bytes_moved, 0);
2268    }
2269
2270    #[test]
2271    fn overhead_ns_expression_string_is_evaluated() {
2272        // An expression STRING is evaluated like flops/bytes (n = 4 -> 40).
2273        let est = gap382_estimate(
2274            Some("n"),
2275            Some("3 * n"),
2276            Some(serde_yaml_ng::Value::String("n * 10".into())),
2277        );
2278        assert_eq!(
2279            est.kernel_overhead_ns, 40,
2280            "GAP-382: string overhead_ns dropped"
2281        );
2282        assert_eq!(est.flops, 4);
2283        assert_eq!(est.bytes_moved, 12, "GAP-376 bytes_moved is unaffected");
2284    }
2285
2286    #[test]
2287    fn absent_or_null_overhead_ns_stays_zero() {
2288        // Sabotage sibling: the tests above cannot pass by filling the field
2289        // unconditionally.
2290        let none = gap382_estimate(Some("2 * n"), Some("3 * n"), None);
2291        assert_eq!(none.kernel_overhead_ns, 0);
2292        let null = gap382_estimate(
2293            Some("2 * n"),
2294            Some("3 * n"),
2295            Some(serde_yaml_ng::Value::Null),
2296        );
2297        assert_eq!(null.kernel_overhead_ns, 0, "`~` means no declared overhead");
2298    }
2299
2300    #[test]
2301    fn a_real_contract_overhead_ns_reaches_the_cost_estimate() {
2302        // cpu/compare-where.fkc.md declares `overhead_ns: 40` beside
2303        // `flops: "n"`. Lower it and evaluate a primitive's cost at n = 8.
2304        const COMPARE_WHERE: &str = include_str!("../../kernel-contracts/cpu/compare-where.fkc.md");
2305        let file = parse_file(COMPARE_WHERE).expect("compare-where parses");
2306        let declared: Vec<u64> = file
2307            .kernels
2308            .iter()
2309            .filter_map(|k| k.cost.as_ref())
2310            .filter_map(|c| c.overhead_ns.as_ref())
2311            .filter_map(|v| v.as_u64())
2312            .collect();
2313        assert!(
2314            declared.contains(&40),
2315            "PRECONDITION: the contract declares overhead_ns: 40, got {declared:?}"
2316        );
2317        let resolved = lower_file(&file, &StubLink, &mut Vec::new()).expect("lowers");
2318        let prim = resolved
2319            .iter()
2320            .find_map(|r| match r {
2321                Resolved::Primitive(p) if p.op == OpKind::EqualElementwise => Some(p),
2322                _ => None,
2323            })
2324            .expect("an EqualElementwise primitive");
2325        let est = crate::fkc::cost_estimate(
2326            &prim.cost,
2327            prim.op,
2328            &[fuel_ir::Shape::from_dims(&[8])],
2329            &[DType::F32, DType::F32, DType::U8],
2330            &crate::kernel::OpParams::None,
2331        )
2332        .expect("declared compare cost evaluates");
2333        assert_eq!(est.flops, 8, "flops: \"n\" at n = 8");
2334        assert_eq!(
2335            est.kernel_overhead_ns, 40,
2336            "GAP-382: the corpus contract's declared overhead_ns never reached the estimate"
2337        );
2338    }
2339
2340    /// GAP-382 corpus run: every contract section across the three kernel-contract
2341    /// trees (this crate, `fuel-cuda-dispatch`, `fuel-vulkan-dispatch`) is compiled
2342    /// and costed at n = 8; every section declaring a numeric `overhead_ns` must
2343    /// give an estimate carrying exactly that value. Prints how many sections
2344    /// changed their candidate cost (before the fix: 0 for all of them).
2345    #[test]
2346    fn corpus_declared_overhead_ns_reaches_every_estimate() {
2347        fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2348            let Ok(rd) = std::fs::read_dir(dir) else {
2349                return;
2350            };
2351            for e in rd.flatten() {
2352                let path = e.path();
2353                if path.is_dir() {
2354                    walk(&path, out);
2355                } else if path.to_string_lossy().ends_with(".fkc.md") {
2356                    out.push(path);
2357                }
2358            }
2359        }
2360        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2361        let mut files = Vec::new();
2362        for tree in [
2363            "kernel-contracts",
2364            "../fuel-cuda-dispatch/kernel-contracts",
2365            "../fuel-vulkan-dispatch/kernel-contracts",
2366        ] {
2367            walk(&base.join(tree), &mut files);
2368        }
2369        files.sort();
2370        assert!(
2371            files.len() > 50,
2372            "CONTROL: the walk must find the corpus, found {}",
2373            files.len()
2374        );
2375
2376        let mut sections = 0usize;
2377        let mut with_number = 0usize;
2378        let mut with_expression = 0usize;
2379        let mut full_ok = 0usize;
2380        let mut full_err = 0usize;
2381        let mut unparsed_files = 0usize;
2382        let mut mismatches: Vec<String> = Vec::new();
2383        let mut by_tree: std::collections::BTreeMap<String, usize> = Default::default();
2384        for f in &files {
2385            let Ok(src) = std::fs::read_to_string(f) else {
2386                continue;
2387            };
2388            let Ok(file) = parse_file(&src) else {
2389                unparsed_files += 1;
2390                continue;
2391            };
2392            for k in &file.kernels {
2393                sections += 1;
2394                let Some(cost) = k.cost.as_ref() else {
2395                    continue;
2396                };
2397                let declared = match &cost.overhead_ns {
2398                    Some(serde_yaml_ng::Value::Number(n)) => n.as_f64(),
2399                    Some(serde_yaml_ng::Value::String(_)) => {
2400                        with_expression += 1;
2401                        continue;
2402                    }
2403                    _ => continue,
2404                };
2405                let Some(want) = declared else { continue };
2406                with_number += 1;
2407                let tree = f
2408                    .strip_prefix(base)
2409                    .ok()
2410                    .and_then(|p| p.components().next())
2411                    .map(|c| c.as_os_str().to_string_lossy().to_string())
2412                    .unwrap_or_else(|| "../".to_string());
2413                *by_tree.entry(tree).or_default() += 1;
2414                let expr = match compile_cost(Some(cost), &k.kernel) {
2415                    Ok(e) => e,
2416                    Err(e) => {
2417                        mismatches.push(format!("{}: {}: compile {e:?}", f.display(), k.kernel));
2418                        continue;
2419                    }
2420                };
2421                // The overhead is a literal: evaluate it directly, independent of
2422                // whether the flops / bytes_moved expressions bind under this generic
2423                // context (some use `b`, `batch`, `out_shape[0]`, bound per op in
2424                // production, or answered by the entry's hand-written cost fn).
2425                let direct = crate::fkc::cost_expr::eval_overhead_ns(&expr, &Default::default());
2426                if direct != Ok(want.max(0.0) as u32) {
2427                    mismatches.push(format!(
2428                        "{}: {}: declared {want} got {direct:?}",
2429                        f.display(),
2430                        k.kernel
2431                    ));
2432                }
2433                match crate::fkc::cost_estimate(
2434                    &expr,
2435                    OpKind::AddElementwise,
2436                    &[fuel_ir::Shape::from_dims(&[8])],
2437                    &[DType::F32],
2438                    &crate::kernel::OpParams::None,
2439                ) {
2440                    Ok(est) => {
2441                        full_ok += 1;
2442                        if Ok(est.kernel_overhead_ns) != direct {
2443                            mismatches.push(format!(
2444                                "{}: {}: estimate {} != direct {direct:?}",
2445                                f.display(),
2446                                k.kernel,
2447                                est.kernel_overhead_ns
2448                            ));
2449                        }
2450                    }
2451                    Err(_) => full_err += 1,
2452                }
2453            }
2454        }
2455        println!(
2456            "\nGAP-382 corpus: {} files ({} unparsed), {} sections; sections with a numeric overhead_ns \
2457             (candidate cost changes 0 -> declared): {}; with an expression-string overhead_ns: {};              of the numeric ones the whole estimate evaluates under the generic n = 8 context for {} and              needs op-bound symbols (hand-written cost fn answers in production) for {}; by tree: {:?}",
2458            files.len(),
2459            unparsed_files,
2460            sections,
2461            with_number,
2462            with_expression,
2463            full_ok,
2464            full_err,
2465            by_tree
2466        );
2467        assert!(
2468            with_number > 100,
2469            "CONTROL: the corpus declares far more than 100 numeric overhead_ns sections, saw {with_number}"
2470        );
2471        assert!(
2472            mismatches.is_empty(),
2473            "declared overhead_ns not reaching the estimate: {mismatches:#?}"
2474        );
2475    }
2476
2477    /// Ledger-coverage report (GAP-383): imports every contract in the three kernel-contract trees
2478    /// through the SAME steps as `import_bundle_str` (`lower_file`, then the V-FKC-9 `gate_precision`
2479    /// against the embedded verification ledger) and reports, per (op, dtype signature) PAIR, whether
2480    /// any record of a backend still meets the accuracy bound after the gate.
2481    ///
2482    /// Why pairs and not records: an op can have several records per signature (variants), and
2483    /// `AccuracyPreferenceFilter` only removes a GPU candidate when NO GPU candidate for that
2484    /// (op, dtypes) meets the bound while a CPU candidate does. So a GPU pair is placed on the host
2485    /// for lack of evidence iff it has zero meeting records and the CPU pair has at least one.
2486    ///
2487    /// Limits: CPU kernels registered by hand (not from a contract) are not in the CPU map; "meets
2488    /// the bound" is approximated as bit-stable or a relative/absolute claim (the filter's default
2489    /// bound value is not applied); the link is a stub (the revision hash does not depend on it);
2490    /// the ledger match key includes the kernel revision hash. Prints the report (`--nocapture`);
2491    /// asserts only its controls.
2492    #[test]
2493    fn contract_claims_without_a_ledger_pass_by_dtype_signature() {
2494        use std::collections::BTreeMap;
2495        fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2496            let Ok(rd) = std::fs::read_dir(dir) else {
2497                return;
2498            };
2499            for e in rd.flatten() {
2500                let path = e.path();
2501                if path.is_dir() {
2502                    walk(&path, out);
2503                } else if path.to_string_lossy().ends_with(".fkc.md") {
2504                    out.push(path);
2505                }
2506            }
2507        }
2508        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2509        let mut files = Vec::new();
2510        for tree in [
2511            "kernel-contracts",
2512            "../fuel-cuda-dispatch/kernel-contracts",
2513            "../fuel-vulkan-dispatch/kernel-contracts",
2514        ] {
2515            walk(&base.join(tree), &mut files);
2516        }
2517        files.sort();
2518        let ledger = crate::fkc::verify::embedded();
2519        let claims = |g: &crate::fused::PrecisionGuarantee| {
2520            g.bit_stable_on_same_hardware
2521                || g.max_ulp.is_some()
2522                || g.max_relative.is_some()
2523                || g.max_absolute.is_some()
2524        };
2525        let meets = |g: &crate::fused::PrecisionGuarantee| {
2526            g.bit_stable_on_same_hardware || g.max_relative.is_some() || g.max_absolute.is_some()
2527        };
2528        // (backend, op, signature) -> (records, records declaring a claim, records meeting the bound
2529        // AFTER the gate, records meeting the bound BEFORE the gate)
2530        type PairKey = (String, String, String);
2531        type PairStats = (usize, usize, usize, usize);
2532        let mut pairs: BTreeMap<PairKey, PairStats> = BTreeMap::new();
2533        let mut lower_errors = 0usize;
2534        for f in &files {
2535            let Ok(src) = std::fs::read_to_string(f) else {
2536                continue;
2537            };
2538            let Ok(file) = parse_file(&src) else { continue };
2539            let mut warnings = Vec::new();
2540            let Ok(mut resolved) = lower_file(&file, &StubLink, &mut warnings) else {
2541                lower_errors += 1;
2542                continue;
2543            };
2544            for r in &mut resolved {
2545                let (op, backend, sig, declared, gated) = match r {
2546                    Resolved::Primitive(p) => {
2547                        let q = crate::fkc::verify::LedgerQuery {
2548                            kernel_ref: p.kernel_source.as_str(),
2549                            backend: p.backend,
2550                            dtypes: p.dtypes.as_slice(),
2551                            kernel_revision_hash: p.revision.0,
2552                        };
2553                        let declared = p.precision;
2554                        let gated = crate::fkc::verify::gate_precision(
2555                            p.precision,
2556                            &q,
2557                            ledger,
2558                            &mut warnings,
2559                        );
2560                        (
2561                            format!("{:?}", p.op),
2562                            p.backend,
2563                            format!("{:?}", p.dtypes.as_slice()),
2564                            declared,
2565                            gated,
2566                        )
2567                    }
2568                    Resolved::Fused(fz) => {
2569                        let q = crate::fkc::verify::LedgerQuery {
2570                            kernel_ref: fz.kernel_source.as_str(),
2571                            backend: fz.backend,
2572                            dtypes: fz.dtypes.as_slice(),
2573                            kernel_revision_hash: fz.revision.0,
2574                        };
2575                        let declared = fz.precision;
2576                        let gated = crate::fkc::verify::gate_precision(
2577                            fz.precision,
2578                            &q,
2579                            ledger,
2580                            &mut warnings,
2581                        );
2582                        (
2583                            format!("Fused({:?})", fz.id),
2584                            fz.backend,
2585                            format!("{:?}", fz.dtypes.as_slice()),
2586                            declared,
2587                            gated,
2588                        )
2589                    }
2590                };
2591                let e = pairs.entry((format!("{backend:?}"), op, sig)).or_default();
2592                e.0 += 1;
2593                if claims(&declared) {
2594                    e.1 += 1;
2595                }
2596                if meets(&gated) {
2597                    e.2 += 1;
2598                }
2599                if meets(&declared) {
2600                    e.3 += 1;
2601                }
2602            }
2603        }
2604        let cpu_meets = |op: &String, sig: &String| {
2605            pairs
2606                .get(&("Cpu".to_string(), op.clone(), sig.clone()))
2607                .is_some_and(|v| v.2 > 0)
2608        };
2609        for backend in ["Cuda", "Vulkan"] {
2610            let mine: Vec<(&PairKey, &PairStats)> =
2611                pairs.iter().filter(|((b, _, _), _)| b == backend).collect();
2612            let n_pairs = mine.len();
2613            let records: usize = mine.iter().map(|(_, v)| v.0).sum();
2614            let declared_ok = mine.iter().filter(|(_, v)| v.3 > 0).count();
2615            let cost_placed = mine.iter().filter(|(_, v)| v.2 > 0).count();
2616            let lost_to_gate = mine.iter().filter(|(_, v)| v.3 > 0 && v.2 == 0).count();
2617            let host_pref: Vec<_> = mine
2618                .iter()
2619                .filter(|((_, op, sig), v)| v.2 == 0 && cpu_meets(op, sig))
2620                .collect();
2621            let no_cpu: usize = mine
2622                .iter()
2623                .filter(|((_, op, sig), v)| v.2 == 0 && !cpu_meets(op, sig))
2624                .count();
2625            println!(
2626                "\n=== {backend}: {n_pairs} (op, dtype signature) pairs from {records} contract records ===\n  \
2627                 {declared_ok} pairs DECLARE a meeting claim; {cost_placed} still meet the bound after the gate (placed by cost);\n  \
2628                 {lost_to_gate} pairs LOSE their declared claim at the V-FKC-9 gate (no ledger pass) and have no other meeting record;\n  \
2629                 {} pairs have no meeting record and a CPU record that meets the bound => PLACED ON THE HOST by AccuracyPreferenceFilter;\n  \
2630                 {no_cpu} pairs have no meeting record and no CPU contract record meeting the bound (filter skipped: the GPU kernel still runs)",
2631                host_pref.len()
2632            );
2633            let mut by_op: BTreeMap<String, usize> = BTreeMap::new();
2634            let mut by_sig: BTreeMap<String, usize> = BTreeMap::new();
2635            for ((_, op, sig), _) in &host_pref {
2636                *by_op.entry(op.clone()).or_default() += 1;
2637                *by_sig.entry(sig.clone()).or_default() += 1;
2638            }
2639            let mut v: Vec<_> = by_sig.into_iter().collect();
2640            v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
2641            println!(
2642                "  host-preferred pairs BY DTYPE SIGNATURE ({} signatures):",
2643                v.len()
2644            );
2645            for (sig, n) in &v {
2646                println!("      {sig:<40} {n}");
2647            }
2648            let mut v: Vec<_> = by_op.into_iter().collect();
2649            v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
2650            println!("  host-preferred pairs BY OP ({} ops):", v.len());
2651            for (op, n) in &v {
2652                println!("      {op:<34} {n}");
2653            }
2654            // The pairs over only the float / index dtypes a decode graph uses.
2655            let decode: Vec<_> = host_pref
2656                .iter()
2657                .filter(|((_, _, sig), _)| {
2658                    !["F64", "F8", "I8", "I32", "I64", "U8"]
2659                        .iter()
2660                        .any(|d| sig.contains(d))
2661                })
2662                .collect();
2663            println!(
2664                "  host-preferred pairs over F32/F16/BF16/U32/Bool only ({}):",
2665                decode.len()
2666            );
2667            for ((_, op, sig), _) in &decode {
2668                println!("      {op:<30} {sig}");
2669            }
2670        }
2671        println!(
2672            "\ncontract files scanned: {}, files that did not lower with the stub link: {lower_errors}",
2673            files.len()
2674        );
2675        let cuda_pairs = pairs.iter().filter(|((b, _, _), _)| b == "Cuda").count();
2676        let cuda_host: usize = pairs
2677            .iter()
2678            .filter(|((b, op, sig), v)| b == "Cuda" && v.2 == 0 && cpu_meets(op, sig))
2679            .count();
2680        let cuda_met: usize = pairs
2681            .iter()
2682            .filter(|((b, _, _), v)| b == "Cuda" && v.2 > 0)
2683            .count();
2684        assert!(files.len() > 50, "CONTROL: the walk must find the corpus");
2685        assert!(
2686            cuda_pairs > 100,
2687            "CONTROL: the instrument must see the CUDA pairs"
2688        );
2689        assert!(
2690            cuda_host > 0,
2691            "CONTROL: the recipe's Cast(U32->F32), MaskedFill and Ge are measured host-preferred pairs"
2692        );
2693        assert!(
2694            cuda_met > 0,
2695            "CONTROL: backed CUDA pairs exist (the ledger holds 284 CUDA bit_stable records)"
2696        );
2697    }
2698
2699    #[test]
2700    fn both_op_kind_and_fused_op_is_ambiguous() {
2701        let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
2702        let mut kernel = file.kernels[0].clone();
2703        kernel.fused_op = Some("SoftmaxLastDim".into()); // now both present
2704        let defaults = Defaults {
2705            backend: "Cpu",
2706            kernel_source: "x",
2707            revision_base: "",
2708        };
2709        let err =
2710            lower_kernel(&kernel, &defaults, &StubLink, &mut Vec::new()).expect_err("ambiguous");
2711        assert!(
2712            matches!(err, FkcError::OpTargetAmbiguous { .. }),
2713            "got {err:?}"
2714        );
2715    }
2716}