Skip to main content

fuel_dispatch/
kernel.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Kernel reference + op parameters + binding table. Phase 7.5 B1+B5.
3//!
4//! [`KernelRef`] is the uniform function-pointer type that every
5//! dispatch wrapper matches. Backend-specific typed kernels live in
6//! their backend crates (e.g. `fuel_cpu_backend::byte_kernels`); the
7//! *wrapper* functions here in fuel-storage bridge the dispatch-
8//! erased `Storage` to those typed kernels by matching on
9//! `BackendStorage::Cpu(...)` etc.
10//!
11//! [`OpParams`] is the typed extras bag — one variant per op family
12//! that needs auxiliary data beyond inputs and outputs. Most
13//! elementwise ops use `OpParams::None`; reductions carry their
14//! reduce dims; conv2d carries kernel/stride/padding; etc.
15//!
16//! [`KernelBindingTable`] (B5) maps
17//! `(OpKind, SmallVec<[DType; N]>, BackendId) -> KernelRef`. The dtype
18//! list carries per-operand types — inputs in order, then outputs —
19//! so mixed-precision ops (e.g. `Cast: src→dst`) and same-dtype ops
20//! (e.g. `Add: [T, T, T]`) share the same key shape. Backends register
21//! their dispatch wrappers via the `dispatch::register_*` functions;
22//! op-builder methods consult the table at DAG construction time using
23//! `Graph::target_backend(id)` as the BackendId key.
24//!
25//! ## Architecture (cycle-avoidance)
26//!
27//! - Backend crates (`fuel-cpu-backend`, …): typed kernels on their
28//!   concrete storage types (`CpuStorageBytes`, …). No fuel-storage
29//!   dependency.
30//! - fuel-storage (this crate): dispatch wrappers that match
31//!   `BackendStorage::Cpu(...)`, extract the typed storage, and
32//!   call the backend's typed kernel. KernelBindingTable lives here.
33//! - Backend crates depend on fuel-storage? No — only the wrappers
34//!   do. fuel-storage already depends on backend crates for variant
35//!   types; this round-trip closes naturally.
36
37use std::collections::HashMap;
38use std::sync::Arc;
39use std::sync::RwLock;
40
41use fuel_graph::QuantType;
42use fuel_graph::registry::FusedOpId;
43use fuel_ir::conv::{ParamsConv1D, ParamsConvTranspose1D};
44use fuel_ir::dispatch::OpKind;
45use fuel_ir::probe::BackendId;
46use fuel_ir::{DType, Error, Layout, Result};
47use smallvec::SmallVec;
48
49/// Inline capacity for the per-operand dtype list in the binding-table
50/// key. 8 covers every op currently in flight without spilling to heap:
51/// PagedAttn (q + 2 caches + block_table + context_lens + alibi + out)
52/// at 7 entries is the worst case in inference; mixed-precision matmul
53/// is ≤ 4. Bumping later is one constant change.
54pub type KernelDTypes = SmallVec<[DType; 8]>;
55
56/// One entry of the coverage diagnostic: `(backend, op, operand dtypes)`.
57///
58/// Named rather than spelled out because the bare 3-tuple appears in a return
59/// position where it was unreadable, and `#[allow(type_complexity)]` would
60/// have asserted the tuple is fine as-is. It is not — the alias is the fix and
61/// the lint was right.
62///
63/// NOT `BindingKey`: that name is already a distinct `pub enum` in this
64/// module (`Static` / …). The compiler caught the collision; the lesson is
65/// that a type alias introduced for a lint still needs a name check.
66pub type CoverageBinding = (BackendId, OpKind, Vec<DType>);
67
68/// Per-binding capability flags. Today carries one flag — `strided_input`
69/// — that signals "this kernel walks input strides explicitly and so
70/// can consume non-contiguous input layouts (including stride-0
71/// broadcast axes) without auto-Contiguize materializing them first."
72/// The executor's contiguize gate consults this to skip the materialize
73/// step for capable kernels, so broadcast/transpose/slice layouts can
74/// reach the kernel as metadata-only views.
75///
76/// Default is the conservative all-false; binding sites opt in via
77/// [`KernelBindingTable::register_with_caps`]. Forward-extensible by
78/// adding fields (no enum/bitflags churn).
79#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
80pub struct KernelCaps {
81    /// Kernel handles non-contiguous input layouts directly (consumes
82    /// the strides side-channel from `KernelRef::layouts`). When true,
83    /// the executor passes non-contiguous inputs through unchanged
84    /// instead of running auto-Contiguize first. Inputs with non-zero
85    /// `start_offset` still go through auto-Contiguize today (slicing
86    /// the device buffer to honor offset is a separate concern).
87    pub strided_input: bool,
88    /// This kernel BAKES a specific broadcast pattern into its body — a
89    /// `broadcast_stride0: required` operand it reads as stride-0 (hoisting
90    /// `in[0]` / dropping the bcast-axis stride terms). It is therefore NOT
91    /// a generic dense-safe kernel: a dense operand routed here would be
92    /// read WRONG (element 0 repeatedly). The realize pick
93    /// ([`KernelBindingTable::lookup_with_caps`]) SKIPS such a sibling so a dense operand
94    /// is never routed into a broadcast-baked kernel — the exclusion is
95    /// order-independent (it does not rest on the generic contract being
96    /// registered first). Selecting it CORRECTLY, for an operand genuinely
97    /// stride-0 on exactly the required axes, is the layout-aware follow-on
98    /// (path 1b) that also teaches the contiguize gate; today the safe
99    /// behavior is to exclude it, so a `required`-broadcast contract is a
100    /// present-but-never-mis-selected sibling. Defaults `false` — every
101    /// existing binding is unaffected (the pick stays first-registered).
102    pub requires_broadcast: bool,
103}
104
105impl KernelCaps {
106    /// All flags off. Equivalent to `Default::default()`; provided as a
107    /// const for use in const-context registration tables.
108    pub const fn empty() -> Self {
109        Self {
110            strided_input: false,
111            requires_broadcast: false,
112        }
113    }
114
115    /// Just `strided_input` on. Ergonomic for binary/unary registrations
116    /// that opt in to the wrapper-side broadcast path.
117    pub const fn strided_input() -> Self {
118        Self {
119            strided_input: true,
120            requires_broadcast: false,
121        }
122    }
123}
124
125use fuel_memory::Storage;
126
127/// Uniform function-pointer signature for per-backend op kernels.
128///
129/// Inputs are passed as a slice of `&Storage` to handle multi-input
130/// ops (binary, ternary, custom). Outputs are passed as a slice of
131/// `&mut Storage` to handle multi-output ops (topk, var_mean,
132/// custom). Most ops use single-element slices.
133///
134/// `layouts` is a side-channel that parallels `inputs.append(outputs)`
135/// — i.e. `layouts[0..inputs.len()]` are the input layouts in order,
136/// followed by `layouts[inputs.len()..]` for the output layouts. This
137/// is the load-bearing primitive for stride-aware kernels (broadcast,
138/// transpose, gather-from-strided). Kernels that only support
139/// contiguous-equal-shape inputs (today's default) can ignore
140/// `layouts` because the executor's auto-Contiguize pass guarantees
141/// every input is contiguous before this is called; the layout slice
142/// then carries `Layout::contiguous(shape)` entries that are useful
143/// for shape inference but redundant with `Storage.len_bytes / dtype`.
144///
145/// `OpParams` carries op-family-specific extras (reduce dims,
146/// conv2d geometry, etc.). Most kernels match a specific variant;
147/// mismatches are programming bugs that the dispatch resolver
148/// must prevent. Pure layout/shape duplication that used to live in
149/// `OpParams` (e.g. the old `Reduce::input_layout`) now flows through
150/// `layouts` instead.
151///
152/// **Output Storage is pre-allocated** by the executor before the
153/// kernel is called. Kernels write into the pre-allocated bytes;
154/// they never allocate.
155///
156/// ## Multi-output kernels (Option C, Session 5)
157///
158/// Multi-output ops (e.g. SelectiveScan returning `(y, last_state)`)
159/// emit ONE `KernelRef`. The contract:
160///
161/// - `outputs.len() == 1`. The single `Arc<RwLock<Storage>>` is the
162///   producer's *bundled* Storage — its `bundle()` returns
163///   `Some(&[OutputView; N])` describing each logical slot's
164///   `dtype`/`shape`/`layout`/`byte_offset` inside the bundle's
165///   underlying byte buffer.
166/// - The kernel writes each logical output into its slot's byte
167///   range by acquiring a single write lock on the output and
168///   striding by the slot's `byte_offset`. The bundle metadata is
169///   the authoritative per-slot spec — `outputs[0].read().unwrap()
170///   .bundle().expect("bundled storage").get(slot_idx)` is the
171///   canonical access path.
172/// - Per-slot dtype tags do NOT travel through the kernel's
173///   `KernelDTypes` key (which describes inputs + the bundle's
174///   primary dtype only); the bundle metadata IS the per-slot
175///   dispatch info.
176/// - The bundle is pre-allocated by the executor via
177///   `allocate_bundled_storage(device, &output_views_spec)` (see
178///   `fuel_backend_contract::storage::allocate_bundled_storage`). Kernels
179///   never allocate; they only fill bytes.
180///
181/// Consumers of multi-output producers are NOT multi-output kernels —
182/// they're `Op::View` (zero-copy slot projection) or `Op::ViewOwned`
183/// (independent slot buffer), which the executor handles directly
184/// without invoking a kernel.
185///
186/// **Production-correct**: kernels return `Result`, never panic.
187pub type KernelRef = fn(
188    inputs: &[Arc<RwLock<Storage>>],
189    outputs: &mut [Arc<RwLock<Storage>>],
190    layouts: &[Layout],
191    params: &OpParams,
192) -> Result<()>;
193
194/// How many rows a [`OpParams::Matmul`] computes — the data-determined-M
195/// state for sparse-MoE / capacity-buffer matmuls. `m` in `OpParams::Matmul`
196/// is always the row **capacity** (buffer/stride/size); this says how many
197/// of those rows to actually compute (`<= m`), the rest left zeroed.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub enum MatmulM {
200    /// Compute every one of the `m` rows — the universal static default.
201    All,
202    /// Compute exactly this many rows of the `m`-row capacity buffer. Set
203    /// when the count is known at compile (an input-determined extent) or
204    /// after a [`Self::Deferred`] is resolved at execute.
205    Rows(usize),
206    /// The row count is **data-determined** (a producer binds it mid-pass,
207    /// e.g. `Op::NonZeroIndices`'s per-expert token count) — resolve at
208    /// execute from `produced_syms`, then patch to [`Self::Rows`].
209    Deferred(fuel_ir::DynScalar),
210}
211
212/// Typed extras bag passed to kernels via [`KernelRef`]. One variant
213/// per op family that needs auxiliary parameters; `None` for
214/// parameter-less ops (most elementwise unary and binary).
215#[derive(Debug, Clone)]
216pub enum OpParams {
217    /// Op needs no auxiliary parameters. Used by elementwise
218    /// unary (relu, neg, sqr, …), elementwise binary (add, mul,
219    /// sub, div, …), shape-only ops (reshape, transpose), etc.
220    None,
221
222    /// Reduction (sum, max, mean, …) along specific dims. The input
223    /// tensor's [`Layout`] flows through the new `layouts` side-channel
224    /// (`layouts[0]`) on `KernelRef`, so this variant carries only the
225    /// op-specific extras: which dims to reduce and the keepdim flag.
226    ///
227    /// `dims` is the sorted list of dims to reduce; `keepdim`
228    /// controls whether reduced dims are retained as size-1 in
229    /// the output (today fuel-graph never asks for keepdim, but
230    /// the field is reserved for the future).
231    Reduce { dims: Vec<usize>, keepdim: bool },
232
233    /// Matrix multiplication. Carries the dimensions explicitly
234    /// because [`Storage`](fuel_memory::Storage) only holds bytes + dtype;
235    /// the kernel needs the batch shape and `(m, n, k)` to walk
236    /// inputs and outputs.
237    ///
238    /// Shape contract: lhs `[..lhs_batch.., m, k]` @
239    /// rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
240    /// Per-axis the batch dims must either match or follow GQA-style
241    /// divisibility (`lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0`)
242    /// — the kernel maps each lhs batch slot to the corresponding
243    /// rhs slot via `rhs_axis_idx = lhs_axis_idx / n_rep_axis`.
244    ///
245    /// Equal-batch case: `lhs_batch_dims == rhs_batch_dims`. Rank-2
246    /// case: both batch vectors are empty. Both work uniformly.
247    ///
248    /// Inputs are guaranteed contiguous by the executor's
249    /// auto-Contiguize pass; transpose flags don't appear here
250    /// because `Op::Transpose` is its own metadata-only op in
251    /// fuel-graph.
252    Matmul {
253        lhs_batch_dims: Vec<usize>,
254        rhs_batch_dims: Vec<usize>,
255        /// The output/LHS row **capacity** (drives size checks + strides).
256        m: usize,
257        n: usize,
258        k: usize,
259        /// How many of the `m` rows to actually compute (data-determined-M
260        /// sparse-MoE support). `MatmulM::All` for every ordinary matmul.
261        m_compute: MatmulM,
262    },
263
264    /// 1D convolution geometry (forward path).
265    Conv1D(ParamsConv1D),
266
267    /// 2D convolution geometry (forward path). Carries the tuple-shaped
268    /// stride/padding that fuel-graph's `Op::Conv2D` uses (asymmetric
269    /// supported), plus the input/weight/output shapes the kernel
270    /// needs to walk the multi-index. Storage holds only bytes +
271    /// dtype, so spatial shapes flow through OpParams.
272    ///
273    /// Inputs: `x` shape `[N, Cin, Hin, Win]`, `weight` shape
274    /// `[Cout, Cin/groups, Kh, Kw]`, optional `bias` shape `[Cout]`.
275    /// Output: `[N, Cout, Hout, Wout]`.
276    Conv2D {
277        x_shape: [usize; 4],
278        w_shape: [usize; 4],
279        out_shape: [usize; 4],
280        stride: (usize, usize),
281        padding: (usize, usize),
282        dilation: (usize, usize),
283        groups: usize,
284    },
285
286    /// Conv2D with an elementwise epilogue (row 172 item 3). Inputs `x`, `weight`,
287    /// `bias` iff `has_bias`, then the recipe's extra operands (output-shaped).
288    /// `recipe` binds `0` = the conv output, `1..` = the extras; `scalars` fill its
289    /// open slots in pre-order.
290    Conv2DEpilogue {
291        x_shape: [usize; 4],
292        w_shape: [usize; 4],
293        out_shape: [usize; 4],
294        stride: (usize, usize),
295        padding: (usize, usize),
296        groups: usize,
297        has_bias: bool,
298        recipe: Box<fireline_grammar::PatternNode>,
299        scalars: Vec<f64>,
300    },
301
302    /// 1D transposed-convolution geometry.
303    ConvTranspose1D(ParamsConvTranspose1D),
304
305    /// 2D transposed-convolution geometry. Mirrors `OpParams::Conv2D`
306    /// in shape (inline fields, asymmetric stride/padding/dilation,
307    /// `groups`), with the additional `output_padding` parameter that
308    /// transposed conv needs to disambiguate output spatial size.
309    ///
310    /// Inputs: `x` shape `[N, Cin, Hin, Win]`, `weight` shape
311    /// `[Cin, Cout/groups, Kh, Kw]` (note transposed channel order
312    /// vs Conv2D), optional `bias` shape `[Cout]`.
313    /// Output: `[N, Cout, Hout, Wout]`.
314    ConvTranspose2D {
315        x_shape: [usize; 4],
316        w_shape: [usize; 4],
317        out_shape: [usize; 4],
318        stride: (usize, usize),
319        padding: (usize, usize),
320        output_padding: (usize, usize),
321        dilation: (usize, usize),
322        groups: usize,
323    },
324
325    /// Sum-reduce a tensor to a smaller broadcast-compatible target
326    /// shape. The kernel left-pads `output_shape` with 1s to match
327    /// `input_shape`'s rank, then for each axis: if the padded output
328    /// dim equals the input dim that axis carries through; if it's 1
329    /// the axis is summed away.
330    ReduceSumTo {
331        input_shape: Vec<usize>,
332        output_shape: Vec<usize>,
333    },
334
335    /// Max-reduce a tensor to a smaller broadcast-compatible target
336    /// shape — the max-symmetric counterpart of `ReduceSumTo`. Same
337    /// axis-alignment rules; per-axis reduction is `max` instead of
338    /// `+`.
339    ReduceMaxTo {
340        input_shape: Vec<usize>,
341        output_shape: Vec<usize>,
342    },
343
344    /// Backward of `ReduceMaxTo`. Inputs: `(x, upstream)` where
345    /// `x.shape == input_shape` and `upstream.shape == output_shape`.
346    /// Output: `grad_x` of `input_shape`. The kernel recomputes the
347    /// forward max via `input_shape → output_shape` axis alignment,
348    /// builds a tie-count mask, and routes upstream back to argmax
349    /// positions (fair-share on ties).
350    ReduceMaxToBackward {
351        input_shape: Vec<usize>,
352        output_shape: Vec<usize>,
353    },
354
355    /// Multi-head scaled-dot-product attention shape + math params.
356    /// `q` is `[B, Hq, Sq, D]`, `k` and `v` are `[B, Hkv, Sk, D]`
357    /// (Hkv ≤ Hq, GQA-divisible). Optional 4th input `alibi_slopes`
358    /// has shape `[Hq]` (presence is implicit in `inputs.len() == 4`).
359    ///
360    /// `sk` is the **physical** K/V length axis (the allocated extent —
361    /// used for strides + byte-length checks). `k_len` is the
362    /// **logical** attended length (`k_len <= sk`): a kernel attends only
363    /// the first `k_len` rows of the K/V buffers and bottom-right-aligns
364    /// the causal mask at offset `k_len - sq` (Phase D symbolic extents:
365    /// flash over a fixed-capacity KV-cache with a runtime live prefix).
366    /// For the static path the lowering sets `k_len == sk`, so a kernel
367    /// that loops `0..k_len` with the `k_len - sq` causal offset is
368    /// byte-identical to the old `0..sk` / `kj > qi` form.
369    FlashAttn {
370        b: usize,
371        hq: usize,
372        hkv: usize,
373        sq: usize,
374        sk: usize,
375        d: usize,
376        k_len: usize,
377        softmax_scale: f32,
378        causal: bool,
379        window_size_left: Option<usize>,
380        window_size_right: Option<usize>,
381        softcap: Option<f32>,
382    },
383
384    /// Paged-cache attention. `q` is `[B, Hq, Sq, D]`; `k_cache` and
385    /// `v_cache` are `[num_blocks, block_size, Hkv, D]`. The 4th input
386    /// is `block_table: [B, max_blocks_per_seq]` (U32 — physical block
387    /// index per logical position). The 5th is `context_lens: [B]`
388    /// (U32 — true context length per sequence). Optional 6th is
389    /// `alibi_slopes: [Hq]`.
390    PagedAttn {
391        b: usize,
392        hq: usize,
393        hkv: usize,
394        sq: usize,
395        d: usize,
396        block_size: usize,
397        max_blocks_per_seq: usize,
398        num_blocks: usize,
399        softmax_scale: f32,
400        softcap: Option<f32>,
401    },
402
403    /// Slice along a single dim with explicit start/end/step. The
404    /// dim is implicit in the input Layout's relabeling for
405    /// multi-dim slice; this variant covers the simple case.
406    Slice {
407        dim: usize,
408        start: usize,
409        end: usize,
410        step: usize,
411    },
412
413    // (Earlier `OpParams::Pad { padding: Vec<(usize, usize)>, fill_bytes: Vec<u8> }`
414    // was a speculative multi-dim shape with no consumers. The single-
415    // dim shape that Op::Pad actually emits lives at the bottom of this
416    // enum; if multi-dim padding lands later, it can extend either
417    // shape additively.)
418    /// Cast input dtype → target dtype. The target lives on the
419    /// output Storage's `dtype` field; this variant signals the
420    /// op family without requiring a re-read.
421    Cast,
422
423    /// Affine transformation `y = mul * x + add`. Used by
424    /// `Tensor::affine` / `scale_and_shift`.
425    Affine { mul: f64, add: f64 },
426
427    /// Element-wise clamp: `y = clamp(x, min, max)`.
428    Clamp { min: f64, max: f64 },
429
430    /// Element-wise integer power: `y = x.powi(exp)`.
431    PowI { exp: i32 },
432
433    /// Concatenate N inputs along one dim. The kernel needs the
434    /// outer/inner element counts (product of dims before/after
435    /// the concat dim) plus each input's size along the concat
436    /// dim — that's all that distinguishes a concat from a
437    /// sequence of slab-copies. Order matches `Node::inputs`.
438    ///
439    /// `axis` is the original concat dim in the output's shape;
440    /// kernels that want to walk strided rank-N inputs need it
441    /// to build the per-axis stride mask (the outer/inner factoring
442    /// alone loses the position info).
443    Concat {
444        /// Product of output dims before the concat dim.
445        outer_count: usize,
446        /// Per-input size along the concat dim (length = N inputs).
447        input_dim_sizes: Vec<usize>,
448        /// Product of output dims after the concat dim.
449        inner_count: usize,
450        /// Original concat axis index in the output's rank-N shape.
451        axis: usize,
452    },
453
454    /// Softmax along the last dim. The kernel walks
455    /// `outer_count` rows of `last_dim` elements each.
456    SoftmaxLastDim { outer_count: usize, last_dim: usize },
457
458    /// Last-dim norm parameters shared by RMS-norm and LayerNorm
459    /// (no affine flavor for both today). The OpKind selects which
460    /// kernel reads this variant.
461    NormLastDim {
462        outer_count: usize,
463        last_dim: usize,
464        eps: f64,
465    },
466
467    /// Pick slices along a single dim using a rank-1 U32 index
468    /// tensor. The kernel needs the outer/inner counts (dims
469    /// before/after the selected axis), the source's selected-dim
470    /// size for index bounds checking, and the index count.
471    IndexSelect {
472        outer_count: usize,
473        source_dim_size: usize,
474        n_indices: usize,
475        inner_count: usize,
476    },
477
478    /// N-dimensional gather along `dim`. Source and output shapes
479    /// agree on every dim except `dim`; the indices tensor (U32)
480    /// has output_shape and supplies the source coord for `dim`
481    /// at every output position.
482    Gather {
483        source_shape: Vec<usize>,
484        output_shape: Vec<usize>,
485        dim: usize,
486    },
487
488    /// Rotary position embedding parameters. The kernel walks
489    /// `outer_count` × `seq` × `head_dim` elements; `cos`/`sin`
490    /// have `[seq, head_dim]` shape and broadcast across the
491    /// outer dims.
492    Rope {
493        outer_count: usize,
494        seq: usize,
495        head_dim: usize,
496    },
497
498    /// Quantized matmul shape: `A [batch, m, k] @ dequant(W) [n, k] →
499    /// out [batch, m, n]`. The weight tensor is a flat U32-typed
500    /// byte stream representing `n * k / elements_per_block` blocks
501    /// of `quant_type`. Activations are F32 today; output is F32.
502    QMatMul {
503        quant_type: QuantType,
504        batch_count: usize,
505        m: usize,
506        n: usize,
507        k: usize,
508    },
509
510    /// Index-add along a single dim with rank-1 U32 indices.
511    /// Output is `base` with `src[..., i, ...]` accumulated into
512    /// `base[..., indices[i], ...]` for every i ∈ 0..n_indices.
513    IndexAdd {
514        outer_count: usize,
515        base_dim_size: usize,
516        n_indices: usize,
517        inner_count: usize,
518    },
519
520    /// N-dimensional scatter-add. Indices and src share the same
521    /// shape; base may differ only along `dim`. The kernel walks
522    /// every src/indices position, reads `indices[p]` for the
523    /// destination's `dim` coord, and accumulates `src[p]` into
524    /// `base` at that destination.
525    ScatterAdd {
526        base_shape: Vec<usize>,
527        src_shape: Vec<usize>,
528        dim: usize,
529    },
530
531    /// Flip the order of elements along one dim. The flat-3-axis
532    /// view (outer × dim × inner) lets the kernel walk a tight loop
533    /// without re-deriving the axis split per call. `axis` is the
534    /// original dim index in the input's rank-N shape — needed by
535    /// stride-aware kernels to build a per-axis flip mask.
536    Flip {
537        outer_count: usize,
538        dim_size: usize,
539        inner_count: usize,
540        axis: usize,
541    },
542
543    /// Cyclic shift along one dim by `shift` positions (positive
544    /// shifts move elements to higher indices, wrapping around).
545    /// Same flat-3-axis view as `Flip`. `shift` is signed: negative
546    /// shifts move elements to lower indices.
547    Roll {
548        outer_count: usize,
549        dim_size: usize,
550        inner_count: usize,
551        shift: i64,
552        axis: usize,
553    },
554
555    /// Running cumulative sum along one dim. Same flat-3-axis view
556    /// as `Flip`/`Roll`. Output is always the same dtype as input;
557    /// kernel needs typed addition so it's per-dtype (unlike Flip/Roll).
558    CumSum {
559        outer_count: usize,
560        dim_size: usize,
561        inner_count: usize,
562        axis: usize,
563    },
564
565    /// Triangular mask parameters (used by both Triu and Tril — the
566    /// op-kind picks the direction). `batch_count` is the product of
567    /// leading dims; `rows`/`cols` are the last two dims. `diagonal`
568    /// is signed (0 = main diagonal, positive shifts up, negative
569    /// shifts down).
570    Triangular {
571        batch_count: usize,
572        rows: usize,
573        cols: usize,
574        diagonal: i64,
575    },
576
577    /// LogSoftmax along the last dim. Walks `outer_count` rows of
578    /// `last_dim` elements each. Per-dtype kernel (uses log/exp).
579    LogSoftmaxLastDim { outer_count: usize, last_dim: usize },
580
581    /// MaskedFill: per-element fill where mask is nonzero. The kernel
582    /// reads the element count from the layout; `fill_bytes` is
583    /// pre-encoded in the output's dtype (one element's worth).
584    MaskedFill { fill_bytes: Vec<u8> },
585
586    /// Backward helper for Pad. Carries the input shape so the kernel
587    /// can size its scatter-add buffer; the output shape is implicit
588    /// from the input shape + padding.
589    PadBackward {
590        in_shape: Vec<usize>,
591        out_shape: Vec<usize>,
592        padding: Vec<(usize, usize)>,
593        mode_tag: u8,
594    },
595
596    /// Multi-dim Pad: per-axis (before, after) plus a `mode_tag`
597    /// (0=Constant, 1=Reflect, 2=Replicate) and pre-encoded
598    /// `fill_bytes` for Constant fill. Dtype-agnostic at the byte
599    /// level: the kernel just copies bytes per the input/output shapes,
600    /// which is why fill is bytes (already encoded in the output's
601    /// dtype) rather than `f64` (which would force the kernel to
602    /// know its dtype).
603    ///
604    /// `in_shape.len() == out_shape.len() == padding.len()`, and
605    /// `out_shape[i] == in_shape[i] + padding[i].0 + padding[i].1`.
606    /// `fill_bytes.len() == dtype_size_in_bytes` (one element's worth).
607    Pad {
608        in_shape: Vec<usize>,
609        out_shape: Vec<usize>,
610        padding: Vec<(usize, usize)>,
611        mode_tag: u8,
612        fill_bytes: Vec<u8>,
613    },
614
615    /// In-place scatter write parameters. The destination shape +
616    /// source shape together determine the kernel walk; `ranges`
617    /// gives the per-axis (start, end) slab inside the destination.
618    /// `dest_shape[i] >= ranges[i].1`, and source shape is implicitly
619    /// `ranges[i].1 - ranges[i].0` along axis `i`.
620    ///
621    /// Phase E.3.2: backs `Op::WriteSlice` for persistent KV-cache
622    /// writes.
623    ///
624    /// `deferred_dyn_offset` is the **data-determined dynamic-shapes** seam
625    /// (increment 2b). Normally `None` — `ranges` is already resolved at
626    /// compile (static, or an *input-determined* `dyn_offset` bound in the
627    /// per-pass `SymEnv`). It is `Some((axis, sym))` only when the offset is
628    /// *data-determined* — its `SymId` is UNBOUND at compile because a
629    /// producer (e.g. `Op::NonZeroIndices`) computes it mid-pass. The
630    /// `WorkItemKind::WriteSlice` executor arm resolves it from
631    /// `produced_syms` and overrides `ranges[axis]` to `(base, base+width)`
632    /// just before the kernel runs; the kernel wrappers ignore this field.
633    WriteSlice {
634        dest_shape: Vec<usize>,
635        ranges: Vec<(usize, usize)>,
636        deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)>,
637    },
638
639    /// In-place ring-buffer scatter write parameters. Like
640    /// `WriteSlice` except `axis` wraps modulo `modulus`; the
641    /// dynamic start on that axis is read from an extra input (rank-0
642    /// U32). On the rotating axis, `ranges[axis].0` is ignored
643    /// (dynamic) and `ranges[axis].1 - ranges[axis].0` is the slab
644    /// width (must equal the source dim on that axis, and must not
645    /// exceed `modulus`).
646    ///
647    /// Phase C: backs `Op::WriteSliceRotating` for sliding-window
648    /// KV caches.
649    WriteSliceRotating {
650        dest_shape: Vec<usize>,
651        axis: usize,
652        modulus: usize,
653        ranges: Vec<(usize, usize)>,
654    },
655
656    /// In-place scatter write whose start on `axis` is read from a
657    /// **device-resident** rank-0 `I64` input (`inputs[2]`) at kernel
658    /// launch — the CUDA-graph-capturable KV-cache append. Like
659    /// `WriteSlice` except `ranges[axis].0` is a placeholder overridden
660    /// device-side by the offset; no modulo wrap. The CUDA wrapper
661    /// passes the offset buffer's device pointer straight through as
662    /// `dyn_start_dev` (NO D2H — that would break capture); the CPU
663    /// wrapper reads it host-side and delegates to `write_slice_cpu`.
664    /// Bounds (`offset + width <= dest_shape[axis]`) are the caller's
665    /// contract; the kernel does not clamp.
666    ///
667    /// CapturedRun (2026-07): backs `Op::WriteSliceDoff` for
668    /// `DecodeSession` decode-step capture/replay.
669    WriteSliceDoff {
670        dest_shape: Vec<usize>,
671        axis: usize,
672        ranges: Vec<(usize, usize)>,
673    },
674
675    /// FusedSoftmaxCrossEntropy execution parameters. Inputs:
676    /// `logits [n_rows, vocab]` (F32, flattened from the original
677    /// `[..., V]` shape) and `targets [n_rows]` (I64). The kernel
678    /// walks row-by-row, computing stable log-softmax + NLL +
679    /// `ignore_index` masking + the requested reduction in a single
680    /// pass, allocating only an `[n_rows]` per-row accumulator (and
681    /// a scalar for Mean/Sum). Output is F32 scalar `[]` for
682    /// Mean/Sum, F32 `[n_rows]` for None.
683    ///
684    /// `n_rows` and `vocab` are derived at translate time from the
685    /// logits layout; the kernel uses them to iterate without
686    /// re-parsing shapes.
687    FusedSoftmaxCrossEntropy {
688        n_rows: usize,
689        vocab: usize,
690        reduction: fuel_graph::registry::Reduction,
691        ignore_index: i64,
692    },
693
694    /// CausalConv1d execution parameters. Inputs:
695    /// `x [batch, channels, seq_in]` (pre-padded by caller with
696    /// `kernel - 1` left zeros), `weight [channels, 1, kernel]`,
697    /// `bias [channels]`. Output `[batch, channels, seq_out]` where
698    /// `seq_out = seq_in - (kernel - 1)`. All tensors share dtype.
699    ///
700    /// Carries both `seq_in` and `seq_out` so the kernel walks the
701    /// time axis without re-deriving from shapes. `use_silu` toggles
702    /// the fused SiLU activation on the output store (matches
703    /// baracuda's `causal_conv1d_*_run` signature flag).
704    CausalConv1d {
705        batch: usize,
706        channels: usize,
707        seq_in: usize,
708        seq_out: usize,
709        kernel: usize,
710        use_silu: bool,
711    },
712
713    /// SelectiveScan execution parameters. 5 required inputs:
714    /// `u [batch, seqlen, dim]`, `delta [batch, seqlen, dim]`,
715    /// `a [dim, dstate]`, `b [batch, seqlen, dstate]`,
716    /// `c [batch, seqlen, dstate]`. Output `y [batch, seqlen, dim]`.
717    /// All tensors share dtype.
718    ///
719    /// `delta_softplus` toggles applying softplus(delta) before use
720    /// (matches baracuda's `selective_scan_*_run` flag).
721    SelectiveScan {
722        batch: usize,
723        seqlen: usize,
724        dim: usize,
725        dstate: usize,
726        delta_softplus: bool,
727    },
728
729    /// SsdChunkScan execution parameters. 5 inputs:
730    /// `x [batch, seqlen, heads, head_dim]`,
731    /// `dt [batch, seqlen, heads]`, `a [heads]`,
732    /// `b [batch, seqlen, heads, state_dim]`,
733    /// `c [batch, seqlen, heads, state_dim]`. Output `y` matches `x`'s
734    /// shape. All tensors share dtype.
735    ///
736    /// `chunk_size` is the SSD block size (GPU-parallelism knob).
737    /// On CPU the kernel runs a sequential scan regardless;
738    /// validation requires `chunk_size > 0` and
739    /// `seqlen % chunk_size == 0`.
740    SsdChunkScan {
741        batch: usize,
742        seqlen: usize,
743        heads: usize,
744        head_dim: usize,
745        state_dim: usize,
746        chunk_size: usize,
747    },
748
749    /// Nf4Matmul execution parameters. 3 inputs:
750    /// `activations [batch, m, k]` (rank ≥ 2; leading dims flattened
751    /// into `batch`), `w_packed [n, k/2]` U8, `absmax [n, k/block_size]`
752    /// F32. Output `[batch, m, n]` matching activations' dtype.
753    ///
754    /// `block_size` is the per-output-row, per-block scale granularity
755    /// (typically 64 in bitsandbytes). `k` must be even (w_packed
756    /// layout requirement) and a multiple of `block_size`.
757    Nf4Matmul {
758        batch: usize,
759        m: usize,
760        n: usize,
761        k: usize,
762        block_size: usize,
763    },
764
765    /// AwqMatmul execution parameters. 4 inputs: `activations [..., m, k]`
766    /// (rank ≥ 2; every leading dim is flattened into `batch`, so the CUDA
767    /// wrapper runs a GEMM of `batch * m` rows), `weight [n, k/8]` U32,
768    /// `zeros [n, zeros_w]` U32, `scales [n, 8 * zeros_w]` F16 (baracuda W4A16
769    /// kernel layout). Output `[batch, m, n]` matching activations' dtype.
770    ///
771    /// `group_size` ∈ {64, 128}; `split_k_iters` is the CUDA launch-tuning
772    /// parameter (typically 8).
773    AwqMatmul {
774        batch: usize,
775        m: usize,
776        n: usize,
777        k: usize,
778        group_size: usize,
779        split_k_iters: i32,
780    },
781
782    /// TopKLastDim execution parameters (ROADMAP row 172 item 2). 1 input
783    /// `x [.., n]` (every leading dim flattened into `rows`); the output is the
784    /// bundled `[values (rows*k, input dtype) ; indices (rows*k, U32)]`.
785    TopKLastDim { rows: usize, n: usize, k: usize },
786
787    /// MatMulTopK execution parameters (row 172 item 2 step B). `a [batch, m, k]`,
788    /// `b [batch, k, n]` (equal batch counts); the output is the TopK bundle over
789    /// the `batch*m` rows of the (unmaterialized) `[.., n]` matmul result.
790    MatMulTopK {
791        batch: usize,
792        m: usize,
793        n: usize,
794        k: usize,
795        top_k: usize,
796    },
797
798    /// A **runtime fused op's** live scalar args (the `extract:` values from
799    /// `FusedOpParams::Runtime { scalars }`), in the region's pattern
800    /// pre-order — the same canonical slot order the synthesized kernel's
801    /// trailing `, float p0, float p1, …` launch parameters are declared in
802    /// (the synthesizer's scalar ABI appends them after `long long n`, always
803    /// `float`-typed regardless of the kernel's element dtype). Only produced
804    /// by `compile_one`'s `is_runtime` arm; a param-free runtime op carries
805    /// `OpParams::None` instead.
806    JitScalars {
807        /// Slot values, pattern pre-order. `f64` at rest (the graph-side
808        /// carrier); the CUDA launch narrows each to `f32` per the ABI.
809        scalars: Vec<f64>,
810    },
811
812    /// NonZeroIndices execution parameters. 1 input `x` (the value
813    /// tensor); one bundled output `[indices [capacity] U32 ; count
814    /// [1] U32]` where `capacity == x.elem_count()`. The kernel writes
815    /// the ascending flat indices of `x`'s nonzero elements into slot 0
816    /// (first `count` entries) and the runtime `count` into slot 1.
817    ///
818    /// `count_sym` is the [`fuel_ir::symbol::SymId`] the executor binds to the realized
819    /// `count` in the per-pass `SymEnv` *after* this op runs — the
820    /// data-determined dynamic-shape seam. The kernel itself ignores it.
821    NonZeroIndices {
822        capacity: usize,
823        count_sym: fuel_ir::SymId,
824    },
825}
826
827// =============================================================================
828// Phase 7.5 B5 — kernel binding table
829// =============================================================================
830
831/// Maps `(OpKind, KernelDTypes, BackendId)` triples to dispatch wrapper
832/// functions, where `KernelDTypes` lists per-operand dtypes (inputs in
833/// order, then outputs). Built once at backend registration time
834/// (typically a process-wide `OnceLock` though that's not enforced
835/// here for testability), consulted at execute time via lookup.
836///
837/// Same-dtype ops register `[T, T, ..., T]` for the right operand
838/// count; mixed-precision ops (Cast, future F32×BF16→F32 matmul)
839/// register the exact combo. Variadic ops (Concat) register a
840/// canonical short shape `[T, T]` (one input dtype + output dtype);
841/// the lookup site for those ops collapses its dtypes vector to the
842/// same shorthand.
843///
844/// Backends register their wrappers via the `dispatch::register_*`
845/// functions in this crate (e.g.
846/// [`crate::dispatch::register_cpu_kernels`]).
847/// Cost-fn signature for primitive-op registrations stored in
848/// [`KernelBindingTable`]. Mirrors the fused-op cost-fn shape but
849/// takes [`OpParams`] (the binding-table param payload) instead of
850/// `FusedOpParams`.
851///
852/// Implementations return a [`crate::fused::CostEstimate`] computed
853/// statically from shapes + dtypes + op-specific params + backend
854/// capabilities. The architecture's Layer-1 (FLOP-count + bandwidth)
855/// cost model lives here; Layer-2 empirical refinement composes on
856/// top via the telemetry framework, not by changing this signature.
857pub type CostFn = fn(
858    &[fuel_ir::Shape],
859    &[DType],
860    &OpParams,
861    &fuel_ir::backend::BackendCapabilities,
862) -> crate::fused::CostEstimate;
863
864/// Sentinel "no cost claim" function — returns
865/// [`crate::fused::CostEstimate::default`] (all-zero). The fill pass
866/// (`fill_unset_cpu_cost`) recognizes this exact function pointer
867/// to decide which entries get the OpKind-family default.
868pub fn unknown_cost(
869    _shapes: &[fuel_ir::Shape],
870    _dtypes: &[DType],
871    _params: &OpParams,
872    _caps: &fuel_ir::backend::BackendCapabilities,
873) -> crate::fused::CostEstimate {
874    crate::fused::CostEstimate::default()
875}
876
877/// One concrete kernel registered against a `(OpKind, dtypes, backend)`
878/// decision-point key. Phase 7.6 step 9a: a single key now carries
879/// `SmallVec<[BindingEntry; 2]>` — multiple alternatives compete at
880/// the same decision point (e.g. cuBLAS bf16 matmul + CUTLASS bf16
881/// matmul at `(MatMul, [BF16, BF16, BF16], Cuda)`). The route picker
882/// (step 9b) selects among them at plan time; today's single-impl
883/// callers (`lookup`, `lookup_with_caps`, `lookup_precision`,
884/// `lookup_cost`) return the first entry, preserving the pre-9a
885/// behavior for sites that haven't migrated.
886#[derive(Clone, Copy, Debug)]
887pub struct BindingEntry {
888    pub kernel: KernelRef,
889    pub caps: KernelCaps,
890    pub precision: crate::fused::PrecisionGuarantee,
891    pub cost: CostFn,
892    /// Diagnostic tag identifying the kernel's implementation source
893    /// when multiple alternatives register at the same `(op, dtypes,
894    /// backend)` key. Used to distinguish e.g. AOCL's matmul from
895    /// MKL's matmul from the portable scalar matmul — all three live
896    /// at `(MatMul, [F32×3], Cpu)` as siblings.
897    ///
898    /// `""` is the default for kernels that don't need to distinguish.
899    /// Conventional values: `"portable-cpu"` for fuel-cpu-backend
900    /// scalar/gemm kernels, `"aocl"` for AOCL-BLAS, `"mkl"` for oneMKL,
901    /// `"cublas"` / `"cutlass"` for CUDA variants. The string is
902    /// diagnostic-only — never used for dispatch routing (the kernel
903    /// function pointer is the dispatch identifier).
904    pub kernel_source: &'static str,
905    /// Whether this kernel's FKC accept-contract is the **GENERIC**
906    /// (fully-permissive strided) one — admissible anywhere because it
907    /// imposes no structure tightness (FKC §4.12). This is the
908    /// structural-**miss** fallback bit: when the winning contract at a
909    /// dispatch cell is generic, a structure-specialized kernel would have
910    /// fit but none is registered, and the Baracuda miss telemetry records
911    /// the demand.
912    ///
913    /// Computed **once at registration** by the FKC importer from the
914    /// kernel's retained `ResolvedLayout` set
915    /// ([`crate::fkc::is_generic_contract`]) and stamped here, so
916    /// the live dispatch pick site reads a precomputed bool rather than
917    /// re-deriving genericity from the lossy single-bool [`KernelCaps`].
918    ///
919    /// **Hand-written registrations default `false`.** Every non-FKC
920    /// `register*` path routes through
921    /// [`KernelBindingTable::register_full_with_source`], which sets this
922    /// `false`: genericity is a claim about being the FKC generic-fallback
923    /// contract in Baracuda's structure-key specialization space, and a
924    /// hand-written kernel makes no such claim. This holds even for a
925    /// hand-written strided kernel (`register_with_caps(strided_input=true)`):
926    /// strided-capability is not the same as being the generic fallback, and
927    /// conflating them would fabricate a miss demand signal for cells that are
928    /// not part of Baracuda's matrix. Only the FKC importer, which computed
929    /// genericity from the declared contract, ever sets this `true`.
930    pub is_generic: bool,
931    /// Stable per-implementation-version hash — the fifth axis of the FKC
932    /// kernel-identity basis tuple (FKC §4.11), pinning the exact kernel build
933    /// so a persisted plan / telemetry record re-resolves to it. `0`
934    /// ([`crate::fused::KernelRevisionHash::UNTRACKED`]) for hand-written
935    /// registrations (which carry no revision); the FKC importer threads the
936    /// contract-computed revision from `ResolvedPrimitive.revision` here. Read
937    /// by the Baracuda dispatch-telemetry `ImplId` at the plan pick site so the
938    /// `chosen`/`candidates` ids carry a real revision instead of a stamped `0`.
939    pub kernel_revision_hash: u64,
940    /// The contract's parsed cost-expression AST (FKC §4.4 / adoption plan
941    /// §2.3), when the kernel came from an FKC-imported contract that
942    /// declares one. `&'static` so the entry stays `Copy` (`CompiledCostExpr`
943    /// derives `Debug`, which is all `&'static T` needs to stay `Copy` /
944    /// `Clone` / `Debug` itself). `None` for every hand-written registration
945    /// (`register`/`register_full*`) — those carry no declared cost AST, only
946    /// a `CostFn` fn-pointer. Only the FKC importer, once it lowers a
947    /// contract's cost block to a live `CostFn` (a later Group-2 task),
948    /// stamps `Some(&CompiledCostExpr)` here.
949    pub cost_expr: Option<&'static crate::fkc::CompiledCostExpr>,
950}
951
952/// The binding table's op key — generalized so **runtime-registered** fused
953/// ops live in the SAME registry as static kernels (the 2026-07-08
954/// decisions-log end-state; retires the transitional runtime-kernel sidecar).
955///
956/// `Static` is the compile-time `OpKind` family every existing registration
957/// uses (a bare `OpKind` converts via `From`, so those call sites are
958/// unchanged). `RuntimeFused` names a Tier-2 (JIT-synthesized / import-time)
959/// fused op by its runtime `FusedOpId` (`>= RUNTIME_FUSED_BASE`) — the id IS
960/// the op identity, so no fake `OpKind` ever enters the table.
961#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
962pub enum BindingKey {
963    /// A compile-time op family (every static kernel registration).
964    Static(OpKind),
965    /// A runtime-registered fused op, keyed by its runtime id.
966    RuntimeFused(FusedOpId),
967}
968
969impl From<OpKind> for BindingKey {
970    fn from(op: OpKind) -> Self {
971        BindingKey::Static(op)
972    }
973}
974
975impl BindingKey {
976    /// The `Static` op kind, if this is a static-family key.
977    pub fn static_op(self) -> Option<OpKind> {
978        match self {
979            BindingKey::Static(op) => Some(op),
980            BindingKey::RuntimeFused(_) => None,
981        }
982    }
983}
984
985/// `Clone` is load-bearing, not a convenience: the process-wide table is
986/// published as a copy-on-write snapshot (`RwLock<Arc<KernelBindingTable>>`
987/// in `dispatch.rs`), so a writer clones the current table, mutates the
988/// clone, and swaps the pointer. Readers therefore never hold a lock guard.
989/// The clone is shallow-ish and cheap — [`BindingEntry`] is `Copy` and the
990/// keys are `Copy`/`SmallVec`, so it is a `HashMap` bulk copy of POD, on a
991/// write-rare path (backend init + runtime-fusion adoption).
992#[derive(Default, Clone)]
993pub struct KernelBindingTable {
994    bindings: HashMap<(BindingKey, KernelDTypes, BackendId), SmallVec<[BindingEntry; 2]>>,
995}
996
997/// The outcome of [`KernelBindingTable::unique_runtime_fused`] — three
998/// distinct facts, deliberately not collapsed into an `Option`.
999#[derive(Debug)]
1000pub enum RuntimeFusedLookup<'a> {
1001    /// No runtime-fused binding for this `(fid, backend)`.
1002    NotBound,
1003    /// Exactly one dtype tuple is registered; this is its first alternative.
1004    Unique(&'a [DType], &'a BindingEntry),
1005    /// Several dtype tuples share this id. **No kernel is returned**, because
1006    /// any choice among them would be arbitrary — and one of them may have a
1007    /// different operand arity than the caller expects.
1008    Ambiguous { signatures: Vec<Vec<DType>> },
1009}
1010
1011impl KernelBindingTable {
1012    pub fn new() -> Self {
1013        Self {
1014            bindings: HashMap::new(),
1015        }
1016    }
1017
1018    /// Register a dispatch wrapper for `(op, dtypes, backend)` with the
1019    /// default (all-false) capabilities. `dtypes` is the per-operand
1020    /// dtype list — inputs in order, then outputs.
1021    ///
1022    /// Phase 7.6 step 9a: multiple distinct kernels may register
1023    /// against the same `(op, dtypes, backend)` key — they become
1024    /// sibling alternatives at one decision point. Registration is
1025    /// **append-only and never panics**; the **same** `KernelRef`
1026    /// function pointer registered twice is detected by
1027    /// [`Self::finalize`] (run once after bulk registration) and
1028    /// returned as a `Result`, not raised as an inline panic.
1029    ///
1030    /// PrecisionGuarantee defaults to
1031    /// [`PrecisionGuarantee::UNAUDITED`](crate::fused::PrecisionGuarantee::UNAUDITED).
1032    /// Step-7b convention: the always-built backend
1033    /// (fuel-cpu-backend) runs [`Self::fill_unset_cpu_precision`] at
1034    /// the end of its bulk registration pass to upgrade every UNAUDITED
1035    /// CPU entry to `PRIMITIVE_DETERMINISTIC_CPU` (bit-stable per
1036    /// hardware). Kernels with weaker guarantees should call
1037    /// [`Self::register_with_precision`] explicitly *before* the fill
1038    /// pass to opt out of the default.
1039    pub fn register(
1040        &mut self,
1041        op: impl Into<BindingKey>,
1042        dtypes: &[DType],
1043        backend: BackendId,
1044        kernel: KernelRef,
1045    ) {
1046        self.register_full(
1047            op,
1048            dtypes,
1049            backend,
1050            kernel,
1051            KernelCaps::empty(),
1052            crate::fused::PrecisionGuarantee::UNAUDITED,
1053            unknown_cost,
1054        );
1055    }
1056
1057    /// Register a dispatch wrapper with explicit capability flags.
1058    /// Used by binding sites that opt into kernel-side broadcast or
1059    /// other non-default behavior — the executor consults the caps to
1060    /// decide whether to auto-Contiguize inputs before kernel call.
1061    pub fn register_with_caps(
1062        &mut self,
1063        op: impl Into<BindingKey>,
1064        dtypes: &[DType],
1065        backend: BackendId,
1066        kernel: KernelRef,
1067        caps: KernelCaps,
1068    ) {
1069        self.register_full(
1070            op,
1071            dtypes,
1072            backend,
1073            kernel,
1074            caps,
1075            crate::fused::PrecisionGuarantee::UNAUDITED,
1076            unknown_cost,
1077        );
1078    }
1079
1080    /// Register with an explicit [`crate::fused::PrecisionGuarantee`].
1081    /// Use this when a kernel has a precision claim that differs from
1082    /// the bulk-fill default (e.g., a multi-threaded reduction with
1083    /// non-deterministic accumulation order — bit_stable_on_same_hardware
1084    /// must be false).
1085    pub fn register_with_precision(
1086        &mut self,
1087        op: impl Into<BindingKey>,
1088        dtypes: &[DType],
1089        backend: BackendId,
1090        kernel: KernelRef,
1091        precision: crate::fused::PrecisionGuarantee,
1092    ) {
1093        self.register_full(
1094            op,
1095            dtypes,
1096            backend,
1097            kernel,
1098            KernelCaps::empty(),
1099            precision,
1100            unknown_cost,
1101        );
1102    }
1103
1104    /// Backwards-compatible alias for full-form registration without
1105    /// an explicit cost function. New code should prefer
1106    /// [`Self::register_full`].
1107    pub fn register_with_caps_and_precision(
1108        &mut self,
1109        op: impl Into<BindingKey>,
1110        dtypes: &[DType],
1111        backend: BackendId,
1112        kernel: KernelRef,
1113        caps: KernelCaps,
1114        precision: crate::fused::PrecisionGuarantee,
1115    ) {
1116        self.register_full(op, dtypes, backend, kernel, caps, precision, unknown_cost);
1117    }
1118
1119    /// Phase 7.6 step 8: full-form register with caps + precision +
1120    /// cost. Cost defaults to [`unknown_cost`] in the other
1121    /// signatures; sites with non-default cost claims must use this
1122    /// form (and not be overwritten by the bulk
1123    /// [`Self::fill_unset_cpu_cost`] pass, which only touches
1124    /// entries whose cost is still `unknown_cost`).
1125    ///
1126    /// Phase 7.6 step 9a: appends to the alternative set for `(op,
1127    /// dtypes, backend)`. Distinct `KernelRef` function pointers
1128    /// compose as siblings. Append-only — a duplicate `KernelRef` is
1129    /// detected by [`Self::finalize`] after bulk registration, not by
1130    /// an inline panic (see [`Self::register`]).
1131    pub fn register_full(
1132        &mut self,
1133        op: impl Into<BindingKey>,
1134        dtypes: &[DType],
1135        backend: BackendId,
1136        kernel: KernelRef,
1137        caps: KernelCaps,
1138        precision: crate::fused::PrecisionGuarantee,
1139        cost: CostFn,
1140    ) {
1141        self.register_full_with_source(op, dtypes, backend, kernel, caps, precision, cost, "");
1142    }
1143
1144    /// Phase: backend-extensions refactor (2026-06-07). Same as
1145    /// [`Self::register_full`] but tags the binding with a
1146    /// `kernel_source` identifier used to distinguish kernels that
1147    /// register at the same `(op, dtypes, backend)` key from
1148    /// different implementation sources (AOCL vs MKL vs portable
1149    /// CPU, etc.). The tag is diagnostic-only — the picker still
1150    /// distinguishes alternatives by function-pointer identity.
1151    pub fn register_full_with_source(
1152        &mut self,
1153        op: impl Into<BindingKey>,
1154        dtypes: &[DType],
1155        backend: BackendId,
1156        kernel: KernelRef,
1157        caps: KernelCaps,
1158        precision: crate::fused::PrecisionGuarantee,
1159        cost: CostFn,
1160        kernel_source: &'static str,
1161    ) {
1162        // Hand-written registrations make no FKC generic-fallback claim —
1163        // see [`BindingEntry::is_generic`]. The FKC importer uses
1164        // [`Self::register_full_with_source_generic`] to stamp the computed
1165        // bit. Hand-written kernels carry no revision, so the revision axis is
1166        // `UNTRACKED` (`0`); only the FKC importer threads a real revision.
1167        self.register_full_with_source_generic(
1168            op,
1169            dtypes,
1170            backend,
1171            kernel,
1172            caps,
1173            precision,
1174            cost,
1175            kernel_source,
1176            false,
1177            crate::fused::KernelRevisionHash::UNTRACKED.0,
1178            None,
1179        );
1180    }
1181
1182    /// Full-form register with the FKC structural-fallback `is_generic` bit
1183    /// (see [`BindingEntry::is_generic`]). The FKC importer computes the bit
1184    /// once from a kernel's retained `ResolvedLayout` set
1185    /// ([`crate::fkc::is_generic_contract`]) and stamps it here;
1186    /// every hand-written path routes through
1187    /// [`Self::register_full_with_source`], which passes `false`.
1188    ///
1189    /// Otherwise identical to [`Self::register_full_with_source`]:
1190    /// append-only, never-panic; the same `KernelRef` on one key is caught by
1191    /// [`Self::finalize`], not an inline panic.
1192    pub fn register_full_with_source_generic(
1193        &mut self,
1194        op: impl Into<BindingKey>,
1195        dtypes: &[DType],
1196        backend: BackendId,
1197        kernel: KernelRef,
1198        caps: KernelCaps,
1199        precision: crate::fused::PrecisionGuarantee,
1200        cost: CostFn,
1201        kernel_source: &'static str,
1202        is_generic: bool,
1203        kernel_revision_hash: u64,
1204        cost_expr: Option<&'static crate::fkc::CompiledCostExpr>,
1205    ) {
1206        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1207        let entry = BindingEntry {
1208            kernel,
1209            caps,
1210            precision,
1211            cost,
1212            kernel_source,
1213            is_generic,
1214            kernel_revision_hash,
1215            cost_expr,
1216        };
1217        // Append-only (never-panic): distinct `KernelRef`s compose as
1218        // sibling alternatives at one decision point; the *same*
1219        // function pointer registered twice is NOT rejected inline.
1220        // [`Self::finalize`] detects duplicates after bulk registration
1221        // and returns a `Result`, so the static init boundary can
1222        // fail-fast (`.expect()`) while a dynamic importer surfaces the
1223        // error — honoring never-panic on the import path.
1224        self.bindings.entry(key).or_default().push(entry);
1225    }
1226
1227    /// Validate the fully-assembled table: within the alternative set
1228    /// for any one `(op, dtypes, backend)` key, each `KernelRef`
1229    /// function pointer must appear **at most once**. Distinct
1230    /// alternatives compose as siblings; the same pointer twice is a
1231    /// registration bug (a copy-paste in a hand-written table, or a
1232    /// contract importer wiring one kernel onto two keys that collapse).
1233    ///
1234    /// `register*` is append-only and never panics; this single pass —
1235    /// run once after bulk registration — surfaces a duplicate as a
1236    /// typed `Result`. The static init boundary
1237    /// ([`crate::dispatch::global_bindings`]) `.expect()`s it (fail-fast
1238    /// at startup for hand-written tables); the FKC contract importer
1239    /// will call it with `?`. This is the never-panic replacement for
1240    /// the former inline duplicate `panic!`.
1241    pub fn finalize(&self) -> Result<()> {
1242        for ((op, dtypes, backend), alts) in self.bindings.iter() {
1243            for i in 0..alts.len() {
1244                let ptr_i = alts[i].kernel as *const () as usize;
1245                for entry_j in &alts[i + 1..] {
1246                    if entry_j.kernel as *const () as usize == ptr_i {
1247                        return Err(Error::Msg(format!(
1248                            "KernelBindingTable: duplicate KernelRef registered \
1249                             for (op={op:?}, dtypes={dtypes:?}, backend={backend:?}). \
1250                             The same function pointer was registered twice; \
1251                             distinct alternatives at one decision point must be \
1252                             distinct `fn` items."
1253                        )));
1254                    }
1255                }
1256            }
1257        }
1258        Ok(())
1259    }
1260
1261    /// Phase 7.6 step 7b: upgrade every UNAUDITED-precision CPU
1262    /// registration to the supplied `default`. Convention is to call
1263    /// this at the *end* of bulk registration, so any
1264    /// `register_with_precision(...)` calls that explicitly claimed a
1265    /// non-default value are preserved. The architecture-target
1266    /// shape would be precision-per-call-site, but for the ~335 CPU
1267    /// primitive registrations that all share the deterministic
1268    /// F32-accumulator property, a fill pass keeps the call sites
1269    /// concise without sacrificing the architectural commitment
1270    /// (every entry ends up with an explicit, non-UNAUDITED precision
1271    /// claim before lookup is ever exercised).
1272    ///
1273    /// Only entries with `backend == BackendId::Cpu` and the current
1274    /// `PrecisionGuarantee::UNAUDITED` sentinel are touched. Non-CPU
1275    /// backends register their own precision claims; non-UNAUDITED
1276    /// entries are preserved.
1277    ///
1278    /// Step 9a: applies to **every alternative** registered under a
1279    /// CPU key, not just the first — so a key with N siblings all
1280    /// starting at UNAUDITED ends with N entries upgraded to `default`.
1281    pub fn fill_unset_cpu_precision(&mut self, default: crate::fused::PrecisionGuarantee) {
1282        for ((_, _, backend), alts) in self.bindings.iter_mut() {
1283            if *backend != BackendId::Cpu {
1284                continue;
1285            }
1286            for entry in alts.iter_mut() {
1287                let p = &mut entry.precision;
1288                // Upgrade entries that claim nothing — EXCEPT an audited
1289                // "no static bound applies" conclusion.
1290                //
1291                // GAP-095: the old predicate was purely structural ("all four
1292                // value fields at defaults"), and the comment here asserted
1293                // that "a real weaker claim would set at least one of them."
1294                // That is false for `PrecisionGuarantee::none(reason)`, which
1295                // is field-identical to UNAUDITED and sets none of them. The
1296                // fill therefore overwrote an explicit audit conclusion with
1297                // `bit_stable_on_same_hardware: true` — asserting on the
1298                // kernel's behalf exactly what its audit had declined to
1299                // claim. FKC-4.8-0001 sanctions this fill for blocks left
1300                // absent or `audited: false`; it does not sanction that.
1301                //
1302                // Note what must KEEP being upgraded: a contract claim that
1303                // the V-FKC-9 ledger gate downgraded collapses to the
1304                // UNAUDITED sentinel exactly, so it stays eligible here. That
1305                // is load-bearing — every one of the CPU table's bit-stable
1306                // entries arrives through this path (GAP-077), so excluding
1307                // them would break the FKC-4.8-0001 coverage commitment
1308                // outright.
1309                if p.makes_no_static_claim() && !p.is_audited_no_bound() {
1310                    *p = default;
1311                }
1312            }
1313        }
1314    }
1315
1316    /// Phase 7.6 step 8: upgrade every still-`unknown_cost` CPU
1317    /// registration to the cost function returned by `dispatcher` for
1318    /// its OpKind. The dispatcher's contract: given an `OpKind`,
1319    /// return the appropriate cost-family function — typically
1320    /// [`crate::cost::default_cost_for_op_kind`] in production code,
1321    /// but tests may pass their own dispatcher to exercise specific
1322    /// cost shapes.
1323    ///
1324    /// Convention is to call this at the *end* of bulk registration,
1325    /// so any `register_full(...)` calls that explicitly claimed a
1326    /// non-default cost are preserved. The function-pointer equality
1327    /// check identifies UNKNOWN entries — any caller that wants a
1328    /// "weaker" claim with non-zero values must use a distinct
1329    /// function pointer (which won't compare equal to `unknown_cost`
1330    /// and thus won't be overwritten).
1331    ///
1332    /// Step 9a: applies to **every alternative** with a CPU backend —
1333    /// each sibling entry at a key starting at `unknown_cost` is
1334    /// upgraded independently.
1335    pub fn fill_unset_cpu_cost(&mut self, dispatcher: fn(OpKind) -> CostFn) {
1336        self.fill_unset_cost_for_backend(BackendId::Cpu, dispatcher);
1337    }
1338
1339    /// Per-backend variant of [`Self::fill_unset_cpu_cost`]. Walks
1340    /// every alternative whose backend matches `backend` and replaces
1341    /// `unknown_cost` entries with the dispatcher's choice for the
1342    /// op. Used by `fuel_vulkan_dispatch::register_vulkan_kernels`
1343    /// to bulk-fill cost functions after per-kernel precision
1344    /// registration; future MKL/AOCL/Metal backends register through
1345    /// this same helper.
1346    ///
1347    /// Backend-specific cost adjustments (e.g. higher
1348    /// `kernel_overhead_ns` for Vulkan command-buffer submission vs
1349    /// CPU's nested-loop call overhead) are a Layer-2 refinement —
1350    /// today's `default_cost_for_op_kind` returns the same CPU-flavored
1351    /// functions regardless of backend, which over-estimates Vulkan
1352    /// throughput on small tensors. Either pass a Vulkan-flavored
1353    /// dispatcher to this method, or rely on the empirical calibration
1354    /// framework's per-(op, dtype, backend) refinement.
1355    pub fn fill_unset_cost_for_backend(
1356        &mut self,
1357        backend: BackendId,
1358        dispatcher: fn(OpKind) -> CostFn,
1359    ) {
1360        let sentinel = unknown_cost as *const () as usize;
1361        for ((key, _, this_backend), alts) in self.bindings.iter_mut() {
1362            if *this_backend != backend {
1363                continue;
1364            }
1365            // Runtime-fused entries keep the sentinel: their cost derives from
1366            // the op's recipe (keyed by the runtime id), not an OpKind table.
1367            let BindingKey::Static(op) = key else {
1368                continue;
1369            };
1370            for entry in alts.iter_mut() {
1371                if (entry.cost as usize) == sentinel {
1372                    entry.cost = dispatcher(*op);
1373                }
1374            }
1375        }
1376    }
1377
1378    /// Look up the [`crate::fused::PrecisionGuarantee`] for a
1379    /// registered `(op, dtypes, backend)` triple. Returns the **first
1380    /// alternative**'s precision; multi-impl callers wanting all
1381    /// alternatives use [`Self::lookup_alternatives`]. Returns
1382    /// `PrecisionGuarantee::UNAUDITED` if the binding is missing —
1383    /// callers (notably the step-7b lint) treat that as "no claim"
1384    /// rather than panicking.
1385    pub fn lookup_precision(
1386        &self,
1387        op: impl Into<BindingKey>,
1388        dtypes: &[DType],
1389        backend: BackendId,
1390    ) -> crate::fused::PrecisionGuarantee {
1391        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1392        self.bindings
1393            .get(&key)
1394            .and_then(|alts| alts.first())
1395            .map(|e| e.precision)
1396            .unwrap_or(crate::fused::PrecisionGuarantee::UNAUDITED)
1397    }
1398
1399    /// Look up the [`CostFn`] for a registered `(op, dtypes, backend)`
1400    /// triple. Returns the **first alternative**'s cost; multi-impl
1401    /// callers wanting all alternatives use
1402    /// [`Self::lookup_alternatives`]. Returns [`unknown_cost`] for
1403    /// missing bindings — the step-8 lint treats that as "no cost
1404    /// claim."
1405    pub fn lookup_cost(
1406        &self,
1407        op: impl Into<BindingKey>,
1408        dtypes: &[DType],
1409        backend: BackendId,
1410    ) -> CostFn {
1411        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1412        self.bindings
1413            .get(&key)
1414            .and_then(|alts| alts.first())
1415            .map(|e| e.cost)
1416            .unwrap_or(unknown_cost)
1417    }
1418
1419    /// Iterate `(op, dtypes, backend, precision)` over every
1420    /// registered alternative — one tuple per `BindingEntry`, not per
1421    /// key. Used by the step-7b coverage lint, which groups by
1422    /// OpKind and checks the bit-stable commitment per group; the
1423    /// grouping handles N-alternatives-per-key naturally.
1424    pub fn iter_precision(
1425        &self,
1426    ) -> impl Iterator<
1427        Item = (
1428            OpKind,
1429            &[DType],
1430            BackendId,
1431            crate::fused::PrecisionGuarantee,
1432        ),
1433    > {
1434        self.bindings
1435            .iter()
1436            .filter_map(|((key, dtypes, backend), alts)| {
1437                // Static-kernel audit view: runtime-fused entries are outside the
1438                // per-OpKind commitments these iterators exist to check.
1439                key.static_op().map(|op| (op, dtypes, backend, alts))
1440            })
1441            .flat_map(|(op, dtypes, backend, alts)| {
1442                alts.iter()
1443                    .map(move |e| (op, dtypes.as_slice(), *backend, e.precision))
1444            })
1445    }
1446
1447    /// Iterate `(op, dtypes, backend, &entry)` over every registered
1448    /// alternative — one tuple per `BindingEntry`, mirroring
1449    /// [`Self::iter_precision`] but yielding the FULL entry (by reference)
1450    /// instead of projecting out just the `precision` field. Used by the
1451    /// FKC empirical verification harness (Task 4.4+), which needs the
1452    /// whole `BindingEntry` (the `kernel` fn pointer to invoke, `caps`,
1453    /// `kernel_revision_hash` for ledger keys, ...), not just one field.
1454    /// Runtime-fused/JIT entries are filtered out (`static_op()` returns
1455    /// `None` for them) — same "static-kernel audit view" as
1456    /// `iter_precision`/`iter_cost`.
1457    pub fn iter_entries(
1458        &self,
1459    ) -> impl Iterator<Item = (OpKind, &[DType], BackendId, &BindingEntry)> {
1460        self.bindings
1461            .iter()
1462            .filter_map(|((key, dtypes, backend), alts)| {
1463                key.static_op().map(|op| (op, dtypes, backend, alts))
1464            })
1465            .flat_map(|(op, dtypes, backend, alts)| {
1466                alts.iter()
1467                    .map(move |e| (op, dtypes.as_slice(), *backend, e))
1468            })
1469    }
1470
1471    /// Iterate `(op, dtypes, backend, cost_fn)` over every registered
1472    /// alternative — one tuple per `BindingEntry`. Used by the step-8
1473    /// coverage lint to check the "every primitive op has a
1474    /// non-default cost function" commitment per OpKind.
1475    pub fn iter_cost(&self) -> impl Iterator<Item = (OpKind, &[DType], BackendId, CostFn)> {
1476        self.bindings
1477            .iter()
1478            .filter_map(|((key, dtypes, backend), alts)| {
1479                key.static_op().map(|op| (op, dtypes, backend, alts))
1480            })
1481            .flat_map(|(op, dtypes, backend, alts)| {
1482                alts.iter()
1483                    .map(move |e| (op, dtypes.as_slice(), *backend, e.cost))
1484            })
1485    }
1486
1487    /// Iterate every registered `(op, dtypes, backend)` decision-point
1488    /// key — one item per key, regardless of how many alternatives
1489    /// share it. Consumed by `SystemTopology::build_at` to derive
1490    /// which backends have kernels registered + which (op, dtype)
1491    /// pairs each backend covers.
1492    pub fn iter_keys(&self) -> impl Iterator<Item = (OpKind, &[DType], BackendId)> {
1493        self.bindings.keys().filter_map(|(key, dtypes, backend)| {
1494            key.static_op().map(|op| (op, dtypes.as_slice(), *backend))
1495        })
1496    }
1497
1498    /// Whether ANY runtime-fused entry is bound for `(fid, backend)`,
1499    /// regardless of dtype tuple — the coarse capability-gate query (the
1500    /// optimizer's fuse/don't-fuse predicate is id-level; the dtype-precise
1501    /// check is the dispatch-time [`Self::lookup_with_caps`] itself).
1502    pub fn has_runtime_fused(&self, fid: FusedOpId, backend: BackendId) -> bool {
1503        self.bindings
1504            .keys()
1505            .any(|(k, _, b)| *b == backend && matches!(k, BindingKey::RuntimeFused(f) if *f == fid))
1506    }
1507
1508    /// Resolve `(fid, backend)` to a runtime-fused binding, **refusing to pick
1509    /// when the answer is ambiguous**.
1510    ///
1511    /// A [`FusedOpId`] names a RECIPE, not a signature: `register_runtime_fused`
1512    /// deduplicates on the region's base-map hash, so one id can legitimately
1513    /// carry several dtype tuples — `[F32, F32]` and `[F32, F32, F32]` are
1514    /// different arities under the same id. The pre-GAP-213 `first_runtime_fused` scanned
1515    /// for `(fid, backend)` and **binds `dtypes` without testing it**, so it
1516    /// answers such a question by `HashMap::iter()` order: a coin flip per
1517    /// process, and capable of returning a kernel of the wrong operand arity.
1518    ///
1519    /// The three outcomes are kept as three values rather than folded into an
1520    /// `Option`, because *not bound* and *ambiguous* are different facts with
1521    /// different fixes, and an `Option` would make them indistinguishable to the
1522    /// caller — the same collapse that let GAP-001 read as a version regression
1523    /// for eleven days.
1524    ///
1525    /// **Scope: this is the diagnostic/test resolution path.** Production
1526    /// dispatch never came through here — it uses [`Self::lookup_with_caps`],
1527    /// which takes the dtype tuple and does an exact keyed `get`, so it can
1528    /// neither be ambiguous nor return a wrong arity. See GAP-213.
1529    pub fn unique_runtime_fused(
1530        &self,
1531        fid: FusedOpId,
1532        backend: BackendId,
1533    ) -> RuntimeFusedLookup<'_> {
1534        let mut matches = self.bindings.iter().filter(|((k, _, b), _)| {
1535            *b == backend && matches!(k, BindingKey::RuntimeFused(f) if *f == fid)
1536        });
1537        let Some(((_, dtypes, _), alts)) = matches.next() else {
1538            return RuntimeFusedLookup::NotBound;
1539        };
1540        if matches.next().is_some() {
1541            let mut signatures: Vec<Vec<DType>> = self
1542                .bindings
1543                .iter()
1544                .filter(|((k, _, b), _)| {
1545                    *b == backend && matches!(k, BindingKey::RuntimeFused(f) if *f == fid)
1546                })
1547                .map(|((_, d, _), _)| d.to_vec())
1548                .collect();
1549            // HashMap order is per-process, so the report would otherwise vary run to
1550            // run. `DType` is not `Ord`, so key on arity then the debug spelling —
1551            // a presentation order only; nothing depends on which comes first.
1552            signatures.sort_by_key(|d| (d.len(), format!("{d:?}")));
1553            return RuntimeFusedLookup::Ambiguous { signatures };
1554        }
1555        match alts.first() {
1556            Some(e) => RuntimeFusedLookup::Unique(dtypes.as_slice(), e),
1557            None => RuntimeFusedLookup::NotBound,
1558        }
1559    }
1560
1561    /// **TEST-ONLY.** Drop every runtime-fused entry (static entries retained).
1562    /// The runtime-fused reset story: the metadata sidecar's Vec length is the
1563    /// id allocator, so clearing it MUST clear these bindings in the same
1564    /// breath or a reused id resolves a stale kernel
1565    /// (`runtime_fused_kernels::clear_runtime_fused_for_tests` does both).
1566    #[doc(hidden)]
1567    pub fn remove_runtime_fused_for_tests(&mut self) {
1568        self.bindings
1569            .retain(|(k, _, _), _| matches!(k, BindingKey::Static(_)));
1570    }
1571
1572    /// Look up the wrapper for `(op, dtypes, backend)`. Returns the
1573    /// **first alternative**'s [`KernelRef`]; for capability-aware
1574    /// lookup use [`Self::lookup_with_caps`]; for the full alternative
1575    /// set use [`Self::lookup_alternatives`].
1576    pub fn lookup(
1577        &self,
1578        op: impl Into<BindingKey>,
1579        dtypes: &[DType],
1580        backend: BackendId,
1581    ) -> Result<KernelRef> {
1582        self.lookup_with_caps(op, dtypes, backend).map(|(k, _)| k)
1583    }
1584
1585    /// Capability-aware lookup. Returns the first **dense-safe** alternative
1586    /// — the first sibling whose caps do NOT set
1587    /// [`KernelCaps::requires_broadcast`] — paired with its registered
1588    /// [`KernelCaps`]. A baked-broadcast sibling (`broadcast_stride0:
1589    /// required`) is SKIPPED, so a dense operand is never routed into a
1590    /// kernel that reads `in[0]`; the exclusion is order-independent (path
1591    /// 1a). For every existing binding — none set `requires_broadcast` —
1592    /// this is byte-identical to returning the first-registered alternative.
1593    /// Surfaces [`Error::NoBackendForOp`] on a missing binding OR when every
1594    /// sibling is broadcast-baked (production-correct: a surfaced miss, never
1595    /// a wrong read, no panic).
1596    pub fn lookup_with_caps(
1597        &self,
1598        op: impl Into<BindingKey>,
1599        dtypes: &[DType],
1600        backend: BackendId,
1601    ) -> Result<(KernelRef, KernelCaps)> {
1602        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1603        self.bindings
1604            .get(&key)
1605            .and_then(|alts| alts.iter().find(|e| !e.caps.requires_broadcast))
1606            .map(|e| (e.kernel, e.caps))
1607            .ok_or_else(|| {
1608                let (available_backends, supported_combinations) = self.coverage_diagnostic();
1609                Error::NoBackendForOp {
1610                    op: key.0.static_op().unwrap_or(OpKind::RuntimeFused),
1611                    dtypes: dtypes.to_vec(),
1612                    available_backends,
1613                    supported_combinations,
1614                }
1615                .bt()
1616            })
1617    }
1618
1619    /// Build the truthful `(available_backends, supported_combinations)`
1620    /// diagnostic pair for a [`Error::NoBackendForOp`] miss: the DISTINCT
1621    /// registered backends, and the full static `(backend, op, dtypes)` coverage
1622    /// (the useful "what exists" context). Shared by
1623    /// [`lookup_with_caps`](Self::lookup_with_caps) AND the plan-time miss
1624    /// (`plan::missing_binding_error`) so BOTH surface the same real context. The
1625    /// plan-time path formerly hardcoded `[]` here, which falsely reads as "no
1626    /// backend is registered" and misdirects diagnosis — a mixed-precision
1627    /// `(op, dtypes)` gap is not an empty registry (observed in the wild:
1628    /// `[F32, BF16, F32]` matmul reported as "available backends: []").
1629    pub fn coverage_diagnostic(&self) -> (Vec<BackendId>, Vec<CoverageBinding>) {
1630        let available_backends: Vec<BackendId> = self
1631            .bindings
1632            .keys()
1633            .map(|(_, _, b)| *b)
1634            .collect::<std::collections::HashSet<_>>()
1635            .into_iter()
1636            .collect();
1637        let supported_combinations: Vec<(BackendId, OpKind, Vec<DType>)> = self
1638            .bindings
1639            .keys()
1640            .filter_map(|(k, d, b)| k.static_op().map(|o| (*b, o, d.to_vec())))
1641            .collect();
1642        (available_backends, supported_combinations)
1643    }
1644
1645    /// Does **this specific backend** serve `(op, dtypes)` with a usable
1646    /// (non-broadcast-baked) binding?
1647    ///
1648    /// Mirrors [`lookup_with_caps`](Self::lookup_with_caps)'s success condition
1649    /// exactly — same key, same `!requires_broadcast` admission — but skips
1650    /// constructing the miss diagnostic, so it is cheap enough to call in a
1651    /// per-node loop (`coverage_diagnostic` walks the entire table).
1652    ///
1653    /// Ask this once per *candidate* backend. There is deliberately no
1654    /// "does any backend anywhere serve it?" sibling: a predicate that ignores
1655    /// the key's backend component cannot answer a dispatch question, because a
1656    /// node executes on one backend rather than on the union of them. Such a
1657    /// sibling did exist (`any_backend_supports`) and it caused a real defect —
1658    /// the dtype-reconciliation pass consulted it, so a backend a node could
1659    /// never run on suppressed the `Op::Cast` that node needed and planning
1660    /// dead-ended at `NoBackendForOp`. See `crate::plan::candidate_backends_for`.
1661    pub fn backend_supports(
1662        &self,
1663        op: impl Into<BindingKey>,
1664        dtypes: &[DType],
1665        backend: BackendId,
1666    ) -> bool {
1667        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1668        self.bindings
1669            .get(&key)
1670            .is_some_and(|alts| alts.iter().any(|e| !e.caps.requires_broadcast))
1671    }
1672
1673    /// Phase 7.6 step 9a: return the full set of registered
1674    /// alternatives at the `(op, dtypes, backend)` decision point.
1675    /// Order is registration order — append-on-register is the step-9a
1676    /// contract. The empty slice means "no kernel registered at this
1677    /// decision point."
1678    ///
1679    /// The route picker (step 9b) consumes this to rank alternatives
1680    /// by cost + precision at plan time. Single-impl callers continue
1681    /// to use [`Self::lookup_with_caps`] (which returns the first
1682    /// alternative — the route picker's job is the longer-term home
1683    /// for selection logic).
1684    pub fn lookup_alternatives(
1685        &self,
1686        op: impl Into<BindingKey>,
1687        dtypes: &[DType],
1688        backend: BackendId,
1689    ) -> &[BindingEntry] {
1690        let key = (op.into(), SmallVec::from_slice(dtypes), backend);
1691        self.bindings
1692            .get(&key)
1693            .map(|alts| alts.as_slice())
1694            .unwrap_or(&[])
1695    }
1696
1697    /// Total number of registered alternatives across all keys (not
1698    /// just unique keys). Step 9a: a key with N siblings counts N.
1699    pub fn len(&self) -> usize {
1700        self.bindings.values().map(|alts| alts.len()).sum()
1701    }
1702
1703    /// Empty binding table.
1704    pub fn is_empty(&self) -> bool {
1705        self.bindings.is_empty()
1706    }
1707
1708    /// Total number of unique `(op, dtypes, backend)` keys. Step 9a:
1709    /// distinct from [`Self::len`], which counts alternatives.
1710    pub fn key_count(&self) -> usize {
1711        self.bindings.len()
1712    }
1713}
1714
1715impl std::fmt::Debug for KernelBindingTable {
1716    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1717        f.debug_struct("KernelBindingTable")
1718            .field("keys", &self.bindings.len())
1719            .field("total_alternatives", &self.len())
1720            .finish_non_exhaustive()
1721    }
1722}
1723
1724#[cfg(test)]
1725mod tests {
1726    use super::*;
1727    use fuel_ir::DType;
1728
1729    /// Smoke: KernelRef can be constructed and stored.
1730    #[test]
1731    fn kernel_ref_stores_function_pointer() {
1732        fn dummy_kernel(
1733            _inputs: &[Arc<RwLock<Storage>>],
1734            _outputs: &mut [Arc<RwLock<Storage>>],
1735            _layouts: &[Layout],
1736            _params: &OpParams,
1737        ) -> Result<()> {
1738            Ok(())
1739        }
1740        let k: KernelRef = dummy_kernel;
1741        // Function pointer is Copy + Clone.
1742        let _k2 = k;
1743        let _k3: KernelRef = k;
1744    }
1745
1746    /// Smoke: OpParams variants construct cleanly and Debug-format.
1747    #[test]
1748    fn op_params_variants_construct() {
1749        let _ = OpParams::None;
1750        let _ = OpParams::Reduce {
1751            dims: vec![0, 1],
1752            keepdim: false,
1753        };
1754        let _ = OpParams::Matmul {
1755            lhs_batch_dims: vec![],
1756            rhs_batch_dims: vec![],
1757            m: 4,
1758            n: 8,
1759            k: 16,
1760            m_compute: MatmulM::All,
1761        };
1762        let _ = OpParams::Slice {
1763            dim: 0,
1764            start: 0,
1765            end: 10,
1766            step: 1,
1767        };
1768        let _ = OpParams::Cast;
1769        let _ = OpParams::Affine { mul: 2.0, add: 1.0 };
1770        // Debug format compiles.
1771        let _ = format!("{:?}", OpParams::None);
1772    }
1773
1774    /// Smoke: a hand-constructed kernel that allocates the output
1775    /// Storage outside this crate would be:
1776    ///   1. allocate output via fuel_memory::alloc_cpu_zeroed
1777    ///   2. wrap inputs as &[Arc<RwLock<Storage>>]
1778    ///   3. call the kernel
1779    ///
1780    /// Phase B5 lands the first such migration; B1 just type-checks
1781    /// the surface.
1782    #[test]
1783    fn kernel_ref_can_be_called() {
1784        fn copy_kernel(
1785            inputs: &[Arc<RwLock<Storage>>],
1786            outputs: &mut [Arc<RwLock<Storage>>],
1787            _layouts: &[Layout],
1788            _params: &OpParams,
1789        ) -> Result<()> {
1790            // Simplest real kernel: copy bytes from inputs[0] to outputs[0].
1791            let in_arc = &inputs[0];
1792            let out_arc = &outputs[0];
1793            let in_guard = in_arc.read().unwrap();
1794            let mut out_guard = out_arc.write().unwrap();
1795            let in_bytes = match &in_guard.inner {
1796                fuel_memory::BackendStorage::Cpu(s) => s.bytes(),
1797                #[allow(unreachable_patterns)]
1798                _ => return Ok(()),
1799            };
1800            if let fuel_memory::BackendStorage::Cpu(s) = &mut out_guard.inner {
1801                s.bytes_mut().copy_from_slice(in_bytes);
1802            }
1803            Ok(())
1804        }
1805
1806        let input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
1807        let output = fuel_memory::alloc_cpu_zeroed(DType::F32, 4).unwrap();
1808        let inputs = vec![Arc::new(RwLock::new(input))];
1809        let mut outputs = vec![Arc::new(RwLock::new(output))];
1810
1811        let k: KernelRef = copy_kernel;
1812        k(&inputs, &mut outputs, &[], &OpParams::None).unwrap();
1813
1814        // Output bytes match input.
1815        let out_guard = outputs[0].read().unwrap();
1816        if let fuel_memory::BackendStorage::Cpu(s) = &out_guard.inner {
1817            let typed: &[f32] = s.as_slice().unwrap();
1818            assert_eq!(typed, &[1.0, 2.0, 3.0, 4.0]);
1819        }
1820    }
1821
1822    fn ok_kernel(
1823        _inputs: &[Arc<RwLock<Storage>>],
1824        _outputs: &mut [Arc<RwLock<Storage>>],
1825        _layouts: &[Layout],
1826        _params: &OpParams,
1827    ) -> Result<()> {
1828        Ok(())
1829    }
1830
1831    fn ok_kernel_alt(
1832        _inputs: &[Arc<RwLock<Storage>>],
1833        _outputs: &mut [Arc<RwLock<Storage>>],
1834        _layouts: &[Layout],
1835        _params: &OpParams,
1836    ) -> Result<()> {
1837        Ok(())
1838    }
1839
1840    /// Phase 7.6 step 9a: two distinct `KernelRef`s register against
1841    /// the same `(op, dtypes, backend)` key as sibling alternatives.
1842    /// `lookup_with_caps` returns the first; `lookup_alternatives`
1843    /// returns both in registration order.
1844    #[test]
1845    fn step_9a_two_alternatives_append_then_first_wins_on_legacy_lookup() {
1846        use fuel_ir::probe::BackendId;
1847        let mut table = KernelBindingTable::new();
1848        let dts = [DType::BF16, DType::BF16, DType::BF16];
1849        table.register(OpKind::MatMul, &dts, BackendId::Cuda, ok_kernel);
1850        table.register(OpKind::MatMul, &dts, BackendId::Cuda, ok_kernel_alt);
1851
1852        // Legacy single-impl lookup returns the first-registered.
1853        let (k1, _caps) = table
1854            .lookup_with_caps(OpKind::MatMul, &dts, BackendId::Cuda)
1855            .unwrap();
1856        assert_eq!(k1 as *const () as usize, ok_kernel as *const () as usize);
1857
1858        // Multi-impl lookup returns both in registration order.
1859        let alts = table.lookup_alternatives(OpKind::MatMul, &dts, BackendId::Cuda);
1860        assert_eq!(alts.len(), 2);
1861        assert_eq!(
1862            alts[0].kernel as *const () as usize,
1863            ok_kernel as *const () as usize
1864        );
1865        assert_eq!(
1866            alts[1].kernel as *const () as usize,
1867            ok_kernel_alt as *const () as usize
1868        );
1869
1870        // Step-9a accounting helpers stay consistent.
1871        assert_eq!(table.key_count(), 1, "one decision point");
1872        assert_eq!(table.len(), 2, "two alternatives total");
1873    }
1874
1875    /// FKC gap-closure Task 2.1: hand-written registrations (the
1876    /// `register`/`register_full*` family that never touches the FKC
1877    /// importer) carry no declared cost-expression AST — `cost_expr`
1878    /// defaults to `None`. Only the FKC importer (a later Group-2 task)
1879    /// stamps a real `Some(&CompiledCostExpr)`.
1880    #[test]
1881    fn cost_expr_field_defaults_none_for_hand_written_registration() {
1882        use fuel_ir::probe::BackendId;
1883        let mut table = KernelBindingTable::new();
1884        let dts = [DType::F32, DType::F32, DType::F32];
1885        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel);
1886        let alts = table.lookup_alternatives(OpKind::AddElementwise, &dts, BackendId::Cpu);
1887        assert_eq!(alts.len(), 1);
1888        assert!(
1889            alts[0].cost_expr.is_none(),
1890            "hand-written registrations carry no declared cost AST"
1891        );
1892    }
1893
1894    /// Task 4.4: `iter_entries` mirrors `iter_precision`/`iter_cost` —
1895    /// yields one `(op, dtypes, backend, &entry)` tuple per registered
1896    /// alternative (both siblings at a shared key show up), and filters
1897    /// out `RuntimeFused` keys just like the precision/cost audit
1898    /// iterators (a "static-kernel audit view").
1899    #[test]
1900    fn iter_entries_yields_full_entries_and_filters_runtime_fused() {
1901        use fuel_ir::probe::BackendId;
1902        let mut table = KernelBindingTable::new();
1903        let dts = [DType::F32, DType::F32, DType::F32];
1904        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel);
1905        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel_alt);
1906        // A runtime-fused key — must be excluded from `iter_entries`.
1907        table.register(
1908            BindingKey::RuntimeFused(FusedOpId(FusedOpId::RUNTIME_FUSED_BASE)),
1909            &dts,
1910            BackendId::Cpu,
1911            ok_kernel,
1912        );
1913
1914        let entries: Vec<_> = table.iter_entries().collect();
1915        assert_eq!(
1916            entries.len(),
1917            2,
1918            "both AddElementwise alternatives, RuntimeFused excluded"
1919        );
1920        for (op, dtypes, backend, entry) in &entries {
1921            assert_eq!(*op, OpKind::AddElementwise);
1922            assert_eq!(*dtypes, dts.as_slice());
1923            assert_eq!(*backend, BackendId::Cpu);
1924            // Full entry is reachable, not just one projected field.
1925            let _ = entry.caps;
1926            let _ = entry.kernel_revision_hash;
1927        }
1928        let fns: Vec<usize> = entries
1929            .iter()
1930            .map(|(_, _, _, e)| e.kernel as *const () as usize)
1931            .collect();
1932        assert!(fns.contains(&(ok_kernel as *const () as usize)));
1933        assert!(fns.contains(&(ok_kernel_alt as *const () as usize)));
1934    }
1935
1936    /// Never-panic (option B): registering the same `KernelRef` twice
1937    /// against one key is append-only — it does NOT panic at
1938    /// registration. `finalize()` detects the duplicate and returns
1939    /// `Err`. (Replaces the former `#[should_panic]` guard.)
1940    #[test]
1941    /// FKC-CLAUSE: FKC-10.10-0001 — the boundary itself: registration stays
1942    /// infallible and `finalize()` RETURNS the duplicate as an error rather than
1943    /// panicking. This is why the clause does not require a `Result` signature on
1944    /// `register_full_with_source`.
1945    fn step_9a_duplicate_kernel_ref_detected_by_finalize_not_panic() {
1946        use fuel_ir::probe::BackendId;
1947        let mut table = KernelBindingTable::new();
1948        let dts = [DType::F32, DType::F32, DType::F32];
1949        table.register(OpKind::MatMul, &dts, BackendId::Cpu, ok_kernel);
1950        table.register(OpKind::MatMul, &dts, BackendId::Cpu, ok_kernel); // dup — must NOT panic
1951        let err = table
1952            .finalize()
1953            .expect_err("finalize must report the duplicate KernelRef");
1954        assert!(
1955            format!("{err}").contains("duplicate KernelRef"),
1956            "unexpected error: {err}"
1957        );
1958    }
1959
1960    /// Distinct sibling kernels under one key finalize cleanly.
1961    #[test]
1962    fn finalize_ok_for_distinct_sibling_kernels() {
1963        use fuel_ir::probe::BackendId;
1964        let mut table = KernelBindingTable::new();
1965        let dts = [DType::F32, DType::F32, DType::F32];
1966        table.register(OpKind::MatMul, &dts, BackendId::Cpu, ok_kernel);
1967        table.register(OpKind::MatMul, &dts, BackendId::Cpu, ok_kernel_alt);
1968        table
1969            .finalize()
1970            .expect("distinct sibling kernels must finalize OK");
1971    }
1972
1973    /// Path 1a: a `broadcast_stride0: required` (baked-broadcast) kernel
1974    /// reads its operand as stride-0; a dense operand routed there
1975    /// miscomputes (reads `in[0]` repeatedly). The realize pick MUST skip
1976    /// such a sibling when a generic one exists, and — the load-bearing
1977    /// part — that exclusion must NOT rest on the generic being registered
1978    /// first. Register the broadcast-baked one FIRST (adversarial: `first()`
1979    /// would return it) and assert the pick returns the GENERIC sibling.
1980    #[test]
1981    fn lookup_with_caps_skips_broadcast_baked_sibling_regardless_of_order() {
1982        use fuel_ir::probe::BackendId;
1983        let mut table = KernelBindingTable::new();
1984        let dts = [DType::F32, DType::F32, DType::F32];
1985        // Baked-broadcast sibling registered FIRST.
1986        table.register_with_caps(
1987            OpKind::AddElementwise,
1988            &dts,
1989            BackendId::Cpu,
1990            ok_kernel,
1991            KernelCaps {
1992                strided_input: true,
1993                requires_broadcast: true,
1994            },
1995        );
1996        // Generic dense-safe sibling registered SECOND.
1997        table.register_with_caps(
1998            OpKind::AddElementwise,
1999            &dts,
2000            BackendId::Cpu,
2001            ok_kernel_alt,
2002            KernelCaps {
2003                strided_input: true,
2004                requires_broadcast: false,
2005            },
2006        );
2007
2008        let (picked, caps) = table
2009            .lookup_with_caps(OpKind::AddElementwise, &dts, BackendId::Cpu)
2010            .expect("a dense-safe sibling exists");
2011        assert!(
2012            !caps.requires_broadcast,
2013            "the realize pick must never be a broadcast-baked kernel",
2014        );
2015        assert_eq!(
2016            picked as *const () as usize, ok_kernel_alt as *const () as usize,
2017            "lookup_with_caps must skip the broadcast-baked sibling and return the generic \
2018             one regardless of registration order",
2019        );
2020        // Both siblings coexist — the exclusion is at the pick, not at
2021        // registration (the baked-broadcast contract is still PRESENT).
2022        let alts = table.lookup_alternatives(OpKind::AddElementwise, &dts, BackendId::Cpu);
2023        assert_eq!(
2024            alts.len(),
2025            2,
2026            "both siblings registered; neither is dropped"
2027        );
2028    }
2029
2030    /// The corner that keeps the exclusion honest: if EVERY sibling is
2031    /// broadcast-baked (no dense-safe fallback), the pick is a surfaced
2032    /// miss (`NoBackendForOp`), NOT a silent wrong dense read.
2033    #[test]
2034    fn lookup_with_caps_misses_when_only_broadcast_baked_siblings_exist() {
2035        use fuel_ir::probe::BackendId;
2036        let mut table = KernelBindingTable::new();
2037        let dts = [DType::F32, DType::F32, DType::F32];
2038        table.register_with_caps(
2039            OpKind::AddElementwise,
2040            &dts,
2041            BackendId::Cpu,
2042            ok_kernel,
2043            KernelCaps {
2044                strided_input: true,
2045                requires_broadcast: true,
2046            },
2047        );
2048        assert!(
2049            table
2050                .lookup_with_caps(OpKind::AddElementwise, &dts, BackendId::Cpu)
2051                .is_err(),
2052            "no dense-safe sibling ⇒ honest miss, never a wrong read",
2053        );
2054    }
2055
2056    /// Phase 7.6 step 9a: `fill_unset_cpu_precision` upgrades every
2057    /// alternative under a CPU key, not just the first.
2058    #[test]
2059    fn step_9a_fill_passes_touch_every_alternative() {
2060        use crate::fused::PrecisionGuarantee;
2061        use fuel_ir::probe::BackendId;
2062        let mut table = KernelBindingTable::new();
2063        let dts = [DType::F32, DType::F32, DType::F32];
2064        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel);
2065        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel_alt);
2066
2067        // Both start at UNAUDITED.
2068        for e in table.lookup_alternatives(OpKind::AddElementwise, &dts, BackendId::Cpu) {
2069            assert!(!e.precision.bit_stable_on_same_hardware);
2070        }
2071
2072        let bit_stable = PrecisionGuarantee {
2073            bit_stable_on_same_hardware: true,
2074            max_ulp: Some(0),
2075            max_relative: None,
2076            max_absolute: None,
2077            notes: "test default",
2078        };
2079        table.fill_unset_cpu_precision(bit_stable);
2080
2081        // Both got upgraded.
2082        let alts = table.lookup_alternatives(OpKind::AddElementwise, &dts, BackendId::Cpu);
2083        assert_eq!(alts.len(), 2);
2084        for e in alts {
2085            assert!(e.precision.bit_stable_on_same_hardware);
2086            assert_eq!(e.precision.max_ulp, Some(0));
2087        }
2088    }
2089
2090    /// GAP-095: the CPU bulk fill must NOT overwrite an audited
2091    /// "no static bound applies" conclusion.
2092    ///
2093    /// `PrecisionGuarantee::none(reason)` and `PrecisionGuarantee::UNAUDITED`
2094    /// carry identical *values* — all four claim fields at their defaults —
2095    /// and differ only in `notes`. The fill's predicate was purely
2096    /// structural, so it conflated them and rewrote an explicit audit
2097    /// conclusion into `PRIMITIVE_DETERMINISTIC_CPU`: it asserted
2098    /// `bit_stable_on_same_hardware: true` on a kernel whose audit had
2099    /// specifically declined to claim it.
2100    ///
2101    /// FKC-4.8-0001 sanctions the fill for precision blocks left *absent* or
2102    /// `audited: false`. It does not sanction overwriting an `audited: true`
2103    /// + `none(reason)` conclusion.
2104    ///
2105    /// **Both directions asserted.** A test that only checked that
2106    /// `none(reason)` survives would also pass with the fill disabled
2107    /// outright, so the UNAUDITED sibling must still be upgraded in the same
2108    /// run — otherwise the test proves nothing about discrimination.
2109    #[test]
2110    fn gap_095_fill_preserves_audited_none_but_still_upgrades_unaudited() {
2111        use crate::fused::PrecisionGuarantee;
2112        use fuel_ir::probe::BackendId;
2113        let mut table = KernelBindingTable::new();
2114        let dts = [DType::F32, DType::F32, DType::F32];
2115
2116        const REASON: &str = "audited: accumulation order is scheduler-dependent; \
2117                              no static bound applies";
2118        // The audited conclusion — must survive untouched.
2119        table.register_with_precision(
2120            OpKind::MatMul,
2121            &dts,
2122            BackendId::Cpu,
2123            ok_kernel,
2124            PrecisionGuarantee::none(REASON),
2125        );
2126        // The never-audited placeholder — must still be upgraded.
2127        table.register(OpKind::AddElementwise, &dts, BackendId::Cpu, ok_kernel);
2128
2129        table.fill_unset_cpu_precision(PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU);
2130
2131        let audited = table
2132            .lookup_alternatives(OpKind::MatMul, &dts, BackendId::Cpu)
2133            .first()
2134            .expect("audited-none entry registered")
2135            .precision;
2136        assert!(
2137            !audited.bit_stable_on_same_hardware,
2138            "the fill asserted bit-stability on a kernel whose audit \
2139             explicitly concluded that no static bound applies",
2140        );
2141        assert_eq!(
2142            audited.notes, REASON,
2143            "the audit reason was overwritten — the reasoning that lived at \
2144             the registration site is gone",
2145        );
2146
2147        // Opposite direction: the fill must still do its job.
2148        let placeholder = table
2149            .lookup_alternatives(OpKind::AddElementwise, &dts, BackendId::Cpu)
2150            .first()
2151            .expect("unaudited entry registered")
2152            .precision;
2153        assert!(
2154            placeholder.bit_stable_on_same_hardware,
2155            "control FAILED: the UNAUDITED placeholder was not upgraded, so \
2156             this test would pass with the fill disabled entirely and proves \
2157             nothing about the discrimination it is meant to check",
2158        );
2159    }
2160}