fireline_grammar/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Frozen kernel-seam wire types — the JIT region / declarative-pattern grammar
3//! shared across the Fuel <-> backend-synthesizer seam (kernel-seam-interop
4//! §3/§5; fkc-fusion-patterns §3). **Types only, no logic, no Fuel-graph
5//! dependency**: a synthesizer backend (e.g. Baracuda) depends on this small
6//! crate; the `Op -> OpTag` projection (`fuel_graph::jit::op_to_tag`) and the
7//! structural matcher (`fuel_graph::jit::match_region`) stay Fuel-side because
8//! they need the graph.
9//!
10//! One [`PatternNode`] serves three roles: the **JIT region** (Fuel ->
11//! synthesizer, "build a kernel for this subgraph"), a contract's `pattern:`
12//! **re-fuse rule**, and a synthesized op's **`decompose`** (the region
13//! re-emitted). The operand-side projection (`OperandDesc`) is the synthesizer's
14//! `structure_key` input and lives in its types crate — not here.
15//!
16//! The handshake envelope (`SeamHello`, §3) lives in the sibling
17//! `fuel-kernel-seam-announce` crate, not here — a provider that only speaks
18//! capability negotiation shouldn't need to pull in this region grammar.
19
20/// The §6.20 shape-expression AST + canonical wire codec + evaluator — the
21/// KISS-consistent shape vocabulary, homed here (std-only) so `fuel-graph` can
22/// carry `Dim`/`ShapeExpr` in [`OpAttrs`] without depending on `fuel-dispatch`
23/// (which re-exports this module at `fkc::shape_expr` for its FKC importer).
24mod canonical;
25pub use canonical::UnresolvedAttr;
26
27pub mod shape_expr;
28
29// ===========================================================================
30// OpTag — the frozen functional-Op vocabulary (kernel-seam-interop §4.1)
31// ===========================================================================
32
33/// The §4.1 graph-`Op` vocabulary, **functional ops only** — the stable op
34/// identifier a [`PatternNode`] carries. Excludes in-place variants (a region
35/// is the *functional* subgraph; in-place is a Fuel-side scheduling rewrite)
36/// and structural / bookkeeping ops (`Const`, `Release`, `Alloc`, views, ...).
37/// The `Op -> OpTag` projection (`op_to_tag`) lives Fuel-side (it needs the
38/// graph `Op`); the inverse — which params an emitted op carries — rides
39/// [`OpAttrs`] + the `extract:` path.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41#[non_exhaustive]
42pub enum OpTag {
43 // binary arithmetic / extremum
44 Add,
45 Sub,
46 Mul,
47 Div,
48 Maximum,
49 Minimum,
50 Pow,
51 Rem,
52 // unary math
53 Neg,
54 Abs,
55 Sqr,
56 Sqrt,
57 Rsqrt,
58 Recip,
59 Exp,
60 Log,
61 Sin,
62 Cos,
63 // activations (GeluTanh = tanh-approx; Gelu = exact erf — distinct, §3 note)
64 Tanh,
65 Sigmoid,
66 Silu,
67 GeluTanh,
68 Gelu,
69 Relu,
70 Erf,
71 Step,
72 // rounding / sign
73 Floor,
74 Ceil,
75 Round,
76 Sign,
77 // scalar-param (value param-ized; attrs carries the slot)
78 AddScalar,
79 MulScalar,
80 PowI,
81 Clamp,
82 // comparison (-> U8 mask)
83 Equal,
84 Ne,
85 Lt,
86 Le,
87 Gt,
88 Ge,
89 // select / mask
90 Where,
91 MaskedFill,
92 // reductions (MaxDim: additive, Increment C slice 1 T4 — the D3 keepdim
93 // swap spells keepdim reduces as {Max,Sum,Mean}Dim + Unsqueeze)
94 SumAll,
95 MaxAll,
96 MinAll,
97 MeanAll,
98 SumDim,
99 MaxDim,
100 MeanDim,
101 ReduceSumTo,
102 ReduceMaxTo,
103 CumSum,
104 // matmul
105 MatMul,
106 // shape / layout (metadata or copy)
107 Transpose,
108 Permute,
109 Reshape,
110 BroadcastTo,
111 Unsqueeze,
112 Squeeze,
113 Cast,
114 Slice,
115 Concat,
116 Flip,
117 Roll,
118 Pad,
119 Triu,
120 Tril,
121 // indexing / gather-scatter
122 IndexSelect,
123 Gather,
124 IndexAdd,
125 ScatterAdd,
126 // fused-primitive helpers
127 LogSoftmaxLastDim,
128 // value source
129 Iota,
130
131 // --- source-op LEAF tokens (childless `Op` nodes; KISS four-leaf ack) ----
132 //
133 // A value a recipe needs as an operand is a **source op** — a childless
134 // `Op` — so the node schema stays closed to two kinds (`Op | Bind`) instead
135 // of growing a schema variant per value kind (recipe-grammar design input
136 // §2). The four byte arms below were acked by the KISS editor on 2026-07-23
137 // ("RULING RECORD — four-leaf-arm ack", no amendments).
138 //
139 // **Wire tokens only — no Fuel graph producer yet.** `jit::op_to_tag` emits
140 // none of these. `runtime_fused::tag_to_op` declines THREE of them (`Const`,
141 // `RuntimeScalar`, `ReducedCount`) as honest
142 // misses). Fuel expresses these values implicitly today (an `Op::Const`
143 // TENSOR operand, a `Runtime { scalars }` slot on the *consuming* op,
144 // `Op::ScanPlaceholder` inside `Op::Scan`'s body, Mean's divisor folded into
145 // `Op::MeanDim`); making them first-class recipe leaves is the flat-DAG-CSE
146 // recipe interior, still unbuilt. See `docs/recipe-signature-reference.md`
147 // §"source-op leaves".
148 /// Scalar literal leaf: a **dtype-agnostic bit pattern** (`const_bits`).
149 /// **NOT** Fuel's `Op::Const` (a whole constant TENSOR / weight leaf) — this
150 /// is the KISS `const` source op, a baked scalar value. Distinct from
151 /// [`OpTag::RuntimeScalar`]: a baked value and an unfilled dispatch slot are
152 /// not interchangeable.
153 Const,
154 /// Dispatch-bound scalar leaf: the `slot_index` of an **unfilled** scalar
155 /// slot (Fuel-side: the pre-order position in `FusedOpParams::Runtime {
156 /// scalars }`, counted by `runtime_fused::count_scalar_slots`).
157 RuntimeScalar,
158 /// The value-side product of extents over the reduced axes — the `Mean`
159 /// divisor, so `mean == div(reduce[sum,..](x), reduced_count(axis))` is one
160 /// flat DAG (canonical KISS §6.12-0001; the retired name was
161 /// `reduce_extent`). Single-axis, riding the same `axis` carrier as the
162 /// fold; it grows to a `reduce_axes` list ONLY in lockstep with the fold.
163 ReducedCount,
164 /// A body hole of `Op::Scan`: `role` (0 = carry, 1 = elem — see
165 /// [`SCAN_ROLE_CARRY`]/[`SCAN_ROLE_ELEM`]) + `index` (which `xs[i]` an
166 /// `elem` hole stands for; a `carry` hole is index 0 in the v1 single-carry
167 /// model).
168 ScanPlaceholder,
169
170 /// Fuel's bounded `lax.scan` recurrence primitive (`fuel_graph::Op::Scan`).
171 /// A **structural token** — like [`OpTag::ScanPlaceholder`], NOT a KISS base op:
172 /// its params (`n_xs`/`bound`/`emit`/`early_exit`) ride the Fuel-internal
173 /// [`OpAttrs`] `scan_*` fields and are NOT serialized to the §6.19
174 /// cross-producer wire (the empty-body `_` arm in
175 /// [`OpAttrs::to_canonical_bytes`]), exactly like the shape-relative
176 /// recipe-interior fields. The body sub-graph rides the node's trailing
177 /// operands (Phase-1 lax.scan input encoding:
178 /// `[init_carry, xs.., consts.., body_new_carry, body_y, [pred_exit]]`).
179 /// Re-emitted by `runtime_fused::tag_to_op`; no `op_to_tag` producer (a
180 /// scan node is a base-map terminal the matcher never recognizes).
181 Scan,
182
183 /// Multi-output slot projection (`fuel_graph::Op::View`) — the bundle
184 /// carrier a scan (or any multi-output producer) exposes its per-slot
185 /// outputs through. A structural token: the `slot` rides the Fuel-internal
186 /// `view_slot` [`OpAttrs`] field, not the §6.19 wire. On re-emit the slot's
187 /// shape/dtype come from the producer's `output_views` bundle (the emitter
188 /// sets that bundle when it re-emits the producing `Scan`), mirroring
189 /// `fuel_graph::Graph::view`.
190 View,
191
192 /// A **nested fused op** carried inside a recipe AS-IS
193 /// (`fuel_graph::Op::Fused(id, params)`) — the attention-trio decompose's
194 /// inner softmax (`flash_attn`/`paged_attn` emit an
195 /// `Op::Fused(SOFTMAX_LAST_DIM, ..)` node; `flash_attn_backward` an
196 /// `Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, ..)`). A **structural token** — like
197 /// [`OpTag::Scan`]/[`OpTag::View`], NOT a KISS base op: it names which registry entry the
198 /// node reconstructs to (via the [`OpAttrs::fused_op`] selector) and is
199 /// **Fuel-internal, NOT serialized to the §6.19 cross-producer wire** (a
200 /// `Fused` node hits the empty-body `_` arm of
201 /// [`OpAttrs::to_canonical_bytes`], exactly like the `scan_*`/`view_slot`
202 /// fields). Re-emitted by `runtime_fused::tag_to_op` for the param-less
203 /// nested fused ops (a small fid → params map); any param-carrying id is an
204 /// honest miss. No `op_to_tag` producer — the base map lowers past a nested
205 /// fused node (it recursively decomposes past itself), so the recipe just
206 /// re-carries it, keeping the softmax fused so the optimizer can re-cover it.
207 /// On re-emit its shape/dtype come from the named registry entry's
208 /// `shape_rule`/`dtype_rule` (`primitive_shape` honest-misses `Fused`).
209 Fused,
210}
211
212/// [`OpTag::ScanPlaceholder`] role code for the per-step recurrent **carry**
213/// hole. Matches `fuel_graph::ScanRole::Carry`'s declaration order.
214pub const SCAN_ROLE_CARRY: u8 = 0;
215/// [`OpTag::ScanPlaceholder`] role code for the per-step **element** hole (the
216/// slice of `xs[index]`). Matches `fuel_graph::ScanRole::Elem`.
217pub const SCAN_ROLE_ELEM: u8 = 1;
218
219/// Place a narrow dtype's **storage** bit pattern into the [`OpTag::Const`]
220/// leaf's `u64` carrier per the acked **MBZ narrow-dtype rule**: the storage
221/// bits occupy the LOW-order bits and the upper bits are ZERO (must-be-zero on
222/// read). `width_bits` is the dtype's storage width (16 for `f16`/`bf16`, 32 for
223/// `f32`/`u32`/`i32`, 64 for `f64`/`i64`); a width ≥ 64 is the identity.
224///
225/// A NaN payload rides **verbatim** — this masks, it never canonicalizes or
226/// quiets. Pure + never-panic (no shift overflow at width 0 or ≥ 64).
227pub fn const_bits_narrow(storage: u64, width_bits: u32) -> u64 {
228 if width_bits == 0 {
229 return 0;
230 }
231 if width_bits >= 64 {
232 return storage;
233 }
234 storage & ((1u64 << width_bits) - 1)
235}
236
237// ===========================================================================
238// PatternNode — the §3 declarative subgraph grammar
239// ===========================================================================
240
241/// Non-tensor attributes a [`PatternNode::Op`] carries (fkc-fusion-patterns
242/// §3a.4; Baracuda reconcile §2). For scalar-param ops the value is **not
243/// baked** — it identifies the slot the emitted `extract:` path points at, and
244/// the matcher re-reads the live value from the matched graph node at match
245/// time. Carries the load-bearing attributes the general vocabulary needs.
246#[derive(Clone, Debug, Default, PartialEq)]
247pub struct OpAttrs {
248 /// Scalar value(s) for scalar-param ops (`AddScalar`/`MulScalar`/`Clamp`),
249 /// as the region's snapshot of the slot (re-read live via `extract:`).
250 pub scalars: Vec<f64>,
251 /// Axis attribute for dim-bearing ops (reductions, `Triu`/`Tril` diagonal).
252 pub axis: Option<i64>,
253 /// Permute/Transpose: the new axis order, **ABSOLUTE** — a permutation of
254 /// `0..rank` with `out.axis[i] = in.axis[perm[i]]` (matches Fuel
255 /// `Op::Permute` semantics exactly; `Op::Transpose` is the last-two-axes
256 /// special case). Empty ⇒ not a permuting node (a matcher wildcard). See
257 /// `baracuda-layout-fusion-response.md` F1/F2a.
258 pub perm: Vec<u8>,
259 /// BroadcastTo/Reshape: the target **LOGICAL** shape (the op's output
260 /// shape); one field serves both (the [`OpTag`] disambiguates which op).
261 /// Empty ⇒ not a shape-target node (a matcher wildcard).
262 pub target_shape: Vec<i64>,
263 /// Squeeze/Unsqueeze: the affected dim list (0-based, output-rank terms).
264 /// Fuel's single-dim `Op::Squeeze`/`Op::Unsqueeze` emit a one-element list.
265 /// Empty ⇒ not a squeeze/unsqueeze node (a matcher wildcard).
266 pub dims: Vec<u8>,
267 /// `Cast` target dtype as the stable `DType::as_str()` name (dep-free:
268 /// this crate can't reference `fuel_ir::DType`; fuel-graph maps back via
269 /// `DType::from_str`). Also carries `MaskedFill`'s value dtype. `None` ⇒
270 /// not a dtype-carrying node (a matcher wildcard). Convergence Increment A.
271 pub cast_dtype: Option<String>,
272 /// `Slice` start offset along `axis` (the dim rides the existing `axis`
273 /// field). `None` ⇒ not a slice node. Convergence Increment A.
274 pub slice_start: Option<u64>,
275 /// `Slice` length along `axis`. `None` ⇒ not a slice node. Convergence
276 /// Increment A.
277 pub slice_len: Option<u64>,
278 /// `Roll` cyclic shift along `axis` (signed; the dim rides `axis`). `None`
279 /// ⇒ not a roll node. Convergence Increment A.
280 pub roll_shift: Option<i64>,
281 /// `Pad` per-axis `(before, after)` amounts, one pair per input dim. Empty
282 /// ⇒ not a pad node. Convergence Increment A.
283 pub pad_amounts: Vec<(u64, u64)>,
284 /// `Pad` fill mode code: `0=Constant, 1=Reflect, 2=Replicate` (mirrors
285 /// Fuel's `PadMode` order; dep-free integer code). `None` ⇒ not a pad node.
286 /// Convergence Increment A.
287 pub pad_mode: Option<u8>,
288 /// `Pad` constant fill value (used by `PadMode::Constant`). `None` ⇒ not a
289 /// pad node. Convergence Increment A.
290 pub pad_value: Option<f64>,
291 /// Reduction `keepdim` flag (§6.19 reduce-schema conformance — serialized
292 /// in the canonical blob). NOT consumed by `tag_to_op`: Fuel's reduce Ops
293 /// encode keepdim structurally (`ReduceSumTo`/`ReduceMaxTo` carry the kept
294 /// shape; `SumDim`/`MeanDim` are rank-reducing). Convergence Increment A.
295 pub keepdim: Option<bool>,
296
297 // --- Shape-RELATIVE recipe-interior fields (Increment C slice 1, D2) ---
298 //
299 // The four fields below make a recipe polymorphic across shapes/ranks:
300 // instead of baking an absolute value they carry an expression over the
301 // region's **Bind space** (`ShapeExpr::SameAs { operand: i }` /
302 // `Dim::Extent { operand: i, .. }` reference `Bind { index: i }` — the same
303 // operand-index convention the merged KISS shape-oracle RFC pins for
304 // contracts). They are resolved to the concrete sibling field at emit time
305 // (`fuel_graph::runtime_fused::resolve_rel_attrs`); a rel field and its
306 // concrete sibling set together is a typed resolution error (mutual
307 // exclusion), never a silent precedence.
308 //
309 // **Deliberately NOT serialized to the §6.19 wire (KISS #67-gated).**
310 // `to_canonical_bytes` serializes only the concrete fields: the pinned
311 // §6.19 arms for `broadcast_to`/`slice` are ABSOLUTE, and the node-envelope
312 // framing that could carry a relative alternative is being defined in
313 // KISS #67 — serializing a rel form now would unilaterally extend a shared
314 // byte contract (propose-first). Emitted/graph nodes are always concrete
315 // post-resolution, so rel-attr recipes never flow to `to_canonical_bytes`
316 // callers. Pinned by `rel_attr_fields_are_absent_from_the_6_19_wire`.
317 /// Shape-relative alternative to `target_shape`: the target is another
318 /// operand's shape (`SameAs { operand }` over the Bind space). `None` ⇒
319 /// use `target_shape` (or not a shape-target node).
320 ///
321 /// **Not every output frame is expressible this way.** A broadcast frame
322 /// assembled by per-axis max across TWO binds (`a[N,1] ⊗ b[1,M] → [N,M]`)
323 /// is carried by NO single operand, so no `SameAs` spelling names it — the
324 /// resolver refuses such a `BroadcastTo` target as a Dims-class gap
325 /// (`RelAttrError::FrameNotExpressible`) rather than silently resolving to
326 /// one operand's PARTIAL frame. The constructor that would express it is
327 /// the reserved [`shape_expr::TAG_DIMS`] entrant (KISS #80).
328 pub target_shape_rel: Option<shape_expr::ShapeExpr>,
329 /// Shape-relative alternative to `slice_start`: a `DimExpr` over the Bind
330 /// space (e.g. rope's `Div(Extent(0, LAST), 2)`). `None` ⇒ use
331 /// `slice_start`.
332 pub slice_start_rel: Option<shape_expr::Dim>,
333 /// Shape-relative alternative to `slice_len`. `None` ⇒ use `slice_len`.
334 pub slice_len_rel: Option<shape_expr::Dim>,
335 /// Rank-relative alternative to the op's axis carrier (`axis`, or `dims`
336 /// for Squeeze/Unsqueeze): this op's axis is its per-tag LAST — resolved
337 /// against `rank(operand[0])` as `rank − 1` for reduces/Slice/Concat/Flip/
338 /// CumSum/… and Squeeze, and `rank` (append) for Unsqueeze. `false` ⇒ use
339 /// the absolute carrier.
340 pub axis_last: bool,
341 /// Shape-relative alternative to `scalars` for a scalar-param op
342 /// (`AddScalar`/`MulScalar`): the scalar VALUE is a `DimExpr` over the Bind
343 /// space, resolved to a concrete number at emit time
344 /// (`fuel_graph::runtime_fused::resolve_rel_attrs`) — the **reduced_count**
345 /// concept made emittable: `Dim::Extent { operand: 0, axis: LAST }` yields
346 /// `n = extent of operand 0's last axis` (the `MulScalar(n)` divisor a norm
347 /// backward needs). It rides the SAME `Dim`/`eval_dim`/`resolve_axis`
348 /// machinery as `slice_start_rel`/`slice_len_rel` (no parallel axis
349 /// resolver). Distinct from an OPEN scalar slot: a `scalar_rel` node is
350 /// filled from an input SHAPE, NOT from the params projection cursor, so it
351 /// is NOT counted by `count_scalar_slots` and never consumes a cursor value.
352 /// `None` ⇒ use `scalars` (a baked value or an open slot). Set together with
353 /// a non-empty `scalars` is a typed resolution error (rel XOR abs). Like the
354 /// other rel fields, it is IN-MEMORY recipe data — deliberately NOT
355 /// serialized to the §6.19 wire (pinned by
356 /// `rel_attr_fields_are_absent_from_the_6_19_wire`).
357 pub scalar_rel: Option<shape_expr::Dim>,
358
359 // --- Matmul contraction role vectors (Increment C slice 1, T9/D5) -------
360 //
361 // The LOCKED reply-3 contraction descriptor (commit `b64aa1db`; §5 of the
362 // recipe-grammar design input). `matmul`'s op_attrs is two per-axis role
363 // vectors over the roles { Batch=0, FreeM=1, FreeN=2, ContractedK=3 } (one
364 // **u8** per axis), `lhs_roles` then `rhs_roles`, each length = operand rank.
365 // Role vectors encode WHICH axis plays which role, **not extents** — so GQA
366 // (differing-but-divisible batch extents) serializes to identical all-Batch
367 // leading roles. Both empty ⇒ the rank-polymorphic implicit form (recipes
368 // keep matmul implicit; concrete/ingested nodes get explicit roles). The
369 // canonical cell (same-rank ≥ 2; leading Batch; lhs=[..,FreeM,ContractedK],
370 // rhs=[..,ContractedK,FreeN]) is derived by [`matmul_roles`] and validated at
371 // resolve time (`fuel_graph::runtime_fused::tag_to_op`).
372 //
373 // Serialized on carrier (a) — `to_canonical_bytes(MatMul)` emits
374 // `u32_le(len lhs) ++ lhs_roles ++ u32_le(len rhs) ++ rhs_roles` when set, or
375 // the canonical empty body `[00,00,00,00]` when both are empty (preserving
376 // today's golden). Baracuda (#68) confirmed the rank-2 golden as the shared
377 // cross-producer fixture and has no near-term binary arm, so Fuel's
378 // serializer is the contract.
379 /// LHS per-axis contraction roles ({Batch=0,FreeM=1,FreeN=2,ContractedK=3},
380 /// u8 each; length = lhs rank). Empty ⇒ implicit (rank-polymorphic) matmul.
381 pub lhs_roles: Vec<u8>,
382 /// RHS per-axis contraction roles (same encoding; length = rhs rank). Empty
383 /// ⇒ implicit (rank-polymorphic) matmul.
384 pub rhs_roles: Vec<u8>,
385
386 // --- source-op LEAF carriers (KISS four-leaf ack, 2026-07-23) -----------
387 //
388 // One carrier per acked leaf arm. `ReducedCount` needs no field of its own:
389 // it rides the existing `axis` (fold-lockstep — byte-identical to the fold
390 // node's axis field, minus keepdim). These are wire carriers; no Fuel graph
391 // Op projects into them yet (see the `OpTag` leaf-token note).
392 /// [`OpTag::Const`] value: the scalar literal's **dtype-agnostic storage bit
393 /// pattern**. Narrow dtypes place their storage bits LOW-order with the
394 /// upper bits zero (MBZ) — use [`const_bits_narrow`]. A NaN payload is
395 /// carried verbatim (never quieted). `None` ⇒ not a const leaf.
396 pub const_bits: Option<u64>,
397 /// [`OpTag::RuntimeScalar`] value: the index of the dispatch-bound scalar
398 /// slot this leaf reads. `None` ⇒ not a runtime-scalar leaf.
399 pub slot_index: Option<u32>,
400 /// [`OpTag::ScanPlaceholder`] role code: [`SCAN_ROLE_CARRY`] (0) or
401 /// [`SCAN_ROLE_ELEM`] (1). `None` ⇒ not a scan-placeholder leaf.
402 pub scan_role: Option<u8>,
403 /// [`OpTag::ScanPlaceholder`] index: which `xs[i]` an `elem` hole stands
404 /// for (a `carry` hole is index 0 in the v1 single-carry model). `None` ⇒
405 /// not a scan-placeholder leaf.
406 pub scan_index: Option<u32>,
407
408 // --- [`OpTag::Scan`] param carriers (Increment C, B1) --------------------
409 //
410 // Fuel-internal recipe fields for the bounded-scan primitive's params.
411 // Like the shape-relative fields above they are NOT on the §6.19 wire (a
412 // `Scan` node hits the empty-body `_` arm of `to_canonical_bytes`): the
413 // scan is Fuel's own sub-graph-carrying primitive, not a KISS base op, so
414 // its params never flow to a cross-producer blob. `None` ⇒ not a scan node.
415 /// [`OpTag::Scan`] `n_carries`: how many recurrent carries the scan threads
416 /// (GAP-303). `1` is the v1 single-carry model.
417 ///
418 /// ⚠️ Like its siblings this is Fuel-internal and NOT on the KISS-OPS-6.19
419 /// wire: `OpTag::Scan` is in `has_empty_canonical_body`'s empty group BY
420 /// DESIGN, so no `Scan` param is serialized and adding one here changes no
421 /// bytes. Carry IDENTITY on the wire is already carried by
422 /// `OpTag::ScanPlaceholder`'s body, which serializes `scan_index` as a
423 /// `u32` — `Carry/0` and `Carry/1` have always produced different bytes.
424 pub scan_n_carries: Option<u32>,
425 /// [`OpTag::Scan`] `n_xs`: number of per-step `xs` operands.
426 pub scan_n_xs: Option<u32>,
427 /// [`OpTag::Scan`] `bound`: the static step horizon.
428 pub scan_bound: Option<u32>,
429 /// [`OpTag::Scan`] emit code: `0` = All (stack per-step ys, slot 0), `1` =
430 /// Final (final carry). Matches `fuel_graph::ScanEmit`'s declaration order.
431 pub scan_emit: Option<u8>,
432 /// [`OpTag::Scan`] early-exit presence flag: `Some(true)` ⇒ the Phase-2
433 /// `ScanPredicate` marker is present (its predicate LOGIC rides the trailing
434 /// `pred_exit` operand). `None`/`Some(false)` ⇒ no early exit.
435 pub scan_early_exit: Option<bool>,
436 /// [`OpTag::View`] slot index: which of the producer's `output_views` slots
437 /// this projection reads. Fuel-internal (not on the §6.19 wire). `None` ⇒
438 /// not a view node.
439 pub view_slot: Option<u32>,
440
441 // --- rank-0 shape-target marker (Increment C, C-T1) ---------------------
442 //
443 /// Marks an INTENTIONAL rank-0 (`[]`, scalar) target on a shape-target op
444 /// (`ReduceSumTo`/`ReduceMaxTo`/`Reshape`/`BroadcastTo`). A rank-0 shape has
445 /// ZERO dims, so its `target_shape` is empty — the SAME empty state a
446 /// wildcard / non-shape-target node carries — leaving the two
447 /// indistinguishable in memory. `true` ⇒ the empty `target_shape` denotes
448 /// the concrete rank-0 shape `[]` (a reduce-to-scalar loss tail, e.g. FSCE's
449 /// `ReduceSumTo([])`); `false` (the default) ⇒ empty `target_shape` is unset
450 /// / a matcher wildcard. Reusable for every future reduce-to-scalar loss.
451 ///
452 /// **Fuel-INTERNAL, off the §6.19 wire.** The wire already encodes a rank-0
453 /// target correctly as a 0-length `target_shape` i64 list
454 /// (`put_i64_list(&[])`), so `to_canonical_bytes` needs no new byte — this
455 /// marker only disambiguates the in-memory wildcard-vs-rank-0 overload that
456 /// the recipe emitter (`fuel_graph::runtime_fused::shape_from_attr`) reads.
457 pub rank0_target: bool,
458
459 // --- nested-fused selector (Increment C, C-T2) --------------------------
460 //
461 /// [`OpTag::Fused`] selector: the stable registry-entry **name** of the
462 /// nested fused op a recipe carries as-is (e.g. `"SoftmaxLastDim"` /
463 /// `"SoftmaxLastDimBackward"`), mirroring [`Self::cast_dtype`]'s
464 /// `DType::as_str` name-string precedent. `fuel-graph`'s
465 /// `runtime_fused::tag_to_op` resolves it back to a `FusedOpId` via
466 /// `registry::id_for_name` and reconstructs the param-less
467 /// `Op::Fused(fid, params)` through a small fid → params map. `None` ⇒ not a
468 /// nested-fused node (an honest miss for [`OpTag::Fused`]).
469 ///
470 /// **Fuel-INTERNAL, off the §6.19 wire.** A `Fused` node serializes to the
471 /// empty canonical body (the `_` arm of [`Self::to_canonical_bytes`]), so
472 /// this selector never flows to a cross-producer blob — a nested fused node
473 /// is a Fuel-side recipe-interior structural token, not a KISS base op.
474 pub fused_op: Option<String>,
475}
476
477/// Structural REGION IDENTITY of an [`OpAttrs`] — the `Hash + Eq` key baracuda's
478/// `region_op_id` uses to bucket kernels (fuel GAP-332 / baracuda #117), replacing a
479/// fragile `format!("{:?}")` of the attrs. Injective over every field that reaches the
480/// emitted kernel:
481///
482/// - `scalars` is DELIBERATELY OMITTED — VALUES *and* LENGTH. A scalar-param value becomes
483/// a runtime `ScalarExpr::Param` and never reaches the kernel (baracuda #115), so keying
484/// the values over-discriminates (one kernel, many ids, a wasted compile per distinct
485/// scalar). The scalar ARITY that DOES reach the kernel is `scalar_slot_arity(op)`, a pure
486/// function of `OpTag` (fuel-graph `runtime_fused`), which baracuda already hashes per node
487/// — so `region_key` need not carry it, and no two same-`OpTag` regions can differ in
488/// arity. `scalars.len()` must NOT be keyed either: the SAME op is `scalars: vec![]` as an
489/// open slot vs `vec![x]` as a baked snapshot (both become a runtime `Param` in baracuda's
490/// emitter — baracuda #115 — hence ONE kernel), so keying the length would split one kernel
491/// into open-vs-baked ids (a milder #115). Every OTHER field participates.
492/// - Float fields are keyed by their `to_bits` pattern (`pad_value_bits`), so `0.0`/`-0.0`
493/// and distinct NaN payloads stay distinct and `Eq` is reflexive — IEEE equality would
494/// break both (it merges `±0` and gives `NaN != NaN`); see GAP-048/300. `const_bits` is
495/// already a bit pattern.
496/// - Every `Option`/count field is carried as-is, so `None` stays DISTINCT from `Some(0)` —
497/// the collapse-of-unset-into-zero failure GAP-287 records is not repeated here. (This doc
498/// avoids that gap's literal anchor text so the dead-anchor baseline stays honest.)
499///
500/// Fields are private: this type exists to be a hashable/comparable region id, and building
501/// one goes through [`OpAttrs::region_key`], which uses an EXHAUSTIVE destructure (no `..`)
502/// so a field added to `OpAttrs` later fails to compile until someone classifies it as part
503/// of the region identity or explicitly excludes it.
504#[derive(Clone, Debug, PartialEq, Eq, Hash)]
505pub struct RegionKey {
506 axis: Option<i64>,
507 perm: Vec<u8>,
508 target_shape: Vec<i64>,
509 dims: Vec<u8>,
510 cast_dtype: Option<String>,
511 slice_start: Option<u64>,
512 slice_len: Option<u64>,
513 roll_shift: Option<i64>,
514 pad_amounts: Vec<(u64, u64)>,
515 pad_mode: Option<u8>,
516 pad_value_bits: Option<u64>,
517 keepdim: Option<bool>,
518 target_shape_rel: Option<shape_expr::ShapeExpr>,
519 slice_start_rel: Option<shape_expr::Dim>,
520 slice_len_rel: Option<shape_expr::Dim>,
521 axis_last: bool,
522 scalar_rel: Option<shape_expr::Dim>,
523 lhs_roles: Vec<u8>,
524 rhs_roles: Vec<u8>,
525 const_bits: Option<u64>,
526 slot_index: Option<u32>,
527 scan_role: Option<u8>,
528 scan_index: Option<u32>,
529 scan_n_carries: Option<u32>,
530 scan_n_xs: Option<u32>,
531 scan_bound: Option<u32>,
532 scan_emit: Option<u8>,
533 scan_early_exit: Option<bool>,
534 view_slot: Option<u32>,
535 rank0_target: bool,
536 fused_op: Option<String>,
537}
538
539impl OpAttrs {
540 /// Structural region identity of these attrs — see [`RegionKey`]. Excludes the
541 /// scalar-param `scalars` VALUES (runtime `ScalarExpr::Param`), keys floats by `to_bits`,
542 /// keeps `None` distinct from `Some(0)`, and is built by an exhaustive destructure so a
543 /// new `OpAttrs` field must be classified before this compiles.
544 pub fn region_key(&self) -> RegionKey {
545 // EXHAUSTIVE destructure (no `..`): a field added to OpAttrs breaks this line until
546 // it is classified as part of the region identity or explicitly excluded here.
547 let OpAttrs {
548 scalars: _, // EXCLUDED (values AND length): runtime Param, never reaches the kernel; arity = scalar_slot_arity(op) = f(OpTag), carried by OpTag; len varies open-vs-baked (baracuda #115).
549 axis,
550 perm,
551 target_shape,
552 dims,
553 cast_dtype,
554 slice_start,
555 slice_len,
556 roll_shift,
557 pad_amounts,
558 pad_mode,
559 pad_value,
560 keepdim,
561 target_shape_rel,
562 slice_start_rel,
563 slice_len_rel,
564 axis_last,
565 scalar_rel,
566 lhs_roles,
567 rhs_roles,
568 const_bits,
569 slot_index,
570 scan_role,
571 scan_index,
572 scan_n_carries,
573 scan_n_xs,
574 scan_bound,
575 scan_emit,
576 scan_early_exit,
577 view_slot,
578 rank0_target,
579 fused_op,
580 } = self;
581 RegionKey {
582 axis: *axis,
583 perm: perm.clone(),
584 target_shape: target_shape.clone(),
585 dims: dims.clone(),
586 cast_dtype: cast_dtype.clone(),
587 slice_start: *slice_start,
588 slice_len: *slice_len,
589 roll_shift: *roll_shift,
590 pad_amounts: pad_amounts.clone(),
591 pad_mode: *pad_mode,
592 // to_bits: keeps 0.0/-0.0 and NaN payloads distinct (Eq-reflexive, cache-safe).
593 pad_value_bits: (*pad_value).map(f64::to_bits),
594 keepdim: *keepdim,
595 target_shape_rel: target_shape_rel.clone(),
596 slice_start_rel: slice_start_rel.clone(),
597 slice_len_rel: slice_len_rel.clone(),
598 axis_last: *axis_last,
599 scalar_rel: scalar_rel.clone(),
600 lhs_roles: lhs_roles.clone(),
601 rhs_roles: rhs_roles.clone(),
602 const_bits: *const_bits,
603 slot_index: *slot_index,
604 scan_role: *scan_role,
605 scan_index: *scan_index,
606 scan_n_carries: *scan_n_carries,
607 scan_n_xs: *scan_n_xs,
608 scan_bound: *scan_bound,
609 scan_emit: *scan_emit,
610 scan_early_exit: *scan_early_exit,
611 view_slot: *view_slot,
612 rank0_target: *rank0_target,
613 fused_op: fused_op.clone(),
614 }
615 }
616}
617
618// --- §6.19-shaped canonical positional-blob serialization (Convergence Increment A) ---
619//
620/// Derive the canonical matmul role vectors for a same-rank ≥ 2 contraction
621/// (the LOCKED reply-3 cell, §5): `lhs = [Batch×(r−2), FreeM, ContractedK]`,
622/// `rhs = [Batch×(r−2), ContractedK, FreeN]` over the roles
623/// { Batch=0, FreeM=1, FreeN=2, ContractedK=3 }. Roles encode axis POSITIONS,
624/// not extents — GQA-divisible batch stays all-`Batch`. Pure + never-panic: a
625/// rank < 2 operand (never a real matmul input) yields an all-`Batch` vector of
626/// that length, which the resolver's exact-match check rejects as non-canonical.
627pub fn matmul_roles(lhs_rank: usize, rhs_rank: usize) -> (Vec<u8>, Vec<u8>) {
628 fn one(rank: usize, second_last: u8, last: u8) -> Vec<u8> {
629 let mut v = vec![0u8; rank]; // Batch = 0 for every leading axis
630 if rank >= 2 {
631 v[rank - 2] = second_last;
632 v[rank - 1] = last;
633 }
634 v
635 }
636 // lhs: [.., FreeM(1), ContractedK(3)]; rhs: [.., ContractedK(3), FreeN(2)].
637 (one(lhs_rank, 1, 3), one(rhs_rank, 3, 2))
638}
639
640/// A node of the §3 declarative subgraph grammar. One type, two directions: a
641/// **region** (Fuel -> synthesizer) populates `Op { op, operands, attrs }` +
642/// `Bind`; an emitted **`pattern:`** (synthesizer -> Fuel) additionally carries
643/// the consumer/`extract` routing the matcher compiler reads. `SeeThrough`/`Any`
644/// are matcher-only and never appear in a concrete region.
645#[derive(Clone, Debug, PartialEq)]
646// `Op` is ~489 bytes (`OpAttrs` is a wide flat attribute struct); the other
647// variants are <=8. Boxing the `Op` payload is the right fix, but it ripples
648// across ~150 `PatternNode::Op` construction sites in fuel-graph and
649// fuel-dispatch, which are mid-rename — deferred to a post-sweep follow-up.
650// `expect` (not `allow`) so this suppression self-reports the day the variant
651// is boxed and the lint stops firing.
652#[expect(
653 clippy::large_enum_variant,
654 reason = "Op-payload boxing deferred: ~150 cross-crate construction sites, sequenced after the in-flight rename sweep"
655)]
656// EXHAUSTIVE-BY-DESIGN: baracuda's region_op_id (baracuda #117) walks this enum
657// with an EXHAUSTIVE match to build its kernel region key. Do NOT add
658// #[non_exhaustive] — it would force downstream wildcard arms and silently drop a
659// new variant from the kernel identity (the GAP-049 failure shape). Enforced by
660// tests/exhaustive_by_design.rs in this crate (marker + #[non_exhaustive] is a
661// hard test failure naming this enum); it moved here from Fuel's
662// fuel-ir/tests/exhaustive_by_design_marker.rs, whose scan can no longer see this type.
663pub enum PatternNode {
664 /// An op over the [`OpTag`] vocabulary with one child per tensor input
665 /// (ordered, exact arity). `attrs` carries the scalar slot / load-bearing
666 /// attributes.
667 Op {
668 op: OpTag,
669 operands: Vec<PatternNode>,
670 attrs: OpAttrs,
671 },
672 /// A leaf: bind the producing node as the fused op's `input[index]`. A
673 /// repeated `index` is a node-identity guard on a shared input (§3.2);
674 /// indices across a region MUST equal `[0, n_inputs)`.
675 Bind { index: u8 },
676 /// Match the inner node after skipping zero-or-more transparent wrappers
677 /// (§3.3). Matcher-only.
678 SeeThrough { then: Box<PatternNode> },
679 /// Wildcard — matches any single node (§3.4). Matcher-only.
680 Any,
681}
682
683impl PatternNode {
684 /// Collect the distinct `Bind` indices in this tree (a region's external
685 /// inputs). Used to validate `bind` indices form `[0, n_inputs)`.
686 pub fn bind_indices(&self) -> Vec<u8> {
687 let mut out = Vec::new();
688 self.collect_binds(&mut out);
689 out.sort_unstable();
690 out.dedup();
691 out
692 }
693
694 fn collect_binds(&self, out: &mut Vec<u8>) {
695 match self {
696 PatternNode::Bind { index } => out.push(*index),
697 PatternNode::Op { operands, .. } => {
698 for o in operands {
699 o.collect_binds(out);
700 }
701 }
702 PatternNode::SeeThrough { then } => then.collect_binds(out),
703 PatternNode::Any => {}
704 }
705 }
706}
707
708// ===========================================================================
709// Advisory ULP-band reference cases — the single drift-pinning fixture
710// ===========================================================================
711
712/// The shared drift-pinning fixture for the **advisory ULP band** formula
713/// (KISS-CONFORM §6.8; kiss-ref tolerance refinement 2026-07-23).
714///
715/// The band formula is hand-maintained in TWO places that cannot be
716/// co-compiled on a CPU build:
717///
718/// * `fuel_kiss_ref_backend::region_advisory_tolerance` (with
719/// `op_ulp_ceiling` / `region_ulp_ceilings`) — the **reference** formula,
720/// in an adapter crate pulled only under `fuel-dispatch`'s `cuda` feature;
721/// and
722/// * `fuel_dispatch::jit_ingest::advisory_ulp_band` — the **live** copy on
723/// the ingestion path, which must stay testable under `--features jit`
724/// alone (i.e. without the cuda-gated adapter).
725///
726/// Because those two live in crates gated apart, no single CPU test sees both.
727/// This table is the shared source of truth each side is pinned to: every
728/// `(region, expected)` pair here is asserted from BOTH sides (the adapter's
729/// `region.rs` tests and fuel-dispatch's `jit_ingest.rs` tests), so a drift in
730/// either formula fails that side's build. It is homed in this dependency-free
731/// grammar crate — the one both already depend on — precisely because it is the
732/// only place visible to both without touching the cuda gating.
733///
734/// `expected` is the NORMALIZED band the live consumer applies:
735/// `None` ⇒ compare `Tolerance::Exact` (an op-free region *or* a single exact
736/// op — both drive an exact comparison), `Some(n)` ⇒ `Tolerance::Ulp(n)`. The
737/// adapter's richer `Option<Tolerance>` collapses `None` (op-free) and
738/// `Some(Exact)` (single exact op) onto `None` here, matching
739/// `advisory_ulp_band`'s native `Option<u64>` shape.
740///
741/// Baked-in ceilings mirror the two formulas' shared rule: transcendental ops
742/// contribute their kiss §6.8 ceiling (Exp/Erf declare 4; kiss non-primitives
743/// Tanh/Sigmoid/Silu/GeluTanh/Rsqrt fall back to 4); IEEE-correctly-rounded
744/// Sqrt/Recip are exact-class (no ceiling); an exact-only region of `n` ops
745/// bands at `n - 1`; a transcendental region bands at `Σ ceilings +
746/// (n_exact - 1)` with the exact term saturating at 0.
747pub fn advisory_band_reference_cases() -> Vec<(PatternNode, Option<u64>)> {
748 fn bind(i: u8) -> PatternNode {
749 PatternNode::Bind { index: i }
750 }
751 fn op(op: OpTag, operands: Vec<PatternNode>) -> PatternNode {
752 PatternNode::Op {
753 op,
754 operands,
755 attrs: OpAttrs::default(),
756 }
757 }
758 vec![
759 // Op-free region: nothing to band -> exact comparison.
760 (bind(0), None),
761 // Single exact op -> exact comparison.
762 (op(OpTag::Add, vec![bind(0), bind(1)]), None),
763 // Multi-node exact-only region -> Ulp(n_ops - 1).
764 (
765 op(OpTag::Relu, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
766 Some(1),
767 ),
768 // Deeper exact-only region (3 ops) -> Ulp(3 - 1).
769 (
770 op(
771 OpTag::Relu,
772 vec![op(
773 OpTag::Relu,
774 vec![op(OpTag::Add, vec![bind(0), bind(1)])],
775 )],
776 ),
777 Some(2),
778 ),
779 // Sqrt is IEEE-correctly-rounded -> exact class; sqrt(a+b) = 2 exact ops.
780 (
781 op(OpTag::Sqrt, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
782 Some(1),
783 ),
784 // Lone transcendental keeps exactly its own ceiling (Exp declares 4).
785 (op(OpTag::Exp, vec![bind(0)]), Some(4)),
786 // Transcendental + one exact: 4 + (1 - 1) = 4.
787 (
788 op(OpTag::Exp, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
789 Some(4),
790 ),
791 // Two transcendentals (Exp 4, Tanh fallback 4) + one exact: 8 + 0 = 8.
792 (
793 op(
794 OpTag::Tanh,
795 vec![op(OpTag::Add, vec![op(OpTag::Exp, vec![bind(0)]), bind(1)])],
796 ),
797 Some(8),
798 ),
799 // All-transcendental exp(tanh(x)): 4 + 4, exact term saturates at 0.
800 (
801 op(OpTag::Exp, vec![op(OpTag::Tanh, vec![bind(0)])]),
802 Some(8),
803 ),
804 // Silu (kiss non-primitive fallback 4) over add(a, exp(b)): 4 + 4 + 0.
805 (
806 op(
807 OpTag::Silu,
808 vec![op(OpTag::Add, vec![bind(0), op(OpTag::Exp, vec![bind(1)])])],
809 ),
810 Some(8),
811 ),
812 ]
813}
814
815// ---- GAP-332: OpAttrs::region_key() -> RegionKey (baracuda #117) ------------
816//
817// region_key() is the Hash+Eq structural region identity baracuda's `region_op_id`
818// buckets kernels by. These tests pin its three contracts: (a) every kernel-relevant
819// field participates (per-field perturbation — ALSO the standing sabotage sibling:
820// drop a field from the key and exactly that field's assert_ne! reddens); (b) the
821// scalar-param VALUES are excluded (regions differing only in scalars reuse one kernel
822// bucket — baracuda #115); (c) floats key by `to_bits` and `None` stays distinct from
823// `Some(0)` (GAP-048/300, GAP-287).
824#[cfg(test)]
825mod region_key_tests {
826 use super::*;
827 use crate::shape_expr::{Dim, ShapeExpr};
828
829 #[test]
830 fn every_included_field_changes_the_key() {
831 // Perturb each INCLUDED field off default and require the key to move. If
832 // region_key() stopped carrying a field, ONLY that field's assert_ne! would
833 // fail — this is the standing sabotage sibling for the born-red.
834 let base = OpAttrs::default().region_key();
835 macro_rules! moves {
836 ($field:ident = $val:expr) => {{
837 let a = OpAttrs {
838 $field: $val,
839 ..Default::default()
840 };
841 assert_ne!(
842 a.region_key(),
843 base,
844 concat!("region_key() ignores field `", stringify!($field), "`")
845 );
846 }};
847 }
848 moves!(axis = Some(3));
849 moves!(perm = vec![1u8, 0]);
850 moves!(target_shape = vec![2i64, 3]);
851 moves!(dims = vec![1u8]);
852 moves!(cast_dtype = Some("f32".to_string()));
853 moves!(slice_start = Some(5));
854 moves!(slice_len = Some(7));
855 moves!(roll_shift = Some(-1));
856 moves!(pad_amounts = vec![(1u64, 2u64)]);
857 moves!(pad_mode = Some(1u8));
858 moves!(pad_value = Some(1.5));
859 moves!(keepdim = Some(true));
860 moves!(target_shape_rel = Some(ShapeExpr::SameAs { operand: 0 }));
861 moves!(slice_start_rel = Some(Dim::Const(1)));
862 moves!(slice_len_rel = Some(Dim::Const(1)));
863 moves!(axis_last = true);
864 moves!(scalar_rel = Some(Dim::Const(1)));
865 moves!(lhs_roles = vec![1u8]);
866 moves!(rhs_roles = vec![2u8]);
867 moves!(const_bits = Some(42u64));
868 moves!(slot_index = Some(1u32));
869 moves!(scan_role = Some(1u8));
870 moves!(scan_index = Some(1u32));
871 moves!(scan_n_carries = Some(1u32));
872 moves!(scan_n_xs = Some(1u32));
873 moves!(scan_bound = Some(1u32));
874 moves!(scan_emit = Some(1u8));
875 moves!(scan_early_exit = Some(true));
876 moves!(view_slot = Some(1u32));
877 moves!(rank0_target = true);
878 moves!(fused_op = Some("SoftmaxLastDim".to_string()));
879 }
880
881 #[test]
882 fn scalars_length_and_values_are_excluded_from_the_key() {
883 // The key must ignore `scalars` ENTIRELY — both VALUES and LENGTH.
884 // VALUES: a scalar-param value becomes a runtime ScalarExpr::Param and never
885 // reaches the kernel (baracuda #115), so keying values over-discriminates.
886 // LENGTH: the kernel's scalar ARITY is `scalar_slot_arity(op)`, a pure function
887 // of OpTag (fuel-graph runtime_fused.rs:589-591), which baracuda already hashes
888 // per node — and the SAME op is `scalars: vec![]` as an open slot vs `vec![x]` as
889 // a baked snapshot (count_scalar_slots, runtime_fused.rs:916, treats the empty one
890 // as a slot; both become a runtime Param in baracuda's emitter, so ONE kernel), so
891 // keying `scalars.len()` would split one kernel into open-vs-baked ids (a milder
892 // #115). So every length AND value maps to one key. (This reddens if a future edit
893 // adds scalars or scalars.len() to RegionKey.)
894 let base = OpAttrs::default().region_key(); // scalars: vec![] (len 0)
895 for scalars in [
896 vec![],
897 vec![0.0],
898 vec![9.0],
899 vec![1.0, 2.0],
900 vec![-0.0, f64::NAN, 3.5],
901 ] {
902 let a = OpAttrs {
903 scalars,
904 ..Default::default()
905 };
906 assert_eq!(
907 a.region_key(),
908 base,
909 "scalars length and values must not affect the region key (baracuda #115; \
910 arity is scalar_slot_arity(op), a function of OpTag)"
911 );
912 }
913 }
914
915 #[test]
916 fn none_stays_distinct_from_some_zero() {
917 // GAP-287: unset must never collapse into zero.
918 let none = OpAttrs::default().region_key();
919 let a = OpAttrs {
920 slice_start: Some(0),
921 ..Default::default()
922 };
923 assert_ne!(a.region_key(), none, "slice_start None vs Some(0)");
924 let b = OpAttrs {
925 pad_value: Some(0.0),
926 ..Default::default()
927 };
928 assert_ne!(b.region_key(), none, "pad_value None vs Some(0.0)");
929 let c = OpAttrs {
930 const_bits: Some(0),
931 ..Default::default()
932 };
933 assert_ne!(c.region_key(), none, "const_bits None vs Some(0)");
934 }
935
936 #[test]
937 fn floats_key_by_to_bits() {
938 let mk = |v: f64| {
939 OpAttrs {
940 pad_value: Some(v),
941 ..Default::default()
942 }
943 .region_key()
944 };
945 // IEEE `==` merges these / breaks reflexivity; `to_bits` does neither.
946 assert_ne!(mk(0.0), mk(-0.0), "pad_value +0.0 vs -0.0 stay distinct");
947 let nan_a = f64::from_bits(0x7ff8_0000_0000_0001);
948 let nan_b = f64::from_bits(0x7ff8_0000_0000_0002);
949 assert!(nan_a.is_nan() && nan_b.is_nan());
950 assert_ne!(mk(nan_a), mk(nan_b), "distinct NaN payloads stay distinct");
951 assert_eq!(
952 mk(f64::NAN),
953 mk(f64::NAN),
954 "same NaN bits => equal keys (Eq reflexive)"
955 );
956 }
957
958 #[test]
959 fn key_buckets_kernels_by_region_ignoring_scalars() {
960 // The end-to-end purpose (baracuda #117): a Hash+Eq map keyed by region_key
961 // reuses one kernel across regions differing only in scalar VALUES, and
962 // separates regions that differ structurally.
963 use std::collections::HashMap;
964 let mut m: HashMap<RegionKey, &str> = HashMap::new();
965 let add = OpAttrs::default(); // e.g. an AddScalar region
966 // structurally different region
967 let other = OpAttrs {
968 axis: Some(1),
969 ..Default::default()
970 };
971 m.insert(add.region_key(), "kernel_add");
972 m.insert(other.region_key(), "kernel_other");
973 assert_eq!(
974 m.len(),
975 2,
976 "structurally distinct regions => distinct kernels"
977 );
978 // Same region, different scalar value => same kernel bucket.
979 let add_val_9 = OpAttrs {
980 scalars: vec![9.0],
981 ..Default::default()
982 };
983 assert_eq!(
984 m.get(&add_val_9.region_key()),
985 Some(&"kernel_add"),
986 "differing scalar values reuse the same kernel (no wasted compile)"
987 );
988 }
989}
990
991#[cfg(test)]
992mod tests {
993 use super::*;
994
995 #[test]
996 fn pattern_node_region_for_relu_a_plus_b() {
997 // relu(a + b) — a 1-output region over 2 inputs.
998 let region = PatternNode::Op {
999 op: OpTag::Relu,
1000 attrs: OpAttrs::default(),
1001 operands: vec![PatternNode::Op {
1002 op: OpTag::Add,
1003 attrs: OpAttrs::default(),
1004 operands: vec![
1005 PatternNode::Bind { index: 0 },
1006 PatternNode::Bind { index: 1 },
1007 ],
1008 }],
1009 };
1010 assert_eq!(region.bind_indices(), vec![0, 1]);
1011 }
1012
1013 #[test]
1014 fn shared_input_node_identity_guard() {
1015 // mul(x, x) — repeated bind: 0 is the shared-input node-identity guard.
1016 let region = PatternNode::Op {
1017 op: OpTag::Mul,
1018 attrs: OpAttrs::default(),
1019 operands: vec![
1020 PatternNode::Bind { index: 0 },
1021 PatternNode::Bind { index: 0 },
1022 ],
1023 };
1024 assert_eq!(region.bind_indices(), vec![0]);
1025 }
1026
1027 // ---- Task 7: §6.19 canonical positional-blob serialization --------------
1028
1029 #[test]
1030 fn empty_schema_op_serializes_zero_length() {
1031 // Add carries no attrs → one canonical byte form: u32 LE length 0.
1032 assert_eq!(
1033 OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap(),
1034 vec![0, 0, 0, 0]
1035 );
1036 assert_eq!(
1037 OpAttrs::default()
1038 .to_canonical_bytes(OpTag::MatMul)
1039 .unwrap(),
1040 vec![0, 0, 0, 0]
1041 );
1042 }
1043
1044 #[test]
1045 fn slice_serializes_positionally() {
1046 // Slice schema (positional): axis(u32), start(u64), len(u64) — see kernel-seam-interop.md.
1047 let a = OpAttrs {
1048 axis: Some(1),
1049 slice_start: Some(2),
1050 slice_len: Some(3),
1051 ..OpAttrs::default()
1052 };
1053 let mut expect = Vec::new();
1054 let body = {
1055 let mut b = Vec::new();
1056 b.extend_from_slice(&1u32.to_le_bytes());
1057 b.extend_from_slice(&2u64.to_le_bytes());
1058 b.extend_from_slice(&3u64.to_le_bytes());
1059 b
1060 };
1061 expect.extend_from_slice(&(body.len() as u32).to_le_bytes());
1062 expect.extend_from_slice(&body);
1063 assert_eq!(a.to_canonical_bytes(OpTag::Slice).unwrap(), expect);
1064 }
1065
1066 #[test]
1067 fn cast_serializes_dtype_name_length_prefixed() {
1068 let a = OpAttrs {
1069 cast_dtype: Some("f16".into()),
1070 ..OpAttrs::default()
1071 };
1072 let mut body = Vec::new();
1073 body.extend_from_slice(&(3u32.to_le_bytes())); // name length
1074 body.extend_from_slice(b"f16");
1075 let mut expect = (body.len() as u32).to_le_bytes().to_vec();
1076 expect.extend_from_slice(&body);
1077 assert_eq!(a.to_canonical_bytes(OpTag::Cast).unwrap(), expect);
1078 }
1079
1080 #[test]
1081 fn canonical_bytes_are_deterministic() {
1082 let a = OpAttrs {
1083 target_shape: vec![2, 3],
1084 ..OpAttrs::default()
1085 };
1086 assert_eq!(
1087 a.to_canonical_bytes(OpTag::Reshape).unwrap(),
1088 a.to_canonical_bytes(OpTag::Reshape).unwrap()
1089 );
1090 }
1091
1092 // ---- Per-carrier width conformance (KISS coordinator pin, vs KISS main c9153b2) --
1093 //
1094 // There are THREE coexisting op_attrs / shape-expr framings. Widths are pinned
1095 // PER-CARRIER, never as "the op_attrs width" — a future consolidation must NOT
1096 // silently unify them (KISS #67 do-not-unify):
1097 // (a) #67 NODE-ENVELOPE op_attrs → u32-LE OUTER byte length, payload
1098 // verbatim, no-parse-inside (KISS-OPS-6.19-0010). Live producer:
1099 // `OpAttrs::to_canonical_bytes`.
1100 // (b) KISS-Grammar §6.8-0007 REGION-NODE-TABLE op_attrs SUB-BLOCK → u16-LE
1101 // length + payload verbatim; EMPTY = 0x0000. A DIFFERENT carrier from (a).
1102 // Fuel ships NO producer yet (node/table wire serializer is #67-gated,
1103 // slice 4); this pin binds that future serializer to u16-LE here.
1104 // (c) §6.20-0005 SHAPE-EXPR binary-node CHILD length → u16-LE. Live producer:
1105 // `shape_expr::Dim::encode`.
1106 #[test]
1107 fn three_carrier_width_pins_stay_distinct() {
1108 use crate::shape_expr::{Dim, LAST};
1109
1110 // Carrier (a): node-envelope op_attrs — outer prefix is EXACTLY 4 bytes
1111 // (u32-LE); an empty schema is the 4-byte zero form.
1112 let empty = OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap();
1113 assert_eq!(
1114 empty,
1115 vec![0u8, 0, 0, 0],
1116 "carrier (a): empty node-envelope op_attrs = u32-LE zero (4 bytes)"
1117 );
1118 let sliced = OpAttrs {
1119 axis: Some(1),
1120 slice_start: Some(2),
1121 slice_len: Some(3),
1122 ..OpAttrs::default()
1123 };
1124 let blob = sliced.to_canonical_bytes(OpTag::Slice).unwrap();
1125 let a_body_len = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]) as usize;
1126 assert_eq!(
1127 blob.len(),
1128 4 + a_body_len,
1129 "carrier (a): outer length prefix is u32-LE (4 bytes), body verbatim"
1130 );
1131
1132 // Carrier (b): region-node-table op_attrs sub-block — u16-LE length +
1133 // verbatim payload; empty = 0x0000. Modeled here (no Fuel producer yet) so
1134 // the width pin is executable and NAMED before the slice-4 serializer lands.
1135 fn region_node_table_op_attrs_sub_block(payload: &[u8]) -> Vec<u8> {
1136 let mut out = (payload.len() as u16).to_le_bytes().to_vec();
1137 out.extend_from_slice(payload); // verbatim, no-parse-inside
1138 out
1139 }
1140 assert_eq!(
1141 region_node_table_op_attrs_sub_block(&[]),
1142 vec![0x00, 0x00],
1143 "carrier (b): EMPTY region-node-table op_attrs sub-block = 0x0000 (u16-LE, 2 bytes)"
1144 );
1145 assert_eq!(
1146 region_node_table_op_attrs_sub_block(&[0xAB, 0xCD]),
1147 vec![0x02, 0x00, 0xAB, 0xCD],
1148 "carrier (b): sub-block length prefix is u16-LE (2 bytes), payload verbatim"
1149 );
1150
1151 // Carrier (c): shape-expr binary-node child length — u16-LE (2 bytes),
1152 // inside Dim::{Add,Sub,Mul,Div}. The rope-half golden's child prefixes:
1153 // tag(0x08) ++ u16-LE(3) ++ Extent(3B) ++ u16-LE(9) ++ Const(9B).
1154 let half = Dim::Div(
1155 Box::new(Dim::Extent {
1156 operand: 0,
1157 axis: LAST,
1158 }),
1159 Box::new(Dim::Const(2)),
1160 );
1161 let bytes = half.encode();
1162 assert_eq!(
1163 [bytes[1], bytes[2]],
1164 3u16.to_le_bytes(),
1165 "carrier (c): first child length prefix is u16-LE (2 bytes)"
1166 );
1167 assert_eq!(
1168 [bytes[6], bytes[7]],
1169 9u16.to_le_bytes(),
1170 "carrier (c): second child length prefix is u16-LE (2 bytes)"
1171 );
1172 assert_eq!(
1173 bytes.len(),
1174 1 + 2 + 3 + 2 + 9,
1175 "carrier (c): whole rope-half blob accounted for"
1176 );
1177
1178 // Pinned widths, side by side — (a)=4 (u32-LE) vs (b)=2 (u16-LE) vs
1179 // (c)=2 (u16-LE). (b) and (c) sharing a width is coincidence, not unity:
1180 // each is pinned by its OWN carrier name above.
1181 }
1182
1183 // ---- T2 (Increment C slice 1): shape-relative interior fields stay OFF
1184 // the §6.19 wire ------------------------------------------------------
1185 //
1186 // D2 pin (KISS #67-gated): `target_shape_rel` / `slice_start_rel` /
1187 // `slice_len_rel` / `axis_last` are IN-MEMORY recipe data, resolved to the
1188 // concrete fields at emit time. The pinned §6.19 arms for
1189 // `broadcast_to`/`slice` are ABSOLUTE (`put_i64_list(target_shape)`,
1190 // `u32(axis) ++ u64(start) ++ u64(len)`), and the node-envelope framing
1191 // that could carry a relative alternative is being defined in KISS #67 —
1192 // serializing a rel form now would unilaterally extend a shared byte
1193 // contract (propose-first says no). This test pins the ABSENCE: the wire
1194 // bytes are identical with and without every rel field set, for every
1195 // schema family the rel fields could plausibly leak into.
1196 #[test]
1197 fn rel_attr_fields_are_absent_from_the_6_19_wire() {
1198 use crate::shape_expr::{Dim, LAST, ShapeExpr};
1199 let half = Dim::Div(
1200 Box::new(Dim::Extent {
1201 operand: 0,
1202 axis: LAST,
1203 }),
1204 Box::new(Dim::Const(2)),
1205 );
1206 let rel_only = OpAttrs {
1207 target_shape_rel: Some(ShapeExpr::SameAs { operand: 0 }),
1208 slice_start_rel: Some(half.clone()),
1209 slice_len_rel: Some(half),
1210 axis_last: true,
1211 scalar_rel: Some(Dim::Extent {
1212 operand: 0,
1213 axis: LAST,
1214 }),
1215 ..OpAttrs::default()
1216 };
1217 // Shape-target arm (BroadcastTo/Reshape): rel-only attrs serialize
1218 // byte-identically to fully-default attrs (an unset target_shape).
1219 assert_eq!(
1220 rel_only.to_canonical_bytes(OpTag::BroadcastTo).unwrap(),
1221 OpAttrs::default()
1222 .to_canonical_bytes(OpTag::BroadcastTo)
1223 .unwrap(),
1224 "target_shape_rel must not reach the broadcast_to wire arm"
1225 );
1226 // Slice arm: the ABSOLUTE fields serialize; adding every rel field on
1227 // top changes NOTHING.
1228 let abs = OpAttrs {
1229 axis: Some(1),
1230 slice_start: Some(2),
1231 slice_len: Some(3),
1232 ..OpAttrs::default()
1233 };
1234 let abs_plus_rel = OpAttrs {
1235 axis: Some(1),
1236 slice_start: Some(2),
1237 slice_len: Some(3),
1238 ..rel_only.clone()
1239 };
1240 assert_eq!(
1241 abs_plus_rel.to_canonical_bytes(OpTag::Slice).unwrap(),
1242 abs.to_canonical_bytes(OpTag::Slice).unwrap(),
1243 "slice_{{start,len}}_rel must not reach the slice wire arm"
1244 );
1245 // Reduce row (axis ++ keepdim): axis_last must not leak.
1246 let sd = OpAttrs {
1247 axis: Some(1),
1248 ..OpAttrs::default()
1249 };
1250 let sd_plus_rel = OpAttrs {
1251 axis: Some(1),
1252 ..rel_only.clone()
1253 };
1254 assert_eq!(
1255 sd_plus_rel.to_canonical_bytes(OpTag::SumDim).unwrap(),
1256 sd.to_canonical_bytes(OpTag::SumDim).unwrap(),
1257 "axis_last must not reach the reduce wire row"
1258 );
1259 // Scalar-param arm (AddScalar/MulScalar): a `scalar_rel` DimExpr with an
1260 // empty `scalars` list serializes byte-identically to a default (the
1261 // wire arm emits only `scalars`), so the reduced_count rel carrier never
1262 // leaks onto the §6.19 wire.
1263 assert_eq!(
1264 rel_only.to_canonical_bytes(OpTag::MulScalar).unwrap(),
1265 OpAttrs::default()
1266 .to_canonical_bytes(OpTag::MulScalar)
1267 .unwrap(),
1268 "scalar_rel must not reach the mul_scalar wire arm"
1269 );
1270 // Empty-schema op: stays the single canonical 4-byte zero form even
1271 // with every rel field set.
1272 assert_eq!(
1273 rel_only.to_canonical_bytes(OpTag::Add).unwrap(),
1274 vec![0, 0, 0, 0]
1275 );
1276 }
1277
1278 // ---- C-T2 (Increment C): OpTag::Fused is a Fuel-internal structural token,
1279 // OFF the §6.19 wire ----------------------------------------------------
1280 //
1281 // A nested fused node (the attention-trio decompose's inner softmax) is
1282 // Fuel-side recipe interior, NOT a KISS base op: it must never flow to a
1283 // cross-producer blob. Like the `scan_*`/`view_slot` fields, `OpTag::Fused`
1284 // hits the empty-body `_` arm of `to_canonical_bytes`, and its `fused_op`
1285 // selector serializes NOTHING.
1286 #[test]
1287 fn fused_nested_op_is_absent_from_the_6_19_wire() {
1288 let fused = OpAttrs {
1289 fused_op: Some("SoftmaxLastDim".into()),
1290 ..OpAttrs::default()
1291 };
1292 // The Fused tag serializes to the single canonical 4-byte zero body —
1293 // byte-identical to a fully-default attrs blob (the selector is off-wire).
1294 assert_eq!(
1295 fused.to_canonical_bytes(OpTag::Fused).unwrap(),
1296 vec![0, 0, 0, 0],
1297 "OpTag::Fused must serialize to the empty canonical body"
1298 );
1299 assert_eq!(
1300 fused.to_canonical_bytes(OpTag::Fused).unwrap(),
1301 OpAttrs::default().to_canonical_bytes(OpTag::Fused).unwrap(),
1302 "the fused_op selector must not reach any wire arm"
1303 );
1304 // The selector also must not leak into any OTHER schema arm it could
1305 // plausibly ride alongside (it shares no field with a real op).
1306 assert_eq!(
1307 fused.to_canonical_bytes(OpTag::Add).unwrap(),
1308 vec![0, 0, 0, 0],
1309 "fused_op must not leak into an empty-schema arm"
1310 );
1311 }
1312
1313 // ---- T4 (Increment C slice 1): additive OpTag::MaxDim -----------------
1314
1315 #[test]
1316 fn max_dim_serializes_the_reduce_row() {
1317 // `OpTag::MaxDim` joins the pinned §6.19 reduce row — carrier (a), the
1318 // node-envelope op_attrs blob (u32-LE outer): body = i64(axis) ++
1319 // u8(keepdim). The monoid rides `op_name` (distinct SumDim/MaxDim/
1320 // MinDim tags — see the module comment's reduce-schema note), so the
1321 // blob is IDENTICAL in shape to SumDim's. Golden for axis=1, keepdim
1322 // unset (=0): u32-LE(9) ++ i64-LE(1) ++ 0x00.
1323 let a = OpAttrs {
1324 axis: Some(1),
1325 ..OpAttrs::default()
1326 };
1327 let mut expect = 9u32.to_le_bytes().to_vec();
1328 expect.extend_from_slice(&1i64.to_le_bytes());
1329 expect.push(0u8);
1330 assert_eq!(a.to_canonical_bytes(OpTag::MaxDim).unwrap(), expect);
1331 // Row-shape identity: byte-identical to the SumDim row for the same
1332 // attrs (the tag disambiguates via op_name, never via the blob).
1333 assert_eq!(
1334 a.to_canonical_bytes(OpTag::MaxDim).unwrap(),
1335 a.to_canonical_bytes(OpTag::SumDim).unwrap(),
1336 "MaxDim must share the SumDim reduce-row schema"
1337 );
1338 }
1339
1340 // ---- T9 (Increment C slice 1): matmul role-vector serialize + derive -----
1341 //
1342 // The LOCKED reply-3 layout (commit `b64aa1db`; §5 of the recipe-grammar
1343 // design input): matmul's op_attrs = two per-axis role vectors over
1344 // { Batch=0, FreeM=1, FreeN=2, ContractedK=3 } (one u8 per axis), `lhs_roles`
1345 // then `rhs_roles`, each length = operand rank —
1346 // body = u32_le(len lhs) ++ lhs_roles ++ u32_le(len rhs) ++ rhs_roles
1347 // wrapped by carrier (a)'s outer u32_le(body_len) frame. Role vectors encode
1348 // WHICH axis plays which role, not extents, so GQA (differing-but-divisible
1349 // batch extents) serializes to identical all-Batch leading roles.
1350
1351 #[test]
1352 fn matmul_role_vectors_serialize_the_locked_rank2_golden() {
1353 // Worked rank-2 example: lhs=[FreeM,ContractedK]=[1,3], rhs=[ContractedK,FreeN]=[3,2].
1354 // body = 02000000 | 0103 | 02000000 | 0302 (12 bytes)
1355 // full = 0C000000 | body (16 bytes)
1356 //
1357 // INJECTED (B9): this golden is ALSO the shared CROSS-PRODUCER contract —
1358 // Baracuda (#68) confirmed the exact bytes and has NO near-term binary
1359 // arm, so Fuel's serializer is first and this golden IS the contract.
1360 let a = OpAttrs {
1361 lhs_roles: vec![1, 3],
1362 rhs_roles: vec![3, 2],
1363 ..OpAttrs::default()
1364 };
1365 let golden: Vec<u8> = vec![
1366 0x0C, 0x00, 0x00, 0x00, // outer u32-LE body length = 12
1367 0x02, 0x00, 0x00, 0x00, // u32-LE len lhs_roles = 2
1368 0x01, 0x03, // lhs_roles = [FreeM, ContractedK]
1369 0x02, 0x00, 0x00, 0x00, // u32-LE len rhs_roles = 2
1370 0x03, 0x02, // rhs_roles = [ContractedK, FreeN]
1371 ];
1372 assert_eq!(
1373 a.to_canonical_bytes(OpTag::MatMul).unwrap(),
1374 golden,
1375 "the rank-2 matmul role-vector golden is the shared cross-producer contract (Baracuda #68)"
1376 );
1377 }
1378
1379 #[test]
1380 fn matmul_empty_roles_stay_the_canonical_zero_body() {
1381 // Empty roles = the rank-polymorphic recipe form: the body is empty → the
1382 // single canonical 4-byte zero form. This preserves today's golden
1383 // (`empty_schema_op_serializes_zero_length`) untouched.
1384 assert_eq!(
1385 OpAttrs::default()
1386 .to_canonical_bytes(OpTag::MatMul)
1387 .unwrap(),
1388 vec![0, 0, 0, 0]
1389 );
1390 }
1391
1392 #[test]
1393 fn matmul_roles_derives_the_canonical_cell() {
1394 // matmul_roles(lhs_rank, rhs_rank): lhs = [Batch.., FreeM(1), ContractedK(3)];
1395 // rhs = [Batch.., ContractedK(3), FreeN(2)]. Role POSITIONS, not extents.
1396 assert_eq!(matmul_roles(2, 2), (vec![1u8, 3], vec![3u8, 2]));
1397 assert_eq!(matmul_roles(4, 4), (vec![0u8, 0, 1, 3], vec![0u8, 0, 3, 2]));
1398 }
1399
1400 // ---- advisory-band drift fixture ----------------------------------------
1401
1402 #[test]
1403 fn advisory_band_reference_cases_are_well_formed() {
1404 // The shared fixture both band impls pin against: non-empty, valid
1405 // bind spaces, and it exercises every branch of the formula (op-free,
1406 // single-exact, multi-exact, and transcendental). The VALUES are
1407 // asserted from the two formula sides (adapter + fuel-dispatch); here
1408 // we only guard the fixture's own structure so a malformed region can
1409 // never silently weaken both sides at once.
1410 let cases = advisory_band_reference_cases();
1411 assert!(
1412 cases.len() >= 8,
1413 "fixture should cover the formula's branches"
1414 );
1415 for (region, _expected) in &cases {
1416 let binds = region.bind_indices();
1417 if let PatternNode::Op { .. } = region {
1418 // Every op region here is closed over a contiguous [0, n) bind
1419 // space (the fixtures are concrete recipe regions).
1420 for (i, b) in binds.iter().enumerate() {
1421 assert_eq!(*b as usize, i, "bind indices must be [0, n)");
1422 }
1423 }
1424 }
1425 // Branch coverage: at least one op-free (expected None), one exact
1426 // multi-op (Some), and one transcendental band value present.
1427 assert!(
1428 cases
1429 .iter()
1430 .any(|(r, e)| matches!(r, PatternNode::Bind { .. }) && e.is_none())
1431 );
1432 assert!(cases.iter().any(|(_, e)| *e == Some(1)));
1433 assert!(cases.iter().any(|(_, e)| *e == Some(4)));
1434 assert!(cases.iter().any(|(_, e)| *e == Some(8)));
1435 }
1436
1437 // ---- L2: the four ACKED source-op LEAF byte arms ------------------------
1438 //
1439 // KISS ruling record "four-leaf-arm ack (2026-07-23)" (KISS issue-comment
1440 // 5061571967, acking Fuel's proposal 5060303085): the editor acked all four
1441 // arms clean, no amendments —
1442 // runtime_scalar → u32(slot_index)
1443 // reduced_count → i64(axis) (fold-lockstep, §6.12-0001)
1444 // const → u64(bits) (MBZ narrow-dtype rule)
1445 // scan_placeholder → u8(role: 0=carry,1=elem) ++ u32(index)
1446 // Every body rides CARRIER (a) — the #67 node-envelope op_attrs blob, u32-LE
1447 // outer length, payload verbatim (KISS-OPS-6.19-0010). NOT carrier (b) (KISS-Grammar
1448 // §6.8-0007 region-table, u16-LE) and NOT carrier (c) (§6.20-0005 shape-expr
1449 // child, u16-LE); see `three_carrier_width_pins_stay_distinct`.
1450
1451 #[test]
1452 fn runtime_scalar_leaf_serializes_the_slot_index() {
1453 // Acked arm: body = u32_le(slot_index). A dispatch-bound scalar is a
1454 // DISTINCT leaf from a baked `const` (an unfilled slot and a baked value
1455 // are not interchangeable) — hence a separate tag, not a `const` with a
1456 // sentinel. Golden for slot 7: u32-LE(4) ++ u32-LE(7).
1457 let a = OpAttrs {
1458 slot_index: Some(7),
1459 ..OpAttrs::default()
1460 };
1461 let golden: Vec<u8> = vec![
1462 0x04, 0x00, 0x00, 0x00, // outer u32-LE body length = 4
1463 0x07, 0x00, 0x00, 0x00, // u32-LE slot_index = 7
1464 ];
1465 assert_eq!(a.to_canonical_bytes(OpTag::RuntimeScalar).unwrap(), golden);
1466 // Slot 0 is a real slot, not "unset": still the 4-byte body.
1467 assert_eq!(
1468 OpAttrs {
1469 slot_index: Some(0),
1470 ..OpAttrs::default()
1471 }
1472 .to_canonical_bytes(OpTag::RuntimeScalar)
1473 .unwrap(),
1474 vec![0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1475 );
1476 }
1477
1478 #[test]
1479 fn reduced_count_leaf_serializes_the_fold_axis() {
1480 // Acked arm: body = i64_le(axis) — single-axis, byte-identical to the
1481 // fold node's axis field MINUS keepdim, so the resolver reuses the fold's
1482 // axis-resolution codepath verbatim. Growth to a `reduce_axes` LIST
1483 // happens ONLY in lockstep with the fold (§6.12-0001).
1484 let a = OpAttrs {
1485 axis: Some(1),
1486 ..OpAttrs::default()
1487 };
1488 let mut golden = 8u32.to_le_bytes().to_vec();
1489 golden.extend_from_slice(&1i64.to_le_bytes());
1490 assert_eq!(a.to_canonical_bytes(OpTag::ReducedCount).unwrap(), golden);
1491
1492 // Fold-lockstep pin: the reduced_count body IS the reduce row's leading
1493 // i64(axis), with the reduce row's trailing u8(keepdim) absent.
1494 let fold = a.to_canonical_bytes(OpTag::SumDim).unwrap();
1495 let rc = a.to_canonical_bytes(OpTag::ReducedCount).unwrap();
1496 assert_eq!(
1497 rc[4..],
1498 fold[4..12],
1499 "reduced_count body = the fold's i64(axis) verbatim"
1500 );
1501 assert_eq!(
1502 fold.len(),
1503 rc.len() + 1,
1504 "the fold row carries exactly one extra byte (keepdim)"
1505 );
1506
1507 // A negative axis (the i64 carrier is signed, like the fold's) round-trips
1508 // its two's-complement bytes.
1509 let neg = OpAttrs {
1510 axis: Some(-1),
1511 ..OpAttrs::default()
1512 };
1513 let mut expect = 8u32.to_le_bytes().to_vec();
1514 expect.extend_from_slice(&(-1i64).to_le_bytes());
1515 assert_eq!(neg.to_canonical_bytes(OpTag::ReducedCount).unwrap(), expect);
1516 }
1517
1518 #[test]
1519 fn const_leaf_serializes_bits_with_the_mbz_narrow_dtype_rule() {
1520 // Acked arm: body = u64_le(bits) — a DTYPE-AGNOSTIC bit pattern (the
1521 // structural DAG is dtype-agnostic, Q7). MBZ narrow-dtype rule: the
1522 // STORAGE bit pattern of the const's dtype occupies the LOW-order bits,
1523 // upper bits ZERO (must-be-zero on read).
1524
1525 // f64 — the full-width case, every bit load-bearing.
1526 let f64_15 = OpAttrs {
1527 const_bits: Some(1.5f64.to_bits()),
1528 ..OpAttrs::default()
1529 };
1530 let mut golden = 8u32.to_le_bytes().to_vec();
1531 golden.extend_from_slice(&0x3FF8_0000_0000_0000u64.to_le_bytes());
1532 assert_eq!(f64_15.to_canonical_bytes(OpTag::Const).unwrap(), golden);
1533
1534 // f32 — 32 storage bits low-order, upper 32 ZERO.
1535 let f32_15 = OpAttrs {
1536 const_bits: Some(const_bits_narrow(1.5f32.to_bits() as u64, 32)),
1537 ..OpAttrs::default()
1538 };
1539 let blob = f32_15.to_canonical_bytes(OpTag::Const).unwrap();
1540 assert_eq!(
1541 blob,
1542 vec![
1543 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00
1544 ],
1545 "f32 1.5 = 0x3FC00000 in the LOW-order bits; upper 4 bytes MBZ"
1546 );
1547
1548 // f16 (1.5 = 0x3E00) and bf16 (1.5 = 0x3FC0) — 16 storage bits low-order,
1549 // upper 48 ZERO.
1550 let f16_15 = OpAttrs {
1551 const_bits: Some(const_bits_narrow(0x3E00, 16)),
1552 ..OpAttrs::default()
1553 };
1554 assert_eq!(
1555 f16_15.to_canonical_bytes(OpTag::Const).unwrap(),
1556 vec![
1557 0x08, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
1558 ],
1559 );
1560 let bf16_15 = OpAttrs {
1561 const_bits: Some(const_bits_narrow(0x3FC0, 16)),
1562 ..OpAttrs::default()
1563 };
1564 assert_eq!(
1565 bf16_15.to_canonical_bytes(OpTag::Const).unwrap(),
1566 vec![
1567 0x08, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
1568 ],
1569 );
1570
1571 // The MBZ widener is the producer-side guarantee: it MASKS, never panics
1572 // (a width of 0 or ≥ 64 is well-defined, no shift overflow).
1573 assert_eq!(
1574 const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 16),
1575 0x0000_0000_0000_FFFF
1576 );
1577 assert_eq!(
1578 const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 32),
1579 0x0000_0000_FFFF_FFFF
1580 );
1581 assert_eq!(
1582 const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 64),
1583 0xFFFF_FFFF_FFFF_FFFF
1584 );
1585 assert_eq!(
1586 const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 200),
1587 0xFFFF_FFFF_FFFF_FFFF
1588 );
1589 assert_eq!(const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 0), 0);
1590 // Every narrow width leaves the upper bits zero — the MBZ invariant.
1591 for w in [1u32, 8, 16, 32, 63] {
1592 let bits = const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, w);
1593 assert_eq!(bits >> w, 0, "width {w}: upper bits must be zero");
1594 }
1595 }
1596
1597 #[test]
1598 fn const_leaf_carries_a_nan_payload_verbatim() {
1599 // "NaN payload = stored bits verbatim" — the serializer must NOT
1600 // canonicalize a NaN to a quiet default. NOTE: carrier (a) has no
1601 // production DECODER (forward-serialization only — see the M-3 note on
1602 // `to_canonical_bytes`), so the read-back below is an in-test byte read,
1603 // not a claim that a decoder exists.
1604 const F32_NAN_PAYLOAD: u32 = 0x7FC0_DEAD;
1605 assert!(
1606 f32::from_bits(F32_NAN_PAYLOAD).is_nan(),
1607 "fixture must be a NaN"
1608 );
1609 let a = OpAttrs {
1610 const_bits: Some(const_bits_narrow(F32_NAN_PAYLOAD as u64, 32)),
1611 ..OpAttrs::default()
1612 };
1613 let blob = a.to_canonical_bytes(OpTag::Const).unwrap();
1614 assert_eq!(
1615 blob,
1616 vec![
1617 0x08, 0x00, 0x00, 0x00, 0xAD, 0xDE, 0xC0, 0x7F, 0x00, 0x00, 0x00, 0x00
1618 ],
1619 "the f32 NaN payload rides the low-order bits verbatim; upper 4 bytes MBZ"
1620 );
1621 let read_back = u64::from_le_bytes(blob[4..12].try_into().unwrap());
1622 assert_eq!(
1623 read_back, F32_NAN_PAYLOAD as u64,
1624 "payload bits round-trip verbatim"
1625 );
1626 assert_eq!(
1627 f32::from_bits(read_back as u32).to_bits(),
1628 F32_NAN_PAYLOAD,
1629 "bit-exact (a NaN never compares equal — compare BITS)"
1630 );
1631
1632 // f64 signalling-NaN payload: full width, nothing masked or quieted.
1633 const F64_SNAN_PAYLOAD: u64 = 0x7FF0_0000_0000_DEAD;
1634 assert!(
1635 f64::from_bits(F64_SNAN_PAYLOAD).is_nan(),
1636 "fixture must be a NaN"
1637 );
1638 let d = OpAttrs {
1639 const_bits: Some(F64_SNAN_PAYLOAD),
1640 ..OpAttrs::default()
1641 };
1642 let dblob = d.to_canonical_bytes(OpTag::Const).unwrap();
1643 assert_eq!(
1644 u64::from_le_bytes(dblob[4..12].try_into().unwrap()),
1645 F64_SNAN_PAYLOAD,
1646 "an f64 sNaN payload is NOT quieted by the serializer"
1647 );
1648 }
1649
1650 #[test]
1651 fn scan_placeholder_leaf_serializes_role_and_index() {
1652 // Acked arm: body = u8(role: 0=carry, 1=elem) ++ u32_le(index). Role
1653 // codes match `fuel_graph::ScanRole`'s declaration order (Carry, Elem).
1654 assert_eq!((SCAN_ROLE_CARRY, SCAN_ROLE_ELEM), (0u8, 1u8));
1655
1656 // Carry hole (always index 0 in the v1 single-carry model).
1657 let carry = OpAttrs {
1658 scan_role: Some(SCAN_ROLE_CARRY),
1659 scan_index: Some(0),
1660 ..OpAttrs::default()
1661 };
1662 assert_eq!(
1663 carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
1664 vec![0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1665 "carry hole: u32-LE(5) ++ u8(0) ++ u32-LE(0)"
1666 );
1667 // Elem hole for xs[2].
1668 let elem = OpAttrs {
1669 scan_role: Some(SCAN_ROLE_ELEM),
1670 scan_index: Some(2),
1671 ..OpAttrs::default()
1672 };
1673 assert_eq!(
1674 elem.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
1675 vec![0x05, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00],
1676 "elem hole: u32-LE(5) ++ u8(1) ++ u32-LE(2)"
1677 );
1678 // The role byte is NOT part of the index: carry{0} and elem{0} differ.
1679 let elem0 = OpAttrs {
1680 scan_role: Some(SCAN_ROLE_ELEM),
1681 scan_index: Some(0),
1682 ..OpAttrs::default()
1683 };
1684 assert_ne!(
1685 carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
1686 elem0.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
1687 );
1688 }
1689
1690 #[test]
1691 fn leaf_arm_bodies_ride_carrier_a_u32_le() {
1692 // Width discipline: all four acked leaf bodies ride CARRIER (a) — the #67
1693 // node-envelope op_attrs blob, u32-LE (4-byte) outer length, payload
1694 // verbatim. None of them may adopt carrier (b)/(c)'s u16-LE width.
1695 let a = OpAttrs {
1696 slot_index: Some(7),
1697 axis: Some(1),
1698 const_bits: Some(0x3FC0_0000),
1699 scan_role: Some(SCAN_ROLE_ELEM),
1700 scan_index: Some(2),
1701 ..OpAttrs::default()
1702 };
1703 for (tag, body_len) in [
1704 (OpTag::RuntimeScalar, 4usize),
1705 (OpTag::ReducedCount, 8),
1706 (OpTag::Const, 8),
1707 (OpTag::ScanPlaceholder, 5),
1708 ] {
1709 let blob = a.to_canonical_bytes(tag).unwrap();
1710 let declared = u32::from_le_bytes(blob[..4].try_into().unwrap()) as usize;
1711 assert_eq!(
1712 declared, body_len,
1713 "{tag:?}: outer u32-LE length = body length"
1714 );
1715 assert_eq!(
1716 blob.len(),
1717 4 + body_len,
1718 "{tag:?}: 4-byte u32-LE prefix + verbatim body"
1719 );
1720 }
1721 }
1722
1723 #[test]
1724 fn leaf_arms_are_wire_tokens_only_no_graph_producer() {
1725 // HONEST SCOPE. These four tags are wire tokens in the shared grammar;
1726 // Fuel's graph has no first-class recipe LEAF for them yet (a value is
1727 // expressed implicitly today — an `Op::Const` tensor operand, an
1728 // `Op::Iota`, a `Runtime { scalars }` slot on the consuming op,
1729 // `Op::ScanPlaceholder` inside `Op::Scan`'s body, and Mean's divisor
1730 // folded into `Op::MeanDim`). So `jit::op_to_tag` emits none of them and
1731 // `runtime_fused::tag_to_op` declines `Const`/`RuntimeScalar`/`ReducedCount`
1732 // as honest misses but RECONSTRUCTS `ScanPlaceholder` (explicit arm,
1733 // `Increment C, B1`) — the
1734 // flat-DAG-CSE recipe interior that would produce them is the (unbuilt)
1735 // Convergence-C home. Pinned here so a later wiring change is deliberate.
1736 //
1737 // The observable consequence in THIS crate, CHANGED BY GAP-287: unset
1738 // attrs are DECLINED, not serialized to a fixed-width body of defaults.
1739 //
1740 // This assertion is the inverse of the one it replaces. The old text
1741 // read "unset attrs still serialize to the tag's fixed-width body (the
1742 // M-3 unset-vs-zero caveat), never a panic and never an empty body" and
1743 // pinned the four LENGTHS -- i.e. it encoded the fabrication as a
1744 // REQUIREMENT. It was the ONLY test in this crate that failed when the
1745 // encoder began declining, which is the born-red for this change: the
1746 // suite already contained an assertion that the defect held.
1747 let d = OpAttrs::default();
1748 for (tag, field) in [
1749 (OpTag::RuntimeScalar, "slot_index"),
1750 (OpTag::ReducedCount, "axis"),
1751 (OpTag::Const, "const_bits"),
1752 (OpTag::ScanPlaceholder, "scan_role"),
1753 ] {
1754 assert_eq!(
1755 d.to_canonical_bytes(tag),
1756 Err(UnresolvedAttr { op: tag, field }),
1757 "{tag:?} must DECLINE an unset `{field}`, not emit a default"
1758 );
1759 }
1760
1761 // CONTROL, so the four declines are not merely "this function always
1762 // errors": a tag whose arm reads nothing still succeeds with the empty
1763 // body, and a fully-populated leaf still serializes to the same length.
1764 assert_eq!(d.to_canonical_bytes(OpTag::Add).unwrap(), vec![0, 0, 0, 0]);
1765 let filled = OpAttrs {
1766 scan_role: Some(SCAN_ROLE_ELEM),
1767 scan_index: Some(2),
1768 ..OpAttrs::default()
1769 };
1770 assert_eq!(
1771 filled
1772 .to_canonical_bytes(OpTag::ScanPlaceholder)
1773 .unwrap()
1774 .len(),
1775 4 + 5,
1776 "a RESOLVED ScanPlaceholder still emits the same 5-byte body"
1777 );
1778 }
1779
1780 /// The GAP-287 defect itself, asserted as GONE: two `Gather`s on different
1781 /// axes no longer collide, because neither is expressible unresolved.
1782 ///
1783 /// `fuel-graph`'s `distinct_gathers_serialize_identically_gap287` pinned the
1784 /// collision from the projection side; this is the same fact from inside the
1785 /// crate that owns the encoder.
1786 #[test]
1787 fn an_unresolved_axis_is_inexpressible_gap287() {
1788 assert_eq!(
1789 OpAttrs::default().to_canonical_bytes(OpTag::Gather),
1790 Err(UnresolvedAttr {
1791 op: OpTag::Gather,
1792 field: "axis"
1793 })
1794 );
1795
1796 // Resolved axes are distinct on the wire -- the property the collapse
1797 // destroyed. This is the assertion no decoder could have restored.
1798 let a0 = OpAttrs {
1799 axis: Some(0),
1800 ..OpAttrs::default()
1801 };
1802 let a2 = OpAttrs {
1803 axis: Some(2),
1804 ..OpAttrs::default()
1805 };
1806 assert_ne!(
1807 a0.to_canonical_bytes(OpTag::Gather).unwrap(),
1808 a2.to_canonical_bytes(OpTag::Gather).unwrap(),
1809 "axis 0 and axis 2 must differ on the wire"
1810 );
1811 }
1812
1813 /// `keepdim` still defaults, and that is deliberate rather than an omission.
1814 ///
1815 /// Declining it would refuse input `tag_to_op` ACCEPTS: the decoder reads no
1816 /// `keepdim` for these tags at all, because Fuel encodes keepdim=true
1817 /// STRUCTURALLY as `ReduceSumTo`/`ReduceMaxTo` on the shape-target arm.
1818 /// Pinned so a future "consistency" sweep does not make this arm strict and
1819 /// break the round-trip in the name of tidiness.
1820 #[test]
1821 fn keepdim_still_defaults_because_the_decoder_never_reads_it() {
1822 let axis_only = OpAttrs {
1823 axis: Some(1),
1824 ..OpAttrs::default()
1825 };
1826 let bytes = axis_only
1827 .to_canonical_bytes(OpTag::SumDim)
1828 .expect("axis is set; keepdim is not required");
1829 assert_eq!(bytes.len(), 4 + 8 + 1, "axis(i64) + keepdim(u8)");
1830 assert_eq!(*bytes.last().unwrap(), 0, "keepdim defaults to false");
1831
1832 // And the axis on the SAME arm is still required -- so this cannot pass
1833 // by the arm having become permissive.
1834 assert_eq!(
1835 OpAttrs::default().to_canonical_bytes(OpTag::SumDim),
1836 Err(UnresolvedAttr {
1837 op: OpTag::SumDim,
1838 field: "axis"
1839 })
1840 );
1841 }
1842}