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