fireline-grammar 0.4.2

The kernel-seam region grammar: OpTag, OpAttrs (with canonical bytes), RegionKey, PatternNode and the shape-expression codec, shared by a kernel consumer and a kernel provider. Types only, no logic, dependency-free.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Frozen kernel-seam wire types — the JIT region / declarative-pattern grammar
//! shared across the Fuel <-> backend-synthesizer seam (kernel-seam-interop
//! §3/§5; fkc-fusion-patterns §3). **Types only, no logic, no Fuel-graph
//! dependency**: a synthesizer backend (e.g. Baracuda) depends on this small
//! crate; the `Op -> OpTag` projection (`fuel_graph::jit::op_to_tag`) and the
//! structural matcher (`fuel_graph::jit::match_region`) stay Fuel-side because
//! they need the graph.
//!
//! One [`PatternNode`] serves three roles: the **JIT region** (Fuel ->
//! synthesizer, "build a kernel for this subgraph"), a contract's `pattern:`
//! **re-fuse rule**, and a synthesized op's **`decompose`** (the region
//! re-emitted). The operand-side projection (`OperandDesc`) is the synthesizer's
//! `structure_key` input and lives in its types crate — not here.
//!
//! The handshake envelope (`SeamHello`, §3) lives in the sibling
//! `fuel-kernel-seam-announce` crate, not here — a provider that only speaks
//! capability negotiation shouldn't need to pull in this region grammar.

/// The §6.20 shape-expression AST + canonical wire codec + evaluator — the
/// KISS-consistent shape vocabulary, homed here (std-only) so `fuel-graph` can
/// carry `Dim`/`ShapeExpr` in [`OpAttrs`] without depending on `fuel-dispatch`
/// (which re-exports this module at `fkc::shape_expr` for its FKC importer).
mod canonical;
pub use canonical::UnresolvedAttr;

pub mod shape_expr;

// ===========================================================================
// OpTag — the frozen functional-Op vocabulary (kernel-seam-interop §4.1)
// ===========================================================================

/// The §4.1 graph-`Op` vocabulary, **functional ops only** — the stable op
/// identifier a [`PatternNode`] carries. Excludes in-place variants (a region
/// is the *functional* subgraph; in-place is a Fuel-side scheduling rewrite)
/// and structural / bookkeeping ops (`Const`, `Release`, `Alloc`, views, ...).
/// The `Op -> OpTag` projection (`op_to_tag`) lives Fuel-side (it needs the
/// graph `Op`); the inverse — which params an emitted op carries — rides
/// [`OpAttrs`] + the `extract:` path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OpTag {
    // binary arithmetic / extremum
    Add,
    Sub,
    Mul,
    Div,
    Maximum,
    Minimum,
    Pow,
    Rem,
    // unary math
    Neg,
    Abs,
    Sqr,
    Sqrt,
    Rsqrt,
    Recip,
    Exp,
    Log,
    Sin,
    Cos,
    // activations (GeluTanh = tanh-approx; Gelu = exact erf — distinct, §3 note)
    Tanh,
    Sigmoid,
    Silu,
    GeluTanh,
    Gelu,
    Relu,
    Erf,
    Step,
    // rounding / sign
    Floor,
    Ceil,
    Round,
    Sign,
    // scalar-param (value param-ized; attrs carries the slot)
    AddScalar,
    MulScalar,
    PowI,
    Clamp,
    // comparison (-> U8 mask)
    Equal,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    // select / mask
    Where,
    MaskedFill,
    // reductions (MaxDim: additive, Increment C slice 1 T4 — the D3 keepdim
    // swap spells keepdim reduces as {Max,Sum,Mean}Dim + Unsqueeze)
    SumAll,
    MaxAll,
    MinAll,
    MeanAll,
    SumDim,
    MaxDim,
    MeanDim,
    ReduceSumTo,
    ReduceMaxTo,
    CumSum,
    // matmul
    MatMul,
    // shape / layout (metadata or copy)
    Transpose,
    Permute,
    Reshape,
    BroadcastTo,
    Unsqueeze,
    Squeeze,
    Cast,
    Slice,
    Concat,
    Flip,
    Roll,
    Pad,
    Triu,
    Tril,
    // indexing / gather-scatter
    IndexSelect,
    Gather,
    IndexAdd,
    ScatterAdd,
    // fused-primitive helpers
    LogSoftmaxLastDim,
    // value source
    Iota,

    // --- source-op LEAF tokens (childless `Op` nodes; KISS four-leaf ack) ----
    //
    // A value a recipe needs as an operand is a **source op** — a childless
    // `Op` — so the node schema stays closed to two kinds (`Op | Bind`) instead
    // of growing a schema variant per value kind (recipe-grammar design input
    // §2). The four byte arms below were acked by the KISS editor on 2026-07-23
    // ("RULING RECORD — four-leaf-arm ack", no amendments).
    //
    // **Wire tokens only — no Fuel graph producer yet.** `jit::op_to_tag` emits
    // none of these. `runtime_fused::tag_to_op` declines THREE of them (`Const`,
    // `RuntimeScalar`, `ReducedCount`) as honest
    // misses). Fuel expresses these values implicitly today (an `Op::Const`
    // TENSOR operand, a `Runtime { scalars }` slot on the *consuming* op,
    // `Op::ScanPlaceholder` inside `Op::Scan`'s body, Mean's divisor folded into
    // `Op::MeanDim`); making them first-class recipe leaves is the flat-DAG-CSE
    // recipe interior, still unbuilt. See `docs/recipe-signature-reference.md`
    // §"source-op leaves".
    /// Scalar literal leaf: a **dtype-agnostic bit pattern** (`const_bits`).
    /// **NOT** Fuel's `Op::Const` (a whole constant TENSOR / weight leaf) — this
    /// is the KISS `const` source op, a baked scalar value. Distinct from
    /// [`OpTag::RuntimeScalar`]: a baked value and an unfilled dispatch slot are
    /// not interchangeable.
    Const,
    /// Dispatch-bound scalar leaf: the `slot_index` of an **unfilled** scalar
    /// slot (Fuel-side: the pre-order position in `FusedOpParams::Runtime {
    /// scalars }`, counted by `runtime_fused::count_scalar_slots`).
    RuntimeScalar,
    /// The value-side product of extents over the reduced axes — the `Mean`
    /// divisor, so `mean == div(reduce[sum,..](x), reduced_count(axis))` is one
    /// flat DAG (canonical KISS §6.12-0001; the retired name was
    /// `reduce_extent`). Single-axis, riding the same `axis` carrier as the
    /// fold; it grows to a `reduce_axes` list ONLY in lockstep with the fold.
    ReducedCount,
    /// A body hole of `Op::Scan`: `role` (0 = carry, 1 = elem — see
    /// [`SCAN_ROLE_CARRY`]/[`SCAN_ROLE_ELEM`]) + `index` (which `xs[i]` an
    /// `elem` hole stands for; a `carry` hole is index 0 in the v1 single-carry
    /// model).
    ScanPlaceholder,

    /// Fuel's bounded `lax.scan` recurrence primitive (`fuel_graph::Op::Scan`).
    /// A **structural token** — like [`OpTag::ScanPlaceholder`], NOT a KISS base op:
    /// its params (`n_xs`/`bound`/`emit`/`early_exit`) ride the Fuel-internal
    /// [`OpAttrs`] `scan_*` fields and are NOT serialized to the §6.19
    /// cross-producer wire (the empty-body `_` arm in
    /// [`OpAttrs::to_canonical_bytes`]), exactly like the shape-relative
    /// recipe-interior fields. The body sub-graph rides the node's trailing
    /// operands (Phase-1 lax.scan input encoding:
    /// `[init_carry, xs.., consts.., body_new_carry, body_y, [pred_exit]]`).
    /// Re-emitted by `runtime_fused::tag_to_op`; no `op_to_tag` producer (a
    /// scan node is a base-map terminal the matcher never recognizes).
    Scan,

    /// Multi-output slot projection (`fuel_graph::Op::View`) — the bundle
    /// carrier a scan (or any multi-output producer) exposes its per-slot
    /// outputs through. A structural token: the `slot` rides the Fuel-internal
    /// `view_slot` [`OpAttrs`] field, not the §6.19 wire. On re-emit the slot's
    /// shape/dtype come from the producer's `output_views` bundle (the emitter
    /// sets that bundle when it re-emits the producing `Scan`), mirroring
    /// `fuel_graph::Graph::view`.
    View,

    /// A **nested fused op** carried inside a recipe AS-IS
    /// (`fuel_graph::Op::Fused(id, params)`) — the attention-trio decompose's
    /// inner softmax (`flash_attn`/`paged_attn` emit an
    /// `Op::Fused(SOFTMAX_LAST_DIM, ..)` node; `flash_attn_backward` an
    /// `Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, ..)`). A **structural token** — like
    /// [`OpTag::Scan`]/[`OpTag::View`], NOT a KISS base op: it names which registry entry the
    /// node reconstructs to (via the [`OpAttrs::fused_op`] selector) and is
    /// **Fuel-internal, NOT serialized to the §6.19 cross-producer wire** (a
    /// `Fused` node hits the empty-body `_` arm of
    /// [`OpAttrs::to_canonical_bytes`], exactly like the `scan_*`/`view_slot`
    /// fields). Re-emitted by `runtime_fused::tag_to_op` for the param-less
    /// nested fused ops (a small fid → params map); any param-carrying id is an
    /// honest miss. No `op_to_tag` producer — the base map lowers past a nested
    /// fused node (it recursively decomposes past itself), so the recipe just
    /// re-carries it, keeping the softmax fused so the optimizer can re-cover it.
    /// On re-emit its shape/dtype come from the named registry entry's
    /// `shape_rule`/`dtype_rule` (`primitive_shape` honest-misses `Fused`).
    Fused,
}

/// [`OpTag::ScanPlaceholder`] role code for the per-step recurrent **carry**
/// hole. Matches `fuel_graph::ScanRole::Carry`'s declaration order.
pub const SCAN_ROLE_CARRY: u8 = 0;
/// [`OpTag::ScanPlaceholder`] role code for the per-step **element** hole (the
/// slice of `xs[index]`). Matches `fuel_graph::ScanRole::Elem`.
pub const SCAN_ROLE_ELEM: u8 = 1;

/// Place a narrow dtype's **storage** bit pattern into the [`OpTag::Const`]
/// leaf's `u64` carrier per the acked **MBZ narrow-dtype rule**: the storage
/// bits occupy the LOW-order bits and the upper bits are ZERO (must-be-zero on
/// read). `width_bits` is the dtype's storage width (16 for `f16`/`bf16`, 32 for
/// `f32`/`u32`/`i32`, 64 for `f64`/`i64`); a width ≥ 64 is the identity.
///
/// A NaN payload rides **verbatim** — this masks, it never canonicalizes or
/// quiets. Pure + never-panic (no shift overflow at width 0 or ≥ 64).
pub fn const_bits_narrow(storage: u64, width_bits: u32) -> u64 {
    if width_bits == 0 {
        return 0;
    }
    if width_bits >= 64 {
        return storage;
    }
    storage & ((1u64 << width_bits) - 1)
}

// ===========================================================================
// PatternNode — the §3 declarative subgraph grammar
// ===========================================================================

/// Non-tensor attributes a [`PatternNode::Op`] carries (fkc-fusion-patterns
/// §3a.4; Baracuda reconcile §2). For scalar-param ops the value is **not
/// baked** — it identifies the slot the emitted `extract:` path points at, and
/// the matcher re-reads the live value from the matched graph node at match
/// time. Carries the load-bearing attributes the general vocabulary needs.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OpAttrs {
    /// Scalar value(s) for scalar-param ops (`AddScalar`/`MulScalar`/`Clamp`),
    /// as the region's snapshot of the slot (re-read live via `extract:`).
    pub scalars: Vec<f64>,
    /// Axis attribute for dim-bearing ops (reductions, `Triu`/`Tril` diagonal).
    pub axis: Option<i64>,
    /// Permute/Transpose: the new axis order, **ABSOLUTE** — a permutation of
    /// `0..rank` with `out.axis[i] = in.axis[perm[i]]` (matches Fuel
    /// `Op::Permute` semantics exactly; `Op::Transpose` is the last-two-axes
    /// special case). Empty ⇒ not a permuting node (a matcher wildcard). See
    /// `baracuda-layout-fusion-response.md` F1/F2a.
    pub perm: Vec<u8>,
    /// BroadcastTo/Reshape: the target **LOGICAL** shape (the op's output
    /// shape); one field serves both (the [`OpTag`] disambiguates which op).
    /// Empty ⇒ not a shape-target node (a matcher wildcard).
    pub target_shape: Vec<i64>,
    /// Squeeze/Unsqueeze: the affected dim list (0-based, output-rank terms).
    /// Fuel's single-dim `Op::Squeeze`/`Op::Unsqueeze` emit a one-element list.
    /// Empty ⇒ not a squeeze/unsqueeze node (a matcher wildcard).
    pub dims: Vec<u8>,
    /// `Cast` target dtype as the stable `DType::as_str()` name (dep-free:
    /// this crate can't reference `fuel_ir::DType`; fuel-graph maps back via
    /// `DType::from_str`). Also carries `MaskedFill`'s value dtype. `None` ⇒
    /// not a dtype-carrying node (a matcher wildcard). Convergence Increment A.
    pub cast_dtype: Option<String>,
    /// `Slice` start offset along `axis` (the dim rides the existing `axis`
    /// field). `None` ⇒ not a slice node. Convergence Increment A.
    pub slice_start: Option<u64>,
    /// `Slice` length along `axis`. `None` ⇒ not a slice node. Convergence
    /// Increment A.
    pub slice_len: Option<u64>,
    /// `Roll` cyclic shift along `axis` (signed; the dim rides `axis`). `None`
    /// ⇒ not a roll node. Convergence Increment A.
    pub roll_shift: Option<i64>,
    /// `Pad` per-axis `(before, after)` amounts, one pair per input dim. Empty
    /// ⇒ not a pad node. Convergence Increment A.
    pub pad_amounts: Vec<(u64, u64)>,
    /// `Pad` fill mode code: `0=Constant, 1=Reflect, 2=Replicate` (mirrors
    /// Fuel's `PadMode` order; dep-free integer code). `None` ⇒ not a pad node.
    /// Convergence Increment A.
    pub pad_mode: Option<u8>,
    /// `Pad` constant fill value (used by `PadMode::Constant`). `None` ⇒ not a
    /// pad node. Convergence Increment A.
    pub pad_value: Option<f64>,
    /// Reduction `keepdim` flag (§6.19 reduce-schema conformance — serialized
    /// in the canonical blob). NOT consumed by `tag_to_op`: Fuel's reduce Ops
    /// encode keepdim structurally (`ReduceSumTo`/`ReduceMaxTo` carry the kept
    /// shape; `SumDim`/`MeanDim` are rank-reducing). Convergence Increment A.
    pub keepdim: Option<bool>,

    // --- Shape-RELATIVE recipe-interior fields (Increment C slice 1, D2) ---
    //
    // The four fields below make a recipe polymorphic across shapes/ranks:
    // instead of baking an absolute value they carry an expression over the
    // region's **Bind space** (`ShapeExpr::SameAs { operand: i }` /
    // `Dim::Extent { operand: i, .. }` reference `Bind { index: i }` — the same
    // operand-index convention the merged KISS shape-oracle RFC pins for
    // contracts). They are resolved to the concrete sibling field at emit time
    // (`fuel_graph::runtime_fused::resolve_rel_attrs`); a rel field and its
    // concrete sibling set together is a typed resolution error (mutual
    // exclusion), never a silent precedence.
    //
    // **Deliberately NOT serialized to the §6.19 wire (KISS #67-gated).**
    // `to_canonical_bytes` serializes only the concrete fields: the pinned
    // §6.19 arms for `broadcast_to`/`slice` are ABSOLUTE, and the node-envelope
    // framing that could carry a relative alternative is being defined in
    // KISS #67 — serializing a rel form now would unilaterally extend a shared
    // byte contract (propose-first). Emitted/graph nodes are always concrete
    // post-resolution, so rel-attr recipes never flow to `to_canonical_bytes`
    // callers. Pinned by `rel_attr_fields_are_absent_from_the_6_19_wire`.
    /// Shape-relative alternative to `target_shape`: the target is another
    /// operand's shape (`SameAs { operand }` over the Bind space). `None` ⇒
    /// use `target_shape` (or not a shape-target node).
    ///
    /// **Not every output frame is expressible this way.** A broadcast frame
    /// assembled by per-axis max across TWO binds (`a[N,1] ⊗ b[1,M] → [N,M]`)
    /// is carried by NO single operand, so no `SameAs` spelling names it — the
    /// resolver refuses such a `BroadcastTo` target as a Dims-class gap
    /// (`RelAttrError::FrameNotExpressible`) rather than silently resolving to
    /// one operand's PARTIAL frame. The constructor that would express it is
    /// the reserved [`shape_expr::TAG_DIMS`] entrant (KISS #80).
    pub target_shape_rel: Option<shape_expr::ShapeExpr>,
    /// Shape-relative alternative to `slice_start`: a `DimExpr` over the Bind
    /// space (e.g. rope's `Div(Extent(0, LAST), 2)`). `None` ⇒ use
    /// `slice_start`.
    pub slice_start_rel: Option<shape_expr::Dim>,
    /// Shape-relative alternative to `slice_len`. `None` ⇒ use `slice_len`.
    pub slice_len_rel: Option<shape_expr::Dim>,
    /// Rank-relative alternative to the op's axis carrier (`axis`, or `dims`
    /// for Squeeze/Unsqueeze): this op's axis is its per-tag LAST — resolved
    /// against `rank(operand[0])` as `rank − 1` for reduces/Slice/Concat/Flip/
    /// CumSum/… and Squeeze, and `rank` (append) for Unsqueeze. `false` ⇒ use
    /// the absolute carrier.
    pub axis_last: bool,
    /// Shape-relative alternative to `scalars` for a scalar-param op
    /// (`AddScalar`/`MulScalar`): the scalar VALUE is a `DimExpr` over the Bind
    /// space, resolved to a concrete number at emit time
    /// (`fuel_graph::runtime_fused::resolve_rel_attrs`) — the **reduced_count**
    /// concept made emittable: `Dim::Extent { operand: 0, axis: LAST }` yields
    /// `n = extent of operand 0's last axis` (the `MulScalar(n)` divisor a norm
    /// backward needs). It rides the SAME `Dim`/`eval_dim`/`resolve_axis`
    /// machinery as `slice_start_rel`/`slice_len_rel` (no parallel axis
    /// resolver). Distinct from an OPEN scalar slot: a `scalar_rel` node is
    /// filled from an input SHAPE, NOT from the params projection cursor, so it
    /// is NOT counted by `count_scalar_slots` and never consumes a cursor value.
    /// `None` ⇒ use `scalars` (a baked value or an open slot). Set together with
    /// a non-empty `scalars` is a typed resolution error (rel XOR abs). Like the
    /// other rel fields, it is IN-MEMORY recipe data — deliberately NOT
    /// serialized to the §6.19 wire (pinned by
    /// `rel_attr_fields_are_absent_from_the_6_19_wire`).
    pub scalar_rel: Option<shape_expr::Dim>,

    // --- Matmul contraction role vectors (Increment C slice 1, T9/D5) -------
    //
    // The LOCKED reply-3 contraction descriptor (commit `b64aa1db`; §5 of the
    // recipe-grammar design input). `matmul`'s op_attrs is two per-axis role
    // vectors over the roles { Batch=0, FreeM=1, FreeN=2, ContractedK=3 } (one
    // **u8** per axis), `lhs_roles` then `rhs_roles`, each length = operand rank.
    // Role vectors encode WHICH axis plays which role, **not extents** — so GQA
    // (differing-but-divisible batch extents) serializes to identical all-Batch
    // leading roles. Both empty ⇒ the rank-polymorphic implicit form (recipes
    // keep matmul implicit; concrete/ingested nodes get explicit roles). The
    // canonical cell (same-rank ≥ 2; leading Batch; lhs=[..,FreeM,ContractedK],
    // rhs=[..,ContractedK,FreeN]) is derived by [`matmul_roles`] and validated at
    // resolve time (`fuel_graph::runtime_fused::tag_to_op`).
    //
    // Serialized on carrier (a) — `to_canonical_bytes(MatMul)` emits
    // `u32_le(len lhs) ++ lhs_roles ++ u32_le(len rhs) ++ rhs_roles` when set, or
    // the canonical empty body `[00,00,00,00]` when both are empty (preserving
    // today's golden). Baracuda (#68) confirmed the rank-2 golden as the shared
    // cross-producer fixture and has no near-term binary arm, so Fuel's
    // serializer is the contract.
    /// LHS per-axis contraction roles ({Batch=0,FreeM=1,FreeN=2,ContractedK=3},
    /// u8 each; length = lhs rank). Empty ⇒ implicit (rank-polymorphic) matmul.
    pub lhs_roles: Vec<u8>,
    /// RHS per-axis contraction roles (same encoding; length = rhs rank). Empty
    /// ⇒ implicit (rank-polymorphic) matmul.
    pub rhs_roles: Vec<u8>,

    // --- source-op LEAF carriers (KISS four-leaf ack, 2026-07-23) -----------
    //
    // One carrier per acked leaf arm. `ReducedCount` needs no field of its own:
    // it rides the existing `axis` (fold-lockstep — byte-identical to the fold
    // node's axis field, minus keepdim). These are wire carriers; no Fuel graph
    // Op projects into them yet (see the `OpTag` leaf-token note).
    /// [`OpTag::Const`] value: the scalar literal's **dtype-agnostic storage bit
    /// pattern**. Narrow dtypes place their storage bits LOW-order with the
    /// upper bits zero (MBZ) — use [`const_bits_narrow`]. A NaN payload is
    /// carried verbatim (never quieted). `None` ⇒ not a const leaf.
    pub const_bits: Option<u64>,
    /// [`OpTag::RuntimeScalar`] value: the index of the dispatch-bound scalar
    /// slot this leaf reads. `None` ⇒ not a runtime-scalar leaf.
    pub slot_index: Option<u32>,
    /// [`OpTag::ScanPlaceholder`] role code: [`SCAN_ROLE_CARRY`] (0) or
    /// [`SCAN_ROLE_ELEM`] (1). `None` ⇒ not a scan-placeholder leaf.
    pub scan_role: Option<u8>,
    /// [`OpTag::ScanPlaceholder`] index: which `xs[i]` an `elem` hole stands
    /// for (a `carry` hole is index 0 in the v1 single-carry model). `None` ⇒
    /// not a scan-placeholder leaf.
    pub scan_index: Option<u32>,

    // --- [`OpTag::Scan`] param carriers (Increment C, B1) --------------------
    //
    // Fuel-internal recipe fields for the bounded-scan primitive's params.
    // Like the shape-relative fields above they are NOT on the §6.19 wire (a
    // `Scan` node hits the empty-body `_` arm of `to_canonical_bytes`): the
    // scan is Fuel's own sub-graph-carrying primitive, not a KISS base op, so
    // its params never flow to a cross-producer blob. `None` ⇒ not a scan node.
    /// [`OpTag::Scan`] `n_carries`: how many recurrent carries the scan threads
    /// (GAP-303). `1` is the v1 single-carry model.
    ///
    /// ⚠️ Like its siblings this is Fuel-internal and NOT on the KISS-OPS-6.19
    /// wire: `OpTag::Scan` is in `has_empty_canonical_body`'s empty group BY
    /// DESIGN, so no `Scan` param is serialized and adding one here changes no
    /// bytes. Carry IDENTITY on the wire is already carried by
    /// `OpTag::ScanPlaceholder`'s body, which serializes `scan_index` as a
    /// `u32` — `Carry/0` and `Carry/1` have always produced different bytes.
    pub scan_n_carries: Option<u32>,
    /// [`OpTag::Scan`] `n_xs`: number of per-step `xs` operands.
    pub scan_n_xs: Option<u32>,
    /// [`OpTag::Scan`] `bound`: the static step horizon.
    pub scan_bound: Option<u32>,
    /// [`OpTag::Scan`] emit code: `0` = All (stack per-step ys, slot 0), `1` =
    /// Final (final carry). Matches `fuel_graph::ScanEmit`'s declaration order.
    pub scan_emit: Option<u8>,
    /// [`OpTag::Scan`] early-exit presence flag: `Some(true)` ⇒ the Phase-2
    /// `ScanPredicate` marker is present (its predicate LOGIC rides the trailing
    /// `pred_exit` operand). `None`/`Some(false)` ⇒ no early exit.
    pub scan_early_exit: Option<bool>,
    /// [`OpTag::View`] slot index: which of the producer's `output_views` slots
    /// this projection reads. Fuel-internal (not on the §6.19 wire). `None` ⇒
    /// not a view node.
    pub view_slot: Option<u32>,

    // --- rank-0 shape-target marker (Increment C, C-T1) ---------------------
    //
    /// Marks an INTENTIONAL rank-0 (`[]`, scalar) target on a shape-target op
    /// (`ReduceSumTo`/`ReduceMaxTo`/`Reshape`/`BroadcastTo`). A rank-0 shape has
    /// ZERO dims, so its `target_shape` is empty — the SAME empty state a
    /// wildcard / non-shape-target node carries — leaving the two
    /// indistinguishable in memory. `true` ⇒ the empty `target_shape` denotes
    /// the concrete rank-0 shape `[]` (a reduce-to-scalar loss tail, e.g. FSCE's
    /// `ReduceSumTo([])`); `false` (the default) ⇒ empty `target_shape` is unset
    /// / a matcher wildcard. Reusable for every future reduce-to-scalar loss.
    ///
    /// **Fuel-INTERNAL, off the §6.19 wire.** The wire already encodes a rank-0
    /// target correctly as a 0-length `target_shape` i64 list
    /// (`put_i64_list(&[])`), so `to_canonical_bytes` needs no new byte — this
    /// marker only disambiguates the in-memory wildcard-vs-rank-0 overload that
    /// the recipe emitter (`fuel_graph::runtime_fused::shape_from_attr`) reads.
    pub rank0_target: bool,

    // --- nested-fused selector (Increment C, C-T2) --------------------------
    //
    /// [`OpTag::Fused`] selector: the stable registry-entry **name** of the
    /// nested fused op a recipe carries as-is (e.g. `"SoftmaxLastDim"` /
    /// `"SoftmaxLastDimBackward"`), mirroring [`Self::cast_dtype`]'s
    /// `DType::as_str` name-string precedent. `fuel-graph`'s
    /// `runtime_fused::tag_to_op` resolves it back to a `FusedOpId` via
    /// `registry::id_for_name` and reconstructs the param-less
    /// `Op::Fused(fid, params)` through a small fid → params map. `None` ⇒ not a
    /// nested-fused node (an honest miss for [`OpTag::Fused`]).
    ///
    /// **Fuel-INTERNAL, off the §6.19 wire.** A `Fused` node serializes to the
    /// empty canonical body (the `_` arm of [`Self::to_canonical_bytes`]), so
    /// this selector never flows to a cross-producer blob — a nested fused node
    /// is a Fuel-side recipe-interior structural token, not a KISS base op.
    pub fused_op: Option<String>,
}

/// Structural REGION IDENTITY of an [`OpAttrs`] — the `Hash + Eq` key baracuda's
/// `region_op_id` uses to bucket kernels (fuel GAP-332 / baracuda #117), replacing a
/// fragile `format!("{:?}")` of the attrs. Injective over every field that reaches the
/// emitted kernel:
///
/// - `scalars` is DELIBERATELY OMITTED — VALUES *and* LENGTH. A scalar-param value becomes
///   a runtime `ScalarExpr::Param` and never reaches the kernel (baracuda #115), so keying
///   the values over-discriminates (one kernel, many ids, a wasted compile per distinct
///   scalar). The scalar ARITY that DOES reach the kernel is `scalar_slot_arity(op)`, a pure
///   function of `OpTag` (fuel-graph `runtime_fused`), which baracuda already hashes per node
///   — so `region_key` need not carry it, and no two same-`OpTag` regions can differ in
///   arity. `scalars.len()` must NOT be keyed either: the SAME op is `scalars: vec![]` as an
///   open slot vs `vec![x]` as a baked snapshot (both become a runtime `Param` in baracuda's
///   emitter — baracuda #115 — hence ONE kernel), so keying the length would split one kernel
///   into open-vs-baked ids (a milder #115). Every OTHER field participates.
/// - Float fields are keyed by their `to_bits` pattern (`pad_value_bits`), so `0.0`/`-0.0`
///   and distinct NaN payloads stay distinct and `Eq` is reflexive — IEEE equality would
///   break both (it merges `±0` and gives `NaN != NaN`); see GAP-048/300. `const_bits` is
///   already a bit pattern.
/// - Every `Option`/count field is carried as-is, so `None` stays DISTINCT from `Some(0)` —
///   the collapse-of-unset-into-zero failure GAP-287 records is not repeated here. (This doc
///   avoids that gap's literal anchor text so the dead-anchor baseline stays honest.)
///
/// Fields are private: this type exists to be a hashable/comparable region id, and building
/// one goes through [`OpAttrs::region_key`], which uses an EXHAUSTIVE destructure (no `..`)
/// so a field added to `OpAttrs` later fails to compile until someone classifies it as part
/// of the region identity or explicitly excludes it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RegionKey {
    axis: Option<i64>,
    perm: Vec<u8>,
    target_shape: Vec<i64>,
    dims: Vec<u8>,
    cast_dtype: Option<String>,
    slice_start: Option<u64>,
    slice_len: Option<u64>,
    roll_shift: Option<i64>,
    pad_amounts: Vec<(u64, u64)>,
    pad_mode: Option<u8>,
    pad_value_bits: Option<u64>,
    keepdim: Option<bool>,
    target_shape_rel: Option<shape_expr::ShapeExpr>,
    slice_start_rel: Option<shape_expr::Dim>,
    slice_len_rel: Option<shape_expr::Dim>,
    axis_last: bool,
    scalar_rel: Option<shape_expr::Dim>,
    lhs_roles: Vec<u8>,
    rhs_roles: Vec<u8>,
    const_bits: Option<u64>,
    slot_index: Option<u32>,
    scan_role: Option<u8>,
    scan_index: Option<u32>,
    scan_n_carries: Option<u32>,
    scan_n_xs: Option<u32>,
    scan_bound: Option<u32>,
    scan_emit: Option<u8>,
    scan_early_exit: Option<bool>,
    view_slot: Option<u32>,
    rank0_target: bool,
    fused_op: Option<String>,
}

impl OpAttrs {
    /// Structural region identity of these attrs — see [`RegionKey`]. Excludes the
    /// scalar-param `scalars` VALUES (runtime `ScalarExpr::Param`), keys floats by `to_bits`,
    /// keeps `None` distinct from `Some(0)`, and is built by an exhaustive destructure so a
    /// new `OpAttrs` field must be classified before this compiles.
    pub fn region_key(&self) -> RegionKey {
        // EXHAUSTIVE destructure (no `..`): a field added to OpAttrs breaks this line until
        // it is classified as part of the region identity or explicitly excluded here.
        let OpAttrs {
            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).
            axis,
            perm,
            target_shape,
            dims,
            cast_dtype,
            slice_start,
            slice_len,
            roll_shift,
            pad_amounts,
            pad_mode,
            pad_value,
            keepdim,
            target_shape_rel,
            slice_start_rel,
            slice_len_rel,
            axis_last,
            scalar_rel,
            lhs_roles,
            rhs_roles,
            const_bits,
            slot_index,
            scan_role,
            scan_index,
            scan_n_carries,
            scan_n_xs,
            scan_bound,
            scan_emit,
            scan_early_exit,
            view_slot,
            rank0_target,
            fused_op,
        } = self;
        RegionKey {
            axis: *axis,
            perm: perm.clone(),
            target_shape: target_shape.clone(),
            dims: dims.clone(),
            cast_dtype: cast_dtype.clone(),
            slice_start: *slice_start,
            slice_len: *slice_len,
            roll_shift: *roll_shift,
            pad_amounts: pad_amounts.clone(),
            pad_mode: *pad_mode,
            // to_bits: keeps 0.0/-0.0 and NaN payloads distinct (Eq-reflexive, cache-safe).
            pad_value_bits: (*pad_value).map(f64::to_bits),
            keepdim: *keepdim,
            target_shape_rel: target_shape_rel.clone(),
            slice_start_rel: slice_start_rel.clone(),
            slice_len_rel: slice_len_rel.clone(),
            axis_last: *axis_last,
            scalar_rel: scalar_rel.clone(),
            lhs_roles: lhs_roles.clone(),
            rhs_roles: rhs_roles.clone(),
            const_bits: *const_bits,
            slot_index: *slot_index,
            scan_role: *scan_role,
            scan_index: *scan_index,
            scan_n_carries: *scan_n_carries,
            scan_n_xs: *scan_n_xs,
            scan_bound: *scan_bound,
            scan_emit: *scan_emit,
            scan_early_exit: *scan_early_exit,
            view_slot: *view_slot,
            rank0_target: *rank0_target,
            fused_op: fused_op.clone(),
        }
    }
}

// --- §6.19-shaped canonical positional-blob serialization (Convergence Increment A) ---
//
/// Derive the canonical matmul role vectors for a same-rank ≥ 2 contraction
/// (the LOCKED reply-3 cell, §5): `lhs = [Batch×(r−2), FreeM, ContractedK]`,
/// `rhs = [Batch×(r−2), ContractedK, FreeN]` over the roles
/// { Batch=0, FreeM=1, FreeN=2, ContractedK=3 }. Roles encode axis POSITIONS,
/// not extents — GQA-divisible batch stays all-`Batch`. Pure + never-panic: a
/// rank < 2 operand (never a real matmul input) yields an all-`Batch` vector of
/// that length, which the resolver's exact-match check rejects as non-canonical.
pub fn matmul_roles(lhs_rank: usize, rhs_rank: usize) -> (Vec<u8>, Vec<u8>) {
    fn one(rank: usize, second_last: u8, last: u8) -> Vec<u8> {
        let mut v = vec![0u8; rank]; // Batch = 0 for every leading axis
        if rank >= 2 {
            v[rank - 2] = second_last;
            v[rank - 1] = last;
        }
        v
    }
    // lhs: [.., FreeM(1), ContractedK(3)]; rhs: [.., ContractedK(3), FreeN(2)].
    (one(lhs_rank, 1, 3), one(rhs_rank, 3, 2))
}

/// A node of the §3 declarative subgraph grammar. One type, two directions: a
/// **region** (Fuel -> synthesizer) populates `Op { op, operands, attrs }` +
/// `Bind`; an emitted **`pattern:`** (synthesizer -> Fuel) additionally carries
/// the consumer/`extract` routing the matcher compiler reads. `SeeThrough`/`Any`
/// are matcher-only and never appear in a concrete region.
#[derive(Clone, Debug, PartialEq)]
// `Op` is ~489 bytes (`OpAttrs` is a wide flat attribute struct); the other
// variants are <=8. Boxing the `Op` payload is the right fix, but it ripples
// across ~150 `PatternNode::Op` construction sites in fuel-graph and
// fuel-dispatch, which are mid-rename — deferred to a post-sweep follow-up.
// `expect` (not `allow`) so this suppression self-reports the day the variant
// is boxed and the lint stops firing.
#[expect(
    clippy::large_enum_variant,
    reason = "Op-payload boxing deferred: ~150 cross-crate construction sites, sequenced after the in-flight rename sweep"
)]
// EXHAUSTIVE-BY-DESIGN: baracuda's region_op_id (baracuda #117) walks this enum
// with an EXHAUSTIVE match to build its kernel region key. Do NOT add
// #[non_exhaustive] — it would force downstream wildcard arms and silently drop a
// new variant from the kernel identity (the GAP-049 failure shape). Enforced by
// tests/exhaustive_by_design.rs in this crate (marker + #[non_exhaustive] is a
// hard test failure naming this enum); it moved here from Fuel's
// fuel-ir/tests/exhaustive_by_design_marker.rs, whose scan can no longer see this type.
pub enum PatternNode {
    /// An op over the [`OpTag`] vocabulary with one child per tensor input
    /// (ordered, exact arity). `attrs` carries the scalar slot / load-bearing
    /// attributes.
    Op {
        op: OpTag,
        operands: Vec<PatternNode>,
        attrs: OpAttrs,
    },
    /// A leaf: bind the producing node as the fused op's `input[index]`. A
    /// repeated `index` is a node-identity guard on a shared input (§3.2);
    /// indices across a region MUST equal `[0, n_inputs)`.
    Bind { index: u8 },
    /// Match the inner node after skipping zero-or-more transparent wrappers
    /// (§3.3). Matcher-only.
    SeeThrough { then: Box<PatternNode> },
    /// Wildcard — matches any single node (§3.4). Matcher-only.
    Any,
}

impl PatternNode {
    /// Collect the distinct `Bind` indices in this tree (a region's external
    /// inputs). Used to validate `bind` indices form `[0, n_inputs)`.
    pub fn bind_indices(&self) -> Vec<u8> {
        let mut out = Vec::new();
        self.collect_binds(&mut out);
        out.sort_unstable();
        out.dedup();
        out
    }

    fn collect_binds(&self, out: &mut Vec<u8>) {
        match self {
            PatternNode::Bind { index } => out.push(*index),
            PatternNode::Op { operands, .. } => {
                for o in operands {
                    o.collect_binds(out);
                }
            }
            PatternNode::SeeThrough { then } => then.collect_binds(out),
            PatternNode::Any => {}
        }
    }
}

// ===========================================================================
// Advisory ULP-band reference cases — the single drift-pinning fixture
// ===========================================================================

/// The shared drift-pinning fixture for the **advisory ULP band** formula
/// (KISS-CONFORM §6.8; kiss-ref tolerance refinement 2026-07-23).
///
/// The band formula is hand-maintained in TWO places that cannot be
/// co-compiled on a CPU build:
///
///   * `fuel_kiss_ref_backend::region_advisory_tolerance` (with
///     `op_ulp_ceiling` / `region_ulp_ceilings`) — the **reference** formula,
///     in an adapter crate pulled only under `fuel-dispatch`'s `cuda` feature;
///     and
///   * `fuel_dispatch::jit_ingest::advisory_ulp_band` — the **live** copy on
///     the ingestion path, which must stay testable under `--features jit`
///     alone (i.e. without the cuda-gated adapter).
///
/// Because those two live in crates gated apart, no single CPU test sees both.
/// This table is the shared source of truth each side is pinned to: every
/// `(region, expected)` pair here is asserted from BOTH sides (the adapter's
/// `region.rs` tests and fuel-dispatch's `jit_ingest.rs` tests), so a drift in
/// either formula fails that side's build. It is homed in this dependency-free
/// grammar crate — the one both already depend on — precisely because it is the
/// only place visible to both without touching the cuda gating.
///
/// `expected` is the NORMALIZED band the live consumer applies:
/// `None` ⇒ compare `Tolerance::Exact` (an op-free region *or* a single exact
/// op — both drive an exact comparison), `Some(n)` ⇒ `Tolerance::Ulp(n)`. The
/// adapter's richer `Option<Tolerance>` collapses `None` (op-free) and
/// `Some(Exact)` (single exact op) onto `None` here, matching
/// `advisory_ulp_band`'s native `Option<u64>` shape.
///
/// Baked-in ceilings mirror the two formulas' shared rule: transcendental ops
/// contribute their kiss §6.8 ceiling (Exp/Erf declare 4; kiss non-primitives
/// Tanh/Sigmoid/Silu/GeluTanh/Rsqrt fall back to 4); IEEE-correctly-rounded
/// Sqrt/Recip are exact-class (no ceiling); an exact-only region of `n` ops
/// bands at `n - 1`; a transcendental region bands at `Σ ceilings +
/// (n_exact - 1)` with the exact term saturating at 0.
pub fn advisory_band_reference_cases() -> Vec<(PatternNode, Option<u64>)> {
    fn bind(i: u8) -> PatternNode {
        PatternNode::Bind { index: i }
    }
    fn op(op: OpTag, operands: Vec<PatternNode>) -> PatternNode {
        PatternNode::Op {
            op,
            operands,
            attrs: OpAttrs::default(),
        }
    }
    vec![
        // Op-free region: nothing to band -> exact comparison.
        (bind(0), None),
        // Single exact op -> exact comparison.
        (op(OpTag::Add, vec![bind(0), bind(1)]), None),
        // Multi-node exact-only region -> Ulp(n_ops - 1).
        (
            op(OpTag::Relu, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
            Some(1),
        ),
        // Deeper exact-only region (3 ops) -> Ulp(3 - 1).
        (
            op(
                OpTag::Relu,
                vec![op(
                    OpTag::Relu,
                    vec![op(OpTag::Add, vec![bind(0), bind(1)])],
                )],
            ),
            Some(2),
        ),
        // Sqrt is IEEE-correctly-rounded -> exact class; sqrt(a+b) = 2 exact ops.
        (
            op(OpTag::Sqrt, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
            Some(1),
        ),
        // Lone transcendental keeps exactly its own ceiling (Exp declares 4).
        (op(OpTag::Exp, vec![bind(0)]), Some(4)),
        // Transcendental + one exact: 4 + (1 - 1) = 4.
        (
            op(OpTag::Exp, vec![op(OpTag::Add, vec![bind(0), bind(1)])]),
            Some(4),
        ),
        // Two transcendentals (Exp 4, Tanh fallback 4) + one exact: 8 + 0 = 8.
        (
            op(
                OpTag::Tanh,
                vec![op(OpTag::Add, vec![op(OpTag::Exp, vec![bind(0)]), bind(1)])],
            ),
            Some(8),
        ),
        // All-transcendental exp(tanh(x)): 4 + 4, exact term saturates at 0.
        (
            op(OpTag::Exp, vec![op(OpTag::Tanh, vec![bind(0)])]),
            Some(8),
        ),
        // Silu (kiss non-primitive fallback 4) over add(a, exp(b)): 4 + 4 + 0.
        (
            op(
                OpTag::Silu,
                vec![op(OpTag::Add, vec![bind(0), op(OpTag::Exp, vec![bind(1)])])],
            ),
            Some(8),
        ),
    ]
}

// ---- GAP-332: OpAttrs::region_key() -> RegionKey (baracuda #117) ------------
//
// region_key() is the Hash+Eq structural region identity baracuda's `region_op_id`
// buckets kernels by. These tests pin its three contracts: (a) every kernel-relevant
// field participates (per-field perturbation — ALSO the standing sabotage sibling:
// drop a field from the key and exactly that field's assert_ne! reddens); (b) the
// scalar-param VALUES are excluded (regions differing only in scalars reuse one kernel
// bucket — baracuda #115); (c) floats key by `to_bits` and `None` stays distinct from
// `Some(0)` (GAP-048/300, GAP-287).
#[cfg(test)]
mod region_key_tests {
    use super::*;
    use crate::shape_expr::{Dim, ShapeExpr};

    #[test]
    fn every_included_field_changes_the_key() {
        // Perturb each INCLUDED field off default and require the key to move. If
        // region_key() stopped carrying a field, ONLY that field's assert_ne! would
        // fail — this is the standing sabotage sibling for the born-red.
        let base = OpAttrs::default().region_key();
        macro_rules! moves {
            ($field:ident = $val:expr) => {{
                let a = OpAttrs {
                    $field: $val,
                    ..Default::default()
                };
                assert_ne!(
                    a.region_key(),
                    base,
                    concat!("region_key() ignores field `", stringify!($field), "`")
                );
            }};
        }
        moves!(axis = Some(3));
        moves!(perm = vec![1u8, 0]);
        moves!(target_shape = vec![2i64, 3]);
        moves!(dims = vec![1u8]);
        moves!(cast_dtype = Some("f32".to_string()));
        moves!(slice_start = Some(5));
        moves!(slice_len = Some(7));
        moves!(roll_shift = Some(-1));
        moves!(pad_amounts = vec![(1u64, 2u64)]);
        moves!(pad_mode = Some(1u8));
        moves!(pad_value = Some(1.5));
        moves!(keepdim = Some(true));
        moves!(target_shape_rel = Some(ShapeExpr::SameAs { operand: 0 }));
        moves!(slice_start_rel = Some(Dim::Const(1)));
        moves!(slice_len_rel = Some(Dim::Const(1)));
        moves!(axis_last = true);
        moves!(scalar_rel = Some(Dim::Const(1)));
        moves!(lhs_roles = vec![1u8]);
        moves!(rhs_roles = vec![2u8]);
        moves!(const_bits = Some(42u64));
        moves!(slot_index = Some(1u32));
        moves!(scan_role = Some(1u8));
        moves!(scan_index = Some(1u32));
        moves!(scan_n_carries = Some(1u32));
        moves!(scan_n_xs = Some(1u32));
        moves!(scan_bound = Some(1u32));
        moves!(scan_emit = Some(1u8));
        moves!(scan_early_exit = Some(true));
        moves!(view_slot = Some(1u32));
        moves!(rank0_target = true);
        moves!(fused_op = Some("SoftmaxLastDim".to_string()));
    }

    #[test]
    fn scalars_length_and_values_are_excluded_from_the_key() {
        // The key must ignore `scalars` ENTIRELY — both VALUES and LENGTH.
        // VALUES: a scalar-param value becomes a runtime ScalarExpr::Param and never
        // reaches the kernel (baracuda #115), so keying values over-discriminates.
        // LENGTH: the kernel's scalar ARITY is `scalar_slot_arity(op)`, a pure function
        // of OpTag (fuel-graph runtime_fused.rs:589-591), which baracuda already hashes
        // per node — and the SAME op is `scalars: vec![]` as an open slot vs `vec![x]` as
        // a baked snapshot (count_scalar_slots, runtime_fused.rs:916, treats the empty one
        // as a slot; both become a runtime Param in baracuda's emitter, so ONE kernel), so
        // keying `scalars.len()` would split one kernel into open-vs-baked ids (a milder
        // #115). So every length AND value maps to one key. (This reddens if a future edit
        // adds scalars or scalars.len() to RegionKey.)
        let base = OpAttrs::default().region_key(); // scalars: vec![] (len 0)
        for scalars in [
            vec![],
            vec![0.0],
            vec![9.0],
            vec![1.0, 2.0],
            vec![-0.0, f64::NAN, 3.5],
        ] {
            let a = OpAttrs {
                scalars,
                ..Default::default()
            };
            assert_eq!(
                a.region_key(),
                base,
                "scalars length and values must not affect the region key (baracuda #115; \
                 arity is scalar_slot_arity(op), a function of OpTag)"
            );
        }
    }

    #[test]
    fn none_stays_distinct_from_some_zero() {
        // GAP-287: unset must never collapse into zero.
        let none = OpAttrs::default().region_key();
        let a = OpAttrs {
            slice_start: Some(0),
            ..Default::default()
        };
        assert_ne!(a.region_key(), none, "slice_start None vs Some(0)");
        let b = OpAttrs {
            pad_value: Some(0.0),
            ..Default::default()
        };
        assert_ne!(b.region_key(), none, "pad_value None vs Some(0.0)");
        let c = OpAttrs {
            const_bits: Some(0),
            ..Default::default()
        };
        assert_ne!(c.region_key(), none, "const_bits None vs Some(0)");
    }

    #[test]
    fn floats_key_by_to_bits() {
        let mk = |v: f64| {
            OpAttrs {
                pad_value: Some(v),
                ..Default::default()
            }
            .region_key()
        };
        // IEEE `==` merges these / breaks reflexivity; `to_bits` does neither.
        assert_ne!(mk(0.0), mk(-0.0), "pad_value +0.0 vs -0.0 stay distinct");
        let nan_a = f64::from_bits(0x7ff8_0000_0000_0001);
        let nan_b = f64::from_bits(0x7ff8_0000_0000_0002);
        assert!(nan_a.is_nan() && nan_b.is_nan());
        assert_ne!(mk(nan_a), mk(nan_b), "distinct NaN payloads stay distinct");
        assert_eq!(
            mk(f64::NAN),
            mk(f64::NAN),
            "same NaN bits => equal keys (Eq reflexive)"
        );
    }

    #[test]
    fn key_buckets_kernels_by_region_ignoring_scalars() {
        // The end-to-end purpose (baracuda #117): a Hash+Eq map keyed by region_key
        // reuses one kernel across regions differing only in scalar VALUES, and
        // separates regions that differ structurally.
        use std::collections::HashMap;
        let mut m: HashMap<RegionKey, &str> = HashMap::new();
        let add = OpAttrs::default(); // e.g. an AddScalar region
        // structurally different region
        let other = OpAttrs {
            axis: Some(1),
            ..Default::default()
        };
        m.insert(add.region_key(), "kernel_add");
        m.insert(other.region_key(), "kernel_other");
        assert_eq!(
            m.len(),
            2,
            "structurally distinct regions => distinct kernels"
        );
        // Same region, different scalar value => same kernel bucket.
        let add_val_9 = OpAttrs {
            scalars: vec![9.0],
            ..Default::default()
        };
        assert_eq!(
            m.get(&add_val_9.region_key()),
            Some(&"kernel_add"),
            "differing scalar values reuse the same kernel (no wasted compile)"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pattern_node_region_for_relu_a_plus_b() {
        // relu(a + b) — a 1-output region over 2 inputs.
        let region = PatternNode::Op {
            op: OpTag::Relu,
            attrs: OpAttrs::default(),
            operands: vec![PatternNode::Op {
                op: OpTag::Add,
                attrs: OpAttrs::default(),
                operands: vec![
                    PatternNode::Bind { index: 0 },
                    PatternNode::Bind { index: 1 },
                ],
            }],
        };
        assert_eq!(region.bind_indices(), vec![0, 1]);
    }

    #[test]
    fn shared_input_node_identity_guard() {
        // mul(x, x) — repeated bind: 0 is the shared-input node-identity guard.
        let region = PatternNode::Op {
            op: OpTag::Mul,
            attrs: OpAttrs::default(),
            operands: vec![
                PatternNode::Bind { index: 0 },
                PatternNode::Bind { index: 0 },
            ],
        };
        assert_eq!(region.bind_indices(), vec![0]);
    }

    // ---- Task 7: §6.19 canonical positional-blob serialization --------------

    #[test]
    fn empty_schema_op_serializes_zero_length() {
        // Add carries no attrs → one canonical byte form: u32 LE length 0.
        assert_eq!(
            OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap(),
            vec![0, 0, 0, 0]
        );
        assert_eq!(
            OpAttrs::default()
                .to_canonical_bytes(OpTag::MatMul)
                .unwrap(),
            vec![0, 0, 0, 0]
        );
    }

    #[test]
    fn slice_serializes_positionally() {
        // Slice schema (positional): axis(u32), start(u64), len(u64) — see kernel-seam-interop.md.
        let a = OpAttrs {
            axis: Some(1),
            slice_start: Some(2),
            slice_len: Some(3),
            ..OpAttrs::default()
        };
        let mut expect = Vec::new();
        let body = {
            let mut b = Vec::new();
            b.extend_from_slice(&1u32.to_le_bytes());
            b.extend_from_slice(&2u64.to_le_bytes());
            b.extend_from_slice(&3u64.to_le_bytes());
            b
        };
        expect.extend_from_slice(&(body.len() as u32).to_le_bytes());
        expect.extend_from_slice(&body);
        assert_eq!(a.to_canonical_bytes(OpTag::Slice).unwrap(), expect);
    }

    #[test]
    fn cast_serializes_dtype_name_length_prefixed() {
        let a = OpAttrs {
            cast_dtype: Some("f16".into()),
            ..OpAttrs::default()
        };
        let mut body = Vec::new();
        body.extend_from_slice(&(3u32.to_le_bytes())); // name length
        body.extend_from_slice(b"f16");
        let mut expect = (body.len() as u32).to_le_bytes().to_vec();
        expect.extend_from_slice(&body);
        assert_eq!(a.to_canonical_bytes(OpTag::Cast).unwrap(), expect);
    }

    #[test]
    fn canonical_bytes_are_deterministic() {
        let a = OpAttrs {
            target_shape: vec![2, 3],
            ..OpAttrs::default()
        };
        assert_eq!(
            a.to_canonical_bytes(OpTag::Reshape).unwrap(),
            a.to_canonical_bytes(OpTag::Reshape).unwrap()
        );
    }

    // ---- Per-carrier width conformance (KISS coordinator pin, vs KISS main c9153b2) --
    //
    // There are THREE coexisting op_attrs / shape-expr framings. Widths are pinned
    // PER-CARRIER, never as "the op_attrs width" — a future consolidation must NOT
    // silently unify them (KISS #67 do-not-unify):
    //   (a) #67 NODE-ENVELOPE op_attrs        → u32-LE OUTER byte length, payload
    //       verbatim, no-parse-inside (KISS-OPS-6.19-0010). Live producer:
    //       `OpAttrs::to_canonical_bytes`.
    //   (b) KISS-Grammar §6.8-0007 REGION-NODE-TABLE op_attrs SUB-BLOCK → u16-LE
    //       length + payload verbatim; EMPTY = 0x0000. A DIFFERENT carrier from (a).
    //       Fuel ships NO producer yet (node/table wire serializer is #67-gated,
    //       slice 4); this pin binds that future serializer to u16-LE here.
    //   (c) §6.20-0005 SHAPE-EXPR binary-node CHILD length → u16-LE. Live producer:
    //       `shape_expr::Dim::encode`.
    #[test]
    fn three_carrier_width_pins_stay_distinct() {
        use crate::shape_expr::{Dim, LAST};

        // Carrier (a): node-envelope op_attrs — outer prefix is EXACTLY 4 bytes
        // (u32-LE); an empty schema is the 4-byte zero form.
        let empty = OpAttrs::default().to_canonical_bytes(OpTag::Add).unwrap();
        assert_eq!(
            empty,
            vec![0u8, 0, 0, 0],
            "carrier (a): empty node-envelope op_attrs = u32-LE zero (4 bytes)"
        );
        let sliced = OpAttrs {
            axis: Some(1),
            slice_start: Some(2),
            slice_len: Some(3),
            ..OpAttrs::default()
        };
        let blob = sliced.to_canonical_bytes(OpTag::Slice).unwrap();
        let a_body_len = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]) as usize;
        assert_eq!(
            blob.len(),
            4 + a_body_len,
            "carrier (a): outer length prefix is u32-LE (4 bytes), body verbatim"
        );

        // Carrier (b): region-node-table op_attrs sub-block — u16-LE length +
        // verbatim payload; empty = 0x0000. Modeled here (no Fuel producer yet) so
        // the width pin is executable and NAMED before the slice-4 serializer lands.
        fn region_node_table_op_attrs_sub_block(payload: &[u8]) -> Vec<u8> {
            let mut out = (payload.len() as u16).to_le_bytes().to_vec();
            out.extend_from_slice(payload); // verbatim, no-parse-inside
            out
        }
        assert_eq!(
            region_node_table_op_attrs_sub_block(&[]),
            vec![0x00, 0x00],
            "carrier (b): EMPTY region-node-table op_attrs sub-block = 0x0000 (u16-LE, 2 bytes)"
        );
        assert_eq!(
            region_node_table_op_attrs_sub_block(&[0xAB, 0xCD]),
            vec![0x02, 0x00, 0xAB, 0xCD],
            "carrier (b): sub-block length prefix is u16-LE (2 bytes), payload verbatim"
        );

        // Carrier (c): shape-expr binary-node child length — u16-LE (2 bytes),
        // inside Dim::{Add,Sub,Mul,Div}. The rope-half golden's child prefixes:
        // tag(0x08) ++ u16-LE(3) ++ Extent(3B) ++ u16-LE(9) ++ Const(9B).
        let half = Dim::Div(
            Box::new(Dim::Extent {
                operand: 0,
                axis: LAST,
            }),
            Box::new(Dim::Const(2)),
        );
        let bytes = half.encode();
        assert_eq!(
            [bytes[1], bytes[2]],
            3u16.to_le_bytes(),
            "carrier (c): first child length prefix is u16-LE (2 bytes)"
        );
        assert_eq!(
            [bytes[6], bytes[7]],
            9u16.to_le_bytes(),
            "carrier (c): second child length prefix is u16-LE (2 bytes)"
        );
        assert_eq!(
            bytes.len(),
            1 + 2 + 3 + 2 + 9,
            "carrier (c): whole rope-half blob accounted for"
        );

        // Pinned widths, side by side — (a)=4 (u32-LE) vs (b)=2 (u16-LE) vs
        // (c)=2 (u16-LE). (b) and (c) sharing a width is coincidence, not unity:
        // each is pinned by its OWN carrier name above.
    }

    // ---- T2 (Increment C slice 1): shape-relative interior fields stay OFF
    // the §6.19 wire ------------------------------------------------------
    //
    // D2 pin (KISS #67-gated): `target_shape_rel` / `slice_start_rel` /
    // `slice_len_rel` / `axis_last` are IN-MEMORY recipe data, resolved to the
    // concrete fields at emit time. The pinned §6.19 arms for
    // `broadcast_to`/`slice` are ABSOLUTE (`put_i64_list(target_shape)`,
    // `u32(axis) ++ u64(start) ++ u64(len)`), and the node-envelope framing
    // that could carry a relative alternative is being defined in KISS #67 —
    // serializing a rel form now would unilaterally extend a shared byte
    // contract (propose-first says no). This test pins the ABSENCE: the wire
    // bytes are identical with and without every rel field set, for every
    // schema family the rel fields could plausibly leak into.
    #[test]
    fn rel_attr_fields_are_absent_from_the_6_19_wire() {
        use crate::shape_expr::{Dim, LAST, ShapeExpr};
        let half = Dim::Div(
            Box::new(Dim::Extent {
                operand: 0,
                axis: LAST,
            }),
            Box::new(Dim::Const(2)),
        );
        let rel_only = OpAttrs {
            target_shape_rel: Some(ShapeExpr::SameAs { operand: 0 }),
            slice_start_rel: Some(half.clone()),
            slice_len_rel: Some(half),
            axis_last: true,
            scalar_rel: Some(Dim::Extent {
                operand: 0,
                axis: LAST,
            }),
            ..OpAttrs::default()
        };
        // Shape-target arm (BroadcastTo/Reshape): rel-only attrs serialize
        // byte-identically to fully-default attrs (an unset target_shape).
        assert_eq!(
            rel_only.to_canonical_bytes(OpTag::BroadcastTo).unwrap(),
            OpAttrs::default()
                .to_canonical_bytes(OpTag::BroadcastTo)
                .unwrap(),
            "target_shape_rel must not reach the broadcast_to wire arm"
        );
        // Slice arm: the ABSOLUTE fields serialize; adding every rel field on
        // top changes NOTHING.
        let abs = OpAttrs {
            axis: Some(1),
            slice_start: Some(2),
            slice_len: Some(3),
            ..OpAttrs::default()
        };
        let abs_plus_rel = OpAttrs {
            axis: Some(1),
            slice_start: Some(2),
            slice_len: Some(3),
            ..rel_only.clone()
        };
        assert_eq!(
            abs_plus_rel.to_canonical_bytes(OpTag::Slice).unwrap(),
            abs.to_canonical_bytes(OpTag::Slice).unwrap(),
            "slice_{{start,len}}_rel must not reach the slice wire arm"
        );
        // Reduce row (axis ++ keepdim): axis_last must not leak.
        let sd = OpAttrs {
            axis: Some(1),
            ..OpAttrs::default()
        };
        let sd_plus_rel = OpAttrs {
            axis: Some(1),
            ..rel_only.clone()
        };
        assert_eq!(
            sd_plus_rel.to_canonical_bytes(OpTag::SumDim).unwrap(),
            sd.to_canonical_bytes(OpTag::SumDim).unwrap(),
            "axis_last must not reach the reduce wire row"
        );
        // Scalar-param arm (AddScalar/MulScalar): a `scalar_rel` DimExpr with an
        // empty `scalars` list serializes byte-identically to a default (the
        // wire arm emits only `scalars`), so the reduced_count rel carrier never
        // leaks onto the §6.19 wire.
        assert_eq!(
            rel_only.to_canonical_bytes(OpTag::MulScalar).unwrap(),
            OpAttrs::default()
                .to_canonical_bytes(OpTag::MulScalar)
                .unwrap(),
            "scalar_rel must not reach the mul_scalar wire arm"
        );
        // Empty-schema op: stays the single canonical 4-byte zero form even
        // with every rel field set.
        assert_eq!(
            rel_only.to_canonical_bytes(OpTag::Add).unwrap(),
            vec![0, 0, 0, 0]
        );
    }

    // ---- C-T2 (Increment C): OpTag::Fused is a Fuel-internal structural token,
    // OFF the §6.19 wire ----------------------------------------------------
    //
    // A nested fused node (the attention-trio decompose's inner softmax) is
    // Fuel-side recipe interior, NOT a KISS base op: it must never flow to a
    // cross-producer blob. Like the `scan_*`/`view_slot` fields, `OpTag::Fused`
    // hits the empty-body `_` arm of `to_canonical_bytes`, and its `fused_op`
    // selector serializes NOTHING.
    #[test]
    fn fused_nested_op_is_absent_from_the_6_19_wire() {
        let fused = OpAttrs {
            fused_op: Some("SoftmaxLastDim".into()),
            ..OpAttrs::default()
        };
        // The Fused tag serializes to the single canonical 4-byte zero body —
        // byte-identical to a fully-default attrs blob (the selector is off-wire).
        assert_eq!(
            fused.to_canonical_bytes(OpTag::Fused).unwrap(),
            vec![0, 0, 0, 0],
            "OpTag::Fused must serialize to the empty canonical body"
        );
        assert_eq!(
            fused.to_canonical_bytes(OpTag::Fused).unwrap(),
            OpAttrs::default().to_canonical_bytes(OpTag::Fused).unwrap(),
            "the fused_op selector must not reach any wire arm"
        );
        // The selector also must not leak into any OTHER schema arm it could
        // plausibly ride alongside (it shares no field with a real op).
        assert_eq!(
            fused.to_canonical_bytes(OpTag::Add).unwrap(),
            vec![0, 0, 0, 0],
            "fused_op must not leak into an empty-schema arm"
        );
    }

    // ---- T4 (Increment C slice 1): additive OpTag::MaxDim -----------------

    #[test]
    fn max_dim_serializes_the_reduce_row() {
        // `OpTag::MaxDim` joins the pinned §6.19 reduce row — carrier (a), the
        // node-envelope op_attrs blob (u32-LE outer): body = i64(axis) ++
        // u8(keepdim). The monoid rides `op_name` (distinct SumDim/MaxDim/
        // MinDim tags — see the module comment's reduce-schema note), so the
        // blob is IDENTICAL in shape to SumDim's. Golden for axis=1, keepdim
        // unset (=0): u32-LE(9) ++ i64-LE(1) ++ 0x00.
        let a = OpAttrs {
            axis: Some(1),
            ..OpAttrs::default()
        };
        let mut expect = 9u32.to_le_bytes().to_vec();
        expect.extend_from_slice(&1i64.to_le_bytes());
        expect.push(0u8);
        assert_eq!(a.to_canonical_bytes(OpTag::MaxDim).unwrap(), expect);
        // Row-shape identity: byte-identical to the SumDim row for the same
        // attrs (the tag disambiguates via op_name, never via the blob).
        assert_eq!(
            a.to_canonical_bytes(OpTag::MaxDim).unwrap(),
            a.to_canonical_bytes(OpTag::SumDim).unwrap(),
            "MaxDim must share the SumDim reduce-row schema"
        );
    }

    // ---- T9 (Increment C slice 1): matmul role-vector serialize + derive -----
    //
    // The LOCKED reply-3 layout (commit `b64aa1db`; §5 of the recipe-grammar
    // design input): matmul's op_attrs = two per-axis role vectors over
    // { Batch=0, FreeM=1, FreeN=2, ContractedK=3 } (one u8 per axis), `lhs_roles`
    // then `rhs_roles`, each length = operand rank —
    //   body = u32_le(len lhs) ++ lhs_roles ++ u32_le(len rhs) ++ rhs_roles
    // wrapped by carrier (a)'s outer u32_le(body_len) frame. Role vectors encode
    // WHICH axis plays which role, not extents, so GQA (differing-but-divisible
    // batch extents) serializes to identical all-Batch leading roles.

    #[test]
    fn matmul_role_vectors_serialize_the_locked_rank2_golden() {
        // Worked rank-2 example: lhs=[FreeM,ContractedK]=[1,3], rhs=[ContractedK,FreeN]=[3,2].
        //   body = 02000000 | 0103 | 02000000 | 0302   (12 bytes)
        //   full = 0C000000 | body                       (16 bytes)
        //
        // INJECTED (B9): this golden is ALSO the shared CROSS-PRODUCER contract —
        // Baracuda (#68) confirmed the exact bytes and has NO near-term binary
        // arm, so Fuel's serializer is first and this golden IS the contract.
        let a = OpAttrs {
            lhs_roles: vec![1, 3],
            rhs_roles: vec![3, 2],
            ..OpAttrs::default()
        };
        let golden: Vec<u8> = vec![
            0x0C, 0x00, 0x00, 0x00, // outer u32-LE body length = 12
            0x02, 0x00, 0x00, 0x00, // u32-LE len lhs_roles = 2
            0x01, 0x03, //             lhs_roles = [FreeM, ContractedK]
            0x02, 0x00, 0x00, 0x00, // u32-LE len rhs_roles = 2
            0x03, 0x02, //             rhs_roles = [ContractedK, FreeN]
        ];
        assert_eq!(
            a.to_canonical_bytes(OpTag::MatMul).unwrap(),
            golden,
            "the rank-2 matmul role-vector golden is the shared cross-producer contract (Baracuda #68)"
        );
    }

    #[test]
    fn matmul_empty_roles_stay_the_canonical_zero_body() {
        // Empty roles = the rank-polymorphic recipe form: the body is empty → the
        // single canonical 4-byte zero form. This preserves today's golden
        // (`empty_schema_op_serializes_zero_length`) untouched.
        assert_eq!(
            OpAttrs::default()
                .to_canonical_bytes(OpTag::MatMul)
                .unwrap(),
            vec![0, 0, 0, 0]
        );
    }

    #[test]
    fn matmul_roles_derives_the_canonical_cell() {
        // matmul_roles(lhs_rank, rhs_rank): lhs = [Batch.., FreeM(1), ContractedK(3)];
        // rhs = [Batch.., ContractedK(3), FreeN(2)]. Role POSITIONS, not extents.
        assert_eq!(matmul_roles(2, 2), (vec![1u8, 3], vec![3u8, 2]));
        assert_eq!(matmul_roles(4, 4), (vec![0u8, 0, 1, 3], vec![0u8, 0, 3, 2]));
    }

    // ---- advisory-band drift fixture ----------------------------------------

    #[test]
    fn advisory_band_reference_cases_are_well_formed() {
        // The shared fixture both band impls pin against: non-empty, valid
        // bind spaces, and it exercises every branch of the formula (op-free,
        // single-exact, multi-exact, and transcendental). The VALUES are
        // asserted from the two formula sides (adapter + fuel-dispatch); here
        // we only guard the fixture's own structure so a malformed region can
        // never silently weaken both sides at once.
        let cases = advisory_band_reference_cases();
        assert!(
            cases.len() >= 8,
            "fixture should cover the formula's branches"
        );
        for (region, _expected) in &cases {
            let binds = region.bind_indices();
            if let PatternNode::Op { .. } = region {
                // Every op region here is closed over a contiguous [0, n) bind
                // space (the fixtures are concrete recipe regions).
                for (i, b) in binds.iter().enumerate() {
                    assert_eq!(*b as usize, i, "bind indices must be [0, n)");
                }
            }
        }
        // Branch coverage: at least one op-free (expected None), one exact
        // multi-op (Some), and one transcendental band value present.
        assert!(
            cases
                .iter()
                .any(|(r, e)| matches!(r, PatternNode::Bind { .. }) && e.is_none())
        );
        assert!(cases.iter().any(|(_, e)| *e == Some(1)));
        assert!(cases.iter().any(|(_, e)| *e == Some(4)));
        assert!(cases.iter().any(|(_, e)| *e == Some(8)));
    }

    // ---- L2: the four ACKED source-op LEAF byte arms ------------------------
    //
    // KISS ruling record "four-leaf-arm ack (2026-07-23)" (KISS issue-comment
    // 5061571967, acking Fuel's proposal 5060303085): the editor acked all four
    // arms clean, no amendments —
    //   runtime_scalar    → u32(slot_index)
    //   reduced_count     → i64(axis)                (fold-lockstep, §6.12-0001)
    //   const             → u64(bits)                (MBZ narrow-dtype rule)
    //   scan_placeholder  → u8(role: 0=carry,1=elem) ++ u32(index)
    // Every body rides CARRIER (a) — the #67 node-envelope op_attrs blob, u32-LE
    // outer length, payload verbatim (KISS-OPS-6.19-0010). NOT carrier (b) (KISS-Grammar
    // §6.8-0007 region-table, u16-LE) and NOT carrier (c) (§6.20-0005 shape-expr
    // child, u16-LE); see `three_carrier_width_pins_stay_distinct`.

    #[test]
    fn runtime_scalar_leaf_serializes_the_slot_index() {
        // Acked arm: body = u32_le(slot_index). A dispatch-bound scalar is a
        // DISTINCT leaf from a baked `const` (an unfilled slot and a baked value
        // are not interchangeable) — hence a separate tag, not a `const` with a
        // sentinel. Golden for slot 7: u32-LE(4) ++ u32-LE(7).
        let a = OpAttrs {
            slot_index: Some(7),
            ..OpAttrs::default()
        };
        let golden: Vec<u8> = vec![
            0x04, 0x00, 0x00, 0x00, // outer u32-LE body length = 4
            0x07, 0x00, 0x00, 0x00, // u32-LE slot_index = 7
        ];
        assert_eq!(a.to_canonical_bytes(OpTag::RuntimeScalar).unwrap(), golden);
        // Slot 0 is a real slot, not "unset": still the 4-byte body.
        assert_eq!(
            OpAttrs {
                slot_index: Some(0),
                ..OpAttrs::default()
            }
            .to_canonical_bytes(OpTag::RuntimeScalar)
            .unwrap(),
            vec![0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
        );
    }

    #[test]
    fn reduced_count_leaf_serializes_the_fold_axis() {
        // Acked arm: body = i64_le(axis) — single-axis, byte-identical to the
        // fold node's axis field MINUS keepdim, so the resolver reuses the fold's
        // axis-resolution codepath verbatim. Growth to a `reduce_axes` LIST
        // happens ONLY in lockstep with the fold (§6.12-0001).
        let a = OpAttrs {
            axis: Some(1),
            ..OpAttrs::default()
        };
        let mut golden = 8u32.to_le_bytes().to_vec();
        golden.extend_from_slice(&1i64.to_le_bytes());
        assert_eq!(a.to_canonical_bytes(OpTag::ReducedCount).unwrap(), golden);

        // Fold-lockstep pin: the reduced_count body IS the reduce row's leading
        // i64(axis), with the reduce row's trailing u8(keepdim) absent.
        let fold = a.to_canonical_bytes(OpTag::SumDim).unwrap();
        let rc = a.to_canonical_bytes(OpTag::ReducedCount).unwrap();
        assert_eq!(
            rc[4..],
            fold[4..12],
            "reduced_count body = the fold's i64(axis) verbatim"
        );
        assert_eq!(
            fold.len(),
            rc.len() + 1,
            "the fold row carries exactly one extra byte (keepdim)"
        );

        // A negative axis (the i64 carrier is signed, like the fold's) round-trips
        // its two's-complement bytes.
        let neg = OpAttrs {
            axis: Some(-1),
            ..OpAttrs::default()
        };
        let mut expect = 8u32.to_le_bytes().to_vec();
        expect.extend_from_slice(&(-1i64).to_le_bytes());
        assert_eq!(neg.to_canonical_bytes(OpTag::ReducedCount).unwrap(), expect);
    }

    #[test]
    fn const_leaf_serializes_bits_with_the_mbz_narrow_dtype_rule() {
        // Acked arm: body = u64_le(bits) — a DTYPE-AGNOSTIC bit pattern (the
        // structural DAG is dtype-agnostic, Q7). MBZ narrow-dtype rule: the
        // STORAGE bit pattern of the const's dtype occupies the LOW-order bits,
        // upper bits ZERO (must-be-zero on read).

        // f64 — the full-width case, every bit load-bearing.
        let f64_15 = OpAttrs {
            const_bits: Some(1.5f64.to_bits()),
            ..OpAttrs::default()
        };
        let mut golden = 8u32.to_le_bytes().to_vec();
        golden.extend_from_slice(&0x3FF8_0000_0000_0000u64.to_le_bytes());
        assert_eq!(f64_15.to_canonical_bytes(OpTag::Const).unwrap(), golden);

        // f32 — 32 storage bits low-order, upper 32 ZERO.
        let f32_15 = OpAttrs {
            const_bits: Some(const_bits_narrow(1.5f32.to_bits() as u64, 32)),
            ..OpAttrs::default()
        };
        let blob = f32_15.to_canonical_bytes(OpTag::Const).unwrap();
        assert_eq!(
            blob,
            vec![
                0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00
            ],
            "f32 1.5 = 0x3FC00000 in the LOW-order bits; upper 4 bytes MBZ"
        );

        // f16 (1.5 = 0x3E00) and bf16 (1.5 = 0x3FC0) — 16 storage bits low-order,
        // upper 48 ZERO.
        let f16_15 = OpAttrs {
            const_bits: Some(const_bits_narrow(0x3E00, 16)),
            ..OpAttrs::default()
        };
        assert_eq!(
            f16_15.to_canonical_bytes(OpTag::Const).unwrap(),
            vec![
                0x08, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            ],
        );
        let bf16_15 = OpAttrs {
            const_bits: Some(const_bits_narrow(0x3FC0, 16)),
            ..OpAttrs::default()
        };
        assert_eq!(
            bf16_15.to_canonical_bytes(OpTag::Const).unwrap(),
            vec![
                0x08, 0x00, 0x00, 0x00, 0xC0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            ],
        );

        // The MBZ widener is the producer-side guarantee: it MASKS, never panics
        // (a width of 0 or ≥ 64 is well-defined, no shift overflow).
        assert_eq!(
            const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 16),
            0x0000_0000_0000_FFFF
        );
        assert_eq!(
            const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 32),
            0x0000_0000_FFFF_FFFF
        );
        assert_eq!(
            const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 64),
            0xFFFF_FFFF_FFFF_FFFF
        );
        assert_eq!(
            const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 200),
            0xFFFF_FFFF_FFFF_FFFF
        );
        assert_eq!(const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, 0), 0);
        // Every narrow width leaves the upper bits zero — the MBZ invariant.
        for w in [1u32, 8, 16, 32, 63] {
            let bits = const_bits_narrow(0xFFFF_FFFF_FFFF_FFFF, w);
            assert_eq!(bits >> w, 0, "width {w}: upper bits must be zero");
        }
    }

    #[test]
    fn const_leaf_carries_a_nan_payload_verbatim() {
        // "NaN payload = stored bits verbatim" — the serializer must NOT
        // canonicalize a NaN to a quiet default. NOTE: carrier (a) has no
        // production DECODER (forward-serialization only — see the M-3 note on
        // `to_canonical_bytes`), so the read-back below is an in-test byte read,
        // not a claim that a decoder exists.
        const F32_NAN_PAYLOAD: u32 = 0x7FC0_DEAD;
        assert!(
            f32::from_bits(F32_NAN_PAYLOAD).is_nan(),
            "fixture must be a NaN"
        );
        let a = OpAttrs {
            const_bits: Some(const_bits_narrow(F32_NAN_PAYLOAD as u64, 32)),
            ..OpAttrs::default()
        };
        let blob = a.to_canonical_bytes(OpTag::Const).unwrap();
        assert_eq!(
            blob,
            vec![
                0x08, 0x00, 0x00, 0x00, 0xAD, 0xDE, 0xC0, 0x7F, 0x00, 0x00, 0x00, 0x00
            ],
            "the f32 NaN payload rides the low-order bits verbatim; upper 4 bytes MBZ"
        );
        let read_back = u64::from_le_bytes(blob[4..12].try_into().unwrap());
        assert_eq!(
            read_back, F32_NAN_PAYLOAD as u64,
            "payload bits round-trip verbatim"
        );
        assert_eq!(
            f32::from_bits(read_back as u32).to_bits(),
            F32_NAN_PAYLOAD,
            "bit-exact (a NaN never compares equal — compare BITS)"
        );

        // f64 signalling-NaN payload: full width, nothing masked or quieted.
        const F64_SNAN_PAYLOAD: u64 = 0x7FF0_0000_0000_DEAD;
        assert!(
            f64::from_bits(F64_SNAN_PAYLOAD).is_nan(),
            "fixture must be a NaN"
        );
        let d = OpAttrs {
            const_bits: Some(F64_SNAN_PAYLOAD),
            ..OpAttrs::default()
        };
        let dblob = d.to_canonical_bytes(OpTag::Const).unwrap();
        assert_eq!(
            u64::from_le_bytes(dblob[4..12].try_into().unwrap()),
            F64_SNAN_PAYLOAD,
            "an f64 sNaN payload is NOT quieted by the serializer"
        );
    }

    #[test]
    fn scan_placeholder_leaf_serializes_role_and_index() {
        // Acked arm: body = u8(role: 0=carry, 1=elem) ++ u32_le(index). Role
        // codes match `fuel_graph::ScanRole`'s declaration order (Carry, Elem).
        assert_eq!((SCAN_ROLE_CARRY, SCAN_ROLE_ELEM), (0u8, 1u8));

        // Carry hole (always index 0 in the v1 single-carry model).
        let carry = OpAttrs {
            scan_role: Some(SCAN_ROLE_CARRY),
            scan_index: Some(0),
            ..OpAttrs::default()
        };
        assert_eq!(
            carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
            vec![0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
            "carry hole: u32-LE(5) ++ u8(0) ++ u32-LE(0)"
        );
        // Elem hole for xs[2].
        let elem = OpAttrs {
            scan_role: Some(SCAN_ROLE_ELEM),
            scan_index: Some(2),
            ..OpAttrs::default()
        };
        assert_eq!(
            elem.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
            vec![0x05, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00],
            "elem hole: u32-LE(5) ++ u8(1) ++ u32-LE(2)"
        );
        // The role byte is NOT part of the index: carry{0} and elem{0} differ.
        let elem0 = OpAttrs {
            scan_role: Some(SCAN_ROLE_ELEM),
            scan_index: Some(0),
            ..OpAttrs::default()
        };
        assert_ne!(
            carry.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
            elem0.to_canonical_bytes(OpTag::ScanPlaceholder).unwrap(),
        );
    }

    #[test]
    fn leaf_arm_bodies_ride_carrier_a_u32_le() {
        // Width discipline: all four acked leaf bodies ride CARRIER (a) — the #67
        // node-envelope op_attrs blob, u32-LE (4-byte) outer length, payload
        // verbatim. None of them may adopt carrier (b)/(c)'s u16-LE width.
        let a = OpAttrs {
            slot_index: Some(7),
            axis: Some(1),
            const_bits: Some(0x3FC0_0000),
            scan_role: Some(SCAN_ROLE_ELEM),
            scan_index: Some(2),
            ..OpAttrs::default()
        };
        for (tag, body_len) in [
            (OpTag::RuntimeScalar, 4usize),
            (OpTag::ReducedCount, 8),
            (OpTag::Const, 8),
            (OpTag::ScanPlaceholder, 5),
        ] {
            let blob = a.to_canonical_bytes(tag).unwrap();
            let declared = u32::from_le_bytes(blob[..4].try_into().unwrap()) as usize;
            assert_eq!(
                declared, body_len,
                "{tag:?}: outer u32-LE length = body length"
            );
            assert_eq!(
                blob.len(),
                4 + body_len,
                "{tag:?}: 4-byte u32-LE prefix + verbatim body"
            );
        }
    }

    #[test]
    fn leaf_arms_are_wire_tokens_only_no_graph_producer() {
        // HONEST SCOPE. These four tags are wire tokens in the shared grammar;
        // Fuel's graph has no first-class recipe LEAF for them yet (a value is
        // expressed implicitly today — an `Op::Const` tensor operand, an
        // `Op::Iota`, a `Runtime { scalars }` slot on the consuming op,
        // `Op::ScanPlaceholder` inside `Op::Scan`'s body, and Mean's divisor
        // folded into `Op::MeanDim`). So `jit::op_to_tag` emits none of them and
        // `runtime_fused::tag_to_op` declines `Const`/`RuntimeScalar`/`ReducedCount`
        // as honest misses but RECONSTRUCTS `ScanPlaceholder` (explicit arm,
        // `Increment C, B1`) — the
        // flat-DAG-CSE recipe interior that would produce them is the (unbuilt)
        // Convergence-C home. Pinned here so a later wiring change is deliberate.
        //
        // The observable consequence in THIS crate, CHANGED BY GAP-287: unset
        // attrs are DECLINED, not serialized to a fixed-width body of defaults.
        //
        // This assertion is the inverse of the one it replaces. The old text
        // read "unset attrs still serialize to the tag's fixed-width body (the
        // M-3 unset-vs-zero caveat), never a panic and never an empty body" and
        // pinned the four LENGTHS -- i.e. it encoded the fabrication as a
        // REQUIREMENT. It was the ONLY test in this crate that failed when the
        // encoder began declining, which is the born-red for this change: the
        // suite already contained an assertion that the defect held.
        let d = OpAttrs::default();
        for (tag, field) in [
            (OpTag::RuntimeScalar, "slot_index"),
            (OpTag::ReducedCount, "axis"),
            (OpTag::Const, "const_bits"),
            (OpTag::ScanPlaceholder, "scan_role"),
        ] {
            assert_eq!(
                d.to_canonical_bytes(tag),
                Err(UnresolvedAttr { op: tag, field }),
                "{tag:?} must DECLINE an unset `{field}`, not emit a default"
            );
        }

        // CONTROL, so the four declines are not merely "this function always
        // errors": a tag whose arm reads nothing still succeeds with the empty
        // body, and a fully-populated leaf still serializes to the same length.
        assert_eq!(d.to_canonical_bytes(OpTag::Add).unwrap(), vec![0, 0, 0, 0]);
        let filled = OpAttrs {
            scan_role: Some(SCAN_ROLE_ELEM),
            scan_index: Some(2),
            ..OpAttrs::default()
        };
        assert_eq!(
            filled
                .to_canonical_bytes(OpTag::ScanPlaceholder)
                .unwrap()
                .len(),
            4 + 5,
            "a RESOLVED ScanPlaceholder still emits the same 5-byte body"
        );
    }

    /// The GAP-287 defect itself, asserted as GONE: two `Gather`s on different
    /// axes no longer collide, because neither is expressible unresolved.
    ///
    /// `fuel-graph`'s `distinct_gathers_serialize_identically_gap287` pinned the
    /// collision from the projection side; this is the same fact from inside the
    /// crate that owns the encoder.
    #[test]
    fn an_unresolved_axis_is_inexpressible_gap287() {
        assert_eq!(
            OpAttrs::default().to_canonical_bytes(OpTag::Gather),
            Err(UnresolvedAttr {
                op: OpTag::Gather,
                field: "axis"
            })
        );

        // Resolved axes are distinct on the wire -- the property the collapse
        // destroyed. This is the assertion no decoder could have restored.
        let a0 = OpAttrs {
            axis: Some(0),
            ..OpAttrs::default()
        };
        let a2 = OpAttrs {
            axis: Some(2),
            ..OpAttrs::default()
        };
        assert_ne!(
            a0.to_canonical_bytes(OpTag::Gather).unwrap(),
            a2.to_canonical_bytes(OpTag::Gather).unwrap(),
            "axis 0 and axis 2 must differ on the wire"
        );
    }

    /// `keepdim` still defaults, and that is deliberate rather than an omission.
    ///
    /// Declining it would refuse input `tag_to_op` ACCEPTS: the decoder reads no
    /// `keepdim` for these tags at all, because Fuel encodes keepdim=true
    /// STRUCTURALLY as `ReduceSumTo`/`ReduceMaxTo` on the shape-target arm.
    /// Pinned so a future "consistency" sweep does not make this arm strict and
    /// break the round-trip in the name of tidiness.
    #[test]
    fn keepdim_still_defaults_because_the_decoder_never_reads_it() {
        let axis_only = OpAttrs {
            axis: Some(1),
            ..OpAttrs::default()
        };
        let bytes = axis_only
            .to_canonical_bytes(OpTag::SumDim)
            .expect("axis is set; keepdim is not required");
        assert_eq!(bytes.len(), 4 + 8 + 1, "axis(i64) + keepdim(u8)");
        assert_eq!(*bytes.last().unwrap(), 0, "keepdim defaults to false");

        // And the axis on the SAME arm is still required -- so this cannot pass
        // by the arm having become permissive.
        assert_eq!(
            OpAttrs::default().to_canonical_bytes(OpTag::SumDim),
            Err(UnresolvedAttr {
                op: OpTag::SumDim,
                field: "axis"
            })
        );
    }
}