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