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