fuel-dispatch 0.20.0

Dispatch infrastructure for fuel: KernelBindingTable, per-backend registration wrappers, CompiledNode + compile_node, ExecutionPlan + compile_plan + resolve_kernel, FusedKernelRegistry, PipelinedExecutor. The layer that takes a graph and runs it against registered backends. Extracted from fuel-memory 2026-05-31.
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
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The REGISTRATION slice: a parsed+lowered provider bundle →
//! live kernel registrations on the two dispatch registries
//! (adoption plan §1.2, §1.3, §2.1, §2.2).
//!
//! This module makes the FKC importer **end-to-end**: a contract bundle
//! file becomes concrete entries in a [`KernelBindingTable`] (primitive
//! `op_kind` contracts) and a [`FusedKernelRegistry`] (`fused_op`
//! contracts). The pipeline is:
//!
//! ```text
//! import_bundle_str(src)  =  parse_file(src) → lower_file(.., link) → ImportedProvider
//! import_bundle(path)     =  read file       → import_bundle_str
//! import_glob(pattern)    =  glob files      → import_bundle_str each → MERGE (front-matter must agree)
//! provider.register_into(table, fused)       =  the actual registry inserts + finalize gate
//! ```
//!
//! ## Cost decision for this slice
//!
//! Two cost paths coexist:
//!
//! 1. **Named cost-fn trampoline (§4.4, Task-F).** A primitive contract whose
//!    `cost.cost_fn` NAMES a registered cost fn has that name resolved through
//!    the provider's [`LinkRegistry::resolve_cost_fn`](crate::fkc::LinkRegistry)
//!    at lower time and the resulting [`CostFn`](crate::kernel::CostFn) pinned
//!    on the binding by [`ImportedProvider::register_into`]. A pinned cost fn
//!    is NOT the [`unknown_cost`] sentinel, so the
//!    [`fill_unset_cost_for_backend`](crate::kernel::KernelBindingTable::fill_unset_cost_for_backend)
//!    pass leaves it — the mechanism that lets a contract carry a real,
//!    shape-aware cost model (e.g. the CUDA `flash_decoding` static
//!    infeasibility gate `cost_flash_decoding_cuda`). An unresolved name is a
//!    typed [`FkcError::UnknownCostFn`], never a silent fallback.
//! 2. **Judge-bootstrapped default (the common case, [consumer-ahead]).** A
//!    contract that names NO cost fn registers with the [`unknown_cost`]
//!    sentinel `CostFn` (primitives) / [`fused_unknown_cost`] (fused ops);
//!    the fill pass then upgrades the primitive sentinel to the op/backend
//!    default, and the Judge refines empirically. The parsed
//!    [`CompiledCostExpr`](crate::fkc::cost_expr::CompiledCostExpr) stays on
//!    the `Resolved*` record. Fused ops have no named-cost-fn path yet (the
//!    fused cost-fn signature differs; no consumer today).

use std::collections::HashSet;
use std::path::Path;
use std::sync::{Mutex, OnceLock};

use fuel_graph::registry::FusedOpParams;
use fuel_ir::Shape;
use fuel_ir::backend::BackendCapabilities;
use fuel_ir::probe::BackendId;

use crate::fkc::error::FkcError;
use crate::fkc::lower::{LinkRegistry, Resolved, ResolvedFused, ResolvedPrimitive, lower_file};
use crate::fkc::parse::parse_file;
use crate::fused::{BackendImpl, CostEstimate, FusedKernelRegistry};
use crate::kernel::{KernelBindingTable, unknown_cost};

// ===========================================================================
// kernel_source interner (§1.3)
// ===========================================================================

/// Intern a `kernel_source` (or any short, bounded-cardinality provider
/// tag) string into a `&'static str`, leaking it on first sighting.
///
/// `BindingEntry.kernel_source` and `BackendImpl.dtypes` use `&'static`
/// data, but a contract's `kernel_source` is read from a file at runtime,
/// so it is not `'static`. Resolution per plan §1.3: a process-wide
/// `OnceLock<Mutex<HashSet<&'static str>>>` interner that `Box::leak`s the
/// owned string on first sighting and returns the cached handle on every
/// repeat.
///
/// **Bounded process-lifetime leak.** Each *distinct* string is leaked
/// exactly once for the life of the process. The set of distinct
/// `kernel_source` tags is a handful (one per provider source: e.g.
/// `"portable-cpu"`, `"aocl"`, `"mkl"`), so the total leaked bytes are
/// trivially bounded and never grow under repeated imports of the same
/// provider. This is the same posture `precision.rs` takes for precision
/// `notes`. (Alternative, out of scope here: widen `kernel_source` to
/// `Cow<'static, str>` in a follow-up.)
pub(crate) fn intern(s: &str) -> &'static str {
    static POOL: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
    let pool = POOL.get_or_init(|| Mutex::new(HashSet::new()));
    let mut guard = pool.lock().expect("kernel_source interner poisoned");
    if let Some(existing) = guard.get(s) {
        return existing;
    }
    let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
    guard.insert(leaked);
    leaked
}

/// Intern a per-operand dtype list into a `&'static [DType]` slice for a
/// fused [`BackendImpl`] (whose `dtypes` field is `&'static [DType]`).
/// Backed by the same bounded process-lifetime leak as [`intern`]: each
/// distinct dtype tuple is leaked once and cached. Distinct fused ops use
/// a small, fixed set of dtype tuples, so the leak is bounded.
fn intern_dtypes(dtypes: &[fuel_ir::DType]) -> &'static [fuel_ir::DType] {
    use fuel_ir::DType;
    static POOL: OnceLock<Mutex<HashSet<&'static [DType]>>> = OnceLock::new();
    let pool = POOL.get_or_init(|| Mutex::new(HashSet::new()));
    let mut guard = pool.lock().expect("fused dtypes interner poisoned");
    if let Some(existing) = guard.get(dtypes) {
        return existing;
    }
    let leaked: &'static [DType] = Box::leak(dtypes.to_vec().into_boxed_slice());
    guard.insert(leaked);
    leaked
}

// ===========================================================================
// Fused-cost sentinel (the fused equivalent of `unknown_cost`)
// ===========================================================================

/// The fused-op cost-fn sentinel — the fused analog of
/// [`unknown_cost`]. There is no public fused sentinel in `fused.rs`
/// (registrations that omit a cost use `CostEstimate::default()` inline),
/// so the importer supplies its own trivial zero-cost fn matching the
/// fused cost-fn signature
/// `fn(&[Shape], &FusedOpParams, &BackendCapabilities) -> CostEstimate`.
///
/// [consumer-ahead]: declared cost priors are retained on
/// `ResolvedFused.cost` but not yet wired into a `CostFn`; the Judge
/// bootstraps all imported costs for now (a follow-up slice adds the cost
/// trampoline, plan §2.3 strategy A).
pub fn fused_unknown_cost(
    _shapes: &[Shape],
    _params: &FusedOpParams,
    _caps: &BackendCapabilities,
) -> CostEstimate {
    CostEstimate::default()
}

// ===========================================================================
// ImportedProvider (§1.2)
// ===========================================================================

/// A parsed + validated provider bundle, holding the resolved per-kernel
/// records ready to register. Construction (`import_*`) already ran the
/// parse + restricted-YAML pre-pass + lowering (string → typed dispatch
/// records); [`Self::register_into`] only does the registry inserts +
/// the duplicate-detection gate.
#[derive(Debug, Clone)]
pub struct ImportedProvider {
    /// `provider.name` (front-matter).
    pub name: String,
    /// `provider.backend` (front-matter), the registry key backend.
    pub backend: BackendId,
    /// `provider.kernel_source` (front-matter), interned to `&'static`.
    pub kernel_source: &'static str,
    /// `provider.revision_base` (front-matter) — the provider build id folded
    /// into `kernel_revision_hash`.
    ///
    /// Retained on the imported provider *specifically* so [`import_glob`] can
    /// enforce §9.2's "front-matter must agree across files". It was previously
    /// consumed during lowering and dropped, which made that agreement
    /// structurally uncheckable: two files of one globbed provider could
    /// declare different bases, and since `revision_base` feeds
    /// `kernel_revision_hash` — the key the verification ledger is looked up
    /// by — the merged provider would silently carry kernels whose revision
    /// hashes were computed against different roots.
    pub revision_base: Option<String>,
    /// `provider.link_registry` (front-matter) — the symbol path of the table
    /// this file's `entry_point`s are declared to resolve against.
    ///
    /// Retained for the same reason as [`Self::revision_base`]: §9.2 requires
    /// it to AGREE across a glob's files, and a field that is consumed during
    /// lowering and dropped cannot be compared at merge time. `import_glob`
    /// binds every file it merges through the single registry its *caller*
    /// supplied, so disagreement here means at least one file's entry points
    /// were resolved against a table its author never named.
    pub link_registry: Option<String>,
    /// Lowered `op_kind` contracts → the binding table.
    pub primitives: Vec<ResolvedPrimitive>,
    /// Lowered `fused_op` contracts → the fused registry.
    pub fused: Vec<ResolvedFused>,
    /// Soft import diagnostics (§3.5 warns, precision downgrades, etc.).
    pub warnings: Vec<crate::fkc::ImportWarning>,
}

impl ImportedProvider {
    /// Split a flat `Vec<Resolved>` into the primitive / fused buckets.
    fn from_resolved(
        name: String,
        backend: BackendId,
        kernel_source: &'static str,
        revision_base: Option<String>,
        link_registry: Option<String>,
        resolved: Vec<Resolved>,
        warnings: Vec<crate::fkc::ImportWarning>,
    ) -> Self {
        let mut primitives = Vec::new();
        let mut fused = Vec::new();
        for r in resolved {
            match r {
                Resolved::Primitive(p) => primitives.push(p),
                Resolved::Fused(f) => fused.push(f),
            }
        }
        ImportedProvider {
            name,
            backend,
            kernel_source,
            revision_base,
            link_registry,
            primitives,
            fused,
            warnings,
        }
    }

    /// Register every primitive contract into `table` and every fused
    /// contract into `fused`, then run the duplicate-detection gate.
    ///
    /// **Describe-only sections (`registrable: false`, §3.10) are already
    /// excluded** before this point: [`lower_file`] (called by the `import_*`
    /// constructors) filters them out, so `self.primitives` / `self.fused`
    /// contain only registrable kernels. A documentation-only section therefore
    /// never reaches the binding table / fused registry or the duplicate-
    /// `KernelRef` gate — it is honest docs, not a dispatch decision point.
    ///
    /// Per slice (§2.1 / §2.2): each primitive becomes a
    /// [`KernelBindingTable::register_full_with_source`] insert; each
    /// fused op becomes a [`FusedKernelRegistry::register`] of a
    /// [`BackendImpl`]. **Cost is the sentinel for every kernel this
    /// slice** — `unknown_cost` for primitives, [`fused_unknown_cost`]
    /// for fused ops (see the module-level cost note); the parsed cost AST
    /// stays on the `Resolved*` record.
    ///
    /// `register_full_with_source` is append-only and returns `()` today;
    /// the **same** `KernelRef` driven onto one `(op, dtypes, backend)`
    /// key twice is detected by [`KernelBindingTable::finalize`], which
    /// this method calls **after all inserts** and maps to
    /// [`FkcError::DuplicateKernelRef`] (never a panic — the import path is
    /// `Result` end-to-end).
    pub fn register_into(
        &self,
        table: &mut KernelBindingTable,
        fused: &mut FusedKernelRegistry,
    ) -> Result<(), FkcError> {
        // --- Primitives → KernelBindingTable (§2.1) ---
        for p in &self.primitives {
            let kernel_source: &'static str = intern(&p.kernel_source);
            // §4.4 cost-fn trampoline (Task-F): when the contract PINS a cost
            // fn (`cost.cost_fn`, resolved through the LinkRegistry at lower
            // time), stamp THAT `CostFn` — it survives the
            // `fill_unset_cost_for_backend` pass (which only replaces the
            // `unknown_cost` sentinel), so a contract can carry a real,
            // shape-aware cost model (e.g. the CUDA `flash_decoding` static
            // infeasibility gate). When it does NOT pin one, keep the
            // `unknown_cost` sentinel so the fill pass upgrades it to the
            // op/backend default (the Judge-bootstrapped path for every other
            // imported primitive).
            let cost_fn = p.cost_fn.unwrap_or(unknown_cost);
            // FKC gap-closure Task 2.2 (§2.3): compile the contract's
            // declared cost AST (if any, and if no pinned `cost_fn` already
            // wins — see `stamp_primitive_cost_expr`) into the interned
            // `'static` handle threaded onto the binding below.
            let cost_expr = crate::fkc::cost_compile::stamp_primitive_cost_expr(p);
            // Structural-miss fallback bit (FKC §4.12): compute genericity
            // ONCE from the retained five-flag `ResolvedLayout` set and stamp
            // it onto the binding so the live dispatch pick site reads a
            // precomputed bool (never re-derives it from the lossy
            // single-bool `KernelCaps`). Baracuda's miss telemetry keys on it.
            let is_generic = crate::fkc::is_generic_contract(&p.layouts);
            // Thread the contract-computed revision hash onto the binding (FKC
            // §4.11 basis tuple) so the Baracuda dispatch-telemetry `ImplId`
            // pins the exact kernel build. Hand-written kernels stamp
            // `UNTRACKED` (`0`); only this FKC-import path carries a real one.
            table.register_full_with_source_generic(
                p.op,
                &p.dtypes,
                p.backend,
                p.kernel,
                p.caps,
                p.precision,
                cost_fn,
                kernel_source,
                is_generic,
                p.revision.0,
                // FKC gap-closure Task 2.2: the compiled cost AST (or `None`
                // when a pinned `cost_fn` already wins, or the contract
                // declared no cost expression at all).
                cost_expr,
            );
        }

        // --- Fused ops → FusedKernelRegistry (§2.2) ---
        for f in &self.fused {
            // FKC gap-closure Task 2.4 (§2.3): compile the contract's
            // declared cost AST (if any) into the interned `'static` handle
            // threaded onto `cost_expr` below. `fused_layer1_cost` prefers
            // it over both the hand-written `cost` fn (still stamped as the
            // `fused_unknown_cost` sentinel here) and the decompose-derived
            // fallback.
            let dtypes: &'static [fuel_ir::DType] = intern_dtypes(&f.dtypes);
            fused.register(
                f.id,
                f.backend,
                BackendImpl {
                    kernel: f.kernel,
                    dtypes,
                    cost: fused_unknown_cost,
                    precision: f.precision,
                    caps: f.caps,
                    revision: f.revision,
                    cost_expr: crate::fkc::cost_compile::stamp_fused_cost_expr(f),
                },
            );
            // Finding 5.4 (FKC side, Task 3.6): preserve the contract's
            // `return.bundle` per-slot names in the side-table, keyed by the
            // SAME (id, backend, dtypes) tuple just registered above. Empty
            // for a single-output section (the common case) — skip the
            // insert rather than recording a vacuous entry.
            if !f.bundle_slot_names.is_empty() {
                fused.record_bundle_slot_names(f.id, f.backend, dtypes, &f.bundle_slot_names);
            }
        }

        // --- The duplicate-detection gate, surfaced as a typed error ---
        // `register_full_with_source` is append-only; `finalize` is the
        // single pass that detects the same `KernelRef` registered twice
        // at one key. Map its dispatch `Error` message into a typed
        // `FkcError::DuplicateKernelRef` (never-panic on the import path).
        table
            .finalize()
            .map_err(|e| FkcError::DuplicateKernelRef(e.to_string()))?;

        Ok(())
    }
}

// ===========================================================================
// Public import entry points (§1.2)
// ===========================================================================

/// Parse + validate a single bundle markdown file's bytes into an
/// [`ImportedProvider`]. Pure: no I/O of its own (tests pass `&str`).
///
/// `parse_file` → `lower_file(.., link)` → assemble. Every failure is a
/// typed [`FkcError`]; never panics.
pub fn import_bundle_str(src: &str, link: &dyn LinkRegistry) -> Result<ImportedProvider, FkcError> {
    let file = parse_file(src)?;
    // Run the build-time validators (the V-FKC-* battery, §10) AFTER parse so a
    // structurally / coherence-bad contract fails import before any lowering or
    // registration touches the dispatch surface. Validation runs over EVERY
    // section, including describe-only ones (§3.10) — their descriptive checks
    // (dtype, layout, cost, precision) still apply; only their dispatch-resolution
    // checks are skipped. The ONE relaxation: a describe-only section's
    // CONSUMER-AHEAD gate (`GatherNotYetSupported` / `MxNotYetRegistrable`) is a
    // correct "describable-but-not-yet-registrable" outcome, so `validate_file`
    // treats it as non-blocking (the same "deferred" posture the corpus CI lint
    // takes) — a describe-only documentation section must not block a bundle's
    // importable sections.
    crate::fkc::validate::validate_file(&file)?;
    // `lower_file` then EXCLUDES describe-only sections from the registered set
    // (§3.10): they never become a Resolved* record and are never registered.
    let mut warnings: Vec<crate::fkc::ImportWarning> = Vec::new();
    let mut resolved = lower_file(&file, link, &mut warnings)?;
    let provider = &file.front_matter.provider;
    let backend = lower_backend_str(&provider.backend)?;
    let kernel_source = intern(&provider.kernel_source);

    // V-FKC-9 (Task 4.3): gate every lowered record's declared precision
    // against the empirical verification ledger BEFORE it reaches
    // `from_resolved` / the binding table. Any machine-checkable claim
    // (bit-stability, ULP, etc.) with no matching `pass` ledger entry for
    // this exact `(kernel_source, backend, dtypes, kernel_revision_hash)`
    // collapses to `PrecisionGuarantee::UNAUDITED` plus a warning — an
    // asserted-but-never-measured claim must not survive import as if it
    // had been verified. Task 4.5b seeded the embedded ledger with real
    // empirical `pass` entries for the fused CPU ops flipped to
    // `audited: true` on 2026-07-03, so THOSE records are honored here
    // (same revision hash, since `default_kernel_registry()`'s
    // `register_*_fused_from_contract` helpers stamp `BackendImpl.revision`
    // from this SAME `ResolvedFused.revision`); a primitive `op_kind`
    // contract like `add_f32` (never in Task 4.5b's fused-op scope) has no
    // ledger entry and is downgraded.
    let ledger = crate::fkc::verify::embedded();
    for r in &mut resolved {
        match r {
            Resolved::Primitive(p) => {
                let q = crate::fkc::verify::LedgerQuery {
                    kernel_ref: p.kernel_source.as_str(),
                    backend: p.backend,
                    dtypes: p.dtypes.as_slice(),
                    kernel_revision_hash: p.revision.0,
                };
                p.precision =
                    crate::fkc::verify::gate_precision(p.precision, &q, ledger, &mut warnings);
            }
            Resolved::Fused(f) => {
                let q = crate::fkc::verify::LedgerQuery {
                    kernel_ref: f.kernel_source.as_str(),
                    backend: f.backend,
                    dtypes: f.dtypes.as_slice(),
                    kernel_revision_hash: f.revision.0,
                };
                f.precision =
                    crate::fkc::verify::gate_precision(f.precision, &q, ledger, &mut warnings);
            }
        }
    }

    Ok(ImportedProvider::from_resolved(
        provider.name.clone(),
        backend,
        kernel_source,
        provider.revision_base.clone(),
        provider.link_registry.clone(),
        resolved,
        warnings,
    ))
}

/// Convenience: read a bundle file at `path`, then [`import_bundle_str`].
pub fn import_bundle(
    path: impl AsRef<Path>,
    link: &dyn LinkRegistry,
) -> Result<ImportedProvider, FkcError> {
    let path = path.as_ref();
    let src = std::fs::read_to_string(path).map_err(|e| FkcError::Io {
        path: path.display().to_string(),
        reason: e.to_string(),
    })?;
    import_bundle_str(&src, link)
}

/// Glob multiple per-kernel / per-bundle FKC files into one provider
/// (§9.2). Each matched file is parsed + lowered independently and then
/// **merged** into a single [`ImportedProvider`]; the front-matter
/// `provider.name` / `provider.backend` / `provider.kernel_source` must
/// **agree** across every file or [`FkcError::ProviderMismatch`].
///
/// Glob order is sorted for determinism (so duplicate-detection /
/// revision-hash order is stable across runs).
///
/// **No new dependency.** `fuel-dispatch` has no `glob` crate dep, and the
/// adoption plan (§1.2) prefers no new dep — so this uses a minimal
/// directory walk + a small filename matcher over the pattern's last
/// component rather than pulling in `glob`. The supported pattern shape is
/// `<dir>/<filename-pattern>` where the filename pattern may contain `*`
/// wildcards (e.g. `docs/kernel-contracts/cpu/*.fkc.md`); `**` is not
/// supported (a single directory level, matching the per-provider layout).
pub fn import_glob(pattern: &str, link: &dyn LinkRegistry) -> Result<ImportedProvider, FkcError> {
    let mut paths = glob_files(pattern)?;
    paths.sort(); // deterministic order

    if paths.is_empty() {
        return Err(FkcError::Io {
            path: pattern.to_string(),
            reason: "glob pattern matched no files".to_string(),
        });
    }

    let mut merged: Option<ImportedProvider> = None;
    for path in &paths {
        let file_label = path.display().to_string();
        let provider = import_bundle(path, link)?;
        match merged.as_mut() {
            None => merged = Some(provider),
            Some(acc) => {
                // Front-matter must agree across files (§9.2).
                if provider.name != acc.name {
                    return Err(FkcError::ProviderMismatch {
                        field: "provider.name".to_string(),
                        expected: acc.name.clone(),
                        found: provider.name.clone(),
                        file: file_label,
                    });
                }
                if provider.backend != acc.backend {
                    return Err(FkcError::ProviderMismatch {
                        field: "provider.backend".to_string(),
                        expected: format!("{:?}", acc.backend),
                        found: format!("{:?}", provider.backend),
                        file: file_label,
                    });
                }
                // kernel_source is interned, so distinct tags compare by
                // pointer-or-content; compare by content for the message.
                if provider.kernel_source != acc.kernel_source {
                    return Err(FkcError::ProviderMismatch {
                        field: "provider.kernel_source".to_string(),
                        expected: acc.kernel_source.to_string(),
                        found: provider.kernel_source.to_string(),
                        file: file_label,
                    });
                }
                // `revision_base` is folded into `kernel_revision_hash`, which
                // is the key the verification ledger is looked up by. A drift
                // here would merge kernels whose revision hashes were computed
                // against different roots while presenting as one provider —
                // silently invalidating those lookups rather than failing.
                // Compared as `Option` so "one file declares it, the other
                // omits it" is caught too, not just two differing values.
                if provider.revision_base != acc.revision_base {
                    return Err(FkcError::ProviderMismatch {
                        field: "provider.revision_base".to_string(),
                        expected: format!("{:?}", acc.revision_base),
                        found: format!("{:?}", provider.revision_base),
                        file: file_label.clone(),
                    });
                }
                // `link_registry` names the symbol table a file's entry points
                // are declared to resolve against — but a glob binds every file
                // it merges through the ONE registry the caller supplied. A
                // drift here means at least one file's `entry_point`s were
                // resolved against a table its author never named; they may
                // still resolve, to a same-named symbol from a different
                // provider. Same `Option` comparison as above, and for the same
                // reason: declared-in-one-file-only is a drift too.
                if provider.link_registry != acc.link_registry {
                    return Err(FkcError::ProviderMismatch {
                        field: "provider.link_registry".to_string(),
                        expected: format!("{:?}", acc.link_registry),
                        found: format!("{:?}", provider.link_registry),
                        file: file_label.clone(),
                    });
                }
                // Agreed — fold this file's kernels into the merged provider.
                acc.primitives.extend(provider.primitives);
                acc.fused.extend(provider.fused);
                acc.warnings.extend(provider.warnings);
            }
        }
    }

    Ok(merged.expect("non-empty path list yields a provider"))
}

// ===========================================================================
// Helpers
// ===========================================================================

/// Map a front-matter `backend` string to a [`BackendId`]. Mirrors
/// `lower.rs`'s `lower_backend` (kept local to avoid widening that fn's
/// visibility for one call site). `UnknownBackend` on a bad string.
fn lower_backend_str(s: &str) -> Result<BackendId, FkcError> {
    match s {
        "Cpu" => Ok(BackendId::Cpu),
        "Cuda" => Ok(BackendId::Cuda),
        "Vulkan" => Ok(BackendId::Vulkan),
        "Metal" => Ok(BackendId::Metal),
        other => Err(FkcError::UnknownBackend {
            section: "<front-matter provider>".to_string(),
            backend: other.to_string(),
        }),
    }
}

/// Minimal `<dir>/<filename-pattern>` glob: list the directory and keep
/// files whose name matches the pattern's last component (with `*`
/// wildcards). No new dependency; no `**` support (single directory level).
fn glob_files(pattern: &str) -> Result<Vec<std::path::PathBuf>, FkcError> {
    // Split into directory + filename pattern on the last path separator.
    let p = Path::new(pattern);
    let file_pat = p
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .ok_or_else(|| FkcError::Io {
            path: pattern.to_string(),
            reason: "glob pattern has no filename component".to_string(),
        })?;
    let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
    let dir = dir.unwrap_or_else(|| Path::new("."));

    let read = std::fs::read_dir(dir).map_err(|e| FkcError::Io {
        path: dir.display().to_string(),
        reason: e.to_string(),
    })?;

    let mut out = Vec::new();
    for entry in read {
        let entry = entry.map_err(|e| FkcError::Io {
            path: dir.display().to_string(),
            reason: e.to_string(),
        })?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        if matches_glob(&file_pat, &name) {
            out.push(path);
        }
    }
    Ok(out)
}

/// Match a filename against a `*`-wildcard glob pattern (single path
/// component; `*` matches any run of non-separator characters). A
/// pattern with no `*` is an exact match.
fn matches_glob(pattern: &str, name: &str) -> bool {
    // Split the pattern on `*`; every literal segment must appear in
    // order, with the first segment anchored at the start and the last at
    // the end (unless the pattern starts/ends with `*`).
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        // No wildcard — exact match.
        return pattern == name;
    }
    let mut pos = 0usize;
    for (i, part) in parts.iter().enumerate() {
        if part.is_empty() {
            continue;
        }
        if i == 0 {
            // First literal segment must anchor at the start.
            if !name[pos..].starts_with(part) {
                return false;
            }
            pos += part.len();
        } else if i == parts.len() - 1 {
            // Last literal segment must anchor at the end (and not overlap
            // an already-consumed prefix).
            let rest = &name[pos..];
            return rest.len() >= part.len() && rest.ends_with(part);
        } else {
            // Middle segment: must occur somewhere at/after pos.
            match name[pos..].find(part) {
                Some(idx) => pos += idx + part.len(),
                None => return false,
            }
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fkc::caps_map::{ResolvedLayout, Tri};
    use crate::fkc::cost_expr::CompiledCostExpr;
    use crate::fkc::lower::ResolvedFused;
    use crate::fused::{KernelRevisionHash, PrecisionGuarantee};
    use crate::kernel::{KernelCaps, KernelDTypes, KernelRef};
    use fuel_graph::registry::FusedOps;
    use fuel_ir::DType;
    use fuel_ir::dispatch::OpKind;
    use smallvec::SmallVec;
    use std::sync::{Arc, RwLock};

    const ELEMENTWISE_BINARY: &str =
        include_str!("../../../docs/kernel-contracts/cpu/elementwise-binary.fkc.md");

    /// Every live CPU contract, read from disk.
    ///
    /// ⚠️ **This started as two hand-picked contracts, and that was the same
    /// mistake one level up.** The tests below were rewritten to LOCATE a
    /// downgraded entry rather than name one, because naming `add_f32` made
    /// them fail once the precision program earned its claims — and then they
    /// failed AGAIN when the program earned everything in the two contracts I
    /// had picked to search. **A hand-picked search SET expires exactly like a
    /// hand-picked fixture.** The population is now "all of them", which is
    /// the only version that does not need re-picking as coverage grows.
    #[allow(
        dead_code,
        reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
    )]
    fn all_cpu_contracts() -> Vec<(String, String)> {
        let dir =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/kernel-contracts/cpu");
        let mut out = Vec::new();
        for e in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("read {dir:?}: {e}")) {
            let path = e.expect("dir entry").path();
            if path.extension().and_then(|x| x.to_str()) != Some("md") {
                continue;
            }
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default()
                .to_string();
            if let Ok(text) = std::fs::read_to_string(&path) {
                out.push((name, text));
            }
        }
        out.sort();
        assert!(
            out.len() >= 10,
            "only {} CPU contracts found under {dir:?} — the search below would be over \
             a subset, and a 'nothing is downgraded' result would then be about the \
             wrong population",
            out.len()
        );
        out
    }

    /// Find an imported primitive whose guarantee was downgraded, together
    /// with the claims the gate reported unbacked.
    #[allow(
        dead_code,
        reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
    )]
    fn find_downgraded() -> Option<(String, Vec<String>)> {
        for (_name, text) in all_cpu_contracts() {
            let link = EntryPointLink::new();
            let Ok(provider) = import_bundle_str(&text, &link) else {
                continue;
            };
            for w in provider.warnings.iter() {
                if !w.message.contains("downgraded to UNAUDITED") {
                    continue;
                }
                let claims = match (w.message.find('['), w.message.find(']')) {
                    (Some(a), Some(b)) if b > a => w.message[a + 1..b]
                        .split(',')
                        .map(|c| c.trim().trim_matches('"').to_string())
                        .collect(),
                    _ => continue,
                };
                return Some((w.message.clone(), claims));
            }
        }
        None
    }

    // -- two distinct dummy kernels (distinct fn items ⇒ distinct ptrs) --

    fn dummy_a(
        _i: &[Arc<RwLock<fuel_memory::Storage>>],
        _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
        _l: &[fuel_ir::Layout],
        _p: &crate::kernel::OpParams,
    ) -> fuel_ir::Result<()> {
        Ok(())
    }
    fn dummy_b(
        _i: &[Arc<RwLock<fuel_memory::Storage>>],
        _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
        _l: &[fuel_ir::Layout],
        _p: &crate::kernel::OpParams,
    ) -> fuel_ir::Result<()> {
        Ok(())
    }

    /// A LinkRegistry stub mapping each DISTINCT `entry_point` string to a
    /// distinct dummy `KernelRef` — so importing a many-section contract
    /// does not collapse every section onto one pointer (which would trip
    /// the finalize gate spuriously). It hands out `dummy_a` / `dummy_b`
    /// in alternation per unique symbol (enough distinct pointers for the
    /// elementwise-binary corpus where every section has a unique key).
    struct DistinctLink {
        seen: Mutex<std::collections::HashMap<String, KernelRef>>,
    }
    impl DistinctLink {
        fn new() -> Self {
            Self {
                seen: Mutex::new(std::collections::HashMap::new()),
            }
        }
        fn resolve(&self, symbol: &str) -> Option<KernelRef> {
            let mut g = self.seen.lock().unwrap();
            if let Some(k) = g.get(symbol) {
                return Some(*k);
            }
            // Alternate between two distinct fn items by current count
            // parity. Each unique symbol gets a stable pointer; the keys
            // in the elementwise-binary corpus are unique per section so
            // two pointers suffice to avoid same-key collisions there.
            let k: KernelRef = if g.len().is_multiple_of(2) {
                dummy_a
            } else {
                dummy_b
            };
            g.insert(symbol.to_string(), k);
            Some(k)
        }
    }
    impl LinkRegistry for DistinctLink {
        fn resolve_primitive(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
        fn resolve_fused(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
    }

    /// A LinkRegistry stub that maps EVERY symbol to the SAME pointer —
    /// used for the duplicate-detection test.
    struct SameLink;
    impl LinkRegistry for SameLink {
        fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
            Some(dummy_a)
        }
        fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
            Some(dummy_a)
        }
    }

    // =====================================================================
    // END-TO-END: a real contract file → live registration
    // =====================================================================

    #[test]
    fn import_real_elementwise_binary_registers_add_f32_end_to_end() {
        // Parse + lower the authored CPU elementwise-binary bundle, then
        // register it into a FRESH binding table and assert the kernel is
        // present + the table finalizes Ok.
        let link = DistinctLink::new();
        let provider = import_bundle_str(ELEMENTWISE_BINARY, &link)
            .expect("authored elementwise-binary.fkc.md imports");

        assert_eq!(provider.name, "fuel-cpu-backend");
        assert_eq!(provider.backend, BackendId::Cpu);
        assert_eq!(provider.kernel_source, "portable-cpu");
        assert!(
            !provider.primitives.is_empty(),
            "elementwise-binary yields primitives"
        );
        assert!(provider.fused.is_empty(), "no fused ops in this bundle");

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into a fresh table succeeds");

        // The add_f32 contract: (AddElementwise, [F32,F32,F32], Cpu).
        let key_dtypes = [DType::F32, DType::F32, DType::F32];
        let looked_up = table.lookup(OpKind::AddElementwise, &key_dtypes, BackendId::Cpu);
        assert!(
            looked_up.is_ok(),
            "AddElementwise/[F32,F32,F32]/Cpu must be registered: {looked_up:?}"
        );

        // The table is internally consistent.
        assert!(table.finalize().is_ok(), "finalize is Ok after import");
        assert!(table.len() >= provider.primitives.len());
    }

    // =====================================================================
    // VERTICAL SLICE: import through a REAL LinkRegistry → the real kernel
    // =====================================================================

    /// A REAL (non-stub) [`LinkRegistry`]: resolves the authored contract's
    /// `add_f32` entry-point symbol to the ACTUAL production CPU kernel
    /// wrapper (`dispatch::add_elementwise_f32_cpu_wrapper`). Every other
    /// section's symbol gets a distinct dummy so the multi-section bundle
    /// still imports without a spurious finalize collision. This is the first
    /// non-stub LinkRegistry — it proves the FKC import path resolves a
    /// contract symbol to a real, executable kernel, not a placeholder.
    struct EntryPointLink {
        seen: Mutex<std::collections::HashMap<String, KernelRef>>,
    }
    impl EntryPointLink {
        fn new() -> Self {
            Self {
                seen: Mutex::new(std::collections::HashMap::new()),
            }
        }
        fn resolve(&self, symbol: &str) -> Option<KernelRef> {
            if symbol == "fuel_cpu_backend::byte_kernels::add_f32" {
                // THE point of the slice: the real production kernel.
                return Some(crate::dispatch::add_elementwise_f32_cpu_wrapper as KernelRef);
            }
            let mut g = self.seen.lock().unwrap();
            if let Some(k) = g.get(symbol) {
                return Some(*k);
            }
            let k: KernelRef = if g.len().is_multiple_of(2) {
                dummy_a
            } else {
                dummy_b
            };
            g.insert(symbol.to_string(), k);
            Some(k)
        }
    }
    impl LinkRegistry for EntryPointLink {
        fn resolve_primitive(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
        fn resolve_fused(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
    }

    #[test]
    fn import_add_f32_through_real_link_registry_binds_the_real_kernel() {
        // The vertical slice: import the authored CPU elementwise-binary
        // contract through a REAL LinkRegistry that resolves add_f32's
        // entry-point symbol to the production kernel wrapper, register it,
        // and prove the registered binding IS that real kernel — by pointer
        // identity AND by executing it on real F32 storage.
        let link = EntryPointLink::new();
        let provider = import_bundle_str(ELEMENTWISE_BINARY, &link)
            .expect("authored elementwise-binary.fkc.md imports through the real link");

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into a fresh table succeeds");

        let key = [DType::F32, DType::F32, DType::F32];
        // The contract registers TWO alternatives at this key: the shared
        // `binary` chassis representative and the concrete `add_f32` — so
        // `lookup` (first alternative) returns the chassis. We assert the real
        // add_f32 wrapper is present *among the alternatives* and invoke it.
        let expected: KernelRef = crate::dispatch::add_elementwise_f32_cpu_wrapper;
        let alts = table.lookup_alternatives(OpKind::AddElementwise, &key, BackendId::Cpu);
        assert!(
            !alts.is_empty(),
            "AddElementwise/[F32,F32,F32]/Cpu present after FKC import"
        );

        // (1) The FKC-imported binding IS the real production kernel — not a
        // stub, not a different fn — proven by pointer identity.
        let resolved: KernelRef = alts
            .iter()
            .map(|e| e.kernel)
            .find(|k| *k as usize == expected as usize)
            .expect("FKC import must bind the real add_f32 wrapper among the alternatives");

        // (2) It actually runs end-to-end on real F32 storage: [1,2,3]+[4,5,6].
        let a = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
            1.0f32, 2.0, 3.0,
        ])));
        let b = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
            4.0f32, 5.0, 6.0,
        ])));
        let out = Arc::new(RwLock::new(
            fuel_memory::alloc_cpu_zeroed(DType::F32, 3).expect("alloc out"),
        ));
        let inputs = [a, b];
        let mut outputs = [out];
        let shape = fuel_ir::Shape::from_dims(&[3]);
        let layouts = [
            fuel_ir::Layout::contiguous(shape.clone()),
            fuel_ir::Layout::contiguous(shape),
        ];
        resolved(
            &inputs,
            &mut outputs,
            &layouts,
            &crate::kernel::OpParams::None,
        )
        .expect("the FKC-resolved add_f32 kernel executes on real storage");
    }

    // =====================================================================
    // V-FKC-9 IMPORT-TIME GATE: unverified precision claims are downgraded
    // =====================================================================

    /// The V-FKC-9 gate downgrades a declared guarantee whose claims are not
    /// all backed, and the warning NAMES which ones.
    ///
    /// ⚠️ **This test has now expired twice on live data and is constructed
    /// because of it.** It first named `add_f32` and failed when the precision
    /// program earned that entry's claims. It was rewritten to LOCATE a
    /// downgraded entry, and failed again when the two contracts it searched
    /// became fully backed. It was widened to every CPU contract — and failed
    /// a third time, because **there are now zero unbacked declared claims on
    /// the whole CPU surface.**
    ///
    /// Each rewrite was a smaller version of the same mistake: sourcing a
    /// NEGATIVE case from data that the work under test is actively removing.
    /// A gate's "it fires" test cannot depend on something still being broken.
    /// So the unbacked case is now BUILT: an empty ledger backs nothing, so
    /// every declared claim is unbacked by construction, permanently.
    #[test]
    fn the_import_gate_downgrades_an_entry_whose_claims_are_not_all_backed() {
        use crate::fkc::verify::{LedgerQuery, VerificationLedger, gate_precision};
        use crate::fused::PrecisionGuarantee;

        let declared = PrecisionGuarantee {
            bit_stable_on_same_hardware: true,
            max_ulp: Some(0),
            ..PrecisionGuarantee::UNAUDITED
        };
        let dtypes = [DType::F32, DType::F32, DType::F32];
        let q = LedgerQuery {
            kernel_ref: "constructed",
            backend: fuel_ir::probe::BackendId::Cpu,
            dtypes: &dtypes,
            kernel_revision_hash: 0xDEAD_BEEF,
        };
        let mut warnings = Vec::new();
        let gated = gate_precision(declared, &q, &VerificationLedger::default(), &mut warnings);

        assert!(
            !gated.bit_stable_on_same_hardware && gated.max_ulp.is_none(),
            "an entry whose claims are backed by NOTHING must be downgraded whole"
        );
        assert_eq!(
            gated.notes,
            PrecisionGuarantee::UNAUDITED.notes,
            "the downgrade must land on the UNAUDITED sentinel, not a partial edit"
        );
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("bit_stable_on_same_hardware")
                    && w.message.contains("max_ulp")),
            "the warning must NAME both unbacked claims, or a census keyed on those \
             names reads a subset: {warnings:?}"
        );
    }

    /// **Earning one claim buys NOTHING while a sibling claim is unearned.**
    ///
    /// `gate_precision` collapses the WHOLE guarantee if ANY declared claim
    /// lacks a pass, so coverage of one claim does not convert into changed
    /// guarantees for dual-claim entries. That is invisible in a
    /// claim-coverage number and is exactly the inference a plan makes
    /// silently — converted into a test so it fails if someone makes it.
    ///
    /// Constructed for the same reason as the test above: a ledger holding
    /// exactly ONE of the two declared claims cannot be produced from live
    /// data any more, and depending on live data to still be broken is what
    /// expired the previous three versions.
    #[test]
    fn a_backed_claim_does_not_rescue_an_entry_whose_sibling_claim_is_unbacked() {
        // `LedgerRecord`'s re-export is feature-gated (`jit`/`cuda`), so reach
        // it by module path — this test is unconditional and must not become
        // one that only runs under a feature nobody's default build enables.
        use crate::fkc::verify::{LedgerQuery, LedgerRecord, VerificationLedger, gate_precision};
        use crate::fused::PrecisionGuarantee;

        let dtypes = [DType::F32, DType::F32, DType::F32];
        let rev = 0xDEAD_BEEF_u64;
        // A ledger that backs bit-stability and NOTHING ELSE.
        let ledger = VerificationLedger::from_records(vec![LedgerRecord {
            kernel_ref: "constructed".to_string(),
            backend: "Cpu".to_string(),
            dtypes: dtypes.iter().map(|d| format!("{d:?}")).collect(),
            kernel_revision_hash: rev,
            claim: "bit_stable_on_same_hardware".to_string(),
            result: "pass".to_string(),
            verified_at: "epoch:0".to_string(),
            protocol_version: 1,
            evidence: serde_json::Value::Null,
        }]);

        let q = LedgerQuery {
            kernel_ref: "constructed",
            backend: fuel_ir::probe::BackendId::Cpu,
            dtypes: &dtypes,
            kernel_revision_hash: rev,
        };

        // Control: the ledger really does back the bit-stable claim, so a
        // failure below is about the SIBLING and not about a lookup miss.
        assert!(
            ledger.has_pass(q.backend, q.dtypes, rev, "bit_stable_on_same_hardware"),
            "precondition: the constructed ledger must back bit-stability"
        );

        let declared = PrecisionGuarantee {
            bit_stable_on_same_hardware: true,
            max_ulp: Some(0),
            ..PrecisionGuarantee::UNAUDITED
        };
        let mut warnings = Vec::new();
        let gated = gate_precision(declared, &q, &ledger, &mut warnings);

        assert!(
            !gated.bit_stable_on_same_hardware,
            "ONE backed claim must not rescue an entry whose sibling is unbacked — the \
             whole guarantee collapses"
        );
        let named: Vec<&str> = warnings.iter().map(|w| w.message.as_str()).collect();
        assert!(
            named.iter().any(|m| m.contains("max_ulp")),
            "the warning must cite the UNBACKED sibling: {named:?}"
        );
        assert!(
            !named
                .iter()
                .any(|m| m.contains("[\"bit_stable_on_same_hardware\"")),
            "the BACKED claim must not be reported unbacked — that would mean the gate \
             does not discriminate per claim: {named:?}"
        );
    }

    #[test]
    fn cpu_link_registry_binds_elementwise_binary_to_live_kernels() {
        // The CPU backend is the first FKC conformance reference: import its
        // authored elementwise-binary contract through the PRODUCTION
        // CpuLinkRegistry (not a stub) and verify every (op, dtype) section
        // resolves to the real production wrapper — proving an imported
        // contract describes, and binds to, the live CPU kernels.
        let provider = import_bundle_str(ELEMENTWISE_BINARY, &crate::fkc::CpuLinkRegistry)
            .expect("elementwise-binary imports through the production CpuLinkRegistry");
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into a fresh table succeeds");

        // All 8 ops × 4 dtypes are bound from the contract.
        let ops = [
            OpKind::AddElementwise,
            OpKind::SubElementwise,
            OpKind::MulElementwise,
            OpKind::DivElementwise,
            OpKind::MaximumElementwise,
            OpKind::MinimumElementwise,
            OpKind::PowElementwise,
            OpKind::RemElementwise,
        ];
        let dts = [DType::F32, DType::F64, DType::F16, DType::BF16];
        for op in ops {
            for dt in dts {
                assert!(
                    table.lookup(op, &[dt, dt, dt], BackendId::Cpu).is_ok(),
                    "{op:?}/{dt:?} must be bound from the imported contract",
                );
            }
        }

        // Spot-check two distinct (op, dtype) resolve to the EXACT production
        // wrappers — the link registry bound real symbols, not stubs.
        let add_f32 = table
            .lookup(OpKind::AddElementwise, &[DType::F32; 3], BackendId::Cpu)
            .unwrap();
        assert_eq!(
            add_f32 as usize,
            crate::dispatch::add_elementwise_f32_cpu_wrapper as *const () as usize,
        );
        let pow_bf16 = table
            .lookup(OpKind::PowElementwise, &[DType::BF16; 3], BackendId::Cpu)
            .unwrap();
        assert_eq!(
            pow_bf16 as usize,
            crate::dispatch::pow_elementwise_bf16_cpu_wrapper as *const () as usize,
        );

        assert!(
            table.finalize().is_ok(),
            "finalize is Ok after a real-link import"
        );
    }

    // =====================================================================
    // FUSED SEAM: the production CpuLinkRegistry resolves a REAL authored
    // `fused_op` bundle's entry_point symbols to the live CPU fused wrappers
    // (the fused analogue of the elementwise-binary live-kernel test above).
    // =====================================================================

    /// The authored norm/softmax FUSED bundle — every section declares
    /// `fused_op:` (a `FusedOps::*` id), not `op_kind:`.
    const FUSED_NORM_SOFTMAX: &str =
        include_str!("../../../docs/kernel-contracts/fused/norm-softmax.fkc.md");

    #[test]
    fn cpu_link_registry_binds_norm_softmax_fused_ops_to_live_kernels() {
        // BORN-RED → GREEN (fused dtype-fan, §3.4). Each `fused_op` section
        // enumerates `dtypes: [F32, F64, BF16, F16]` on a BASE `entry_point`, so
        // `lower_fused` now FANS it into 4 per-dtype impls, each resolving
        // `<base>_<dt>` through `CPU_FUSED_NORM_ENTRY_POINTS`. Before the table
        // grew to its 32 per-dtype rows, the fanned symbols (e.g.
        // `…::softmax_last_dim_cpu_f32`) resolved to `None` → `UnknownEntryPoint`
        // and this import errored (RED). With the 32-row table every fanned
        // symbol binds the ACTUAL per-dtype production wrapper (GREEN) — a 1:1
        // replacement for the hand-written `register_default_fused_kernels`
        // per-dtype registrations, not just the F32 representative.
        let provider = import_bundle_str(FUSED_NORM_SOFTMAX, &crate::fkc::CpuLinkRegistry).expect(
            "authored norm-softmax fused bundle imports through the production CpuLinkRegistry",
        );
        // A fused-only bundle: no primitive `op_kind` sections. The 8 sections
        // each fan over 4 dtypes ⇒ 32 fused impls.
        assert!(
            provider.primitives.is_empty(),
            "norm-softmax declares only fused ops",
        );
        assert_eq!(
            provider.fused.len(),
            32,
            "8 fused sections × 4 dtypes = 32 per-dtype impls (fused dtype-fan)",
        );

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into fresh registries succeeds");

        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];

        // Each FORWARD op (key `[dt, dt]`) binds all 4 dtypes to the EXACT
        // per-dtype production wrapper — proven by pointer identity — and carries
        // the contract's REAL revision hash (hand-written regs stamp UNTRACKED).
        let forward = [
            (
                FusedOps::SOFTMAX_LAST_DIM,
                [
                    crate::dispatch::softmax_last_dim_f32_cpu_wrapper as *const () as usize,
                    crate::dispatch::softmax_last_dim_f64_cpu_wrapper as *const () as usize,
                    crate::dispatch::softmax_last_dim_bf16_cpu_wrapper as *const () as usize,
                    crate::dispatch::softmax_last_dim_f16_cpu_wrapper as *const () as usize,
                ],
            ),
            (
                FusedOps::RMS_NORM_LAST_DIM,
                [
                    crate::dispatch::rms_norm_last_dim_f32_cpu_wrapper as *const () as usize,
                    crate::dispatch::rms_norm_last_dim_f64_cpu_wrapper as *const () as usize,
                    crate::dispatch::rms_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
                    crate::dispatch::rms_norm_last_dim_f16_cpu_wrapper as *const () as usize,
                ],
            ),
            (
                FusedOps::LAYER_NORM_LAST_DIM,
                [
                    crate::dispatch::layer_norm_last_dim_f32_cpu_wrapper as *const () as usize,
                    crate::dispatch::layer_norm_last_dim_f64_cpu_wrapper as *const () as usize,
                    crate::dispatch::layer_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
                    crate::dispatch::layer_norm_last_dim_f16_cpu_wrapper as *const () as usize,
                ],
            ),
        ];
        for (id, wrappers) in forward {
            for (dt, expected) in dts.iter().zip(wrappers) {
                let got = fused
                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt])
                    .unwrap_or_else(|| panic!("{id:?} {dt:?} fused impl bound from the contract"));
                assert_eq!(
                    got.kernel as usize, expected,
                    "{id:?} {dt:?} binds its exact per-dtype production wrapper",
                );
                assert_ne!(
                    got.revision,
                    KernelRevisionHash::UNTRACKED,
                    "FKC import stamps the contract's real revision (hand-written stamps UNTRACKED)",
                );
            }
        }

        // Each BACKWARD op (key `[dt, dt, dt]`) binds all 4 dtypes to the EXACT
        // per-dtype production wrapper.
        let backward = [
            (
                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
                [
                    crate::dispatch::softmax_last_dim_backward_f32_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::softmax_last_dim_backward_f64_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::softmax_last_dim_backward_bf16_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::softmax_last_dim_backward_f16_cpu_wrapper as *const ()
                        as usize,
                ],
            ),
            (
                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
                [
                    crate::dispatch::layer_norm_last_dim_backward_f32_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::layer_norm_last_dim_backward_f64_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::layer_norm_last_dim_backward_bf16_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::layer_norm_last_dim_backward_f16_cpu_wrapper as *const ()
                        as usize,
                ],
            ),
            (
                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
                [
                    crate::dispatch::rms_norm_last_dim_backward_f32_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::rms_norm_last_dim_backward_f64_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::rms_norm_last_dim_backward_bf16_cpu_wrapper as *const ()
                        as usize,
                    crate::dispatch::rms_norm_last_dim_backward_f16_cpu_wrapper as *const ()
                        as usize,
                ],
            ),
            (
                FusedOps::REDUCE_MAX_TO_BACKWARD,
                [
                    crate::dispatch::reduce_max_to_backward_f32_cpu_wrapper as *const () as usize,
                    crate::dispatch::reduce_max_to_backward_f64_cpu_wrapper as *const () as usize,
                    crate::dispatch::reduce_max_to_backward_bf16_cpu_wrapper as *const () as usize,
                    crate::dispatch::reduce_max_to_backward_f16_cpu_wrapper as *const () as usize,
                ],
            ),
            (
                FusedOps::POWI_BACKWARD,
                [
                    crate::dispatch::powi_backward_f32_cpu_wrapper as *const () as usize,
                    crate::dispatch::powi_backward_f64_cpu_wrapper as *const () as usize,
                    crate::dispatch::powi_backward_bf16_cpu_wrapper as *const () as usize,
                    crate::dispatch::powi_backward_f16_cpu_wrapper as *const () as usize,
                ],
            ),
        ];
        for (id, wrappers) in backward {
            for (dt, expected) in dts.iter().zip(wrappers) {
                let got = fused
                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt, *dt])
                    .unwrap_or_else(|| panic!("{id:?} {dt:?} fused impl bound from the contract"));
                assert_eq!(
                    got.kernel as usize, expected,
                    "{id:?} {dt:?} binds its exact per-dtype production wrapper",
                );
            }
        }
    }

    // =====================================================================
    // §5 RETURN-CONTRACT CROSS-CHECK: a fused contract's declared shape_rule /
    // dtype_rule must agree with the REAL registered `FusedOpEntry` fn — the
    // born-red test for Task 3.3 (Finding 5.1).
    // =====================================================================

    #[test]
    fn fused_contract_shape_rule_disagreeing_with_registered_fn_is_rejected() {
        // Real SoftmaxLastDim dtype_rule is passthrough(input0) = F32 at the F32 probe.
        // Mutate ONLY the first section's declared dtype_rule to fixed(F16): now it
        // disagrees with the registered fused fn at every probe combo → hard reject.
        let mutated =
            FUSED_NORM_SOFTMAX.replacen("dtype_rule: passthrough(x)", "dtype_rule: fixed(F16)", 1);
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a return rule that disagrees with the registered fused fn must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn unmutated_fused_corpus_still_imports_after_return_check() {
        import_bundle_str(FUSED_NORM_SOFTMAX, &crate::fkc::CpuLinkRegistry)
            .expect("real corpus return rules agree with the registered fused fns");
    }

    // =====================================================================
    // Convergence-C C-3: the shape-oracle cross-check ACTIVATED across the
    // remaining expressible fused ops. Each op below is proven to FIRE (not
    // merely import clean) by a MUTATION that makes the DECLARED shape rule
    // disagree with the REAL registered FusedOpEntry fn — a skipped/dormant
    // cross-check would let the mutated import succeed (the false-green risk).
    // The unmutated companions prove the real contracts AGREE.
    //
    // NOTE (adversarial fix, review Finding 2): the `const(N)` mutations below
    // change the output RANK, so they only ever proved RANK discrimination. The
    // GQA probe is now shape-DISTINCT (Hq = 2*Hkv), so a same-rank OPERAND-ROLE
    // drift is caught too — see `flash_attn_backward_k_operand_role_swap_is_rejected`
    // (dK `same_as(k)` mis-declared as `same_as(q)`), which used to import clean.
    // =====================================================================

    /// Finding 1 (arity pre-check): a synthetic 3-input FLASH_ATTN contract
    /// (q/k/v, no alibi) — the shape of the metal `matmul-attn.fkc.md`
    /// `sdpa_vector` sections. Its declared FLASH_ATTN registry fn
    /// `debug_assert!`s 4-or-5 inputs, so a 3-input probe panics in DEBUG (caught
    /// + skipped) but is stripped in RELEASE (fn reads operand 0) — the
    ///
    /// debug-vs-release split. The arity pre-check must skip it CONSISTENTLY in
    /// both build modes with a warning (not a silent debug-only skip).
    const SYNTH_FLASH_ATTN_3IN: &str = r#"---
fkc_version: 1
provider:
  name: synth-attn-3input
  backend: Cpu
  kernel_source: "portable-cpu"
---

# synthetic 3-input FLASH_ATTN (Finding 1 arity pre-check)

## flash_attn_3in

Synthetic 3-input flash attention (q, k, v) to exercise the arity pre-check.

```fkc
kernel: flash_attn_3in
fused_op: FLASH_ATTN
blurb: "synthetic 3-input flash attn (q,k,v) to exercise the arity pre-check"
backend: Cpu
kernel_source: "portable-cpu"
entry_point: "synthetic::flash_attn_3in_cpu"
kernel_revision_hash: auto

accept:
  inputs:
    - name: q
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 4
    - name: k
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 4
    - name: v
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 4
  op_params:
    variant: FlashAttn
    fields:
      softmax_scale:     { kind: f32 }
      causal:            { kind: bool }
      window_size_left:  { kind: "Option<usize>" }
      window_size_right: { kind: "Option<usize>" }
      softcap:           { kind: "Option<f32>" }
      k_len:             { kind: DynScalar }

return:
  outputs:
    - name: out
      dtype_rule: passthrough(q)
      shape_rule: same_as(q)
      layout_guarantee: contiguous
      aliasing: none

caps:
  awkward_layout_strategy: requires_contiguous
  in_place: false

cost:
  provenance: judge_measured
  class: attention

precision:
  bit_stable_on_same_hardware: false
  max_ulp: ~
  max_relative: ~
  max_absolute: ~
  audited: false
  notes: "synthetic"

determinism: same_hardware_bitwise
```
"#;

    /// The three fused-op bundles whose cross-checks C-3 turns on.
    const FUSED_ATTENTION: &str =
        include_str!("../../../docs/kernel-contracts/fused/attention.fkc.md");
    const FUSED_LINEAR_QUANT: &str =
        include_str!("../../../docs/kernel-contracts/fused/linear-quant.fkc.md");
    const FUSED_CONV_ROPE: &str =
        include_str!("../../../docs/kernel-contracts/fused/conv-rope.fkc.md");

    /// Replace `from` → `to` exactly once, asserting `from` occurs EXACTLY once
    /// in `src` — so a mutation test can never silently no-op (a 0-count replace
    /// would leave the bundle unmutated and hide a cross-check that never fired).
    /// GAP-175: the anchor is located **whitespace-tolerantly** (see
    /// [`find_ws_tolerant`]) so a `.fkc.md` reflow cannot break these tests.
    /// **The EXACTLY-ONCE guard is unchanged, deliberately** — loosening the
    /// ANCHOR and loosening the COUNT are different changes and only the first
    /// is wanted. A 0- or 2-count must still fail loudly.
    fn mutate_once(src: &str, from: &str, to: &str) -> String {
        let spans = find_ws_tolerant(src, from);
        assert_eq!(
            spans.len(),
            1,
            "mutation anchor `{from}` must occur EXACTLY once (got {}). \
             NOTE (GAP-175): anchors are matched WHITESPACE-TOLERANTLY — a run \
             of spaces matches one-or-more — so a count of 0 is NOT a column \
             alignment problem in the .fkc.md. Look for a changed token, a \
             reworded comment, or a removed contract section instead.",
            spans.len()
        );
        let (start, end) = spans[0];
        format!("{}{}{}", &src[..start], to, &src[end..])
    }

    /// Locate `needle` in `hay` treating **each run of spaces in `needle` as
    /// "one or more spaces"**; every other character matches exactly. Returns
    /// non-overlapping match spans as byte ranges.
    ///
    /// GAP-175: the mutation anchors below quote lines out of `.fkc.md` contract
    /// files whose columns are PADDED for readability, e.g.
    /// `same_as(q)<17 spaces># FusedOp.shape_rule = q shape`. Under exact
    /// matching that padding is load-bearing — realign a table, run a formatter,
    /// reflow a comment, and the anchor silently stops matching, reporting a
    /// MISSING ANCHOR and sending the reader after a contract-parsing bug that
    /// does not exist. Matching space runs elastically makes these tests depend
    /// on the contract's CONTENT rather than its FORMATTING, which was always
    /// the intent.
    ///
    /// Deliberately hand-rolled: `fuel-dispatch` has no `regex` dependency (nor
    /// a dev-dependency on one), and a test helper does not justify adding one.
    fn find_ws_tolerant(hay: &str, needle: &str) -> Vec<(usize, usize)> {
        let h: Vec<(usize, char)> = hay.char_indices().collect();
        let n: Vec<char> = needle.chars().collect();
        let mut out = Vec::new();
        if n.is_empty() {
            return out;
        }
        let mut i = 0usize;
        while i < h.len() {
            let mut hi = i;
            let mut ni = 0usize;
            let matched = loop {
                if ni == n.len() {
                    break true;
                }
                if n[ni] == ' ' {
                    // A run of spaces in the needle consumes 1+ spaces in the hay.
                    let mut seen = 0usize;
                    while hi < h.len() && h[hi].1 == ' ' {
                        hi += 1;
                        seen += 1;
                    }
                    if seen == 0 {
                        break false;
                    }
                    while ni < n.len() && n[ni] == ' ' {
                        ni += 1;
                    }
                } else {
                    if hi >= h.len() || h[hi].1 != n[ni] {
                        break false;
                    }
                    hi += 1;
                    ni += 1;
                }
            };
            if matched {
                let start = h[i].0;
                let end = if hi < h.len() { h[hi].0 } else { hay.len() };
                out.push((start, end));
                i = hi.max(i + 1); // non-overlapping
            } else {
                i += 1;
            }
        }
        out
    }

    /// **GAP-175 born-red witness: a `.fkc.md` reflow must not break a mutation
    /// anchor.** The exact-match form finds the anchor in the aligned text and
    /// NOT in the reflowed text — that is the defect, demonstrated rather than
    /// asserted. The whitespace-tolerant form finds it in both.
    #[test]
    fn mutation_anchor_survives_a_contract_reflow() {
        let aligned = "  - { name: dq, dtype_rule: passthrough(q), \
                       shape_rule: same_as(q)                 # FusedOp.shape_rule_q\n";
        // The SAME content with the column padding collapsed — an innocuous
        // reflow, the event this row is about.
        let reflowed = "  - { name: dq, dtype_rule: passthrough(q), \
                        shape_rule: same_as(q)   # FusedOp.shape_rule_q\n";
        let anchor = "shape_rule: same_as(q)                 # FusedOp.shape_rule_q";

        // The old behaviour, kept as the CONTRAST that makes this test mean
        // something: exact matching is what breaks.
        assert_eq!(
            aligned.matches(anchor).count(),
            1,
            "exact match works on the aligned text"
        );
        assert_eq!(
            reflowed.matches(anchor).count(),
            0,
            "exact match FAILS after a reflow — this is the defect GAP-175 names"
        );

        // The fix: content-dependent, not formatting-dependent.
        assert_eq!(find_ws_tolerant(aligned, anchor).len(), 1);
        assert_eq!(
            find_ws_tolerant(reflowed, anchor).len(),
            1,
            "GAP-175: a column reflow must NOT break the anchor"
        );
        let out = mutate_once(
            reflowed,
            anchor,
            "shape_rule: const(9) # FusedOp.shape_rule_q",
        );
        assert!(
            out.contains("const(9)"),
            "the mutation applies to the reflowed text"
        );
        assert!(!out.contains("same_as(q)"), "and the original rule is gone");
    }

    /// GAP-175: loosening the ANCHOR must not loosen the COUNT guard. A 0-count
    /// is the case that would silently no-op and hide a cross-check that never
    /// fired, so it must still panic.
    #[test]
    #[should_panic(expected = "must occur EXACTLY once")]
    fn mutate_once_still_rejects_a_zero_count() {
        mutate_once("shape_rule: same_as(q)\n", "shape_rule: same_as(NOPE)", "x");
    }

    /// GAP-175: and a 2-count must still panic — whitespace tolerance widens
    /// what matches, so the ambiguity guard matters MORE, not less.
    #[test]
    #[should_panic(expected = "must occur EXACTLY once")]
    fn mutate_once_still_rejects_a_multiple_count() {
        mutate_once("a  b\nand again a b\n", "a b", "x");
    }

    /// A link registry that resolves EVERY symbol to a no-op kernel. The
    /// graph-side fused `attention.fkc.md` is a spec contract for the registry's
    /// `FusedOpEntry` (`shape_rule`/`dtype_rule`) and is NOT bound on the CPU
    /// `CpuLinkRegistry` (its CPU kernels come from the PRIMITIVE
    /// `cpu/attention.fkc.md`), so its `flash_attn_cpu_*` entry points do not
    /// resolve there. The cross-check runs BEFORE entry resolution and uses the
    /// REAL `default_registry()` fns regardless of link, so a resolve-anything
    /// stub isolates the cross-check under test from the (irrelevant here) CPU
    /// binding step.
    struct StubResolveAll;
    fn stub_kernel(
        _inputs: &[std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
        _outputs: &mut [std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
        _layouts: &[fuel_ir::Layout],
        _params: &crate::kernel::OpParams,
    ) -> fuel_ir::Result<()> {
        Ok(())
    }
    impl crate::fkc::lower::LinkRegistry for StubResolveAll {
        fn resolve_primitive(&self, _symbol: &str) -> Option<crate::kernel::KernelRef> {
            Some(stub_kernel)
        }
        fn resolve_fused(&self, _symbol: &str) -> Option<crate::kernel::KernelRef> {
            Some(stub_kernel)
        }
    }

    // ---- Tier 1: same_as / bundle cross-checks (synth-gated) ----

    #[test]
    fn inplace_affine_cross_check_fires() {
        // InplaceAffine now synth-supported; its `same_as(x)` (= input 0) is
        // evaluable. Mutating it to a rank-1 `const(9)` disagrees with the real
        // registry fn (which returns x's shape) at every probe → hard reject.
        let mutated = mutate_once(
            FUSED_LINEAR_QUANT,
            "shape_rule: same_as(x)",
            "shape_rule: const(9)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a mutated InplaceAffine shape_rule must be rejected (proves the check FIRES)",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn fused_linear_matmul_cross_check_fires() {
        // fused_linear declares the whole-shape `matmul(a, b)` rule (Tier-3),
        // now evaluable. The registry fn is `matmul_output_shape` (= a_batch ++
        // [M, N]); the UNMUTATED contract agrees (proven below). Mutate the rule
        // to `same_as(bias)` (rank-1 [N]) — disagrees with the rank-2 [M, N]
        // matmul output at every probe → hard reject (proves the check FIRES).
        let mutated = mutate_once(
            FUSED_LINEAR_QUANT,
            "shape_rule: matmul(a, b)",
            "shape_rule: same_as(bias)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a mutated fused_linear shape_rule must be rejected (proves the matmul check FIRES)",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn flash_attn_cross_check_fires() {
        // FlashAttn out = same_as(q) (Tier-2 doc fix from from_params(q)); the
        // registry fn returns input 0 (q). Mutate ONLY the value to a rank-1
        // const, preserving the `#` comment (the `q shape` tail is unique to
        // FlashAttn vs PagedAttn's `q (decode)` and dQ's `shape_rule_q`).
        let anchor = "same_as(q)                 # FusedOp.shape_rule = q shape";
        let mutated = mutate_once(
            FUSED_ATTENTION,
            anchor,
            "const(9) # FusedOp.shape_rule = q shape",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll)
            .expect_err("a mutated FlashAttn shape_rule must be rejected (proves the check FIRES)");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn paged_attn_cross_check_fires() {
        // PagedAttn out = same_as(q) (Tier-2 doc fix from from_params(q)); the
        // registry fn returns input 0 (q). Mutate ONLY the value, preserving the
        // `#` comment (`q (decode)` is unique to PagedAttn).
        let anchor = "same_as(q)                 # FusedOp.shape_rule = q (decode)";
        let mutated = mutate_once(
            FUSED_ATTENTION,
            anchor,
            "const(9) # FusedOp.shape_rule = q (decode)",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll)
            .expect_err("a mutated PagedAttn shape_rule must be rejected (proves the check FIRES)");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn flash_attn_backward_q_cross_check_fires() {
        // dQ = same_as(q) (= input 0). FLASH_ATTN_BACKWARD_{Q,K,V} share the
        // FlashAttnBackward variant, now synth-supported. Mutate dQ's rule.
        // (Stub link: attention is a graph-side spec contract, not CPU-bound.)
        let mutated = mutate_once(
            FUSED_ATTENTION,
            "shape_rule: same_as(q)                 # FusedOp.shape_rule_q",
            "shape_rule: const(9)                   # FusedOp.shape_rule_q",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll)
            .expect_err("a mutated FlashAttnBackwardQ shape_rule must be rejected");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn flash_attn_backward_k_cross_check_fires() {
        // dK = same_as(k) (= input 1); `same_as(k)` (parenthesised) is unique.
        let mutated = mutate_once(
            FUSED_ATTENTION,
            "shape_rule: same_as(k)",
            "shape_rule: const(9)",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll)
            .expect_err("a mutated FlashAttnBackwardK shape_rule must be rejected");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn flash_attn_backward_v_cross_check_fires() {
        // dV = same_as(v) (= input 2); `same_as(v)` (parenthesised) is unique.
        let mutated = mutate_once(
            FUSED_ATTENTION,
            "shape_rule: same_as(v)",
            "shape_rule: const(9)",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll)
            .expect_err("a mutated FlashAttnBackwardV shape_rule must be rejected");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn selective_scan_bundle_cross_check_fires() {
        // SelectiveScan now synth-supported ⇒ the bundle arity check runs.
        // Add a phantom 3rd slot: declared 3 ≠ real output_views arity 2.
        let ys = "- { name: y,          dtype_rule: passthrough(u), shape_rule: same_as(u),               layout_guarantee: contiguous }";
        let mutated = mutate_once(
            FUSED_CONV_ROPE,
            ys,
            &format!(
                "{ys}\n    - {{ name: phantom, dtype_rule: passthrough(u), shape_rule: same_as(u), layout_guarantee: contiguous }}"
            ),
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry)
            .expect_err("a SelectiveScan bundle with a phantom slot must be rejected");
        assert!(
            matches!(err, FkcError::BundleArityMismatch { .. }),
            "expected BundleArityMismatch, got {err:?}"
        );
    }

    #[test]
    fn ssd_chunk_scan_bundle_cross_check_fires() {
        // SsdChunkScan now synth-supported ⇒ the bundle arity check runs.
        let ys = "- { name: y,          dtype_rule: passthrough(x), shape_rule: same_as(x),               layout_guarantee: contiguous }";
        let mutated = mutate_once(
            FUSED_CONV_ROPE,
            ys,
            &format!(
                "{ys}\n    - {{ name: phantom, dtype_rule: passthrough(x), shape_rule: same_as(x), layout_guarantee: contiguous }}"
            ),
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry)
            .expect_err("an SsdChunkScan bundle with a phantom slot must be rejected");
        assert!(
            matches!(err, FkcError::BundleArityMismatch { .. }),
            "expected BundleArityMismatch, got {err:?}"
        );
    }

    #[test]
    fn unmutated_c3_bundles_still_import_after_activation() {
        // The real contracts AGREE with the registered fns across every probe.
        // linear-quant + conv-rope are CPU-bound (production import path).
        import_bundle_str(FUSED_LINEAR_QUANT, &crate::fkc::CpuLinkRegistry)
            .expect("linear-quant bundle return rules agree with the registered fused fns");
        import_bundle_str(FUSED_CONV_ROPE, &crate::fkc::CpuLinkRegistry)
            .expect("conv-rope bundle return rules agree with the registered fused fns");
        // attention is a graph-side spec contract (not CPU-bound); the cross-check
        // still validates its declared rules against the registry fns.
        import_bundle_str(FUSED_ATTENTION, &StubResolveAll)
            .expect("attention bundle return rules agree with the registered fused fns");
    }

    // =====================================================================
    // Convergence-C C-3 adversarial fix — FINDING 1 (guard_rule warn +
    // arity pre-check closes the debug-vs-release split).
    // =====================================================================

    #[test]
    fn under_arity_flash_attn_skips_differential_consistently_and_warns() {
        // A 3-input FLASH_ATTN contract (the metal `matmul-attn` `sdpa_vector`
        // shape) feeds a 3-input probe to the registry flash_attn fn whose
        // `debug_assert!(len == 4 || 5)` PANICS in a debug build but is stripped
        // in release. The arity pre-check must skip the differential CONSISTENTLY
        // across build modes and record a warning (no silent, debug-only skip).
        // Import succeeds (never-panic) and the warning fires.
        let provider = import_bundle_str(SYNTH_FLASH_ATTN_3IN, &StubResolveAll)
            .expect("a 3-input FLASH_ATTN contract imports (no panic, no debug-only silent skip)");
        assert!(
            provider
                .warnings
                .iter()
                .any(|w| w.message.contains("requires >= 4") && w.message.contains("skipped")),
            "the under-arity attention differential must be skipped WITH a warning \
             (consistent debug/release): {:?}",
            provider.warnings,
        );
    }

    // =====================================================================
    // Convergence-C C-3 adversarial fix — FINDING 2 (GQA probe now
    // shape-DISTINCT: an operand-role swap in a return rule is caught).
    // =====================================================================

    #[test]
    fn flash_attn_backward_k_operand_role_swap_is_rejected() {
        // With the GQA probe now shape-DISTINCT (Hq = 2*Hkv via the cross-operand
        // `divisible(q.dim[1], k.dim[1])`), a realistic operand-role drift — dK's
        // `shape_rule: same_as(k)` mis-authored as `same_as(q)` — is genuinely
        // caught: the declared q shape [.,2*Hkv,.,.] differs from the registry dK
        // oracle (input 1 = k) [.,Hkv,.,.]. Before the fix q/k seeded identically
        // and this swap imported clean (the const(9) mutation only proved RANK
        // discrimination). Proves operand-role drift is now caught, not just rank.
        let mutated = mutate_once(
            FUSED_ATTENTION,
            "shape_rule: same_as(k)",
            "shape_rule: same_as(q)",
        );
        let err = import_bundle_str(&mutated, &StubResolveAll).expect_err(
            "dK same_as(k) mis-declared as same_as(q) must be rejected (operand-role drift)",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    // =====================================================================
    // Convergence-C C-3 adversarial fix — FINDING 3 (bundle slot shapes are
    // now differentially compared to the output_views oracle).
    // =====================================================================

    #[test]
    fn selective_scan_bundle_slot_content_drift_is_rejected() {
        // A SAME-RANK content drift in a bundle slot — SelectiveScan slot 0
        // declared `same_as(b)` instead of `same_as(u)` (both rank 3) — was
        // previously uncaught: the bundle block only checked arity + rank (<= 6),
        // never comparing an evaluated slot shape to the output_views oracle.
        // Over the now role-DISTINCT bundle probe (u [2,2,2] vs bumped b [5,2,2])
        // the drift diverges from the oracle (u-derived [2,2,2]) and is rejected.
        // Stays within §4 (reference = output_views, not decompose).
        let mutated = mutate_once(
            FUSED_CONV_ROPE,
            "shape_rule: same_as(u)",
            "shape_rule: same_as(b)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a same-rank bundle slot content drift (same_as(u) -> same_as(b)) must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    // =====================================================================
    // C-4 T3: the cross-check loops over synthesized param POINTS, so the
    // dtype differentials for the params-DEPENDENT fused ops (Conv2D /
    // ConvTranspose2D / QMatMul / FusedSoftmaxCrossEntropy / CausalConv1d)
    // are now LIVE. Each op is proven to FIRE by a dtype mutation that
    // disagrees with the real registered fn (a dormant differential would
    // let the mutated import succeed — the false-green risk); the unmutated
    // corpus, which agrees, stays importable WITHOUT any guard-caught panic
    // (no debug-only skips hiding under the differential).
    // =====================================================================

    /// EOL-normalize an embedded corpus file. `include_str!` carries the
    /// CHECKOUT's line endings (CRLF on an autocrlf Windows tree, LF
    /// elsewhere), so a multi-line mutation anchor written with `\n` would
    /// fail `mutate_once`'s exactly-once assert on one convention and pass on
    /// the other. Normalizing to LF makes the two-line anchors below
    /// checkout-independent; the FKC parser accepts either convention.
    fn lf(src: &str) -> String {
        src.replace("\r\n", "\n")
    }

    #[test]
    fn fsce_dtype_differential_fires() {
        // FSCE's real registered dtype fn is CONSTANT F32 (the loss
        // accumulator dtype), independent of inputs and params. A contract
        // declaring `fixed(F16)` must be rejected. Before C-4 T3 the FSCE
        // differential never ran at all (`synth_probe_params` returns None
        // for params-dependent variants), so this exact mutation imported
        // clean — the plan's mutation proof that enforcement is now live.
        let mutated = mutate_once(
            FUSED_LINEAR_QUANT,
            "dtype_rule: fixed(F32)          # ALWAYS F32 regardless of input dtype",
            "dtype_rule: fixed(F16)          # ALWAYS F32 regardless of input dtype",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "an FSCE dtype_rule disagreeing with the constant-F32 real fn must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn qmatmul_dtype_differential_fires() {
        // QMatMul's real dtype fn returns input 0 (`a`, F32 at every probe —
        // the contract declares a: [F32]). Declaring fixed(F16) disagrees.
        let mutated = mutate_once(
            FUSED_LINEAR_QUANT,
            "dtype_rule: fixed(F32)          # output is always F32 (dequant-and-contract); = a (F32)",
            "dtype_rule: fixed(F16)          # output is always F32 (dequant-and-contract); = a (F32)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a QMatMul dtype_rule disagreeing with the real passthrough fn must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn conv2d_dtype_differential_fires() {
        // Conv2D's real dtype fn is passthrough(x) (= F32 at the probes; x's
        // first declared dtype). Declaring fixed(F64) disagrees. The bare
        // `dtype_rule: passthrough(x)` line is shared by 4 sections, so the
        // anchor spans into the section-unique shape_rule line (LF-normalized).
        let mutated = mutate_once(
            &lf(FUSED_CONV_ROPE),
            "dtype_rule: passthrough(x)\n      shape_rule: conv2d(params)",
            "dtype_rule: fixed(F64)\n      shape_rule: conv2d(params)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a Conv2D dtype_rule disagreeing with the real passthrough fn must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn conv_transpose2d_dtype_differential_fires() {
        // ConvTranspose2D probes carry 3 operands (x, weight, optional bias —
        // the solver includes optional operands), so this differential also
        // pins the registry fn's 2-or-3 arity tolerance: were the fn still
        // `debug_assert_eq!(len, 2)`, a debug build would guard-catch the
        // panic and SKIP (import clean → this test fails), while release
        // checked — the exact debug-vs-release split the pre-check work bans.
        let mutated = mutate_once(
            &lf(FUSED_CONV_ROPE),
            "dtype_rule: passthrough(x)\n      shape_rule: conv_transpose2d(params)",
            "dtype_rule: fixed(F64)\n      shape_rule: conv_transpose2d(params)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry)
            .expect_err("a ConvTranspose2D dtype_rule disagreeing with the real passthrough fn must be rejected");
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    #[test]
    fn causal_conv1d_dtype_differential_fires() {
        let mutated = mutate_once(
            &lf(FUSED_CONV_ROPE),
            "dtype_rule: passthrough(x)\n      shape_rule: from_params(seq_out)",
            "dtype_rule: fixed(F64)\n      shape_rule: from_params(seq_out)",
        );
        let err = import_bundle_str(&mutated, &crate::fkc::CpuLinkRegistry).expect_err(
            "a CausalConv1d dtype_rule disagreeing with the real passthrough fn must be rejected",
        );
        assert!(
            matches!(err, FkcError::ShapeRuleMismatch { .. }),
            "expected ShapeRuleMismatch, got {err:?}"
        );
    }

    /// C-4 T3 (regression + never-panic): the UNMUTATED corpus imports with
    /// its now-live dtype differentials actually RUNNING — and none of them
    /// leans on a guard-caught panic (a `guard_rule` catch would push a
    /// "panicked" warning and silently skip the differential in debug builds
    /// only). The params-dependent ops' `conv2d(params)`/`from_params(...)`
    /// SHAPE rules remain non-evaluable → documented skips, unchanged.
    #[test]
    fn unmutated_corpus_dtype_differentials_run_without_guard_panics() {
        for (src, name) in [
            (FUSED_LINEAR_QUANT, "linear-quant"),
            (FUSED_CONV_ROPE, "conv-rope"),
        ] {
            let provider = import_bundle_str(src, &crate::fkc::CpuLinkRegistry)
                .unwrap_or_else(|e| panic!("{name} must import clean: {e:?}"));
            let panicked: Vec<_> = provider
                .warnings
                .iter()
                .filter(|w| w.message.contains("panicked"))
                .collect();
            assert!(
                panicked.is_empty(),
                "{name}: live differentials must not rely on guard-caught panics \
                 (debug-only skips): {panicked:?}",
            );
        }
    }

    /// C-4 T3 (Conv2D arity pre-check): a synthetic 1-input CONV2D contract.
    /// The registry conv2d rule fns read `input_shapes[1]` / assert 2-or-3
    /// inputs, so an under-declared contract must be skipped CONSISTENTLY in
    /// debug and release with a warning — mirroring the attention-family
    /// pre-check (real 2-input CONV2D fused sections exist in
    /// `vulkan/conv-attn-rope.fkc.md`, so the under-declaration risk is live).
    const SYNTH_CONV2D_1IN: &str = r#"---
fkc_version: 1
provider:
  name: synth-conv2d-1input
  backend: Cpu
  kernel_source: "portable-cpu"
---

# synthetic 1-input CONV2D (C-4 T3 arity pre-check)

## conv2d_1in

Synthetic 1-input Conv2D (x only, no weight) to exercise the arity pre-check.

```fkc
kernel: conv2d_1in
fused_op: CONV2D
blurb: "synthetic 1-input conv2d (x only) to exercise the arity pre-check"
backend: Cpu
kernel_source: "portable-cpu"
entry_point: "synthetic::conv2d_1in_cpu"
kernel_revision_hash: auto

accept:
  inputs:
    - name: x
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 4
  op_params:
    variant: Conv2D
    fields:
      stride:  { kind: "(usize, usize)" }
      padding: { kind: "(usize, usize)" }
      groups:  { kind: usize }

return:
  outputs:
    - name: out
      dtype_rule: passthrough(x)
      shape_rule: conv2d(params)
      layout_guarantee: contiguous

caps:
  awkward_layout_strategy: requires_contiguous
  in_place: false

cost:
  provenance: judge_measured
  class: conv

precision:
  bit_stable_on_same_hardware: false
  max_ulp: ~
  max_relative: ~
  max_absolute: ~
  audited: false
  notes: "synthetic"

determinism: same_hardware_bitwise
```
"#;

    #[test]
    fn under_arity_conv2d_skips_differential_consistently_and_warns() {
        // Without the pre-check a 1-input CONV2D contract skips SILENTLY
        // (the shape-coupled synth declines the unreadable combo), leaving no
        // trace of the dead differential. The pre-check surfaces the skip.
        let provider = import_bundle_str(SYNTH_CONV2D_1IN, &StubResolveAll)
            .expect("a 1-input CONV2D contract imports (never-panic; differential skipped)");
        assert!(
            provider
                .warnings
                .iter()
                .any(|w| w.message.contains("requires >= 2") && w.message.contains("skipped")),
            "the under-arity Conv2D differential must be skipped WITH a warning \
             (consistent debug/release): {:?}",
            provider.warnings,
        );
    }

    /// Review fix (silent empty-points skip): a params-DEPENDENT variant whose
    /// probe combo the shape-coupled synth can't safely read (here: a rank-3
    /// `x` — the derivation needs rank-4) gets EMPTY param points, so every
    /// shape/dtype differential for that combo is skipped. That skip must
    /// surface an `ImportWarning` (the module's "a caught panic is no longer a
    /// silent skip" norm applied to the points path); it passes the arity
    /// pre-check (2 inputs), so without its own warning the coverage hole
    /// would leave no trace.
    const SYNTH_CONV2D_RANK3: &str = r#"---
fkc_version: 1
provider:
  name: synth-conv2d-rank3
  backend: Cpu
  kernel_source: "portable-cpu"
---

# synthetic rank-3 CONV2D (review fix: empty-param-points warning)

## conv2d_rank3

Synthetic 2-input Conv2D whose `x` declares rank 3 (the shape-coupled synth needs rank 4), to
exercise the empty-points warning.

```fkc
kernel: conv2d_rank3
fused_op: CONV2D
blurb: "synthetic rank-3-x conv2d to exercise the empty-param-points warning"
backend: Cpu
kernel_source: "portable-cpu"
entry_point: "synthetic::conv2d_rank3_cpu"
kernel_revision_hash: auto

accept:
  inputs:
    - name: x
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 3
    - name: weight
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
      rank: 4
  op_params:
    variant: Conv2D
    fields:
      stride:  { kind: "(usize, usize)" }
      padding: { kind: "(usize, usize)" }
      groups:  { kind: usize }

return:
  outputs:
    - name: out
      dtype_rule: passthrough(x)
      shape_rule: conv2d(params)
      layout_guarantee: contiguous

caps:
  awkward_layout_strategy: requires_contiguous
  in_place: false

cost:
  provenance: judge_measured
  class: conv

precision:
  bit_stable_on_same_hardware: false
  max_ulp: ~
  max_relative: ~
  max_absolute: ~
  audited: false
  notes: "synthetic"

determinism: same_hardware_bitwise
```
"#;

    #[test]
    fn empty_param_points_for_params_dependent_variant_warns() {
        let provider = import_bundle_str(SYNTH_CONV2D_RANK3, &StubResolveAll)
            .expect("a rank-3-x CONV2D contract imports (never-panic; differentials skipped)");
        assert!(
            provider
                .warnings
                .iter()
                .any(|w| w.message.contains("no param point") && w.message.contains("skipped")),
            "an unreadable combo for a params-dependent variant must skip its \
             differentials WITH a warning, not silently: {:?}",
            provider.warnings,
        );
    }

    // =====================================================================
    // DUPLICATE: two sections at the same key+pointer → DuplicateKernelRef
    // =====================================================================

    #[test]
    /// FKC-CLAUSE: FKC-10.10-0001 — path (1), the FKC IMPORT path MUST PROPAGATE.
    /// A provider contract is untrusted input, so a duplicate is a rejectable
    /// contract carrying a typed `FkcError::DuplicateKernelRef`, never a crash.
    fn same_pointer_on_one_key_surfaces_duplicate_kernel_ref() {
        // A hand-built bundle: two sections that resolve to the SAME
        // (op, dtypes, backend) key — and the SameLink maps both
        // entry_points to the SAME pointer. register_into's finalize gate
        // must surface DuplicateKernelRef.
        let src = "\
---
fkc_version: 1
provider:
  name: dup-provider
  backend: Cpu
  kernel_source: \"dup-cpu\"
---

# dup bundle

## add_a

A.

```fkc
kernel: add_a
op_kind: AddElementwise
blurb: \"a\"
entry_point: \"x::add_a\"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: \"n\"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```

## add_b

B.

```fkc
kernel: add_b
op_kind: AddElementwise
blurb: \"b\"
entry_point: \"x::add_b\"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: \"n\"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
";
        let provider =
            import_bundle_str(src, &SameLink).expect("the dup bundle imports (lowering is fine)");
        // Both sections share (AddElementwise, [F32,F32,F32], Cpu) AND the
        // same pointer → finalize must reject.
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        let err = provider
            .register_into(&mut table, &mut fused)
            .expect_err("same pointer on one key must error");
        assert!(
            matches!(err, FkcError::DuplicateKernelRef(_)),
            "got {err:?}"
        );
    }

    // =====================================================================
    // COST COMPILER (§2.3, FKC gap-closure Task 2.2): a contract's declared
    // `cost.flops` expression must reach `BindingEntry.cost_expr` as a
    // compiled AST, not be dropped in favor of the `unknown_cost` sentinel.
    // =====================================================================

    #[test]
    fn imported_contract_declared_cost_reaches_binding_cost_fn() {
        let src = "---\nfkc_version: 1\nprovider:\n  name: cost-provider\n  backend: Cpu\n  kernel_source: \"cost-cpu\"\n---\n\n# cost bundle\n\n## add_f32\n\nA.\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\nblurb: \"a\"\nentry_point: \"x::add_f32\"\naccept:\n  inputs:\n    - name: lhs\n      dtypes: [F32]\n      layout: { contiguous: required, strided: rejected }\n    - name: rhs\n      dtypes: [F32]\n      layout: { contiguous: required, strided: rejected }\n  op_params: { variant: None }\nreturn:\n  outputs:\n    - name: out\n      dtype_rule: passthrough(lhs)\ncost:\n  provenance: declared\n  class: cheap_elementwise\n  flops: \"n\"\nprecision:\n  bit_stable_on_same_hardware: true\n  audited: true\ndeterminism: same_hardware_bitwise\n```\n";
        let provider = import_bundle_str(src, &SameLink).expect("declared-cost contract imports");
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("registers");
        let alts = table.lookup_alternatives(
            OpKind::AddElementwise,
            &[DType::F32, DType::F32, DType::F32],
            BackendId::Cpu,
        );
        let entry = alts.first().expect("binding present");
        let expr = entry
            .cost_expr
            .expect("declared flops formula reaches the binding as a compiled AST");
        let est = crate::fkc::cost_estimate(
            expr,
            OpKind::AddElementwise,
            &[fuel_ir::Shape::from_dims(&[4])],
            &[DType::F32, DType::F32, DType::F32],
            &crate::kernel::OpParams::None,
        )
        .expect("declared cost evaluates");
        assert_eq!(est.flops, 4, "flops = n = elem_count([4])");
    }

    // =====================================================================
    // GLOB: agreeing front-matter merges; a mismatch → ProviderMismatch
    // =====================================================================

    fn write_temp(dir: &Path, name: &str, contents: &str) {
        std::fs::write(dir.join(name), contents).expect("write temp fkc file");
    }

    fn bundle_with(provider_backend: &str, kernel: &str, op_kind: &str, entry: &str) -> String {
        bundle_with_revision_base(provider_backend, kernel, op_kind, entry, None)
    }

    fn bundle_with_revision_base(
        provider_backend: &str,
        kernel: &str,
        op_kind: &str,
        entry: &str,
        revision_base: Option<&str>,
    ) -> String {
        bundle_with_front_matter(
            provider_backend,
            kernel,
            op_kind,
            entry,
            revision_base,
            None,
        )
    }

    fn bundle_with_link_registry(
        provider_backend: &str,
        kernel: &str,
        op_kind: &str,
        entry: &str,
        link_registry: Option<&str>,
    ) -> String {
        bundle_with_front_matter(
            provider_backend,
            kernel,
            op_kind,
            entry,
            None,
            link_registry,
        )
    }

    fn bundle_with_front_matter(
        provider_backend: &str,
        kernel: &str,
        op_kind: &str,
        entry: &str,
        revision_base: Option<&str>,
        link_registry: Option<&str>,
    ) -> String {
        // A raw string with real newlines (NO `\`-continuations, which
        // would eat the YAML indentation).
        let template = r#"---
fkc_version: 1
provider:
  name: glob-provider
  backend: __BACKEND__
  kernel_source: "glob-cpu"__REVISION_BASE____LINK_REGISTRY__
---

# glob bundle

## __KERNEL__

blurb.

```fkc
kernel: __KERNEL__
op_kind: __OP_KIND__
blurb: "k"
entry_point: "__ENTRY__"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
"#;
        let rev_line = match revision_base {
            Some(r) => format!("\n  revision_base: \"{r}\""),
            None => String::new(),
        };
        let link_line = match link_registry {
            Some(r) => format!("\n  link_registry: \"{r}\""),
            None => String::new(),
        };
        template
            .replace("__REVISION_BASE__", &rev_line)
            .replace("__LINK_REGISTRY__", &link_line)
            .replace("__BACKEND__", provider_backend)
            .replace("__KERNEL__", kernel)
            .replace("__OP_KIND__", op_kind)
            .replace("__ENTRY__", entry)
    }

    #[test]
    fn import_glob_merges_agreeing_files() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_ok_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        write_temp(
            &dir,
            "a.fkc.md",
            &bundle_with("Cpu", "add_f32", "AddElementwise", "x::add"),
        );
        write_temp(
            &dir,
            "b.fkc.md",
            &bundle_with("Cpu", "sub_f32", "SubElementwise", "x::sub"),
        );

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let provider = import_glob(&pattern, &link).expect("two agreeing files merge");

        assert_eq!(provider.name, "glob-provider");
        assert_eq!(provider.backend, BackendId::Cpu);
        assert_eq!(provider.primitives.len(), 2, "both kernels present");

        // And they register end-to-end.
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("merged provider registers");
        assert!(
            table
                .lookup(
                    OpKind::AddElementwise,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cpu
                )
                .is_ok()
        );
        assert!(
            table
                .lookup(
                    OpKind::SubElementwise,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cpu
                )
                .is_ok()
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// §9.2 says the provider front-matter must AGREE across the files a glob
    /// merges. `revision_base` is part of that front-matter and is folded into
    /// `kernel_revision_hash` — which is in turn the key the verification
    /// ledger is looked up by. Two files of one globbed provider declaring
    /// different bases therefore produce kernels whose revision hashes are
    /// computed against different roots while presenting as a single provider,
    /// silently invalidating ledger lookups.
    ///
    /// This is the "existence != enforcement" shape: the loop is *commented*
    /// "front-matter must agree across files (§9.2)" and checks 3 of the 5
    /// declared fields.
    #[test]
    fn import_glob_mismatched_revision_base_is_provider_mismatch() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_rev_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        write_temp(
            &dir,
            "a.fkc.md",
            &bundle_with_revision_base(
                "Cpu",
                "add_f32",
                "AddElementwise",
                "x::add",
                Some("git:aaaaaaaa"),
            ),
        );
        write_temp(
            &dir,
            "b.fkc.md",
            &bundle_with_revision_base(
                "Cpu",
                "sub_f32",
                "SubElementwise",
                "x::sub",
                Some("git:bbbbbbbb"),
            ),
        );

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let err = import_glob(&pattern, &link)
            .expect_err("a revision_base drift across a globbed provider must error");
        let msg = err.to_string();
        assert!(
            msg.contains("revision_base"),
            "the error must name the drifted field, got: {msg}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The agreeing case must still merge — a guard that rejects everything is
    /// not a guard.
    #[test]
    fn import_glob_matching_revision_base_still_merges() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_rev_ok_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        for (f, k, op, e) in [
            ("a.fkc.md", "add_f32", "AddElementwise", "x::add"),
            ("b.fkc.md", "sub_f32", "SubElementwise", "x::sub"),
        ] {
            write_temp(
                &dir,
                f,
                &bundle_with_revision_base("Cpu", k, op, e, Some("git:deadbeef")),
            );
        }

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let provider =
            import_glob(&pattern, &link).expect("agreeing revision_base must still merge");
        assert_eq!(provider.primitives.len(), 2, "both kernels present");
        assert_eq!(
            provider.revision_base.as_deref(),
            Some("git:deadbeef"),
            "the merged provider must retain the agreed revision_base"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The other half of §9.2's five fields. `link_registry` names the symbol
    /// table a file's `entry_point`s are meant to resolve against; `import_glob`
    /// binds every merged file through the ONE registry its caller passed in.
    /// So a glob whose files disagree on `link_registry` has at least one file
    /// whose entry points were resolved against a table its author never named
    /// — the symbols may well resolve, silently, to a different provider's
    /// kernels of the same name.
    #[test]
    fn import_glob_mismatched_link_registry_is_provider_mismatch() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_link_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        write_temp(
            &dir,
            "a.fkc.md",
            &bundle_with_link_registry(
                "Cpu",
                "add_f32",
                "AddElementwise",
                "x::add",
                Some("fuel_cpu_backend::fkc::ENTRY_POINTS"),
            ),
        );
        write_temp(
            &dir,
            "b.fkc.md",
            &bundle_with_link_registry(
                "Cpu",
                "sub_f32",
                "SubElementwise",
                "x::sub",
                Some("fuel_other_backend::fkc::ENTRY_POINTS"),
            ),
        );

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let err = import_glob(&pattern, &link)
            .expect_err("a link_registry drift across a globbed provider must error");
        let msg = err.to_string();
        assert!(
            msg.contains("link_registry"),
            "the error must name the drifted field, got: {msg}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The agreeing case must still merge, and must retain the agreed value —
    /// otherwise "enforced" could be satisfied by rejecting everything.
    #[test]
    fn import_glob_matching_link_registry_still_merges() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_link_ok_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        for (f, k, op, e) in [
            ("a.fkc.md", "add_f32", "AddElementwise", "x::add"),
            ("b.fkc.md", "sub_f32", "SubElementwise", "x::sub"),
        ] {
            write_temp(
                &dir,
                f,
                &bundle_with_link_registry(
                    "Cpu",
                    k,
                    op,
                    e,
                    Some("fuel_cpu_backend::fkc::ENTRY_POINTS"),
                ),
            );
        }

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let provider =
            import_glob(&pattern, &link).expect("agreeing link_registry must still merge");
        assert_eq!(
            provider.link_registry.as_deref(),
            Some("fuel_cpu_backend::fkc::ENTRY_POINTS"),
            "the merged provider must retain the agreed link_registry"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn import_glob_mismatched_backend_is_provider_mismatch() {
        let dir = std::env::temp_dir().join(format!("fkc_glob_bad_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // Two agreeing CPU files + a third with a different backend.
        write_temp(
            &dir,
            "a.fkc.md",
            &bundle_with("Cpu", "add_f32", "AddElementwise", "x::add"),
        );
        write_temp(
            &dir,
            "b.fkc.md",
            &bundle_with("Cpu", "sub_f32", "SubElementwise", "x::sub"),
        );
        write_temp(
            &dir,
            "c.fkc.md",
            &bundle_with("Vulkan", "mul_f32", "MulElementwise", "x::mul"),
        );

        let link = DistinctLink::new();
        let pattern = dir.join("*.fkc.md").display().to_string();
        let err = import_glob(&pattern, &link).expect_err("mismatched backend must error");
        assert!(
            matches!(
                err,
                FkcError::ProviderMismatch { ref field, .. } if field == "provider.backend"
            ),
            "got {err:?}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    // =====================================================================
    // DESCRIBE-ONLY (§3.10): a registrable: false section is excluded from
    // register_into; a sibling registrable section still registers.
    // =====================================================================

    #[test]
    fn describe_only_section_is_excluded_from_register_into() {
        // A bundle with a describe-only chassis umbrella (`## binary`,
        // op_kind = the DESCRIPTIVE token `binary`, registrable: false) plus
        // one real registrable thunk (`## add_f32`). Only the thunk lowers +
        // registers; the umbrella is documentation.
        let src = "\
---
fkc_version: 1
provider:
  name: describe-provider
  backend: Cpu
  kernel_source: \"describe-cpu\"
---

# describe bundle

## binary

The shared chassis (documentation umbrella).

```fkc
kernel: binary
registrable: false
op_kind: binary
blurb: \"shared binary chassis\"
entry_point: \"x::chassis\"
accept:
  inputs:
    - name: lhs
      dtypes: [F32, F64, BF16, F16]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32, F64, BF16, F16]
      layout: { contiguous: required, strided: rejected }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: judge_measured
  class: cheap_elementwise
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```

## add_f32

The real F32 addition thunk.

```fkc
kernel: add_f32
op_kind: AddElementwise
blurb: \"F32 add\"
entry_point: \"x::add_f32\"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: \"n\"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
";
        let link = DistinctLink::new();
        let provider = import_bundle_str(src, &link)
            .expect("describe-only + registrable bundle imports (umbrella is valid docs)");

        // Only the registrable thunk lowered — the describe-only umbrella is
        // excluded from the registered set.
        assert_eq!(
            provider.primitives.len(),
            1,
            "exactly one registrable primitive (the umbrella is documentation-only)"
        );
        assert_eq!(provider.primitives[0].op, OpKind::AddElementwise);

        // It registers end-to-end and the real key is present.
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into succeeds (no describe-only section reaches the table)");
        assert!(
            table
                .lookup(
                    OpKind::AddElementwise,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cpu
                )
                .is_ok()
        );
    }

    // =====================================================================
    // DESCRIBE-ONLY GATHER (§3.10 + §14): a `registrable: false` section that
    // trips a consumer-ahead validator (FDX gather → GatherNotYetSupported)
    // must NOT block a bundle's importable sections. The valid sibling still
    // imports + registers; the describe-only gather section is documentation.
    // =====================================================================

    #[test]
    fn describe_only_gather_section_does_not_block_bundle_import() {
        // A bundle with (a) one VALID registrable op_kind section (add_f32) and
        // (b) a `registrable: false` section whose operand carries an
        // `fdx.gather: paged_blocks` block — which the VALIDATE pass flags
        // `GatherNotYetSupported` (§14, consumer-ahead). Import must SKIP the
        // describe-only section's validation (it is documentation, carries no
        // dispatch target) and still register the valid sibling.
        //
        // **Born-red**: before the validate-skip fix, `validate_file` walked
        // EVERY section (incl. describe-only) and `validate_kernel` ran the gather
        // coherence check on the describe-only section → the whole
        // `import_bundle_str` returned `GatherNotYetSupported` (RED). After the
        // fix (`validate_file` skips `registrable: false` sections) → the valid
        // section imports + registers (GREEN).
        let src = r#"---
fkc_version: 1
provider:
  name: gather-describe-provider
  backend: Cpu
  kernel_source: "gather-cpu"
---

# describe-only gather bundle

## add_f32

The real F32 addition thunk (registrable).

```fkc
kernel: add_f32
op_kind: AddElementwise
blurb: "F32 add"
entry_point: "x::add_f32"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```

## paged_gather

Describe-only: a paged KV pool with an FDX gather sidecar (consumer-ahead).

```fkc
kernel: paged_gather
registrable: false
op_kind: PagedAttn
blurb: "describe-only paged gather"
entry_point: "x::paged_gather"
accept:
  inputs:
    - name: q
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: k_cache
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
      fdx:
        requires_ext: true
        symbolic_extent: required
        gather: { kind: paged_blocks, block_table: block_table, context_lens: context_lens }
    - name: block_table
      dtypes: [U32]
      layout: { contiguous: required, strided: rejected }
    - name: context_lens
      dtypes: [U32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: PagedAttn }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(q)
cost:
  provenance: declared
  class: attention
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
"#;
        let link = DistinctLink::new();
        let provider = import_bundle_str(src, &link).expect(
            "a describe-only gather section must NOT block the bundle's importable sections",
        );

        // Only the registrable add_f32 lowered; the describe-only gather section
        // is documentation (excluded from the registered set).
        assert_eq!(
            provider.primitives.len(),
            1,
            "exactly one registrable primitive (the gather section is describe-only)",
        );
        assert_eq!(provider.primitives[0].op, OpKind::AddElementwise);

        // The valid sibling registers end-to-end.
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("the valid sibling registers end-to-end");
        assert!(
            table
                .lookup(
                    OpKind::AddElementwise,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cpu
                )
                .is_ok()
        );
    }

    // =====================================================================
    // FUSED: a hand-built ResolvedFused registers into the fused registry
    // =====================================================================

    #[test]
    fn hand_built_fused_registers_into_registry() {
        // The fused corpus declares `fused_op:` names that don't match the
        // registry's CamelCase entry names today, so we cover the fused
        // register path with a hand-built ResolvedFused (faithful to the
        // shape `register_into` consumes).
        let mut dtypes: KernelDTypes = SmallVec::new();
        dtypes.push(DType::F32); // input x
        dtypes.push(DType::F32); // output

        let f = ResolvedFused {
            id: FusedOps::SOFTMAX_LAST_DIM,
            dtypes,
            backend: BackendId::Cpu,
            caps: KernelCaps::empty(),
            layouts: vec![ResolvedLayout {
                contiguous: Tri::Required,
                strided: Tri::Rejected,
                broadcast_stride0: Tri::Rejected,
                start_offset: Tri::Rejected,
                reverse_strides: Tri::Rejected,
            }],
            precision: PrecisionGuarantee::UNAUDITED,
            cost: CompiledCostExpr::Unknown,
            kernel: dummy_a,
            kernel_source: "portable-cpu".to_string(),
            revision: KernelRevisionHash::UNTRACKED,
            variant: None,
            bundle_slot_names: Vec::new(),
        };

        let provider = ImportedProvider {
            name: "fuel-fused-registry".to_string(),
            backend: BackendId::Cpu,
            kernel_source: intern("portable-cpu"),
            revision_base: None,
            link_registry: None,
            primitives: Vec::new(),
            fused: vec![f],
            warnings: Vec::new(),
        };

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("fused-only provider registers");

        // The fused op is present in the registry.
        let got = fused.lookup_by_dtypes(
            FusedOps::SOFTMAX_LAST_DIM,
            BackendId::Cpu,
            &[DType::F32, DType::F32],
        );
        assert!(got.is_some(), "softmax fused impl registered + looked up");
        let impl_ = got.unwrap();
        // The interned dtypes round-trip.
        assert_eq!(impl_.dtypes, &[DType::F32, DType::F32]);
        // The fused-cost sentinel pointer was wired ([consumer-ahead]).
        let sentinel = fused_unknown_cost as *const () as usize;
        assert_eq!(
            impl_.cost as *const () as usize, sentinel,
            "the fused-unknown sentinel CostFn is wired for imported fused ops"
        );
        // The revision rode through unchanged.
        assert_eq!(impl_.revision, KernelRevisionHash::UNTRACKED);
    }

    // =====================================================================
    // MULTI-DTYPE FAN-OUT (§3.4): a section whose operand(s) vary fans out
    // into N per-dtype bindings; `passthrough(role)` resolves the named
    // operand's dtype (NOT blindly the first input — the "where bug").
    // =====================================================================

    /// A [`LinkRegistry`] that resolves EVERY requested symbol to a dummy
    /// pointer (keyed by the symbol string so a symbol maps stably) and
    /// RECORDS every requested symbol — so a test can assert exactly which
    /// `<base>_<suffix>` entry points the importer resolved. Permissive on
    /// purpose: it resolves the base symbol too, so the pre-change importer
    /// (which resolves the base as-is) still imports — letting the born-red
    /// fail on a clean binding-COUNT assertion, not an import error.
    struct FanStubLink {
        seen: Mutex<std::collections::HashMap<String, KernelRef>>,
        requested: Mutex<Vec<String>>,
    }
    impl FanStubLink {
        fn new() -> Self {
            Self {
                seen: Mutex::new(std::collections::HashMap::new()),
                requested: Mutex::new(Vec::new()),
            }
        }
        fn resolve(&self, symbol: &str) -> Option<KernelRef> {
            self.requested.lock().unwrap().push(symbol.to_string());
            let mut g = self.seen.lock().unwrap();
            if let Some(k) = g.get(symbol) {
                return Some(*k);
            }
            let k: KernelRef = if g.len().is_multiple_of(2) {
                dummy_a
            } else {
                dummy_b
            };
            g.insert(symbol.to_string(), k);
            Some(k)
        }
    }
    impl LinkRegistry for FanStubLink {
        fn resolve_primitive(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
        fn resolve_fused(&self, symbol: &str) -> Option<KernelRef> {
            self.resolve(symbol)
        }
    }

    /// A synthetic bundle with (a) a UNIFORM multi-dtype section (`relu`: one
    /// input varying over `[F32,F64,BF16,F16]`, base `entry_point`) and (b) a
    /// MIXED section (`where_op`: a fixed `U8` `cond` + two varying operands +
    /// `passthrough(a)`). Authored with BASE entry_points (no dtype suffix) so
    /// the importer must resolve `<base>_<suffix>` per fanned dtype.
    const FANOUT_CONTRACT: &str = r#"---
fkc_version: 1
provider:
  name: fanout-provider
  backend: Cpu
  kernel_source: "fanout-cpu"
---

# fanout bundle

## relu

Uniform multi-dtype unary: one input varying over 4 dtypes.

```fkc
kernel: relu
op_kind: ReluElementwise
blurb: "relu fan-out"
entry_point: "stub::relu"
accept:
  inputs:
    - name: in
      dtypes: [F32, F64, BF16, F16]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(in)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```

## where_op

Mixed: a fixed U8 cond + two varying operands; passthrough(a).

```fkc
kernel: where_op
op_kind: Where
blurb: "where fan-out with passthrough(a)"
entry_point: "stub::where"
accept:
  inputs:
    - name: cond
      dtypes: [U8]
      layout: { contiguous: required, strided: rejected }
    - name: a
      dtypes: [F32, F64, BF16, F16]
      layout: { contiguous: required, strided: rejected }
    - name: b
      dtypes: [F32, F64, BF16, F16]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(a)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
"#;

    #[test]
    fn multi_dtype_section_fans_out_into_per_dtype_bindings() {
        let link = FanStubLink::new();
        let provider = import_bundle_str(FANOUT_CONTRACT, &link).expect("fan-out contract imports");

        // (1) FAN-OUT: `relu` (1 varying input) + `where_op` (2 varying inputs)
        // each fan to 4 per-dtype bindings ⇒ 8 primitives. Pre-change the
        // importer keyed on each operand's FIRST dtype and registered ONE
        // binding per section → 2. RED→GREEN.
        assert_eq!(
            provider.primitives.len(),
            8,
            "relu×4 + where×4 = 8 fanned bindings (pre-change: 2 — first-dtype only)"
        );

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("fanned bindings register");

        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];

        // (2) UNIFORM fan-out: ReluElementwise bound at [dt, dt] for every dt.
        for dt in dts {
            assert!(
                table
                    .lookup(OpKind::ReluElementwise, &[dt, dt], BackendId::Cpu)
                    .is_ok(),
                "relu must be bound at [{dt:?}, {dt:?}]",
            );
        }

        // (3) MIXED fan-out + passthrough-role FIX: Where bound at
        // [U8, dt, dt, dt] — the output mirrors operand `a` (= dt), NOT the
        // first input `cond` (U8).
        for dt in dts {
            assert!(
                table
                    .lookup(OpKind::Where, &[DType::U8, dt, dt, dt], BackendId::Cpu)
                    .is_ok(),
                "where must be bound at [U8, {dt:?}, {dt:?}, {dt:?}] (passthrough(a) = a's dtype)",
            );
            // The OLD buggy key (passthrough mirrored cond=U8) must NOT exist.
            assert!(
                table
                    .lookup(
                        OpKind::Where,
                        &[DType::U8, dt, dt, DType::U8],
                        BackendId::Cpu
                    )
                    .is_err(),
                "the pre-fix buggy key [U8,{dt:?},{dt:?},U8] must NOT be registered",
            );
        }

        // (4) ENTRY-POINT base+suffix: the importer resolved `<base>_<suffix>`
        // for every fanned dtype (canonical `DType::as_str`, not a hand-rolled
        // spelling), NOT the bare base symbol.
        let requested = link.requested.lock().unwrap().clone();
        for suffix in ["f32", "f64", "bf16", "f16"] {
            assert!(
                requested
                    .iter()
                    .any(|s| s == &format!("stub::relu_{suffix}")),
                "relu variant must resolve stub::relu_{suffix}; requested={requested:?}",
            );
            assert!(
                requested
                    .iter()
                    .any(|s| s == &format!("stub::where_{suffix}")),
                "where variant must resolve stub::where_{suffix}; requested={requested:?}",
            );
        }
    }

    /// Backward-compat guard: a section with NO varying operand (every operand
    /// single-dtype) produces EXACTLY ONE binding and resolves its declared
    /// `entry_point` AS-IS (no `_<suffix>` appended). This is what keeps the
    /// already-migrated per-(op,dtype) binary / affine / cast families
    /// byte-identical under fan-out. GREEN before AND after the change.
    #[test]
    fn single_dtype_section_yields_exactly_one_unchanged_binding() {
        let src = r#"---
fkc_version: 1
provider:
  name: single-provider
  backend: Cpu
  kernel_source: "single-cpu"
---

# single bundle

## add_f32

```fkc
kernel: add_f32
op_kind: AddElementwise
blurb: "single-dtype add"
entry_point: "stub::add_f32"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
"#;
        let link = FanStubLink::new();
        let provider = import_bundle_str(src, &link).expect("single-dtype imports");
        assert_eq!(
            provider.primitives.len(),
            1,
            "no varying operand ⇒ exactly one binding"
        );
        assert_eq!(
            provider.primitives[0].dtypes.as_slice(),
            &[DType::F32, DType::F32, DType::F32],
        );

        // entry_point resolved AS-IS (no `_f32` suffix appended to a
        // single-variant section — its declared symbol is already specific).
        let requested = link.requested.lock().unwrap().clone();
        assert!(
            requested.iter().any(|s| s == "stub::add_f32"),
            "single-variant resolves the declared symbol as-is; requested={requested:?}",
        );
        assert!(
            !requested.iter().any(|s| s == "stub::add_f32_f32"),
            "must NOT append a suffix to a single-variant section",
        );
    }

    // =====================================================================
    // OPTIONAL-OPERAND FAN-OUT (§3.4): an `optional: true` LAST input fans
    // EACH dtype variant into TWO keys — one OMITTING the optional operand,
    // one INCLUDING it — BOTH bound to the SAME kernel_ref. Composes with
    // the dtype fan-out (multi-dtype AND optional ⇒ 2N bindings).
    // =====================================================================

    /// A synthetic single-dtype contract: one REQUIRED input `x` + one
    /// `optional: true` LAST input `bias`, output `passthrough(x)`. With
    /// optional-operand support the importer registers TWO primitive bindings
    /// — no-bias `[x, out]` = `[F32, F32]` and with-bias `[x, bias, out]` =
    /// `[F32, F32, F32]` — BOTH resolving the SAME (single, as-is) `entry_point`
    /// ⇒ the SAME `KernelRef`.
    ///
    /// **Born-red**: BEFORE the fix the schema `TensorDesc` has no `optional`
    /// field, so serde silently drops `optional: true`; the operand is treated
    /// as REQUIRED and ONLY the with-bias key builds → `primitives.len() == 1`
    /// (RED). After the schema+key-builder fix → 2 (GREEN).
    const OPTIONAL_LAST_OPERAND_CONTRACT: &str = r#"---
fkc_version: 1
provider:
  name: opt-provider
  backend: Cpu
  kernel_source: "opt-cpu"
---

# optional-operand bundle

## opt_add

One required input + one optional LAST input.

```fkc
kernel: opt_add
op_kind: AddElementwise
blurb: "optional last operand"
entry_point: "stub::opt_add"
accept:
  inputs:
    - name: x
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: bias
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
      optional: true
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(x)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: "n"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
"#;

    #[test]
    fn optional_last_operand_registers_both_with_and_without_keys() {
        let link = FanStubLink::new();
        let provider = import_bundle_str(OPTIONAL_LAST_OPERAND_CONTRACT, &link)
            .expect("optional-operand contract imports");

        // TWO bindings: the with-optional key AND the without-optional key.
        // Pre-change (no `optional` schema field): serde drops the flag, the
        // operand is required, only the with-operand key builds → 1. RED→GREEN.
        assert_eq!(
            provider.primitives.len(),
            2,
            "an optional LAST input fans into 2 keys (with + without the operand); \
             pre-change (no `optional` schema field) only the with-operand key builds → 1",
        );

        // BOTH keys bind the SAME kernel_ref (same entry_point resolved AS-IS —
        // single-dtype, so no `_<suffix>` is appended).
        let k0 = provider.primitives[0].kernel as usize;
        let k1 = provider.primitives[1].kernel as usize;
        assert_eq!(
            k0, k1,
            "both the with- and without-optional keys resolve the SAME kernel (one entry_point)",
        );

        // The two keys are exactly `[x, out]` and `[x, bias, out]`.
        let mut keys: Vec<Vec<DType>> = provider
            .primitives
            .iter()
            .map(|p| p.dtypes.to_vec())
            .collect();
        keys.sort_by_key(|k| k.len());
        assert_eq!(
            keys[0],
            vec![DType::F32, DType::F32],
            "no-optional key = [x, out]",
        );
        assert_eq!(
            keys[1],
            vec![DType::F32, DType::F32, DType::F32],
            "with-optional key = [x, bias, out]",
        );

        // Both register into the binding table + look up.
        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("both keys register");
        assert!(
            table
                .lookup(
                    OpKind::AddElementwise,
                    &[DType::F32, DType::F32],
                    BackendId::Cpu
                )
                .is_ok(),
            "no-optional key [F32, F32] is bound",
        );
        assert!(
            table
                .lookup(
                    OpKind::AddElementwise,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cpu,
                )
                .is_ok(),
            "with-optional key [F32, F32, F32] is bound",
        );

        // The declared entry_point resolved AS-IS (single-dtype ⇒ no suffix).
        let requested = link.requested.lock().unwrap().clone();
        assert!(
            requested.iter().any(|s| s == "stub::opt_add"),
            "single-dtype section resolves its declared symbol as-is; requested={requested:?}",
        );

        // BACKWARD-COMPAT: the SAME contract WITHOUT the `optional: true` flag is
        // a plain 2-input section → EXACTLY ONE binding (the fan is driven ONLY
        // by the optional flag; nothing else changed).
        let non_optional = OPTIONAL_LAST_OPERAND_CONTRACT.replace("      optional: true\n", "");
        let link2 = FanStubLink::new();
        let provider2 =
            import_bundle_str(&non_optional, &link2).expect("non-optional twin imports");
        assert_eq!(
            provider2.primitives.len(),
            1,
            "no optional operand ⇒ exactly one binding (backward-compat)",
        );
        assert_eq!(
            provider2.primitives[0].dtypes.to_vec(),
            vec![DType::F32, DType::F32, DType::F32],
            "the required-both key [x, bias, out]",
        );
    }

    // =====================================================================
    // COST-FN TRAMPOLINE (§4.4, Task-F): a contract's `cost.cost_fn` NAME
    // resolves through the LinkRegistry to a real CostFn that is stamped on
    // the binding and SURVIVES the fill_unset pass. The LinkRegistry analog
    // of entry_point resolution — a named cost model, not the unknown_cost
    // sentinel. An unknown name is a typed UnknownCostFn (never silent).
    // =====================================================================

    /// A distinctive test `CostFn` (distinct fn item ⇒ distinct pointer) that
    /// the trampoline pins onto a binding. Its 999_999 FLOPs value + its unique
    /// pointer identity make it observable that the CONTRACT's cost fn — not
    /// `unknown_cost` and not the op-family default — is what the binding
    /// carries after `register_into` AND after `fill_unset`.
    fn test_pinned_cost(
        _s: &[fuel_ir::Shape],
        _d: &[DType],
        _p: &crate::kernel::OpParams,
        _c: &fuel_ir::backend::BackendCapabilities,
    ) -> CostEstimate {
        CostEstimate {
            flops: 999_999,
            bytes_moved: 0,
            kernel_overhead_ns: 0,
        }
    }

    /// A `LinkRegistry` that resolves the `cost.cost_fn` name `test_pinned_cost`
    /// to [`test_pinned_cost`] (and every entry_point to a dummy kernel) — the
    /// test analog of a provider that pins a real cost fn over its own cost-fn
    /// table (e.g. the CUDA `CUDA_COST_FNS` table).
    struct CostPinLink;
    impl LinkRegistry for CostPinLink {
        fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
            Some(dummy_a)
        }
        fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
            Some(dummy_a)
        }
        fn resolve_cost_fn(&self, name: &str) -> Option<crate::kernel::CostFn> {
            if name == "test_pinned_cost" {
                Some(test_pinned_cost)
            } else {
                None
            }
        }
    }

    /// A one-section bundle naming a cost fn in its `cost:` block. `__COST_FN__`
    /// is replaced by the test with the real (resolvable) or a bogus name.
    const COST_PIN_BUNDLE: &str = "\
---
fkc_version: 1
provider:
  name: cost-pin-provider
  backend: Cpu
  kernel_source: \"cost-pin-cpu\"
---

# cost-pin bundle

## add_pinned

A.

```fkc
kernel: add_pinned
op_kind: AddElementwise
blurb: \"a\"
entry_point: \"x::add_pinned\"
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
    - name: rhs
      dtypes: [F32]
      layout: { contiguous: required, strided: rejected }
  op_params: { variant: None }
return:
  outputs:
    - name: out
      dtype_rule: passthrough(lhs)
cost:
  provenance: declared
  class: cheap_elementwise
  flops: \"n\"
  cost_fn: \"__COST_FN__\"
precision:
  bit_stable_on_same_hardware: true
  audited: true
determinism: same_hardware_bitwise
```
";

    #[test]
    fn contract_pinned_cost_fn_survives_fill_unset() {
        // BORN-RED → GREEN. A contract whose cost block NAMES `test_pinned_cost`
        // must register the binding with THAT CostFn (resolved through the
        // LinkRegistry), and the `fill_unset_cost_for_backend` pass must LEAVE it
        // (that pass only replaces the `unknown_cost` sentinel). RED before the
        // trampoline wiring: `register_into` stamped `unknown_cost`, so fill_unset
        // clobbered the cell with the op-family default `cost_elementwise_binary_cpu`.
        let src = COST_PIN_BUNDLE.replace("__COST_FN__", "test_pinned_cost");
        let provider = import_bundle_str(&src, &CostPinLink)
            .expect("a bundle naming a resolvable cost fn imports");

        // (1) Lowering resolved the NAME to the concrete CostFn on the record.
        assert_eq!(provider.primitives.len(), 1);
        assert!(
            provider.primitives[0].cost_fn.is_some(),
            "lower_primitive must resolve cost.cost_fn through resolve_cost_fn",
        );

        let mut table = KernelBindingTable::new();
        let mut fused = FusedKernelRegistry::new();
        provider
            .register_into(&mut table, &mut fused)
            .expect("register_into succeeds");

        let key = [DType::F32, DType::F32, DType::F32];

        // (2) register_into stamped the PINNED cost fn, NOT the unknown_cost sentinel.
        let cost_before = table.lookup_cost(OpKind::AddElementwise, &key, BackendId::Cpu);
        assert_eq!(
            cost_before as usize, test_pinned_cost as *const () as usize,
            "register_into must stamp the contract-pinned CostFn (not unknown_cost)",
        );
        assert_ne!(
            cost_before as usize,
            crate::kernel::unknown_cost as *const () as usize,
            "the pinned CostFn must not be the unknown_cost sentinel",
        );

        // (3) THE POINT OF TASK-F: fill_unset must NOT overwrite the pinned cost.
        table.fill_unset_cpu_cost(crate::cost::default_cost_for_op_kind);
        let cost_after = table.lookup_cost(OpKind::AddElementwise, &key, BackendId::Cpu);
        assert_eq!(
            cost_after as usize, test_pinned_cost as *const () as usize,
            "fill_unset must leave the contract-pinned CostFn untouched",
        );
        assert_ne!(
            cost_after as usize,
            crate::cost::cost_elementwise_binary_cpu as *const () as usize,
            "the pinned cost must NOT have been clobbered by the op-family default",
        );

        // (4) FKC gap-closure Task 2.2: this contract ALSO declares
        // `flops: "n"` alongside the pinned `cost_fn` — the pinned fn must
        // win outright, so the binding's declared-AST slot stays None (the
        // AST does not compete with a contract-pinned CostFn).
        let alts = table.lookup_alternatives(OpKind::AddElementwise, &key, BackendId::Cpu);
        let entry = alts.first().expect("binding present");
        assert!(
            entry.cost_expr.is_none(),
            "a pinned cost_fn wins outright; the declared cost AST must not be stamped alongside it",
        );
    }

    #[test]
    fn unknown_cost_fn_name_is_typed_error() {
        // A cost block naming a cost fn absent from the link registry's cost-fn
        // table is a typed UnknownCostFn at import time — never a silent
        // fallback to unknown_cost.
        let src = COST_PIN_BUNDLE.replace("__COST_FN__", "no_such_cost_fn");
        let err = import_bundle_str(&src, &CostPinLink)
            .expect_err("an unresolved cost_fn name must error");
        assert!(
            matches!(err, FkcError::UnknownCostFn { ref cost_fn, .. } if cost_fn == "no_such_cost_fn"),
            "got {err:?}",
        );
    }

    // =====================================================================
    // WARNINGS SINK (Task 0.2): ImportedProvider carries a warnings vec.
    // =====================================================================

    #[test]
    fn imported_provider_exposes_warnings_field_defaulting_empty() {
        // Direct struct construction (not via import) so this stays green across
        // every later component (component 4's gate will make import-path warnings
        // non-empty for precision-claiming contracts).
        let p = ImportedProvider {
            name: "p".into(),
            backend: fuel_ir::probe::BackendId::Cpu,
            kernel_source: "ks",
            revision_base: None,
            link_registry: None,
            primitives: Vec::new(),
            fused: Vec::new(),
            warnings: Vec::new(),
        };
        assert!(p.warnings.is_empty());
    }
}