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

use std::collections::{HashMap, HashSet};

use fuel_graph::opt::insert_cross_device_copies;
use fuel_graph::{Graph, NodeId, Op, extract_runs_multi, topo_order_multi};
use fuel_ir::{DType, DeviceLocation, Result};

use crate::driver::{OptimizationContext, PassRegistry};
use crate::kernel::KernelBindingTable;
use crate::plan::{ExecutionPlan, PlanOptions, compile_plan};
use crate::topology::SystemTopology;

/// Round cap for the residency-eviction pass `optimize_graph` runs under a device byte budget
/// (the legacy rule's default; the pass stops earlier once the budget is met).
const RESIDENCY_EVICTION_MAX_ROUNDS: usize = 16;

/// The transient *view* [`optimize_graph`] returns — the realize-roots
/// it optimized for plus the topology generation it ran under. It is
/// **not** stored on the graph; the optimized form is the graph itself
/// (with its `Op::Branch` decision points, of which A3a emits none).
///
/// The dispatch order is derived on demand from `fuel-graph`'s run
/// extraction so the run view is always recomputed from the current
/// arena — never a stale snapshot. This is the shape PR-A3b swaps the
/// bridge onto in place of `ExecutionPlan::order`.
#[derive(Debug, Clone)]
pub struct OptimizedGraph {
    /// The realize roots this optimization targeted (the same
    /// `targets` the bridge passes today).
    pub roots: Vec<NodeId>,
    /// `SystemTopology` generation snapshotted at optimize time —
    /// mirrors [`crate::plan::ExecutionPlan::generation`] so a later
    /// chunk-boundary check can detect a topology shift exactly as
    /// the executor does today.
    pub generation: u64,
    /// Final effective placement per node, as the optimizer resolved it.
    /// Read via [`OptimizedGraph::placement_of`].
    ///
    /// `None` when the residency pass did not run — it is gated on
    /// `PlanOptions::pinned_device`, which the production realize path always
    /// sets and bare-graph test callers often do not. `None` therefore means
    /// **"not computed"**, never "placed nowhere".
    pub(crate) placements: Option<HashMap<NodeId, DeviceLocation>>,
    /// What the budgeted eviction pass did (ROADMAP row 67 I1): `Some` only when
    /// `PlanOptions::device_budget_bytes` was set and a device was pinned. Read
    /// [`crate::residency::EvictionOutcome::fits`] before trusting that the budget was met: today a same-device
    /// budget cannot be met (the reload is not delayed), and this says so.
    pub eviction: Option<crate::residency::EvictionOutcome>,
}

impl OptimizedGraph {
    /// Extract the runs of the optimized graph, in topological order
    /// of their entries (delegates to [`extract_runs_multi`]). A
    /// branchless, single-residency graph yields exactly one run.
    pub fn runs(&self, graph: &Graph) -> Vec<fuel_graph::Run> {
        extract_runs_multi(graph, &self.roots)
    }

    /// **The device the optimizer decided this node runs on** — the observable
    /// form of the placement decision, for callers that need to check *where*
    /// work landed rather than infer it from timing.
    ///
    /// This is the resolved *effective* placement, not a hint. It is the same
    /// map the residency pass uses to decide where to stitch cross-device
    /// copies, resolved by the priority in `effective_placements`:
    /// residency-declaring ops → explicit `Graph::placement` → input residency
    /// → **plan winner** → backend stamp → view pass-through.
    ///
    /// **Do not substitute [`fuel_graph::Graph::placement`] for this.** That is
    /// only *level 2* of the six — a hint set by inserted copies and caller
    /// overrides. The planner's actual choice for a compute node arrives at
    /// level 4 ("plan winner"), so `Graph::placement` returns `None` for
    /// precisely the nodes whose placement is interesting, and reading that
    /// `None` as "unplaced" is a wrong answer that looks like a null one.
    ///
    /// Returns `None` if the node is unknown to this optimization **or** if the
    /// residency pass did not run (no `pinned_device`; see the field docs) —
    /// the two are deliberately not distinguished here because neither means
    /// "placed nowhere". Use [`OptimizedGraph::has_placements`] to tell them
    /// apart before drawing a conclusion from a `None`.
    pub fn placement_of(&self, node: NodeId) -> Option<DeviceLocation> {
        self.placements.as_ref()?.get(&node).copied()
    }

    /// Whether placement was computed at all. Distinguishes "this node has no
    /// placement" from "no node does, because the pass was skipped" — the
    /// difference between a real observation and an absent instrument.
    pub fn has_placements(&self) -> bool {
        self.placements.is_some()
    }

    /// Every resolved `(node, device)` pair, for dumping a whole graph's
    /// placement. Empty iterator when placement was not computed — check
    /// [`OptimizedGraph::has_placements`] first if that distinction matters.
    pub fn placements(&self) -> impl Iterator<Item = (NodeId, DeviceLocation)> + '_ {
        self.placements
            .iter()
            .flat_map(|m| m.iter().map(|(&id, &loc)| (id, loc)))
    }

    /// The flat executable dispatch order — the **arm-0 single-route
    /// lowering** (PR-A4). It follows arm 0 through every `Op::Branch`
    /// (pre-run, arm-0's run, post-run) and **skips every non-arm-0
    /// arm's run**, via [`fuel_graph::lower_runs_arm0`].
    ///
    /// For a graph with **zero `Op::Branch` nodes** this is the exact
    /// `NodeId` sequence today's executor walks via
    /// [`crate::plan::compile_plan`]`(...).order` — the equivalence gate
    /// proves it (no arm to skip ⇒ identical to concatenating
    /// [`fuel_graph::run::lower_run`] over the runs). For a branched graph it is the
    /// single-route lowering on **arm 0 = the DP winner** (the route
    /// realize used before the branch was recorded), so a branched graph
    /// realizes to the same result. The Phase-C runtime picker is what
    /// will later select non-arm-0 arms at the decision points.
    pub fn dispatch_order(&self, graph: &Graph) -> Vec<NodeId> {
        fuel_graph::lower_runs_arm0(graph, &self.roots)
    }

    /// The number of `Op::Branch` decision points in the arena. Counting
    /// over the whole arena (not just the roots' reachable set) is the
    /// stronger claim. Zero for a single-route graph (CPU-only build, or
    /// any graph with no genuine ≥2-placement fork); PR-A4's
    /// deliberate-fork pathfinder emits one per genuine placement fork.
    pub fn branch_count(&self, graph: &Graph) -> usize {
        (0..graph.len())
            .map(NodeId)
            .filter(|&id| matches!(graph.node(id).op, Op::Branch { .. }))
            .count()
    }
}

/// Optimize `graph` **in place** into the "plan IS the graph" form and
/// return the transient [`OptimizedGraph`] lowering view.
///
/// `roots` are the realize targets (the bridge's `targets`);
/// `bindings_table` is the kernel registry the placement/cost
/// machinery queries (production passes [`crate::dispatch::global_bindings`];
/// tests pass a local table); `opts` is the same [`PlanOptions`] the
/// bridge builds for `compile_plan`.
///
/// ## Behavior
///
/// `optimize_graph`:
///
/// 1. Derives the dispatch order via `fuel_graph::opt::execution_plan`
///    — exactly the order the bridge feeds `compile_plan` today
///    (data-flow topo refined by destructive-op ordering edges).
/// 2. Drives [`compile_plan`] over that order to **reuse** the
///    existing placement DP / cost composer / filter chain and to
///    fail-fast at build time on a missing binding or absent device
///    context (validate-at-graph-build-time per the working
///    agreement). Its [`crate::plan::ExecutionPlan`] is a transient
///    by-product here — the source of truth is the graph.
/// 3. Runs the PR-A4 deliberate-fork pathfinder
///    ([`PlacementForkPathfinder`](crate::driver::PlacementForkPathfinder)): records ONE `Op::Branch` per
///    genuine ≥2-placement fork (arm-0 = winner, arm-1 = runner-up). A
///    graph with no competing routes gets **zero** branches — it is
///    already its own single-route plan.
///
/// The returned view's [`OptimizedGraph::dispatch_order`] is the arm-0
/// single-route lowering; for any branchless graph it reproduces
/// `compile_plan(...).order` exactly — the equivalence gate.
///
/// ## The internal `ExecutionPlan` (Step D — no longer returned)
///
/// `optimize_graph` drives [`compile_plan`] internally for
/// placement/cost/validation; the resulting `ExecutionPlan` is a
/// **transient, optimizer-internal** accumulator the stamp / residency /
/// layout-fixup passes + the lock-step rankers read below. It is NOT
/// returned or threaded anywhere — the durable output is the graph's
/// `target_backend` stamps + `Op::Branch` arms. The executor reads the
/// graph + re-derives any per-arm candidate from the binding registry at
/// realize time, so the plan never becomes a dispatch-time authority.
pub fn optimize_graph(
    graph: &mut Graph,
    roots: &[NodeId],
    bindings_table: &KernelBindingTable,
    opts: &PlanOptions<'_>,
) -> Result<OptimizedGraph> {
    optimize_graph_with_passes(
        graph,
        roots,
        bindings_table,
        opts,
        PassRegistry::default_passes(),
    )
}

/// [`optimize_graph`] with the runtime-fusion pathfinder registered
/// ([`PassRegistry::default_passes_with_runtime_fusion`]): adopted (Tier-2 /
/// JIT-synthesized) fused ops get their gated `Op::Branch` arms emitted before
/// placement runs. This is the **production realize path's** entry once a
/// process can adopt runtime kernels; `optimize_graph` stays runtime-op-free so
/// bare-graph callers and tests never scan the process-global sidecar.
pub fn optimize_graph_with_runtime_fusion(
    graph: &mut Graph,
    roots: &[NodeId],
    bindings_table: &KernelBindingTable,
    opts: &PlanOptions<'_>,
) -> Result<OptimizedGraph> {
    optimize_graph_with_passes(
        graph,
        roots,
        bindings_table,
        opts,
        PassRegistry::default_passes_with_runtime_fusion(),
    )
}

fn optimize_graph_with_passes(
    graph: &mut Graph,
    roots: &[NodeId],
    bindings_table: &KernelBindingTable,
    opts: &PlanOptions<'_>,
    passes: PassRegistry,
) -> Result<OptimizedGraph> {
    // (1) The dispatch order today: data-flow topo refined by ordering
    //     edges. `compile_plan` copies this verbatim into
    //     `ExecutionPlan::order`, so it IS the executor's walk order.
    let mut order = fuel_graph::opt::execution_plan(graph, roots);

    // (1a) GAP-380 (a1): lower a fused op with NO kernel on the pinned device to its primitive recipe
    //      BEFORE placement, so the recipe's nodes are placed on the device instead of the whole fused
    //      op landing on the host (a round trip of its device-resident operands every call). Runs first
    //      because it changes what the planner enumerates; the order is re-derived if it rewrote.
    if lower_fused_unbound_on_pinned_device(graph, roots, opts, &|id, backend| {
        crate::fused::default_kernel_registry()
            .impls_for(id)
            .iter()
            .any(|(b, _)| *b == backend)
    }) > 0
    {
        order = fuel_graph::opt::execution_plan(graph, roots);
    }

    // (2) Reuse the placement/cost/validation machinery. The plan is a
    //     transient, optimizer-INTERNAL by-product — we drive `compile_plan`
    //     so the same fail-fast diagnostics (missing binding, no device
    //     context) fire at optimize time, and so the placement DP / cost
    //     composer run unchanged. The plan is the working accumulator the
    //     stamp / residency / layout-fixup passes + the lock-step rankers
    //     read below; it is NOT returned or threaded (Step D — the graph
    //     stamps + arms are the only durable output).
    // (2a) Dtype-reconciliation fixup — insert promoting `Op::Cast`s so a node
    //      whose per-operand key no compiled-in backend serves natively (e.g. a
    //      mixed-precision `[F32, BF16, F32]` matmul) becomes servable, instead of
    //      dead-ending in `compile_plan` below. Runs BEFORE the plan because it
    //      changes what's enumerable; if it rewrites, re-derive the execution
    //      order over the mutated graph. The layout/residency fixups are its
    //      post-plan siblings.
    let order = if insert_dtype_fixups(graph, roots, bindings_table, opts) {
        fuel_graph::opt::execution_plan(graph, roots)
    } else {
        order
    };

    let plan = compile_plan(graph, &order, bindings_table, opts)?;
    let generation = plan.generation;

    // (3) PR-B3: the lock-step pass driver. The pre-B3 hardcoded
    //     `seed_placement_fork_branches(...)` call is replaced by a
    //     registry of pathfinders + optimizers run lock-step
    //     (prune-as-you-go): for each registered pathfinder, ADD its
    //     candidate paths, then immediately run every registered
    //     optimizer to MERGE/DISCARD over the region just touched. The
    //     shipped configuration ([`PassRegistry::default_passes`]) is the
    //     PR-A4 `PlacementForkPathfinder` (the deliberate-fork seed) +
    //     the `FrontierConvergenceOptimizer` (duplicate-path convergence
    //     + the never-strand / no-active-cycle invariant guards) — which
    //     is exactly the pre-B3 sequence, re-expressed. A CPU-only build
    //     has one placement per node ⇒ the pathfinder proposes zero
    //     branches ⇒ today's single-route graph (unchanged).
    //
    //     The *ranker* + the PR-B2 per-device Pareto frontier are applied
    //     per kernel-bearing node *inside* `compile_plan` (the MEASURE +
    //     per-node PRUNE), and the ranked, frontier-pruned result is the
    //     `plan` the driver reads via `OptimizationContext::plan`. Batch
    //     optimize has no executing region, so the cycle guard is empty.
    let cycle_guard: HashSet<NodeId> = HashSet::new();
    let ctx = OptimizationContext {
        order: &order,
        plan: &plan,
        cycle_guard: &cycle_guard,
        bindings: bindings_table,
    };
    passes.run_lockstep(graph, &ctx)?;

    // "Plan IS the graph": commit the placement decision INTO the graph's
    // `target_backend` side-table here, so a fully-optimized graph carries
    // its own backend stamps and downstream consumers read the graph, not a
    // threaded plan. Guarded on a pinned device — the production realize
    // path always sets one (`PlanOptions::with_pinned_device`); bare-graph
    // test callers that don't are unaffected. (Cleanup Step A: this is
    // idempotent with the bridge's transitional `stamp_plan_backends`, which
    // re-stamps the identical result; Step A2 removes the bridge copy.)
    // Stays `None` when the residency pass below is skipped (no pinned device),
    // so a caller can tell "not computed" from "no placement" — see
    // `OptimizedGraph::has_placements`.
    let mut resolved_placements: Option<HashMap<NodeId, DeviceLocation>> = None;
    let mut eviction: Option<crate::residency::EvictionOutcome> = None;
    if let Some(pinned) = opts.pinned_device {
        stamp_plan_backends(graph, roots, &plan, pinned);
        // Every node stamped for a backend must have an executor arm there (typed plan-time error
        // rather than an executor failure mid-run).
        crate::pipelined::check_direct_arms_wired(graph, roots)?;
        // Optimize-time kernel-variant bake: resolve **same-device**
        // kernel-variant branches (a decomposed region vs. a fused kernel on
        // the SAME device — e.g. the CUDA flash decode arm) to their cost
        // winner and COLLAPSE them, so the winning variant is selectable
        // without a runtime pick (04-optimization: kernel-variant choice is
        // "largely baked at optimize time"). Runs AFTER `stamp_plan_backends`
        // (the arms now carry `target_backend`, which the same-device gate
        // reads) and BEFORE `insert_residency_copies` (so the residency pass
        // stitches inbound copies only for the surviving winner arm, not a
        // pruned one). A **placement** branch (arms on ≥2 devices) is left
        // LIVE for the runtime route picker; a graph with no same-device
        // variant branch — every CPU/Vulkan build today, since no CUDA flash
        // arm is offered there — is a strict no-op. Ties / unknown costs /
        // capability-missing default to arm 0 (the decomposed oracle).
        // The cost provider consults the Judge's MEASURED latency (Layer-2)
        // FIRST per arm node, falling back to the Layer-1 composite where the
        // Judge has no cell (the hybrid sum). With `opts.judge == None` this is
        // byte-identical to the Layer-1-only provider, so the no-Judge path is
        // unchanged. The same oracle `cost.rs`/`plan.rs` read is threaded here.
        let judge = opts.judge;
        crate::variant_bake::bake_variant_branches(graph, roots, &|g, branch, arm, interior| {
            let backend = g.target_backend(g.node(branch).inputs.first().copied()?)?;
            crate::variant_bake::decode_arm_composite_ns_judged(
                g, branch, arm, interior, backend, judge,
            )
        });
        // Cleanup Step B (residency): the optimizer-side cross-device copy pass
        // (was the bridge's `insert_resident_input_copies`). Runs AFTER stamping
        // (it reads `target_backend`) and BEFORE layout-fixup, preserving the
        // prior residency→layout order. Cache residency (where persistent /
        // const inputs already live) arrives via the `opts.input_residency`
        // provider the realize path already threads in — the optimizer reads
        // that fact, it does not touch realize-time storage.
        // Capture the resolved placement map on the way past — it is the pass's
        // own input, and surfacing it is what makes `OptimizedGraph::placement_of`
        // an observation rather than an inference.
        let placements = insert_residency_copies(graph, roots, &plan, pinned, opts.input_residency);
        // ROADMAP row 67 (I1): with a device byte budget, evict + reload around the
        // best candidates while the analysed peak exceeds it. Runs after the copy pass
        // (it reads the resolved placements) and before layout fixups. No budget = no-op.
        if let Some(budget) = opts.device_budget_bytes {
            let mut outcome = crate::residency::insert_residency_evictions_in(
                graph,
                roots,
                pinned,
                budget,
                RESIDENCY_EVICTION_MAX_ROUNDS,
                |id| placements.get(&id).copied(),
            )?;
            outcome.budget_source = opts.device_budget_source;
            eviction = Some(outcome);
        }
        resolved_placements = Some(placements);
        // Cleanup Step B (layout): insert `Op::Contiguize` before any kernel
        // whose chosen winner rejects strided inputs and whose input layout is
        // non-contiguous — the optimizer writing the layout-fixup decision INTO
        // the graph (was the bridge's `apply_layout_fixups`, now retired). No
        // runtime deps: reads only the in-scope `plan` winner caps + graph
        // layout. CSE-deduped + idempotent. Gated on `pinned_device` so it runs
        // on the realize path (which always sets one), matching the prior
        // bridge behavior; bare-graph test callers without a pin are unaffected.
        fuel_graph::opt::insert_layout_fixups(graph, roots, |id| {
            plan.alternatives(id)
                .and_then(|set| set.winner())
                .map(|cand| cand.caps.strided_input)
                .unwrap_or(true)
        });
    }

    Ok(OptimizedGraph {
        roots: roots.to_vec(),
        generation,
        placements: resolved_placements,
        eviction,
    })
}

/// Fused ops the optimizer lowers to their primitive recipe when the pinned device has no kernel
/// for them (GAP-380 / ROADMAP row 149 (a1)). Deliberately a short allowlist: a fused op belongs
/// here only after the recipe's placement was measured on the device. `PAGED_ATTN`: 25 -> 1
/// host-placed nodes and 104.8 -> 50.7 ms/token at the mid Llama decode fixture (Fuel 1,
/// 2026-11-12, n=1, ROADMAP row 149).
const LOWER_WHEN_NO_DEVICE_KERNEL: &[fuel_graph::registry::FusedOpId] =
    &[fuel_graph::registry::FusedOps::PAGED_ATTN];

/// Lower every reachable [`LOWER_WHEN_NO_DEVICE_KERNEL`] fused node whose pinned backend has no
/// kernel (`bound(op, backend)` is false) to its primitive recipe, in place. A no-op unless the
/// pinned device is CUDA (the measured case; a CPU or Vulkan pin keeps the fused host kernel).
/// Returns the number of nodes lowered; reported through `tracing` so a deoptimization is visible
/// (C-6: fuel never changes a plan silently).
///
/// Not a numerics-neutral swap: the recipe computes the attention in the primitives' dtype order,
/// so a consumer that needs the fused kernel's exact bits must pin a backend that has one.
fn lower_fused_unbound_on_pinned_device(
    graph: &mut Graph,
    roots: &[NodeId],
    opts: &PlanOptions<'_>,
    bound: &dyn Fn(fuel_graph::registry::FusedOpId, fuel_ir::probe::BackendId) -> bool,
) -> usize {
    let Some(pinned) = opts.pinned_device else {
        return 0;
    };
    let backend = pinned.backend();
    if backend != fuel_ir::probe::BackendId::Cuda {
        return 0;
    }
    let lowered = fuel_graph::opt::lower_selected_fused(graph, roots, &|g, id| {
        matches!(&g.node(id).op, Op::Fused(fid, _)
            if LOWER_WHEN_NO_DEVICE_KERNEL.contains(fid) && !bound(*fid, backend))
    });
    if lowered > 0 {
        tracing::info!(
            lowered,
            "GAP-380: lowered {lowered} fused node(s) with no {backend:?} kernel to their primitive              recipe so they place on the pinned device instead of the host"
        );
    }
    lowered
}

/// Dtype-reconciliation fixup (runs BEFORE `compile_plan`): for any kernel-
/// bearing node whose per-operand `(op, dtypes)` key is not servable by any
/// compiled-in backend, insert `Op::Cast`(s) promoting the mismatched input(s)
/// to the node's OUTPUT dtype — IF that lossless upcast yields a key some backend
/// DOES support. This is "backends advertise; the optimizer adapts"
/// ([04-optimization], [05-backend-contract]) applied to dtype, and the sibling
/// of `insert_layout_fixups` (`Op::Contiguize`) and `insert_residency_copies`
/// (`Op::Copy`).
///
/// It is the non-native-kernel fallback the mixed-precision matmul path already
/// ASSUMED exists — `vulkan_dispatch`'s matmul route picker documents "otherwise
/// falls back to f32 matmul (after a Cast)" — but which was never built as a
/// pass, so a graph builder emitting a mixed `[F32, BF16] → F32` matmul
/// dead-ended at `NoBackendForOp` on every backend without the native mixed key
/// (all but Vulkan; and CPU-only default builds have none).
///
/// SAFE + CONSERVATIVE: promotes ONLY by a value-LOSSLESS upcast to the output
/// dtype ([`lossless_upcast`]), so it never changes op semantics (a comparison's
/// `U8` output is not a lossless upcast target, so comparisons are left alone) and
/// never corrupts a value.
///
/// **NUMERIC CAVEAT:** the upcast is value-lossless but the promoted op is NOT
/// numerically identical to a native mixed-precision kernel — it accumulates in
/// the higher precision, so the *same graph* can differ by which arm ran (a CPU
/// upcast vs a native `[F32,BF16,F32]` kernel; and it already differs
/// CPU-vs-CUDA). The pass REPORTS every promotion via `tracing` (visibility, per
/// C-6's "never silently deoptimize"). Making a promoting cast **forbiddable
/// under a C-5 determinism/tolerance constraint** (so a byte-exact-oracle or
/// CPU-vs-CUDA-parity consumer gets the native path or a hard fail, not a silent
/// upcast) and **accounting its extra resident bytes under C-4** (BF16→F32
/// doubles a weight) are tracked ROADMAP follow-ups.
///
/// When no lossless promotion yields a supported key, the node is left unchanged
/// and fails cleanly at `compile_plan` with the truthful coverage diagnostic — a
/// genuine gap, surfaced honestly. Returns whether it changed the graph (so the
/// caller re-derives the execution order).
///
/// The broader fix — expanding per-op dtype coverage across kernels (starting
/// CPU) so fewer combos need reconciling — is a tracked ROADMAP item; this pass
/// makes the graph builder's mixed-precision promise executable everywhere today.
fn insert_dtype_fixups(
    graph: &mut Graph,
    roots: &[NodeId],
    bindings: &KernelBindingTable,
    options: &PlanOptions<'_>,
) -> bool {
    let order = topo_order_multi(graph, roots);
    // Decision only (immutable graph reads): the `(consumer, input, target)` edges
    // to promote. The mechanical Cast-insert + rewire is
    // `fuel_graph::opt::insert_cast_fixups` (the dtype-changing sibling of the
    // layout fixup). Built in topo order ⇒ deterministic cast-node assignment.
    let mut casts: Vec<(NodeId, NodeId, DType)> = Vec::new();

    for &id in &order {
        let (op, inputs, out_dtype) = {
            let node = graph.node(id);
            (node.op.clone(), node.inputs.clone(), node.dtype)
        };
        let op_kind = match crate::pipelined::op_to_op_kind(&op) {
            Some(k) => k,
            None => continue, // view / Const / not-dispatched → no binding key
        };
        // The exact per-operand key the dispatcher will look up.
        let native_key = crate::pipelined::build_lookup_dtypes(graph, graph.node(id));
        // Only reconcile the generic `[in0, in1, …, out]` key shape. Ops whose
        // key is canonicalized (Concat, WriteSlice*) share a uniform input dtype
        // by construction, so they never present a mixed-input miss here.
        if native_key.len() != inputs.len() + 1 {
            continue;
        }
        // The backends THIS node may actually be placed on. Asked via the
        // planner's own resolver so the two cannot drift: a weaker predicate
        // here (e.g. "does any registered backend serve it?") lets a backend
        // the node can never run on suppress the reconciliation the node needs,
        // and `compile_plan` below then dead-ends at `NoBackendForOp`.
        let candidates = crate::plan::candidate_backends_for(graph, options, id, graph.node(id));
        let servable = |key: &[DType]| {
            candidates
                .iter()
                .any(|&backend| bindings.backend_supports(op_kind, key, backend))
        };

        if servable(&native_key) {
            continue; // a backend this node can run on serves it natively
        }
        // Promotion target = the output dtype ("compute dtype"), taken ONLY when
        // every input can losslessly upcast to it — else decline.
        let target = out_dtype;
        if !inputs
            .iter()
            .all(|&i| lossless_upcast(graph.node(i).dtype, target))
        {
            continue;
        }
        // Uniform promoted key `[target, …, target, out]` (target == out).
        let promoted_key: Vec<DType> = inputs
            .iter()
            .map(|_| target)
            .chain(std::iter::once(out_dtype))
            .collect();
        if promoted_key == native_key {
            continue; // inputs already == target; nothing to promote
        }
        if !servable(&promoted_key) {
            continue; // the lossless promotion still isn't servable — genuine gap
        }
        for &input_id in &inputs {
            if graph.node(input_id).dtype != target {
                casts.push((id, input_id, target));
            }
        }
    }

    if casts.is_empty() {
        return false;
    }
    // Visibility (C-6 "fuel never silently deoptimizes without saying so", applied
    // to precision rather than fusion): a promoting cast is NOT numerically
    // identical to a native mixed-precision kernel — it accumulates the upcast in
    // higher precision, so the same graph can diverge by which arm ran (CPU upcast
    // vs CUDA native mixed) — and it increases the promoted operand's resident
    // bytes (e.g. BF16→F32 doubles a weight). A byte-exact-oracle or determinism
    // consumer must be able to SEE it. Reported via `tracing`; forbidding it under
    // a C-5 constraint + full C-4 cost accounting are tracked ROADMAP follow-ups.
    tracing::warn!(
        promoting_casts = casts.len(),
        "dtype-reconciliation inserted {} promoting Cast(s): a node's per-operand \
         dtype key had no native kernel on any backend, so input(s) were upcast to \
         the output dtype. This CHANGES numerics vs a native mixed-precision kernel \
         and increases resident bytes for the promoted operand(s).",
        casts.len(),
    );
    fuel_graph::opt::insert_cast_fixups(graph, &casts);
    true
}

/// Lossless dtype upcast predicate for [`insert_dtype_fixups`] — `true` ONLY for
/// conversions that preserve every value exactly (identity + float widenings
/// where the target's exponent AND mantissa cover the source's). Deliberately
/// conservative: an unlisted pair returns `false`, so the pass declines rather
/// than risk a lossy or semantics-changing promotion.
fn lossless_upcast(from: DType, to: DType) -> bool {
    use DType::*;
    if from == to {
        return true;
    }
    matches!(
        (from, to),
        (BF16, F32) | (BF16, F64) | (F16, F32) | (F16, F64) | (F32, F64)
    )
}

/// Commit the plan's per-node winner backend to the graph's
/// `target_backend` side-table — the optimizer writing its placement
/// decision into the graph.
///
/// Per kernel-bearing node: stamp `winner.backend` if the plan has an
/// `AlternativeSet` for it, else the pinned device's backend (structural
/// ops the planner skips — `Op::Copy`/`Op::Move`/`Op::Alloc`/`Op::ZeroFill`
/// — plus any op without an `OpKind` mapping). `Op::Const`/`Op::Release`/
/// `Op::Contiguize`/view ops/`Op::Reshape` inherit or don't need a stamp
/// and are skipped. Always overwrites, so re-optimizing after a
/// `TopologyChanged` retry re-stamps consistently from the fresh plan.
fn stamp_plan_backends(
    graph: &mut Graph,
    roots: &[NodeId],
    plan: &ExecutionPlan,
    pinned_loc: DeviceLocation,
) {
    let pinned_backend = pinned_loc.backend();
    let order = topo_order_multi(graph, roots);
    for &id in &order {
        let node = graph.node(id);
        if matches!(node.op, Op::Const | Op::Release | Op::Contiguize)
            || node.op.is_view_op()
            || matches!(node.op, Op::Reshape(_))
        {
            continue;
        }
        let stamp = plan
            .alternatives(id)
            .and_then(|set| set.winner())
            .map(|c| c.backend)
            .unwrap_or(pinned_backend);
        graph.set_target_backend(id, stamp);
    }
}

/// Cleanup Step B (residency): the optimizer-side cross-device copy pass —
/// insert `Op::Copy { target }` on every edge whose producer's resident
/// location doesn't share a storage substrate with the consumer's placement,
/// then stamp each inserted copy's `target_backend` with the SOURCE backend
/// (the pipelined executor's `Op::Copy` convention: the transfer kernel runs
/// on the backend the bytes come FROM). Was the bridge's
/// `insert_resident_input_copies`; moved here so the optimizer — not the
/// realize-time bridge — owns the residency decision and writes it into the
/// graph.
///
/// Placements come from graph-knowable facts only (no realize-time storage):
/// residency-declaring ops, explicit `Graph::placement` (the bridge converts
/// cache residency into placement stamps before optimize — cleanup Step B),
/// the plan winner's device, the `target_backend` stamp (→ pinned), and view
/// pass-through. Substrate sharing is queried via the process-global
/// `SystemTopology` (available pre-realize once backends are registered).
///
/// Runs after `stamp_plan_backends` (it reads `target_backend`); the re-stamp
/// sweep below restores the source-backend stamp on copies/moves that the
/// stamping pass overwrote with the pinned backend.
/// Returns the effective-placement map it resolved, so the optimizer can hand
/// it out via [`OptimizedGraph::placement_of`]. The map is the pass's own input
/// — surfacing it costs nothing and makes the placement decision observable
/// instead of inferable.
///
/// Note the snapshot is taken BEFORE copy insertion (see the `placements`
/// comment below), which is the right vantage for "where did this node land":
/// it reports the placement of the original nodes, with the inserted copies
/// being the consequence rather than part of the answer.
pub(crate) fn insert_residency_copies(
    graph: &mut Graph,
    roots: &[NodeId],
    plan: &ExecutionPlan,
    pinned_loc: DeviceLocation,
    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
) -> HashMap<NodeId, DeviceLocation> {
    // Step E Phase C, PR C-0: walk the ARM-INCLUSIVE reachable set, not bare
    // `roots`. A finalized `Op::Branch` is orphaned (its `reconverge_at` reads
    // arm-0 directly, per the PR-A1 runnability invariant), so a plain
    // `topo_order_multi(roots)` never reaches it — and therefore never reaches
    // its non-arm-0 arms. The residency pass MUST stitch inbound cross-device
    // copies for EVERY surviving arm so the executor can legally re-pick
    // arm-1+ at runtime by live load (C2): whichever arm it picks, that arm's
    // device-inputs are already resident. `effective_roots` (the same seeding
    // the run extractor + route picker use) pulls every Branch's arms into the
    // walk. On a branchless graph it returns exactly `roots` ⇒ byte-identical.
    let eff_roots = fuel_graph::effective_roots(graph, roots);
    let placements = effective_placements(graph, &eff_roots, plan, pinned_loc, input_residency);
    let topology = SystemTopology::current();
    // Identical locations short-circuit to `true` BEFORE the topology lookup
    // (a location trivially shares bytes with itself; `shares_storage` returns
    // `false` for unknown backends, so without this an unprobed topology would
    // wrap every same-device edge in a copy).
    let shares = |a: DeviceLocation, b: DeviceLocation| -> bool {
        if a == b {
            return true;
        }
        topology.shares_storage((a.backend(), a), (b.backend(), b))
    };
    // Hop-count oracle: an edge whose transfer path is `HostStaging` can't
    // be done as a single `Op::Copy` (no direct device-to-device copy
    // kernel between distinct GPU substrates — the cross-VENDOR CUDA↔Vulkan
    // case), so the residency pass routes it through a CPU intermediate as
    // TWO hops. `SystemTopology::transfer_path` already returns `HostStaging`
    // for such pairs and `SameDevice` for `a == b`; CPU↔CUDA / CPU↔Vulkan
    // resolve to a direct path (or the universal host-staging fallback only
    // when CPU is NOT one of the endpoints), so any CPU-touching edge stays
    // single-hop. We additionally guard on neither endpoint being CPU: a CPU
    // intermediate for a CPU-touching edge would be nonsensical (and the
    // single-hop CPU↔GPU Copy kernels exist and are byte-identical to
    // today). Same-vendor GPU pairs that don't share storage (e.g. CUDA gpu0
    // ↔ gpu1) fall back to `HostStaging` too — correctly two-hop, since
    // there's no direct cross-gpu_id copy kernel today either.
    let needs_host_staging = |a: DeviceLocation, b: DeviceLocation| -> bool {
        if a == DeviceLocation::Cpu || b == DeviceLocation::Cpu {
            return false;
        }
        matches!(
            topology.transfer_path(a, b),
            fuel_ir::backend::TransferPath::HostStaging
        )
    };
    let inserted = insert_cross_device_copies(
        graph,
        &eff_roots,
        |id| placements.get(&id).copied(),
        shares,
        needs_host_staging,
    );
    // Source-location resolver for stamping inserted copies. The
    // `placements` snapshot was computed BEFORE insertion, so it does NOT
    // contain the freshly-inserted CPU intermediate of a two-hop edge. That
    // intermediate's placement was written into the graph by the pass
    // (`set_placement(cpu_id, Cpu)`), so fall back to `graph.placement(src)`
    // when the snapshot lacks the node — this is what stamps a two-hop's
    // consumer-side hop with `Cpu` (its bytes come FROM the CPU intermediate,
    // so its Copy kernel is the CPU `copy_from_cpu_wrapper`).
    let src_location = |graph: &Graph, src: NodeId| -> Option<DeviceLocation> {
        placements
            .get(&src)
            .copied()
            .or_else(|| graph.placement(src))
    };
    // Stamp the new copies: target_backend = SOURCE backend. The pass only
    // inserts a copy when the producer's placement resolved to Some.
    for &copy_id in &inserted {
        if let Some(&src) = graph.node(copy_id).inputs.first()
            && let Some(src_loc) = src_location(graph, src)
        {
            graph.set_target_backend(copy_id, src_loc.backend());
        }
    }
    // Re-stamp ALL copies/moves with their SOURCE backend — graph rewrites are
    // sticky and `stamp_plan_backends` just overwrote pre-existing ones (e.g.
    // realize-root splices) with the pinned backend; the transfer kernel runs
    // where the bytes come from. The freshly-inserted copies are visited too,
    // but their input's placement resolves to the same source location, so the
    // sweep re-applies the identical stamp (idempotent). Copies whose source
    // placement is absent keep whatever stamp they already have. The two-hop
    // CPU intermediate's source is the original GPU producer (stamped to that
    // GPU); the consumer-side hop's source is the CPU intermediate (stamped
    // Cpu via the `graph.placement` fallback in `src_location`).
    // Arm-inclusive (C-0): re-walk from the arm-seeded roots so copies just
    // inserted inside non-arm-0 arms are re-stamped too. The `eff_roots` seed
    // set (Branch nodes are unchanged by insertion) reaches the fresh arm
    // copies via the now-rewired arm-input edges.
    let order = topo_order_multi(graph, &eff_roots);
    for &id in &order {
        if !matches!(graph.node(id).op, Op::Copy { .. } | Op::Move { .. }) {
            continue;
        }
        let Some(&src) = graph.node(id).inputs.first() else {
            continue;
        };
        let Some(src_loc) = src_location(graph, src) else {
            continue;
        };
        graph.set_target_backend(id, src_loc.backend());
    }

    placements
}

/// Compute every reachable node's *effective placement* for the residency
/// pass, mirroring the bridge's old `effective_placements`. Priority per node:
///
/// 1. **Residency-declaring ops** — `Op::Copy`/`Op::Move`/`Op::Alloc` carry
///    their output location in the variant (definitional).
/// 2. **Explicit `Graph::placement`** — set by inserted copies (and any
///    caller-provided placement hints).
/// 3. **Input residency** — where a persistent / const input already lives,
///    supplied by the realize path via `PlanOptions::input_residency`. This is
///    the only runtime fact, read through the provider closure — the optimizer
///    never touches the storage itself.
/// 4. **Plan winner** — a planned node runs on its winner's device.
/// 5. **Backend stamp** — a node with `target_backend` but no plan entry
///    (structural ops) follows the pinned device.
/// 6. **View pass-throughs** — view ops / `Reshape` / `Contiguize` follow
///    their data input (already resolved; `order` is topological).
fn effective_placements(
    g: &Graph,
    roots: &[NodeId],
    plan: &ExecutionPlan,
    pinned_loc: DeviceLocation,
    input_residency: Option<&dyn Fn(NodeId) -> Option<DeviceLocation>>,
) -> HashMap<NodeId, DeviceLocation> {
    let order = topo_order_multi(g, roots);
    let mut map: HashMap<NodeId, DeviceLocation> = HashMap::with_capacity(order.len());
    for &id in &order {
        let node = g.node(id);
        match node.op {
            Op::Copy { target } | Op::Move { target } | Op::Alloc { target } => {
                map.insert(id, target);
                continue;
            }
            _ => {}
        }
        if let Some(loc) = g.placement(id) {
            map.insert(id, loc);
            continue;
        }
        if let Some(loc) = input_residency.and_then(|f| f(id)) {
            map.insert(id, loc);
            continue;
        }
        if let Some(winner) = plan.alternatives(id).and_then(|set| set.winner()) {
            map.insert(id, winner.device);
            continue;
        }
        if g.target_backend(id).is_some() {
            map.insert(id, pinned_loc);
            continue;
        }
        if (node.op.is_view_op() || matches!(node.op, Op::Reshape(_) | Op::Contiguize))
            && let Some(&loc) = node.inputs.first().and_then(|i| map.get(i))
        {
            map.insert(id, loc);
        }
    }
    map
}

/// The PR-A4 deliberate-fork pathfinder + the PR-B2 frontier
/// convergence optimizer now live in [`crate::driver`] as registered
/// [`crate::driver::Pathfinder`] / [`crate::driver::Optimizer`] impls
/// ([`crate::driver::PlacementForkPathfinder`] /
/// [`crate::driver::FrontierConvergenceOptimizer`]). PR-B3 replaced the
/// hardcoded `seed_placement_fork_branches(...)` call in
/// [`optimize_graph`] with a lock-step
/// [`crate::driver::PassRegistry::run_lockstep`] drive over those
/// registered passes (see the module docs). The pathfinder body is
/// unchanged — it moved verbatim behind the trait.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::fused::PrecisionGuarantee;
    use crate::kernel::{KernelCaps, OpParams, unknown_cost};
    use fuel_graph::opt::execution_plan;
    use fuel_graph::{Node, Op};
    use fuel_ir::dispatch::OpKind;
    use fuel_ir::probe::BackendId;
    use fuel_ir::{DType, DeviceLocation, Layout, Result as FuelResult, Shape};
    use fuel_memory::Storage;
    use std::sync::{Arc, RwLock};

    fn noop_kernel(
        _i: &[Arc<RwLock<Storage>>],
        _o: &mut [Arc<RwLock<Storage>>],
        _l: &[Layout],
        _p: &OpParams,
    ) -> FuelResult<()> {
        Ok(())
    }

    fn register_elementwise(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
        let mut dtypes = vec![DType::F32; n_in];
        dtypes.push(DType::F32); // output dtype
        table.register_full(
            op,
            &dtypes,
            BackendId::Cpu,
            noop_kernel,
            KernelCaps::empty(),
            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
            unknown_cost,
        );
    }

    fn f32_node(g: &mut Graph, op: Op, inputs: Vec<NodeId>) -> NodeId {
        // No pre-stamp: post-Step-A `optimize_graph` writes `target_backend`
        // itself, so pre-stamping here is redundant for the tests that run the
        // optimizer — and it would falsify the `*_stamps_backends_*` tests'
        // "unstamped before optimize" / "Const leaf not stamped" preconditions.
        g.push(Node {
            op,
            inputs,
            shape: Shape::from_dims(&[4]),
            dtype: DType::F32,
        })
    }

    /// A representative branchless CPU graph the optimizer can fully
    /// place: a fan-in (`Add` over two unary chains) feeding a unary
    /// tail. Every kernel-bearing op has a CPU binding registered. The
    /// fan-in exercises the run extractor's multi-predecessor boundary,
    /// so the equivalence holds across more than a single straight
    /// chain.
    fn build_branchless_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
        register_elementwise(table, OpKind::ReluElementwise, 1);
        register_elementwise(table, OpKind::SiluElementwise, 1);
        register_elementwise(table, OpKind::AddElementwise, 2);
        register_elementwise(table, OpKind::TanhElementwise, 1);

        let mut g = Graph::new();
        let a = f32_node(&mut g, Op::Const, vec![]);
        let a1 = f32_node(&mut g, Op::Relu, vec![a]);
        let b = f32_node(&mut g, Op::Const, vec![]);
        let b1 = f32_node(&mut g, Op::Silu, vec![b]);
        let sum = f32_node(&mut g, Op::Add, vec![a1, b1]);
        let out = f32_node(&mut g, Op::Tanh, vec![sum]);
        (g, out)
    }

    /// ROADMAP row 67 (I1): a graph whose analysed peak exceeds a small budget. `a` is read by `b` early and
    /// by `c` late, so its longest inactive gap is evictable (the same shape the residency tests use).
    fn build_over_budget_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
        register_elementwise(table, OpKind::ReluElementwise, 1);
        register_elementwise(table, OpKind::NegElementwise, 1);
        register_elementwise(table, OpKind::MulElementwise, 2);
        register_elementwise(table, OpKind::AddElementwise, 2);
        let mut g = Graph::new();
        let a = f32_node(&mut g, Op::Const, vec![]);
        let b = f32_node(&mut g, Op::Relu, vec![a]);
        let pad = f32_node(&mut g, Op::Neg, vec![b]);
        let pad2 = f32_node(&mut g, Op::Neg, vec![pad]);
        let c = f32_node(&mut g, Op::Mul, vec![pad2, a]);
        let out = f32_node(&mut g, Op::Add, vec![b, c]);
        (g, out)
    }

    fn count_ops(g: &Graph, pred: impl Fn(&Op) -> bool) -> usize {
        (0..g.len())
            .filter(|i| pred(&g.node(NodeId(*i)).op))
            .count()
    }

    fn peak_bytes(g: &Graph, root: NodeId) -> usize {
        crate::residency::ResidencyPlanner::analyze(g, &[root]).peak_bytes
    }

    #[test]
    fn a_device_budget_below_the_peak_inserts_evict_reload_chains() {
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_over_budget_graph(&mut table);
        let before = peak_bytes(&g, root);
        let opts = cpu_opts().with_device_budget_bytes(before - 1);
        let optimized =
            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph under a budget");
        let outcome = optimized
            .eviction
            .as_ref()
            .expect("a budgeted run reports what the eviction pass did");
        assert!(
            !outcome.chains.is_empty(),
            "the outcome lists the inserted chains"
        );
        assert_eq!(outcome.budget_bytes, before - 1);
        assert!(
            count_ops(&g, |op| matches!(op, Op::Move { .. })) >= 1,
            "a budget below the peak must insert an Op::Move eviction"
        );
        assert!(
            count_ops(&g, |op| matches!(op, Op::Copy { .. })) >= 1,
            "and its reload Op::Copy"
        );
        // Not asserted here: a drop in the analysed peak. This graph is pinned to the CPU, and a
        // spill to the CPU cannot lower CPU residency; that property is pinned in
        // `residency::tests::today_the_reload_runs_eagerly_so_the_device_peak_does_not_drop`
        // (which documents that no round lowers the analysed peak until ROADMAP row 67 I3).
    }

    #[test]
    fn the_plan_report_names_where_the_budget_came_from() {
        use crate::device_budget::{BudgetSource, ResolvedBudget};
        let run = |opts: PlanOptions<'_>| {
            let mut table = KernelBindingTable::new();
            let (mut g, root) = build_over_budget_graph(&mut table);
            optimize_graph(&mut g, &[root], &table, &opts)
                .expect("optimize_graph")
                .eviction
                .expect("a budgeted run reports an outcome")
        };
        let mut table = KernelBindingTable::new();
        let (g, root) = build_over_budget_graph(&mut table);
        let budget = peak_bytes(&g, root) - 1;
        let resolved = ResolvedBudget {
            bytes: budget,
            source: BudgetSource::Probed {
                available: (budget as u64) * 10 / 9,
                fraction: 0.9,
            },
        };
        let from_policy = run(cpu_opts().with_resolved_device_budget(resolved));
        assert_eq!(from_policy.budget_bytes, budget);
        assert_eq!(from_policy.budget_source, Some(resolved.source));
        // Control: a hand-set number carries no source, so the two paths are told apart.
        let by_hand = run(cpu_opts().with_device_budget_bytes(budget));
        assert_eq!(by_hand.budget_source, None);
    }

    #[test]
    fn no_budget_a_roomy_budget_or_no_pinned_device_leave_the_graph_alone() {
        let nodes_of = |opts: &PlanOptions<'_>| {
            let mut table = KernelBindingTable::new();
            let (mut g, root) = build_over_budget_graph(&mut table);
            if opts.pinned_device.is_none() {
                // No pinned device: nodes need explicit placements to plan at all.
                for i in 0..g.len() {
                    g.set_placement(NodeId(i), DeviceLocation::Cpu);
                }
            }
            let optimized = optimize_graph(&mut g, &[root], &table, opts).expect("optimize_graph");
            if opts.device_budget_bytes.is_none() {
                assert!(optimized.eviction.is_none(), "no budget: no outcome");
            }
            (g.len(), count_ops(&g, |op| matches!(op, Op::Move { .. })))
        };
        // Negative control: no budget at all.
        assert_eq!(nodes_of(&cpu_opts()).1, 0, "no budget: no eviction");
        // A budget the graph already fits.
        assert_eq!(
            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).1,
            0,
            "roomy budget: no eviction"
        );
        // The pass is gated on a pinned device, like the residency pass it follows.
        let unpinned = PlanOptions::new()
            .without_cost_population()
            .with_device_budget_bytes(1);
        assert_eq!(nodes_of(&unpinned).1, 0, "no pinned device: no eviction");
        // Node counts match the no-budget run exactly.
        assert_eq!(
            nodes_of(&cpu_opts()).0,
            nodes_of(&cpu_opts().with_device_budget_bytes(usize::MAX)).0
        );
    }

    /// A pure straight-line CPU graph — the simplest no-competing-route
    /// case (exactly one run by construction).
    fn build_straight_line_graph(table: &mut KernelBindingTable) -> (Graph, NodeId) {
        register_elementwise(table, OpKind::ReluElementwise, 1);
        register_elementwise(table, OpKind::SiluElementwise, 1);
        register_elementwise(table, OpKind::TanhElementwise, 1);

        let mut g = Graph::new();
        let a = f32_node(&mut g, Op::Const, vec![]);
        let b = f32_node(&mut g, Op::Relu, vec![a]);
        let c = f32_node(&mut g, Op::Silu, vec![b]);
        let d = f32_node(&mut g, Op::Tanh, vec![c]);
        (g, d)
    }

    fn cpu_opts() -> PlanOptions<'static> {
        // No cost machinery: A3a only needs placement/validation, not
        // ranking. Pin the realize device so every node resolves.
        PlanOptions::new()
            .without_cost_population()
            .with_pinned_device(DeviceLocation::Cpu)
    }

    /// Cleanup Step A: `optimize_graph` stamps each computational node's
    /// chosen backend onto the graph (the optimizer writes its placement
    /// decision INTO the graph). On a pinned-CPU straight-line graph every
    /// kernel-bearing node is stamped `Cpu`; the leaf `Op::Const` is
    /// skipped (it inherits / needs no stamp). When `pinned_device` is
    /// unset, no stamping occurs (the bare-graph test contract).
    #[test]
    fn optimize_graph_stamps_backends_onto_the_graph() {
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_straight_line_graph(&mut table);
        // a=Const(0), b=Relu(1), c=Silu(2), d=Tanh(3) by construction.
        let (a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));
        assert!(g.target_backend(b).is_none(), "unstamped before optimize");

        let _optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
            .expect("optimize_graph on a straight-line CPU graph");

        assert_eq!(
            g.target_backend(b),
            Some(BackendId::Cpu),
            "Relu stamped Cpu"
        );
        assert_eq!(
            g.target_backend(c),
            Some(BackendId::Cpu),
            "Silu stamped Cpu"
        );
        assert_eq!(
            g.target_backend(d),
            Some(BackendId::Cpu),
            "Tanh stamped Cpu"
        );
        assert!(
            g.target_backend(a).is_none(),
            "Op::Const leaf is not stamped"
        );
    }

    /// `OptimizedGraph::placement_of` makes the placement DECISION observable,
    /// so a consumer can check where work landed instead of inferring it from
    /// timing (or from `Graph::placement`, which is only level 2 of the six-way
    /// resolution and returns `None` for exactly the compute nodes that matter).
    ///
    /// Two halves, and the second is the **positive control**: an accessor that
    /// silently returned `None` for everything would satisfy any test that only
    /// asserted `is_none()` on the unpinned path. So the pinned path asserts
    /// concrete `Some(Cpu)` values AND a non-empty map — if placement were never
    /// captured, that half fails loudly rather than passing vacuously.
    #[test]
    fn placement_of_observes_the_decision_and_marks_not_computed() {
        // --- pinned: the residency pass runs, placements are captured ---
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_straight_line_graph(&mut table);
        let (_a, b, c, d) = (NodeId(0), NodeId(1), NodeId(2), NodeId(3));

        let optimized = optimize_graph(&mut g, &[root], &table, &cpu_opts())
            .expect("optimize_graph on a straight-line CPU graph");

        assert!(
            optimized.has_placements(),
            "a pinned device runs the residency pass, so placements must be computed",
        );
        // POSITIVE CONTROL: concrete values, not merely "not None". An empty or
        // never-populated map would fail here instead of passing quietly.
        assert_eq!(
            optimized.placement_of(b),
            Some(DeviceLocation::Cpu),
            "Relu placed Cpu"
        );
        assert_eq!(
            optimized.placement_of(c),
            Some(DeviceLocation::Cpu),
            "Silu placed Cpu"
        );
        assert_eq!(
            optimized.placement_of(d),
            Some(DeviceLocation::Cpu),
            "Tanh placed Cpu"
        );
        assert!(
            optimized.placements().count() >= 3,
            "the map must actually be populated, got {} entries",
            optimized.placements().count(),
        );

        // --- unpinned: the pass is skipped, and that is DISTINGUISHABLE ---
        // This is the property that keeps a `None` from being misread as
        // "placed nowhere" — the failure mode this accessor exists to prevent.
        //
        // Device context has to come from SOMEWHERE or `compile_plan` refuses
        // outright ("node has no device context — set PlanOptions::pinned_device,
        // a graph placement, or the node's target_backend"). So supply it via
        // per-node graph placement instead of a pin: the graph optimizes fine,
        // but `pinned_device` is unset so the residency pass never runs — which
        // is exactly the "optimized successfully, placement not computed" state
        // a caller must be able to tell apart from "placed nowhere".
        let mut table2 = KernelBindingTable::new();
        let (mut g2, root2) = build_straight_line_graph(&mut table2);
        for n in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
            g2.set_placement(n, DeviceLocation::Cpu);
        }
        let bare = PlanOptions::new().without_cost_population();
        let unpinned = optimize_graph(&mut g2, &[root2], &table2, &bare)
            .expect("optimize_graph with graph placements but no pinned device");

        assert!(
            !unpinned.has_placements(),
            "no pinned device => residency pass skipped => placements NOT computed",
        );
        assert_eq!(
            unpinned.placement_of(b),
            None,
            "and every lookup is None — which `has_placements()` explains as \
             'not computed', never 'placed nowhere'",
        );
    }

    /// Dtype-reconciliation declines on the REAL CPU table: the mixed-precision `[F32, BF16, F32]`
    /// and `[F32, F16, F32]` matmuls (f32 activation x half weight) are served natively by the CPU
    /// kernels `matmul_f32_bf16` / `matmul_f32_f16` (ROADMAP row 34), so `optimize_graph` plans them
    /// as they are and inserts no `Cast`: the weight stays half-width instead of being promoted to a
    /// resident f32 copy. Before row 34 this test asserted the opposite (a `Cast(F32)` on the
    /// weight, the fallback that the local-table tests below still pin for a backend WITHOUT the
    /// native key).
    #[test]
    fn optimize_graph_keeps_mixed_precision_matmul_native_on_cpu() {
        for weight in [DType::BF16, DType::F16] {
            let bindings = crate::dispatch::global_bindings(); // real populated CPU table
            let mut g = Graph::new();
            let lhs = g.push(Node {
                op: Op::Const,
                inputs: vec![],
                shape: Shape::from_dims(&[2, 3]),
                dtype: DType::F32,
            });
            let rhs = g.push(Node {
                op: Op::Const,
                inputs: vec![],
                shape: Shape::from_dims(&[3, 2]),
                dtype: weight,
            });
            let mm = g.push(Node {
                op: Op::MatMul,
                inputs: vec![lhs, rhs],
                shape: Shape::from_dims(&[2, 2]),
                dtype: DType::F32,
            });

            optimize_graph(&mut g, &[mm], &bindings, &cpu_opts())
                .expect("mixed-precision matmul plans natively on CPU");

            assert_eq!(
                g.node(mm).inputs,
                vec![lhs, rhs],
                "{weight:?}: no Cast, the CPU serves [F32, {weight:?}, F32] natively",
            );
            assert_eq!(g.node(rhs).dtype, weight, "the weight stays {weight:?}");
        }
    }

    fn register_matmul(table: &mut KernelBindingTable, dtypes: &[DType], backend: BackendId) {
        table.register_full(
            OpKind::MatMul,
            dtypes,
            backend,
            noop_kernel,
            KernelCaps::empty(),
            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
            unknown_cost,
        );
    }

    /// The reconciling `Op::Cast` the pass inserts needs a binding of its own to
    /// plan. The production table has these (`(Cpu, Cast, [BF16, F32])`); a
    /// hand-built test table must register them explicitly.
    fn register_cast(table: &mut KernelBindingTable, from: DType, to: DType, backend: BackendId) {
        table.register_full(
            OpKind::Cast,
            &[from, to],
            backend,
            noop_kernel,
            KernelCaps::empty(),
            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
            unknown_cost,
        );
    }

    /// `[F32] @ [BF16] -> [F32]` on a graph pinned to `pinned`.
    fn mixed_matmul_graph() -> (Graph, NodeId, NodeId, NodeId) {
        let mut g = Graph::new();
        let lhs = g.push(Node {
            op: Op::Const,
            inputs: vec![],
            shape: Shape::from_dims(&[2, 3]),
            dtype: DType::F32,
        });
        let rhs = g.push(Node {
            op: Op::Const,
            inputs: vec![],
            shape: Shape::from_dims(&[3, 2]),
            dtype: DType::BF16,
        });
        let mm = g.push(Node {
            op: Op::MatMul,
            inputs: vec![lhs, rhs],
            shape: Shape::from_dims(&[2, 2]),
            dtype: DType::F32,
        });
        (g, lhs, rhs, mm)
    }

    /// **Born-red regression guard: a backend must never break a graph that
    /// isn't running on it.**
    ///
    /// `insert_dtype_fixups` used to guard on `any_backend_supports` — a
    /// predicate over the WHOLE binding table that ignores the key's backend
    /// component. `compile_plan` enumerates over the node's *candidate
    /// placement set*. So when a non-candidate backend owned the only native
    /// mixed-dtype kernel, the pass saw "someone serves it", declined to
    /// reconcile, and the planner then dead-ended at `NoBackendForOp`.
    ///
    /// In-tree that surfaced as `--features vulkan` breaking CPU-pinned
    /// mixed-precision matmul, because Vulkan happens to be the only backend
    /// registering `MatMul[F32, BF16, F32]`. This test builds that situation
    /// from a LOCAL table so it reproduces in **every** build configuration —
    /// the feature-gated version is why the defect shipped unnoticed.
    #[test]
    fn dtype_reconciliation_ignores_kernels_on_non_candidate_backends() {
        let mut table = KernelBindingTable::new();
        // The pinned backend serves only the uniform key...
        register_matmul(
            &mut table,
            &[DType::F32, DType::F32, DType::F32],
            BackendId::Cpu,
        );
        // ...while a backend this graph will never run on owns the mixed key.
        register_matmul(
            &mut table,
            &[DType::F32, DType::BF16, DType::F32],
            BackendId::Vulkan,
        );
        register_cast(&mut table, DType::BF16, DType::F32, BackendId::Cpu);

        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect(
            "CPU-pinned mixed-precision matmul must reconcile via Cast even though \
             a NON-candidate backend owns the native mixed kernel",
        );

        let mm_inputs = g.node(mm).inputs.clone();
        assert_eq!(mm_inputs[0], lhs, "lhs (already F32) untouched");
        let cast_id = mm_inputs[1];
        assert_ne!(cast_id, rhs, "rhs was rewired to a Cast");
        assert!(
            matches!(g.node(cast_id).op, Op::Cast(DType::F32)),
            "rhs cast to F32"
        );
        assert_eq!(
            g.node(cast_id).inputs,
            vec![rhs],
            "cast reads the original BF16 weight"
        );
    }

    /// The converse guard — the fix must not over-cast. When the node's own
    /// candidate backend serves the mixed key natively, reconciliation must
    /// decline, so the native mixed-precision kernel is preserved (casting
    /// would change numerics and double the promoted operand's bytes).
    #[test]
    fn dtype_reconciliation_declines_when_the_candidate_backend_serves_it_natively() {
        let mut table = KernelBindingTable::new();
        register_matmul(
            &mut table,
            &[DType::F32, DType::BF16, DType::F32],
            BackendId::Cpu,
        );

        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
        optimize_graph(&mut g, &[mm], &table, &cpu_opts()).expect("native mixed kernel plans");

        assert_eq!(
            g.node(mm).inputs,
            vec![lhs, rhs],
            "no Cast: the candidate backend has the native mixed kernel",
        );
    }

    /// Multi-device behavior must be PRESERVED, not sacrificed to fix the bug
    /// above. When an off-device fallback is admitted, the foreign backend IS
    /// a candidate for this node — so its native mixed kernel is reachable and
    /// reconciliation must still decline. This is why the fix mirrors the
    /// planner's candidate set rather than narrowing to the pinned device.
    #[test]
    fn dtype_reconciliation_counts_admitted_off_device_fallback_as_a_candidate() {
        let mut table = KernelBindingTable::new();
        register_matmul(
            &mut table,
            &[DType::F32, DType::F32, DType::F32],
            BackendId::Cpu,
        );
        register_matmul(
            &mut table,
            &[DType::F32, DType::BF16, DType::F32],
            BackendId::Vulkan,
        );

        let fallback = |_from: DeviceLocation| -> Vec<(BackendId, DeviceLocation)> {
            vec![(BackendId::Vulkan, DeviceLocation::Vulkan { gpu_id: 0 })]
        };
        let opts = PlanOptions::new()
            .without_cost_population()
            .with_pinned_device(DeviceLocation::Cpu)
            .with_fallback_placements_for(&fallback);

        let (mut g, lhs, rhs, mm) = mixed_matmul_graph();
        optimize_graph(&mut g, &[mm], &table, &opts).expect("off-device native mixed kernel plans");

        assert_eq!(
            g.node(mm).inputs,
            vec![lhs, rhs],
            "no Cast: the admitted off-device fallback backend serves the mixed key natively",
        );
    }

    /// The stamping is guarded on a pinned device — an `optimize_graph`
    /// with no `pinned_device` leaves the graph unstamped (so the bare
    /// optimize.rs test callers below are unaffected by Step A).
    #[test]
    fn optimize_graph_without_pinned_device_does_not_stamp() {
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_straight_line_graph(&mut table);
        // Give each node a device context via a graph PLACEMENT (a distinct
        // side-table from `target_backend`), so `compile_plan` resolves without
        // a pinned device — then assert `optimize_graph` performs no
        // `target_backend` stamping (the stamping arm is guarded on
        // `pinned_device`, so without a pin nothing is stamped).
        for id in [NodeId(0), NodeId(1), NodeId(2), NodeId(3)] {
            g.set_placement(id, DeviceLocation::Cpu);
        }
        let opts = PlanOptions::new().without_cost_population(); // no pinned device
        let _ = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");
        assert!(
            g.target_backend(NodeId(1)).is_none(),
            "no pinned device ⇒ no target_backend stamping",
        );
    }

    /// Cleanup Step B (layout): `optimize_graph` inserts an `Op::Contiguize`
    /// before a kernel whose chosen winner rejects strided inputs
    /// (`caps.strided_input == false`, e.g. the `KernelCaps::empty()`
    /// elementwise bindings) and whose input layout is non-contiguous — the
    /// layout-fixup pass moved from the realize-time bridge into the optimizer.
    /// The pass itself is exhaustively tested in `fuel-graph::opt`; this guards
    /// the optimizer-side wiring (callback reads the plan winner's caps, runs
    /// inside the pinned guard).
    #[test]
    fn optimize_graph_inserts_layout_fixup_for_strided_input() {
        let mut table = KernelBindingTable::new();
        register_elementwise(&mut table, OpKind::ReluElementwise, 1); // empty caps ⇒ rejects strided
        let mut g = Graph::new();
        let a = f32_node(&mut g, Op::Const, vec![]);
        let r = f32_node(&mut g, Op::Relu, vec![a]);
        // Make `a`'s effective layout non-contiguous (non-zero start_offset),
        // so the strided-rejecting Relu needs a Contiguize on its input.
        g.set_layout(a, Layout::contiguous_with_offset(Shape::from_dims(&[4]), 1));

        let _optimized = optimize_graph(&mut g, &[r], &table, &cpu_opts())
            .expect("optimize_graph with a strided input");

        // Relu's input was `a`; after the fixup it must read through an inserted
        // Op::Contiguize wrapping `a`.
        let relu_input = g.node(r).inputs[0];
        assert!(
            matches!(g.node(relu_input).op, Op::Contiguize),
            "strided input to a strided-rejecting kernel must be fixed up via \
             Op::Contiguize, got {:?}",
            g.node(relu_input).op,
        );
        assert_eq!(
            g.node(relu_input).inputs,
            vec![a],
            "the inserted Op::Contiguize wraps the original strided input",
        );
    }

    // ---- Cleanup Step B (residency) — insert_residency_copies tests ----
    // (migrated from the bridge's insert_resident_input_copies unit tests;
    // cache residency is supplied via an `input_residency` closure instead of a
    // live StorageCache. Placement metadata only — no GPU needed; the unprobed
    // test `SystemTopology` reports Cpu/Cuda as non-sharing, so a crossing is
    // detected and a copy inserted.)

    /// Co-located graph ⇒ `insert_residency_copies` is a no-op (no crossings).
    #[test]
    fn residency_noop_when_colocated() {
        let mut g = Graph::new();
        let c1 = f32_node(&mut g, Op::Const, vec![]);
        let c2 = f32_node(&mut g, Op::Const, vec![]);
        let add = f32_node(&mut g, Op::Add, vec![c1, c2]);
        g.set_target_backend(add, BackendId::Cpu);
        let residency = |id: NodeId| (id == c1 || id == c2).then_some(DeviceLocation::Cpu);
        let pre = g.len();
        insert_residency_copies(
            &mut g,
            &[add],
            &ExecutionPlan::empty(),
            DeviceLocation::Cpu,
            Some(&residency),
        );
        assert_eq!(g.len(), pre, "co-located graph must be a no-op");
        assert_eq!(g.node(add).inputs, vec![c1, c2], "edges untouched");
    }

    /// A CPU-resident input feeding two CUDA-pinned consumers ⇒ exactly ONE
    /// `Op::Copy` bridges the crossing (CSE-deduped), targeting the consumer
    /// device, stamped `target_backend = SOURCE` (Cpu, the H2D wrapper) with
    /// its output placed on the consumer device.
    #[test]
    fn residency_one_copy_per_crossing_deduped() {
        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
        let mut g = Graph::new();
        let c1 = f32_node(&mut g, Op::Const, vec![]);
        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
        let sqr = f32_node(&mut g, Op::Sqr, vec![c1]);
        g.set_target_backend(neg, BackendId::Cuda);
        g.set_target_backend(sqr, BackendId::Cuda);
        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);

        let pre = g.len();
        insert_residency_copies(
            &mut g,
            &[neg, sqr],
            &ExecutionPlan::empty(),
            cuda0,
            Some(&residency),
        );

        assert_eq!(g.len(), pre + 1, "one crossing → one copy, CSE-deduped");
        let neg_in = g.node(neg).inputs[0];
        let sqr_in = g.node(sqr).inputs[0];
        assert_eq!(neg_in, sqr_in, "both consumers share the one copy");
        assert_ne!(neg_in, c1, "consumers rewired off the raw input");
        let copy = g.node(neg_in);
        assert!(
            matches!(copy.op, Op::Copy { target } if target == cuda0),
            "copy targets the consumer device; got {:?}",
            copy.op,
        );
        assert_eq!(copy.inputs, vec![c1], "copy reads the resident slot");
        assert_eq!(
            g.target_backend(neg_in),
            Some(BackendId::Cpu),
            "stamped with the SOURCE backend (H2D runs on the CPU wrapper)",
        );
        assert_eq!(
            g.placement(neg_in),
            Some(cuda0),
            "copy output placed on the consumer device",
        );
    }

    /// Idempotence + re-stamp: a second pass on the rewritten graph inserts
    /// nothing and restores the source-backend stamp even after a clobber
    /// (mimicking `stamp_plan_backends` overwriting it with the pinned backend).
    #[test]
    fn residency_idempotent_and_restamped_on_second_call() {
        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
        let mut g = Graph::new();
        let c1 = f32_node(&mut g, Op::Const, vec![]);
        let neg = f32_node(&mut g, Op::Neg, vec![c1]);
        g.set_target_backend(neg, BackendId::Cuda);
        let residency = |id: NodeId| (id == c1).then_some(DeviceLocation::Cpu);

        insert_residency_copies(
            &mut g,
            &[neg],
            &ExecutionPlan::empty(),
            cuda0,
            Some(&residency),
        );
        let copy_id = g.node(neg).inputs[0];
        // Simulate stamp_plan_backends clobbering the copy with the pinned backend.
        g.set_target_backend(copy_id, BackendId::Cuda);

        let pre = g.len();
        insert_residency_copies(
            &mut g,
            &[neg],
            &ExecutionPlan::empty(),
            cuda0,
            Some(&residency),
        );
        assert_eq!(g.len(), pre, "re-run inserts nothing");
        assert_eq!(
            g.target_backend(copy_id),
            Some(BackendId::Cpu),
            "re-stamp sweep restores the source-backend stamp",
        );
    }

    // ---- Step E Phase C, PR C-0: arm residency-copy audit ----
    //
    // C2 lets the executor re-pick an `Op::Branch` arm at runtime by live
    // device load — it may choose arm-1+ instead of the static arm-0 winner.
    // That is only legal if the optimizer's residency pass has ALREADY
    // stitched the inbound cross-device `Op::Copy` for EVERY surviving arm,
    // so whichever arm the executor picks, that arm's device-inputs are
    // resident on its device. This test builds a 2-arm diamond whose two arms
    // live on DIFFERENT devices (arm-0 CPU, arm-1 CUDA) sharing one CPU
    // producer, runs the residency pass, and asserts BOTH arms' cross-device
    // inputs got their copy — not just arm-0's.
    //
    // The finalized `Op::Branch` is orphaned (its `reconverge_at` reads arm-0
    // directly, per the PR-A1 runnability invariant), so arm-1 is reachable
    // ONLY through the Branch node. `insert_residency_copies` walks
    // `topo_order_multi(roots)` directly (NOT `effective_roots`), so it never
    // reaches an orphaned Branch — and therefore never reaches arm-1. The
    // run/route machinery (`extract_runs_multi`, `branches_in_topo_order`)
    // does use `effective_roots`; the residency pass does not. This is the
    // C-0 prerequisite gap.

    /// Build a 2-arm diamond: a CPU producer `diverge` fans into arm-0 (CPU)
    /// and arm-1 (`arm1_loc`); `reconverge` reads arm-0 (the runnability
    /// invariant); the Branch merges {arm0, arm1} at `reconverge`. Returns
    /// `(graph, branch, diverge, arm0, arm1, post)`. Placements are set via
    /// `set_placement` so the residency pass reads them with no plan/winner.
    fn residency_diamond(
        arm1_loc: DeviceLocation,
    ) -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId) {
        let mut g = Graph::new();
        let pre = f32_node(&mut g, Op::Const, vec![]);
        let diverge = f32_node(&mut g, Op::Relu, vec![pre]);
        let arm0 = f32_node(&mut g, Op::Silu, vec![diverge]);
        let arm1 = f32_node(&mut g, Op::GeluTanh, vec![diverge]);
        let reconverge = f32_node(&mut g, Op::Relu, vec![arm0]);
        let mut b = g.open_branch(diverge);
        b.add_arm(arm0);
        b.add_arm(arm1);
        let branch = b
            .finalize_branches(&mut g, reconverge)
            .expect("well-formed 2-arm branch")
            .expect("2 arms survive");
        let post = f32_node(&mut g, Op::Tanh, vec![reconverge]);
        // Producer + arm-0 + the post-merge region on CPU; arm-1 elsewhere.
        g.set_placement(pre, DeviceLocation::Cpu);
        g.set_placement(diverge, DeviceLocation::Cpu);
        g.set_placement(arm0, DeviceLocation::Cpu);
        g.set_placement(reconverge, DeviceLocation::Cpu);
        g.set_placement(post, DeviceLocation::Cpu);
        g.set_placement(arm1, arm1_loc);
        (g, branch, diverge, arm0, arm1, post)
    }

    /// C-0 PREREQUISITE: the residency pass must insert the inbound
    /// cross-device `Op::Copy` for BOTH arms of a 2-device branch — arm-0
    /// (CPU, same device as the producer ⇒ no copy needed) AND arm-1 (CUDA,
    /// crosses ⇒ MUST get a copy). If only arm-0 were stitched, re-picking
    /// arm-1 at runtime (C2) would dispatch a CUDA kernel whose input was
    /// never copied to the GPU → the un-bridged-mixed-edge error / a UAF.
    #[test]
    fn residency_stitches_every_branch_arm_not_just_arm0() {
        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
        let (mut g, _branch, diverge, arm0, arm1, post) = residency_diamond(cuda0);

        insert_residency_copies(
            &mut g,
            &[post],
            &ExecutionPlan::empty(),
            DeviceLocation::Cpu,
            None,
        );

        // arm-0 is CPU, same substrate as the CPU producer ⇒ its input edge
        // does NOT cross ⇒ no copy (and must stay reading `diverge`).
        assert_eq!(
            g.node(arm0).inputs,
            vec![diverge],
            "arm-0 is co-located with its producer ⇒ no copy, edge untouched",
        );

        // arm-1 is CUDA, its producer `diverge` is CPU ⇒ the edge crosses ⇒
        // the residency pass MUST have inserted an Op::Copy targeting CUDA on
        // arm-1's input. THIS is the C-0 invariant: every surviving arm's
        // device-inputs are made resident, not just arm-0's.
        let arm1_in = g.node(arm1).inputs[0];
        assert_ne!(
            arm1_in, diverge,
            "arm-1 (CUDA) reads the CPU producer directly — its inbound \
             cross-device Op::Copy was NEVER inserted. Re-picking arm-1 at \
             runtime (C2) would dispatch a CUDA kernel over un-copied CPU \
             bytes. The residency pass stitched only arm-0's route.",
        );
        let copy = g.node(arm1_in);
        assert!(
            matches!(copy.op, Op::Copy { target } if target == cuda0),
            "arm-1's inbound copy must target CUDA; got {:?}",
            copy.op,
        );
        assert_eq!(
            copy.inputs,
            vec![diverge],
            "arm-1's copy reads the shared CPU producer",
        );
    }

    // ---- PR-A4 deliberate-fork-seed test substrate ----

    fn noop_kernel_b(
        _i: &[Arc<RwLock<Storage>>],
        _o: &mut [Arc<RwLock<Storage>>],
        _l: &[Layout],
        _p: &OpParams,
    ) -> FuelResult<()> {
        Ok(())
    }

    /// Register a CPU AND a (synthetic) CUDA binding for `op` so a node
    /// enumerated against both placements gets two viable
    /// `(backend, device)` candidates — the genuine placement fork the
    /// A4 pathfinder seeds a branch from.
    fn register_two_backend(table: &mut KernelBindingTable, op: OpKind, n_in: usize) {
        let mut dtypes = vec![DType::F32; n_in];
        dtypes.push(DType::F32);
        table.register_full(
            op,
            &dtypes,
            BackendId::Cpu,
            noop_kernel,
            KernelCaps::empty(),
            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
            unknown_cost,
        );
        table.register_full(
            op,
            &dtypes,
            BackendId::Cuda,
            noop_kernel_b,
            KernelCaps::empty(),
            PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
            unknown_cost,
        );
    }

    fn two_backend_placements(dev: DeviceLocation) -> Vec<BackendId> {
        if dev == DeviceLocation::Cpu {
            vec![BackendId::Cpu, BackendId::Cuda]
        } else {
            vec![]
        }
    }

    /// Two backends co-located at the realize device, so every
    /// kernel-bearing node enumerates ≥2 placements — the multi-backend
    /// build the A4 pathfinder forks on. CPU-only builds (one placement
    /// per node) never hit this; the equivalence/idempotence gates above
    /// cover that.
    fn two_backend_opts() -> PlanOptions<'static> {
        PlanOptions::new()
            .without_cost_population()
            .with_pinned_device(DeviceLocation::Cpu)
            .with_placements_for_device(&two_backend_placements)
    }

    /// A graph with a single kernel-bearing node that has a genuine
    /// ≥2-placement choice AND exactly one consumer (so it is a
    /// deliberate fork, not plain fan-out). Only `fork`'s op (`Silu`) is
    /// registered on two backends, so it is the ONLY node with a real
    /// ≥2-placement choice — exactly the "most ops are CPU-only, the
    /// matmul has cuBLAS too" shape.
    ///
    /// A long CPU-only `Relu` body surrounds the fork so the single
    /// deliberate branch sits far below the fewness threshold (a tiny
    /// graph would be all-branch by node count): `c -> body* -> prod ->
    /// fork -> tail -> body*`. `prod` is the diverge; `tail` is the
    /// reconverge (it reads `fork`).
    fn build_single_fork_graph(
        table: &mut KernelBindingTable,
    ) -> (Graph, NodeId, NodeId, NodeId, NodeId) {
        register_elementwise(table, OpKind::ReluElementwise, 1);
        register_two_backend(table, OpKind::SiluElementwise, 1); // the fork
        register_elementwise(table, OpKind::TanhElementwise, 1);

        let mut g = Graph::new();
        let mut prev = f32_node(&mut g, Op::Const, vec![]);
        // Straight-line CPU body before the fork.
        for _ in 0..20 {
            prev = f32_node(&mut g, Op::Relu, vec![prev]);
        }
        let prod = prev; // the diverge (fork's producer)
        let fork = f32_node(&mut g, Op::Silu, vec![prod]);
        let tail = f32_node(&mut g, Op::Tanh, vec![fork]); // reconverge
        // Straight-line CPU body after the reconverge — the realize root
        // is the body's tail, so the whole graph is reachable and the
        // single fork sits far below the fewness threshold.
        let mut prev = tail;
        for _ in 0..20 {
            prev = f32_node(&mut g, Op::Relu, vec![prev]);
        }
        let root = prev;
        (g, prod, fork, tail, root)
    }

    /// THE A4 DELIBERATE-FORK GATE (born-red until the pathfinder
    /// emits a Branch).
    ///
    /// (a) A node with two viable `(backend, device)` placements and a
    /// single consumer ⇒ `optimize_graph` emits exactly ONE 2-arm
    /// `Op::Branch` whose arm-0 is the DP winner, and the result passes
    /// the fewness gate.
    #[test]
    fn deliberate_fork_emits_one_two_arm_branch() {
        use fuel_graph::{branch_density, passes_fewness_gate};
        let mut table = KernelBindingTable::new();
        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
        let opts = two_backend_opts();

        let nodes_before = g.len();
        let optimized = optimize_graph(&mut g, &[root], &table, &opts)
            .expect("optimize_graph succeeds on a 2-placement graph");

        // Exactly one Op::Branch in the arena.
        assert_eq!(
            optimized.branch_count(&g),
            1,
            "a single genuine placement fork emits exactly one Op::Branch",
        );

        // It is a 2-arm branch (arm-0 = the winner = `fork`).
        let branch_id = (nodes_before..g.len())
            .map(NodeId)
            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
            .expect("a Branch node was appended");
        let branch = g.node(branch_id);
        assert_eq!(branch.inputs.len(), 2, "the branch has exactly two arms");
        assert_eq!(
            branch.inputs[0], fork,
            "arm-0 is the DP winner node (the route realize uses today)",
        );
        assert_ne!(
            branch.inputs[1], fork,
            "arm-1 is a distinct (runner-up placement) node",
        );

        // The fewness gate holds — one branch among many nodes.
        assert!(
            passes_fewness_gate(&g, root),
            "a single deliberate fork passes the fewness gate; density={}",
            branch_density(&g, root),
        );
    }

    /// (b) An ordinary DAG fan-out (one result, two distinct consumers)
    /// with the SAME 2-placement freedom is NOT flagged as a branch —
    /// fan-out is not a decision point.
    #[test]
    fn plain_fan_out_is_not_a_branch() {
        let mut table = KernelBindingTable::new();
        // Only the fan-out node's op (`Relu`) is dual-backend, so it is
        // the sole ≥2-placement candidate — and it is excluded purely
        // because it fans out (two consumers), not because it lacks a
        // placement choice. The consumers are CPU-only.
        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
        register_elementwise(&mut table, OpKind::TanhElementwise, 1);
        register_elementwise(&mut table, OpKind::AddElementwise, 2);

        // `shared` has two distinct consumers (c0, c1) that join at
        // `out` — plain fan-out, not a fork — even though it has a real
        // 2-placement choice.
        let mut g = Graph::new();
        let c = f32_node(&mut g, Op::Const, vec![]);
        let shared = f32_node(&mut g, Op::Relu, vec![c]);
        let c0 = f32_node(&mut g, Op::Silu, vec![shared]);
        let c1 = f32_node(&mut g, Op::Tanh, vec![shared]);
        let out = f32_node(&mut g, Op::Add, vec![c0, c1]);
        let opts = two_backend_opts();

        let optimized =
            optimize_graph(&mut g, &[out], &table, &opts).expect("optimize_graph succeeds");
        assert_eq!(
            optimized.branch_count(&g),
            0,
            "plain fan-out (multiple consumers) is not a deliberate fork",
        );
        let _ = shared;
    }

    /// (c) A branched graph realizes correctly via arm-0: the dispatch
    /// order follows {pre, arm-0, post} and SKIPS arm-1's run.
    #[test]
    fn branched_graph_realizes_via_arm0() {
        let mut table = KernelBindingTable::new();
        let (mut g, prod, fork, tail, root) = build_single_fork_graph(&mut table);
        let opts = two_backend_opts();

        // Capture the single-route order BEFORE the branch is emitted —
        // this is the order realize must reproduce on arm-0.
        let pre_order = execution_plan(&g, &[root]);

        let optimized =
            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");

        // The arm-1 node is the branch's second input — it must NOT
        // appear in the arm-0 dispatch order.
        let branch_id = (0..g.len())
            .map(NodeId)
            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
            .expect("a Branch node exists");
        let arm1 = g.node(branch_id).inputs[1];

        let order = optimized.dispatch_order(&g);
        assert!(
            !order.contains(&arm1),
            "arm-0 lowering must skip arm-1's run; order={order:?} arm1={arm1:?}",
        );
        // arm-0 (fork) and the pre/post nodes ARE executed.
        assert!(order.contains(&prod), "pre-run (diverge producer) executes");
        assert!(order.contains(&fork), "arm-0 (the winner) executes");
        assert!(order.contains(&tail), "post-run (reconverge) executes");
        assert!(order.contains(&root), "the realize root executes");

        // Behavior preserving: arm-0 lowering reproduces exactly the
        // pre-branch single-route order (arm-0 = the DP winner = the
        // graph realize used before the branch was recorded).
        assert_eq!(
            order, pre_order,
            "arm-0 dispatch order equals the pre-branch single-route order",
        );
    }

    /// Return type of [`cached_env_test_fixture`] — named purely to dodge
    /// `clippy::type_complexity`, not because any caller needs the alias.
    type CachedEnvTestFixture = (
        Arc<RwLock<Graph>>,
        crate::pipelined::StorageCache,
        OptimizedGraph,
        std::sync::OnceLock<Vec<NodeId>>,
        Arc<dyn crate::ranker::RuntimeSelector>,
        NodeId,
    );

    /// Shared setup for the two `cached_env_*` tests below: a single-fork
    /// graph, a two-backend `OptimizedGraph`, a seeded `StorageCache`, a
    /// fresh `order_cache`, and a real (non-stub) `WinnerSelector`.
    /// Factored out purely to keep each test under Codacy's method-length
    /// bound — no behavior lives here that either test's own body needs to
    /// see inline.
    fn cached_env_test_fixture() -> CachedEnvTestFixture {
        use crate::pipelined::StorageCache;
        use crate::ranker::runtime_selector::WinnerSelector;

        let mut table = KernelBindingTable::new();
        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
        let opts = two_backend_opts();
        let optimized =
            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");

        let graph = Arc::new(RwLock::new(g));
        let mut cache = StorageCache::new();
        cache.insert(
            NodeId(0), // the leaf Const build_single_fork_graph pushes first.
            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
                1.0_f32, 2.0, 3.0, 4.0,
            ]))),
        );
        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
        let selector: Arc<dyn crate::ranker::RuntimeSelector> = Arc::new(WinnerSelector);
        (graph, cache, optimized, order_cache, selector, root)
    }

    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
    /// §5), answering the PM's review question directly: on a graph with a
    /// REAL `Op::Branch` and a REAL selector (so the executor's picking
    /// entry point resolves a genuine pick, not just "no branches to
    /// pick"), `realize_with_optimized_picking_cached_env` must route
    /// through `OrderSource::Streaming`, NEVER through `OrderSource::Cached`
    /// — proven here by checking `order_cache` stays EMPTY across two
    /// separate picking realizes, not merely by reading the routing code.
    /// This is the stronger property PR review asked for: the fix doesn't
    /// need a cache key that "covers the pick" because picked graphs never
    /// reach the cache in the first place — `realize_with_optimized_picking_env`'s
    /// OWN routing (`streaming_pick_for` returning `Some` whenever a
    /// selector is given over a branched graph) already excludes them, and
    /// this test is what proves that exclusion actually holds for the
    /// cached sibling too, not just the uncached original.
    ///
    /// `result`/`result2` tolerate `Error::TopologyChanged` as a passing
    /// outcome, not just `Ok`: `optimized.generation` is stamped once, from
    /// the process-wide `topology_generation()` counter, at `optimize_graph`
    /// time above — and that counter is shared by every test in this binary
    /// (`register_runtime_kernel`/`extend_global_bindings`'s own doc admits
    /// this; see `register_runtime_kernel_into`'s test-only escape hatch).
    /// A sibling test registering a runtime-fused kernel between here and
    /// either realize call bumps it, and `realize_inner`'s chunk-boundary
    /// check (pipelined.rs) deliberately does NOT retry at this layer —
    /// only `pipelined_bridge`'s wrapper does (by design, so a low-level
    /// `PipelinedExecutor` caller sees the typed error, not a silent stall).
    /// A real retry would need a fresh `optimize_graph` call, which would
    /// defeat this test's actual subject (whether the same `OptimizedGraph`
    /// and `order_cache` stay consistent across repeat calls), so instead
    /// of retrying we just don't fail on the one outcome this test was
    /// never about. The `order_cache`-emptiness assertions stay
    /// unconditional: the `Streaming` path never touches `order_cache`
    /// regardless of whether the realize that invoked it succeeded or hit
    /// this race.
    #[test]
    fn cached_env_never_caches_a_branched_graph_with_a_real_selector() {
        use crate::PipelinedExecutor;
        use fuel_ir::{Error, SymEnv};

        let (graph, cache, optimized, order_cache, selector, root) = cached_env_test_fixture();

        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
            graph.clone(),
            root,
            cache.clone(),
            &optimized,
            &order_cache,
            Some(selector.clone()),
            None,
            SymEnv::default(),
        );
        assert!(
            result.is_ok() || matches!(result, Err(Error::TopologyChanged { .. })),
            "a picked realize over a branched graph must either succeed or hit the \
             (unrelated, expected-under-concurrency) TopologyChanged race: {:?}",
            result.err()
        );
        assert!(
            order_cache.get().is_none(),
            "a branched graph with a real selector pick must NEVER populate order_cache — \
             it must route through OrderSource::Streaming, not OrderSource::Cached",
        );

        // A second call, same cache slot: still must not populate it.
        let result2 = PipelinedExecutor::realize_with_optimized_picking_cached_env(
            graph,
            root,
            cache,
            &optimized,
            &order_cache,
            Some(selector),
            None,
            SymEnv::default(),
        );
        assert!(
            result2.is_ok() || matches!(result2, Err(Error::TopologyChanged { .. })),
            "second picked realize must either succeed or hit the same expected-under- \
             concurrency TopologyChanged race: {:?}",
            result2.err()
        );
        assert!(
            order_cache.get().is_none(),
            "order_cache must still be empty after a second picked realize",
        );
    }

    /// Deterministic sibling of the test above: forces the EXACT race
    /// `Error::TopologyChanged` tolerance was added for, instead of relying
    /// on another test in the binary to collide by chance. Proves two
    /// things the flaky-under-`-j4` observation alone couldn't: (1) that a
    /// stale `optimized.generation` is SUFFICIENT to reproduce the exact
    /// failure this test's sibling hit (confirming the root cause, not
    /// just a plausible story), and (2) that `order_cache` stays empty
    /// even on the `Err` branch (the property this test file is actually
    /// about, independent of the race).
    ///
    /// Deliberately does NOT call the real, process-wide
    /// `bump_topology_generation()` to force this — that would inflict the
    /// exact `-j4` cross-test hazard this test documents onto every OTHER
    /// concurrently-running test in the binary that assumes a stable
    /// generation (an earlier draft of this test did exactly that, and
    /// broke `realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm`
    /// under `-j4`). `OptimizedGraph::generation` is `pub`, so mutating
    /// this test's own LOCAL copy to a value that can't match the live
    /// counter reproduces the identical code path with zero blast radius.
    #[test]
    fn cached_env_tolerates_a_concurrent_topology_generation_bump() {
        use crate::PipelinedExecutor;
        use fuel_ir::{Error, SymEnv};

        let (graph, cache, mut optimized, order_cache, selector, root) = cached_env_test_fixture();

        // Simulate a sibling test's legitimate `register_runtime_kernel`/
        // `extend_global_bindings` call landing between `optimize_graph`
        // (which stamped `optimized.generation` above) and this realize —
        // exactly the collision `cached_env_never_caches_a_branched_graph_with_a_real_selector`
        // hit under `-j4` — by staling THIS test's own copy of the stamp,
        // not the shared live counter every other test also reads.
        optimized.generation = optimized.generation.wrapping_add(1);

        let result = PipelinedExecutor::realize_with_optimized_picking_cached_env(
            graph,
            root,
            cache,
            &optimized,
            &order_cache,
            Some(selector),
            None,
            SymEnv::default(),
        );
        assert!(
            matches!(result, Err(Error::TopologyChanged { .. })),
            "a forced generation bump before realize must surface as TopologyChanged, \
             not silently succeed or fail some other way: {:?}",
            result
        );
        assert!(
            order_cache.get().is_none(),
            "order_cache must stay empty even when the realize that would have \
             populated it (if it were ever going to) failed with TopologyChanged",
        );
    }

    /// (d) No `DEFAULT_MAX_N` truncation: the fork records the winner +
    /// a runner-up without a fixed top-N cap stranding placements. Both
    /// arms survive; the per-device frontier — not a fixed N — bounds
    /// the arms.
    #[test]
    fn no_default_max_n_truncation() {
        let mut table = KernelBindingTable::new();
        let (mut g, _prod, fork, _tail, root) = build_single_fork_graph(&mut table);
        let opts = two_backend_opts();

        let optimized =
            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
        assert_eq!(optimized.branch_count(&g), 1);
        let branch_id = (0..g.len())
            .map(NodeId)
            .find(|&id| matches!(g.node(id).op, Op::Branch { .. }))
            .expect("a Branch node exists");
        // Two distinct placements ⇒ two arms survive; the runner-up was
        // not dropped by any top-N cap.
        assert_eq!(g.node(branch_id).inputs.len(), 2);
        assert_eq!(g.node(branch_id).inputs[0], fork);
    }

    /// THE EQUIVALENCE GATE (born-red until `optimize_graph` exists and
    /// its lowered order matches `compile_plan`).
    ///
    /// On representative no-competing-route graphs, assert:
    ///   (a) `optimize_graph` leaves ZERO `Op::Branch` nodes, and
    ///   (b) the concatenated `extract_runs`/`lower_run` dispatch order
    ///       EQUALS today's `compile_plan(...).order` exactly (same
    ///       NodeIds, same order).
    #[test]
    fn equivalence_gate_branchless_order_matches_compile_plan() {
        for build in [
            build_straight_line_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
        ] {
            let mut table = KernelBindingTable::new();
            let (mut g, root) = build(&mut table);
            let opts = cpu_opts();

            // Today's path: the exact order the executor walks.
            let order = execution_plan(&g, &[root]);
            let plan = compile_plan(&g, &order, &table, &opts)
                .expect("today's compile_plan succeeds on a placeable graph");

            // New path.
            let optimized = optimize_graph(&mut g, &[root], &table, &opts)
                .expect("optimize_graph succeeds on the same graph");

            // (a) zero competing routes => zero Branch nodes.
            assert_eq!(
                optimized.branch_count(&g),
                0,
                "a no-competing-route graph optimizes to zero Op::Branch nodes",
            );

            // (b) EXACT order equality against compile_plan(...).order.
            let lowered = optimized.dispatch_order(&g);
            assert_eq!(
                lowered, plan.order,
                "the extract_runs/lower_run dispatch order must equal \
                 compile_plan(...).order exactly (same NodeIds, same order)",
            );
            // And it covers every reachable node — the executor walks
            // the whole graph, runs partition it with no gaps/dupes.
            assert_eq!(
                lowered.len(),
                order.len(),
                "the lowered order covers every node compile_plan ordered",
            );
        }
    }

    /// `optimize_graph` on a branchless graph is idempotent and adds no
    /// nodes: the node count is unchanged across repeated calls, the
    /// branch count stays zero, and the lowered order is stable.
    #[test]
    fn optimize_graph_branchless_is_idempotent_and_adds_no_nodes() {
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_branchless_graph(&mut table);
        let opts = cpu_opts();

        let nodes_before = g.len();
        let first =
            optimize_graph(&mut g, &[root], &table, &opts).expect("first optimize succeeds");
        let order_first = first.dispatch_order(&g);
        let nodes_after_first = g.len();

        let second =
            optimize_graph(&mut g, &[root], &table, &opts).expect("second optimize succeeds");
        let order_second = second.dispatch_order(&g);
        let nodes_after_second = g.len();

        assert_eq!(
            nodes_before, nodes_after_first,
            "optimize_graph adds no nodes (A3a is single-route-only)",
        );
        assert_eq!(
            nodes_after_first, nodes_after_second,
            "a second optimize_graph adds no further nodes — idempotent",
        );
        assert_eq!(first.branch_count(&g), 0, "no branches after first");
        assert_eq!(second.branch_count(&g), 0, "no branches after second");
        assert_eq!(
            order_first, order_second,
            "the lowered dispatch order is stable across repeated optimize",
        );
    }

    /// Identity proof for `docs/design/incremental-consumer-index.md` §5's
    /// `order_for` fix track: that fix proposes memoizing `dispatch_order`'s
    /// output WHOLESALE once per plan-once session, instead of recomputing
    /// it (via `extract_runs_multi` + `non_chosen_arm_nodes`, measured
    /// ~56ms/step, the single largest named sub-cost in a live decode step)
    /// on every `realize_inner` call. That's only valid if calling
    /// `dispatch_order` repeatedly on the SAME `OptimizedGraph` view with NO
    /// intervening graph mutation — exactly the plan-once decode shape,
    /// where only leaf values are rebound between tokens, never the graph's
    /// structure — yields a byte-identical `Vec<NodeId>` every time. Proven
    /// here, not assumed: five repeated calls, two structurally different
    /// branchless graphs (a fan-in boundary and a plain chain), zero
    /// mutation between calls (deliberately — this is NOT the existing
    /// `optimize_graph_branchless_is_idempotent_and_adds_no_nodes` test
    /// above, which re-runs `optimize_graph` itself between its two
    /// `dispatch_order` calls; this one proves `dispatch_order` is pure on
    /// its own, independent of re-optimizing).
    #[test]
    fn dispatch_order_is_stable_across_repeated_calls_with_no_mutation() {
        for build in [
            build_branchless_graph as fn(&mut KernelBindingTable) -> (Graph, NodeId),
            build_straight_line_graph,
        ] {
            let mut table = KernelBindingTable::new();
            let (mut g, root) = build(&mut table);
            let opts = cpu_opts();
            let optimized = optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph");

            let orders: Vec<Vec<NodeId>> = (0..5).map(|_| optimized.dispatch_order(&g)).collect();
            for (i, order) in orders.iter().enumerate().skip(1) {
                assert_eq!(
                    &orders[0], order,
                    "dispatch_order call {i} diverged from call 0 with no intervening \
                     mutation — the order_for memoization fix would be UNSAFE if this failed",
                );
            }
        }
    }

    /// Build-time validation: optimize_graph fails fast (Result, never
    /// panic) when a kernel-bearing node has no registered binding —
    /// reusing compile_plan's missing-binding diagnostic.
    #[test]
    fn optimize_graph_fails_fast_on_missing_binding() {
        let table = KernelBindingTable::new(); // empty — no bindings.
        let mut g = Graph::new();
        let a = f32_node(&mut g, Op::Const, vec![]);
        let relu = f32_node(&mut g, Op::Relu, vec![a]);
        let opts = cpu_opts();

        let err = optimize_graph(&mut g, &[relu], &table, &opts)
            .map(|_| ())
            .unwrap_err();
        match err {
            fuel_ir::Error::NoBackendForOp { op, .. } => {
                assert_eq!(op, OpKind::ReluElementwise);
            }
            other => panic!("expected NoBackendForOp, got {other:?}"),
        }
    }

    // ===== Phase B PR-B3: the lock-step pathfinder/ranker/optimizer
    //        driver. =====

    use crate::driver::{
        FrontierConvergenceOptimizer, OptimizationContext, Optimizer, PassRegistry, Pathfinder,
        PlacementForkPathfinder,
    };
    use std::collections::HashSet;

    /// Snapshot of a graph's `Op::Branch` decision points, keyed by
    /// arena order: `(branch_id, reconverge_at, arm NodeIds)`. Two
    /// optimization paths that produce the same snapshot produced the
    /// same multi-path graph (behavior-preservation).
    fn branch_snapshot(g: &Graph) -> Vec<(NodeId, NodeId, Vec<NodeId>)> {
        (0..g.len())
            .map(NodeId)
            .filter_map(|id| match g.node(id).op {
                Op::Branch { reconverge_at } => {
                    Some((id, reconverge_at, g.node(id).inputs.clone()))
                }
                _ => None,
            })
            .collect()
    }

    /// THE LOAD-BEARING BEHAVIOR-PRESERVATION GATE (born-red until
    /// `optimize_graph` routes through the lock-step driver).
    ///
    /// On a representative multi-placement graph, the driver
    /// (`PassRegistry::default_passes().run_lockstep`) produces the
    /// **identical** multi-path graph as the old hardcoded sequence
    /// (pathfinder then optimizer, in that order): same branch count,
    /// same arm-0 winner, same arms, same reconverge points, and the
    /// same arm-0 dispatch order. B3 is a structural refactor — the
    /// optimized result must not change.
    #[test]
    fn driver_matches_legacy_sequence() {
        // (A) The reference: drive the registered passes BY HAND in the
        //     legacy order (propose, then prune) onto a freshly compiled
        //     plan — exactly what the pre-B3 hardcoded sequence did.
        let mut ref_table = KernelBindingTable::new();
        let (mut ref_g, _prod, ref_fork, _tail, ref_root) = build_single_fork_graph(&mut ref_table);
        let opts = two_backend_opts();
        let ref_order = execution_plan(&ref_g, &[ref_root]);
        let ref_plan = compile_plan(&ref_g, &ref_order, &ref_table, &opts)
            .expect("reference compile_plan succeeds");
        {
            let guard: HashSet<NodeId> = HashSet::new();
            let ctx = OptimizationContext {
                order: &ref_order,
                plan: &ref_plan,
                cycle_guard: &guard,
                bindings: &ref_table,
            };
            // Legacy order: the pathfinder ADDs, then the optimizer
            // prunes — the same two operations the hardcoded sequence ran.
            PlacementForkPathfinder
                .propose(&mut ref_g, &ctx)
                .expect("pathfinder proposes");
            FrontierConvergenceOptimizer
                .prune(&mut ref_g, &ctx)
                .expect("optimizer prunes");
        }
        let ref_snapshot = branch_snapshot(&ref_g);
        let ref_dispatch = fuel_graph::lower_runs_arm0(&ref_g, &[ref_root]);

        // (B) The driver path: optimize_graph routes through
        //     PassRegistry::default_passes().run_lockstep.
        let mut table = KernelBindingTable::new();
        let (mut g, _p, fork, _t, root) = build_single_fork_graph(&mut table);
        let optimized =
            optimize_graph(&mut g, &[root], &table, &opts).expect("optimize_graph succeeds");
        let got_snapshot = branch_snapshot(&g);
        let got_dispatch = optimized.dispatch_order(&g);

        // Identical multi-path graph: same branches, arms, reconverge.
        assert_eq!(
            got_snapshot, ref_snapshot,
            "driver produces the identical Op::Branch structure as the legacy \
             pathfinder→optimizer sequence",
        );
        assert_eq!(
            got_snapshot.len(),
            1,
            "the representative multi-placement graph produces exactly one branch",
        );
        assert_eq!(
            got_snapshot[0].2[0], fork,
            "arm-0 is the DP winner (the route realize uses)",
        );
        // Identical dispatch order (arm-0 single-route lowering).
        assert_eq!(
            got_dispatch, ref_dispatch,
            "driver yields the identical arm-0 dispatch order as the legacy sequence",
        );
        let _ = ref_fork;
    }

    /// A no-op registry (no registered pathfinders) leaves a branchless
    /// graph unchanged: no nodes added, zero branches, identical
    /// dispatch order. Proves the driver itself introduces no structure.
    #[test]
    fn noop_registry_leaves_branchless_graph_unchanged() {
        let mut table = KernelBindingTable::new();
        let (mut g, root) = build_branchless_graph(&mut table);
        let opts = cpu_opts();

        let order = execution_plan(&g, &[root]);
        let plan = compile_plan(&g, &order, &table, &opts).expect("compile_plan succeeds");

        let dispatch_before = fuel_graph::lower_runs_arm0(&g, &[root]);
        let nodes_before = g.len();

        let registry = PassRegistry::new(); // empty — no passes.
        assert_eq!(registry.pathfinder_count(), 0);
        assert_eq!(registry.optimizer_count(), 0);

        let guard: HashSet<NodeId> = HashSet::new();
        let ctx = OptimizationContext {
            order: &order,
            plan: &plan,
            cycle_guard: &guard,
            bindings: &table,
        };
        registry
            .run_lockstep(&mut g, &ctx)
            .expect("empty registry runs cleanly");

        assert_eq!(g.len(), nodes_before, "no-op registry adds no nodes");
        let branches = (0..g.len())
            .map(NodeId)
            .filter(|&id| matches!(g.node(id).op, Op::Branch { .. }))
            .count();
        assert_eq!(branches, 0, "no-op registry adds no branches");
        let dispatch_after = fuel_graph::lower_runs_arm0(&g, &[root]);
        assert_eq!(
            dispatch_before, dispatch_after,
            "no-op registry leaves the dispatch order unchanged",
        );
    }

    /// Lock-step ordering: a pathfinder ADDs before its dependent
    /// optimizer PRUNEs. We register a recording pathfinder and a
    /// recording optimizer that each stamp a shared log when invoked;
    /// `run_lockstep` must invoke the pathfinder strictly before the
    /// optimizer (prune-as-you-go, never optimizer-first).
    #[test]
    fn lockstep_runs_pathfinder_before_dependent_optimizer() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct RecordPathfinder(Arc<Mutex<Vec<&'static str>>>);
        impl Pathfinder for RecordPathfinder {
            fn name(&self) -> &'static str {
                "RecordPathfinder"
            }
            fn propose(
                &self,
                _g: &mut Graph,
                _ctx: &OptimizationContext<'_>,
            ) -> fuel_ir::Result<()> {
                self.0.lock().unwrap().push("propose");
                Ok(())
            }
        }
        #[derive(Clone)]
        struct RecordOptimizer(Arc<Mutex<Vec<&'static str>>>);
        impl Optimizer for RecordOptimizer {
            fn name(&self) -> &'static str {
                "RecordOptimizer"
            }
            fn prune(&self, _g: &mut Graph, _ctx: &OptimizationContext<'_>) -> fuel_ir::Result<()> {
                self.0.lock().unwrap().push("prune");
                Ok(())
            }
        }

        let log = Arc::new(Mutex::new(Vec::new()));
        let registry = PassRegistry::new()
            .with_pathfinder(Box::new(RecordPathfinder(log.clone())))
            .with_optimizer(Box::new(RecordOptimizer(log.clone())));

        let mut g = Graph::new();
        let _a = f32_node(&mut g, Op::Const, vec![]);
        let plan = ExecutionPlan::empty();
        let order: Vec<NodeId> = Vec::new();
        let guard: HashSet<NodeId> = HashSet::new();
        let table = KernelBindingTable::new();
        let ctx = OptimizationContext {
            order: &order,
            plan: &plan,
            cycle_guard: &guard,
            bindings: &table,
        };
        registry.run_lockstep(&mut g, &ctx).expect("drive runs");

        let seq = log.lock().unwrap().clone();
        assert_eq!(
            seq,
            vec!["propose", "prune"],
            "lock-step drive runs the pathfinder ADD strictly before its \
             dependent optimizer PRUNE (prune-as-you-go)",
        );
    }

    /// **Where does `PagedAttn`'s DECOMPOSED form land on CUDA?** — the
    /// measurement that gates whether offering a decomposed arm is worth
    /// building, and what to ask Baracuda for.
    ///
    /// Established already: the FUSED `Op::PagedAttn` node executes on the CPU
    /// under CUDA decode (`paged_decode_node_placement_report_cuda`), because
    /// no CUDA backend advertises it — so "runs on host" is not a decision the
    /// planner made, it is the only move it had. `decompose` exists and is
    /// closed-basis, but the planner is never offered it.
    ///
    /// This asks the question that decides the next build, and it is a
    /// GPU-vs-GPU question that the 186× host-ward figure cannot answer —
    /// **any** on-device path removes that round-trip equally, so its magnitude
    /// says something must be built without saying what:
    ///
    /// - **every recipe node CUDA-placed** → the round-trip is removable with
    ///   NO kernel work at all; the ask to Baracuda may be nothing.
    /// - **some primitive falls back to host** → *that primitive* is the ask,
    ///   far smaller and better-specified than "paged attention".
    ///
    /// A grep cannot answer this. I tried: it reported `Permute` in zero
    /// CUDA-backend files while the measured placement dump showed
    /// `Permute Cuda×6` — it undercounts ops served by generic dispatch. Only
    /// the planner's own resolved map settles it.
    ///
    /// REPORTS rather than asserting a verdict, for the same reason as the
    /// fused-node report: pre-committing to an answer is the error being
    /// corrected. What it DOES assert is that the instrument ran
    /// (`has_placements()`) and that decomposition actually happened (the root
    /// moved off the fused node) — an all-`None` dump would read as "nothing
    /// is on CUDA", a wrong answer wearing a null answer's clothes.
    #[test]
    #[ignore = "live GPU (CUDA); run via scripts/gpu-run.ps1"]
    #[cfg(feature = "cuda")]
    fn paged_attn_decomposed_arm_placement_report_cuda() {
        use fuel_graph::registry::{FusedOpParams, FusedOps};
        use std::collections::BTreeMap;

        const B: usize = 1;
        const HQ: usize = 4;
        const HKV: usize = 4;
        const SQ: usize = 1;
        const D: usize = 4;
        const NUM_BLOCKS: usize = 32;
        const BLOCK_SIZE: usize = 4;
        const MAX_BLK: usize = 8;

        let mut g = Graph::new();
        let leaf = |g: &mut Graph, dims: &[usize], dtype: DType| {
            g.push(Node {
                op: Op::Const,
                inputs: vec![],
                shape: Shape::from_dims(dims),
                dtype,
            })
        };
        let q = leaf(&mut g, &[B, HQ, SQ, D], DType::F32);
        let kc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
        let vc = leaf(&mut g, &[NUM_BLOCKS, BLOCK_SIZE, HKV, D], DType::F32);
        let bt = leaf(&mut g, &[B, MAX_BLK], DType::U32);
        let cl = leaf(&mut g, &[B], DType::U32);

        let params = FusedOpParams::PagedAttn {
            softmax_scale: 1.0 / (D as f32).sqrt(),
            block_size: BLOCK_SIZE,
            softcap: None,
        };
        let fused = g.push(Node {
            op: Op::Fused(FusedOps::PAGED_ATTN, params.clone()),
            inputs: vec![q, kc, vc, bt, cl],
            shape: Shape::from_dims(&[B, HQ, SQ, D]),
            dtype: DType::F32,
        });

        // Lower the fused node to its primitive recipe — the arm the planner is
        // never currently offered.
        let root = fuel_graph::registry::paged_attn::decompose(&mut g, fused, &params);
        assert_ne!(
            root, fused,
            "PRECONDITION: decompose must actually lower. A self-return is the \
             G2 fixpoint signal (malformed node / declined recipe), and every \
             placement below would then describe the FUSED node, silently \
             answering a different question than the one asked.",
        );

        // THE PRODUCTION TABLE, not a hand-assembled one. An earlier version of
        // this test built the table with `register_cuda_kernels` alone and got
        // "no backend supports index_select" — which was an artifact of the
        // HARNESS, not a fact about Fuel: that function makes ~5 registrations
        // and the bulk of CUDA lives in `register_baracuda_cuda_kernels`, which
        // the real path (`register_optional_backends`) also calls, on top of
        // `register_cpu_kernels` and a cost fill. Reproducing that assembly by
        // hand is precisely the kind of thing that silently drifts, so ask for
        // the table the realize path actually uses.
        let table = crate::dispatch::global_bindings();

        // POSITIVE CONTROL — the instrument must be able to see a CUDA binding
        // at all. Without this, an under-populated table reports "no CUDA
        // support" for EVERY op, which reads exactly like a real finding: it is
        // specific, it names a primitive, and it is completely wrong. That is
        // how the first run of this test nearly shipped a false Baracuda ask.
        // MatMul is the control because the fuel-core placement report measured
        // `MatMul Cuda×15` on a real decode graph — an independently observed
        // fact this table must reproduce.
        assert!(
            table
                .lookup(
                    OpKind::MatMul,
                    &[DType::F32, DType::F32, DType::F32],
                    BackendId::Cuda
                )
                .is_ok(),
            "INSTRUMENT BROKEN: the binding table has no CUDA MatMul, so every \
             'no CUDA support' conclusion below would be an artifact of the \
             harness. Fix the table before reading any verdict from this test.",
        );

        // ---- THE COMPLETE MISSING-BINDING SET, asked directly ----
        //
        // `optimize_graph` fails at the FIRST unplaceable node, so driving this
        // off its error yields one op per run — a trickle, and each run costs a
        // CUDA rebuild. Worse, it conflates two different things: "CUDA has no
        // kernel for this op" and "the planner could not place it under THIS
        // pin". Asking the binding table per node separates them and returns the
        // whole set at once.
        let mut missing_cuda: Vec<String> = Vec::new();
        let mut present_cuda: Vec<String> = Vec::new();
        for i in 0..g.len() {
            let id = NodeId(i);
            let node = g.node(id);
            let Some(kind) = crate::pipelined::op_to_op_kind(&node.op) else {
                continue; // Const / view / fused — not a binding-table lookup
            };
            let mut dtypes: Vec<DType> = node.inputs.iter().map(|&i| g.node(i).dtype).collect();
            dtypes.push(node.dtype); // binding key is [inputs.., output]
            let sig = format!(
                "{kind:?}{:?}",
                dtypes.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>()
            );
            if table.lookup(kind, &dtypes, BackendId::Cuda).is_ok() {
                present_cuda.push(sig);
            } else {
                missing_cuda.push(sig);
            }
        }
        missing_cuda.sort();
        missing_cuda.dedup();
        present_cuda.sort();
        present_cuda.dedup();

        println!("\n=== PagedAttn recipe: CUDA binding coverage (asked per node) ===");
        println!("PRESENT on CUDA ({}):", present_cuda.len());
        for s in &present_cuda {
            println!("    {s}");
        }
        println!("MISSING on CUDA ({}):", missing_cuda.len());
        for s in &missing_cuda {
            println!("    {s}");
        }
        // A run where NOTHING resolves would mean the table is empty again — the
        // MatMul control above already guards that, but state the invariant that
        // makes the "missing" list meaningful rather than vacuous.
        assert!(
            !present_cuda.is_empty(),
            "INSTRUMENT BROKEN: not one recipe node resolved on CUDA, so the \
             MISSING list is a property of the lookup, not of the backend",
        );
        println!(
            "\n>>> THE ASK: the {} signature(s) above are what CUDA lacks for the \
             §1 dense recipe. Each is a small, named primitive — not \"paged \
             attention\".\n",
            missing_cuda.len()
        );

        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
        let optimized = match optimize_graph(&mut g, &[root], &table, &opts) {
            Ok(o) => o,
            Err(e) => {
                println!("\n=== DECOMPOSED ARM DOES NOT PLAN ON CUDA ===");
                println!("optimize_graph error: {e:?}");
                println!("That is itself the answer: some recipe primitive has no CUDA");
                println!("binding, and the error names it. THAT is the Baracuda ask.");
                return;
            }
        };

        assert!(
            optimized.has_placements(),
            "placement NOT COMPUTED — every placement_of would be None and the \
             report below would describe the missing instrument, not the graph",
        );

        let mut by_op: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
        let mut host_ops: Vec<String> = Vec::new();
        for i in 0..g.len() {
            let id = NodeId(i);
            let op_name = match &g.node(id).op {
                Op::Fused(fid, _) => format!("Fused({fid:?})"),
                other => format!("{other:?}")
                    .split(' ')
                    .next()
                    .unwrap_or("?")
                    .to_string(),
            };
            let place = match optimized.placement_of(id) {
                Some(d) => format!("{d:?}"),
                None => "None".to_string(),
            };
            if place.starts_with("Cpu") {
                host_ops.push(op_name.clone());
            }
            *by_op.entry(op_name).or_default().entry(place).or_insert(0) += 1;
        }

        println!("\n=== PagedAttn DECOMPOSED arm: node placement (CUDA-pinned) ===");
        println!(
            "total nodes: {} (fused node #{} lowered to root #{})",
            g.len(),
            fused.0,
            root.0
        );
        for (op, places) in &by_op {
            let rendered: Vec<String> = places.iter().map(|(d, n)| format!("{d}×{n}")).collect();
            println!("  {op:<40} {}", rendered.join("  "));
        }

        println!("\n--- VERDICT ---");
        if host_ops.is_empty() {
            println!(
                "EVERY recipe node is off-host. The decomposed paged attention runs \
                 ON DEVICE, so the 186x round-trip is removable by OFFERING THIS ARM \
                 — no Baracuda kernel required to eliminate it. A kernel would then \
                 be a throughput question (the recipe materialises padded capacity, \
                 not live context_len), not a round-trip one."
            );
        } else {
            host_ops.sort();
            host_ops.dedup();
            println!(
                "HOST-PLACED recipe primitives: {host_ops:?}\n\
                 These are the ask — each is a far smaller and better-specified \
                 request than \"paged attention\", and until they exist on device \
                 the decomposed arm cannot win."
            );
        }
        println!("--- END VERDICT ---\n");
    }

    // ---- GAP-380 (a1): lower a fused op with no kernel on the pinned device -------------------

    /// `[q, k_cache, v_cache, block_table, context_lens]` consts, a fused PAGED_ATTN, and a
    /// `Contiguize` consumer. Returns `(graph, consumer)`.
    fn paged_attn_graph() -> (Graph, NodeId) {
        use fuel_graph::registry::{FusedOpParams, FusedOps};
        let mut g = Graph::new();
        let mut leaf = |dims: &[usize], dtype: DType| {
            g.push(Node {
                op: Op::Const,
                inputs: vec![],
                shape: Shape::from_dims(dims),
                dtype,
            })
        };
        let q = leaf(&[1, 2, 1, 4], DType::F32);
        let kc = leaf(&[3, 2, 2, 4], DType::F32);
        let vc = leaf(&[3, 2, 2, 4], DType::F32);
        let bt = leaf(&[1, 2], DType::U32);
        let cl = leaf(&[1], DType::U32);
        let fused = g.push(Node {
            op: Op::Fused(
                FusedOps::PAGED_ATTN,
                FusedOpParams::PagedAttn {
                    softmax_scale: 0.5,
                    block_size: 2,
                    softcap: None,
                },
            ),
            inputs: vec![q, kc, vc, bt, cl],
            shape: Shape::from_dims(&[1, 2, 1, 4]),
            dtype: DType::F32,
        });
        let consumer = g.push(Node {
            op: Op::Contiguize,
            inputs: vec![fused],
            shape: Shape::from_dims(&[1, 2, 1, 4]),
            dtype: DType::F32,
        });
        (g, consumer)
    }

    fn paged_attn_nodes(g: &Graph, root: NodeId) -> usize {
        topo_order_multi(g, &[root])
            .into_iter()
            .filter(|&n| {
                matches!(
                    g.node(n).op,
                    Op::Fused(fuel_graph::registry::FusedOps::PAGED_ATTN, _)
                )
            })
            .count()
    }

    #[test]
    fn a_cuda_pin_with_no_cuda_paged_attn_kernel_lowers_the_fused_node() {
        let (mut g, root) = paged_attn_graph();
        let opts = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
        assert_eq!(
            paged_attn_nodes(&g, root),
            1,
            "PRECONDITION: one fused node"
        );
        let n = lower_fused_unbound_on_pinned_device(&mut g, &[root], &opts, &|_, _| false);
        assert_eq!(n, 1);
        assert_eq!(
            paged_attn_nodes(&g, root),
            0,
            "no fused PAGED_ATTN stays reachable"
        );
    }

    /// Sabotage siblings: each condition of the gate, taken away alone, leaves the node fused.
    #[test]
    fn the_gate_needs_a_cuda_pin_no_bound_kernel_and_a_listed_op() {
        // A bound CUDA kernel: keep the fused node (the fast path wins when it exists).
        let (mut g, root) = paged_attn_graph();
        let cuda = PlanOptions::new().with_pinned_device(DeviceLocation::Cuda { gpu_id: 0 });
        assert_eq!(
            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cuda, &|_, _| true),
            0
        );
        assert_eq!(paged_attn_nodes(&g, root), 1);
        // A CPU pin: the host kernel IS the right place, so nothing lowers.
        let (mut g, root) = paged_attn_graph();
        let cpu = PlanOptions::new().with_pinned_device(DeviceLocation::Cpu);
        assert_eq!(
            lower_fused_unbound_on_pinned_device(&mut g, &[root], &cpu, &|_, _| false),
            0
        );
        assert_eq!(paged_attn_nodes(&g, root), 1);
        // No pin at all (bare-graph callers): untouched.
        let (mut g, root) = paged_attn_graph();
        let bare = PlanOptions::new();
        assert_eq!(
            lower_fused_unbound_on_pinned_device(&mut g, &[root], &bare, &|_, _| false),
            0
        );
        assert_eq!(paged_attn_nodes(&g, root), 1);
    }

    /// The production predicate is the real registry: CUDA has no PAGED_ATTN kernel today, CPU does.
    /// Red the day a CUDA kernel is bound (then the recipe is the slower path and this list must be
    /// revisited, which is the point).
    #[test]
    fn the_registry_has_a_cpu_paged_attn_kernel_and_no_cuda_one() {
        let impls = crate::fused::default_kernel_registry()
            .impls_for(fuel_graph::registry::FusedOps::PAGED_ATTN);
        assert!(
            impls
                .iter()
                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cpu),
            "CONTROL: the registry lookup sees the CPU PAGED_ATTN kernels"
        );
        assert!(
            !impls
                .iter()
                .any(|(b, _)| *b == fuel_ir::probe::BackendId::Cuda),
            "a CUDA PAGED_ATTN kernel is bound: revisit LOWER_WHEN_NO_DEVICE_KERNEL (the fused kernel may now beat the recipe)"
        );
    }
    /// Helper for the row-157 region tests: every kernel op registered on two placements.
    fn two_placement_table() -> KernelBindingTable {
        let mut table = KernelBindingTable::new();
        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
        register_two_backend(&mut table, OpKind::SiluElementwise, 1);
        register_two_backend(&mut table, OpKind::TanhElementwise, 1);
        register_two_backend(&mut table, OpKind::AddElementwise, 2);
        table
    }

    /// `(branch_id, arm-0 exit, reconverge)` of every `Op::Branch` added after `from`.
    fn branches_after(g: &Graph, from: usize) -> Vec<(NodeId, NodeId, NodeId)> {
        (from..g.len())
            .map(NodeId)
            .filter_map(|id| match g.node(id).op {
                Op::Branch { reconverge_at } => Some((id, g.node(id).inputs[0], reconverge_at)),
                _ => None,
            })
            .collect()
    }

    /// ROW 157 / GAP-385, RESIDUAL JOIN AND FAN-OUT (born red against the one-node fork, which made
    /// 8 one-node forks here and none at `n1` or `res`).
    ///
    /// A transformer-block-shaped graph, every op on two placements: a residual block whose body fans
    /// out (`n1` feeds q, k and v which rejoin through `a` and `b`), then a second residual block.
    /// Expect one multi-node region per residual block: block 1 has diverge `x`, a seven-node arm
    /// (`n1 q k v a b o`) and reconverge `res`, which reads `x` directly (the residual edge); block 2
    /// has diverge `res`, a two-node arm (`n2 m`) and reconverge `res2`.
    #[test]
    fn transformer_shaped_graph_forks_residual_blocks_as_multi_node_regions() {
        let table = two_placement_table();
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let n1 = f32_node(&mut g, Op::Relu, vec![x]); // fan-out: q, k, v
        let q = f32_node(&mut g, Op::Silu, vec![n1]);
        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
        let v = f32_node(&mut g, Op::Relu, vec![n1]);
        let a = f32_node(&mut g, Op::Add, vec![q, k]);
        let b = f32_node(&mut g, Op::Add, vec![a, v]);
        let o = f32_node(&mut g, Op::Silu, vec![b]);
        let res = f32_node(&mut g, Op::Add, vec![x, o]); // residual join
        let n2 = f32_node(&mut g, Op::Relu, vec![res]);
        let m = f32_node(&mut g, Op::Silu, vec![n2]);
        let res2 = f32_node(&mut g, Op::Add, vec![res, m]);

        let before = g.len();
        let optimized = optimize_graph(&mut g, &[res2], &table, &two_backend_opts())
            .expect("optimize_graph succeeds on a transformer-shaped two-placement graph");

        let mut branches = branches_after(&g, before);
        branches.sort_by_key(|(_, exit, _)| exit.0);
        assert_eq!(
            optimized.branch_count(&g),
            2,
            "one region per residual block"
        );
        assert_eq!(
            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
            vec![(o, res), (m, res2)],
            "arm-0 exits and reconverge nodes: (o, res) and (m, res2)"
        );
        // Arm 1 clones the whole stretch: 7 + 2 clone nodes beside the 2 branch nodes.
        assert_eq!(
            g.len() - before,
            7 + 2 + 2,
            "clones of both stretches plus two branch nodes"
        );
        // Block 1's arm-1 head reads the shared diverge node x (not a clone), and res reads x directly.
        assert!(
            g.node(res).inputs.contains(&x),
            "the residual edge x -> res is untouched"
        );
    }

    /// ROW 158: a region's arm 1 on ANOTHER device must read every value from outside its arm through an
    /// `Op::Copy`, and hand its result back to arm 0's device through one. The first run of arm 1 on a GPU
    /// (a CPU arm in a Vulkan realize) failed with `cpu kernel wrapper called with non-CPU input` on a clone
    /// `Add` reading two Vulkan `Mul` nodes directly: the pathfinder's clones carried a `target_backend`
    /// but no placement, so the residency pass placed them on the pinned device and saw no crossing.
    ///
    /// The stretch `a, t` has TWO external inputs (the diverge `d` and the earlier `e`) and its exit feeds
    /// a reconverge on the host. The alternative runs on `Cuda { gpu_id: 0 }`. Built through
    /// `try_record_branch` with explicit devices because the synthetic two-backend fixture of
    /// `optimize_graph` puts its "Cuda" placement at the CPU location and so cannot show a crossing.
    #[test]
    fn a_cross_device_arm_one_gets_inbound_copies_for_every_external_input_and_an_exit_copy() {
        use crate::region_pathfinder::try_record_branch;
        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let e = f32_node(&mut g, Op::Relu, vec![x]);
        let d = f32_node(&mut g, Op::Silu, vec![e]); // the diverge
        let a = f32_node(&mut g, Op::Add, vec![d, e]); // entry: reads d AND e, both outside the stretch
        let t = f32_node(&mut g, Op::Tanh, vec![a]);
        let res = f32_node(&mut g, Op::Add, vec![d, t]); // reconverge: reads the exit t (and d)
        for n in [x, e, d, a, t, res] {
            g.set_placement(n, DeviceLocation::Cpu);
            if n != x {
                g.set_target_backend(n, BackendId::Cpu);
            }
        }
        let branch = try_record_branch(
            &mut g,
            d,
            res,
            &[a, t],
            t,
            BackendId::Cuda,
            cuda0,
            DeviceLocation::Cpu,
        )
        .expect("well-formed branch")
        .expect("two arms");
        insert_residency_copies(
            &mut g,
            &[res],
            &ExecutionPlan::empty(),
            DeviceLocation::Cpu,
            None,
        );

        let arm1_exit = g.node(branch).inputs[1];
        // The arm's result comes back to the host through a copy, so both exits live on one device.
        assert!(
            matches!(g.node(arm1_exit).op, Op::Copy { target } if target == DeviceLocation::Cpu),
            "arm 1's exit must be a copy back to the host; got {:?}",
            g.node(arm1_exit).op
        );
        let clone_t = g.node(arm1_exit).inputs[0];
        let clone_a = g.node(clone_t).inputs[0];
        assert_eq!(g.node(clone_a).op, Op::Add, "the clone of the entry node");
        // Both external inputs of the clone entry node go through a copy onto the alternative device.
        assert_eq!(g.node(clone_a).inputs.len(), 2);
        for &input in &g.node(clone_a).inputs {
            assert!(
                matches!(g.node(input).op, Op::Copy { target } if target == cuda0),
                "clone entry node reads {:?} ({:?}) from outside its arm with no copy onto {cuda0:?}",
                input,
                g.node(input).op,
            );
        }
        // The copies read the original host values (the shared diverge and the earlier node).
        let sources: Vec<NodeId> = g
            .node(clone_a)
            .inputs
            .iter()
            .map(|&c| g.node(c).inputs[0])
            .collect();
        assert_eq!(sources, vec![d, e]);
        // Arm 0 is untouched: still host to host, no copies.
        assert_eq!(g.node(a).inputs, vec![d, e]);
    }

    /// ROW 157 / GAP-385, PURE FAN-OUT (no residual edge): `x -> n1 -> {q, k} -> a -> t`. The region is
    /// the fan-out and everything up to its join: diverge `x`, a four-node arm (`n1 q k a`), reconverge
    /// `t`. Born red: the one-node fork never forked `n1` (two consumers) and made one-node forks of
    /// `q`, `k` (sole consumer `a`) and `a`.
    #[test]
    fn fan_out_that_rejoins_is_one_multi_node_region() {
        let table = two_placement_table();
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
        let q = f32_node(&mut g, Op::Silu, vec![n1]);
        let k = f32_node(&mut g, Op::Tanh, vec![n1]);
        let a = f32_node(&mut g, Op::Add, vec![q, k]);
        let t = f32_node(&mut g, Op::Relu, vec![a]);

        let before = g.len();
        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
        let branches = branches_after(&g, before);
        assert_eq!(
            branches.iter().map(|&(_, e, r)| (e, r)).collect::<Vec<_>>(),
            vec![(a, t)],
            "one region: arm-0 exit a, reconverge t"
        );
        assert_eq!(
            g.len() - before,
            4 + 1,
            "four cloned nodes (n1 q k a) plus the branch node"
        );
    }
    /// Cross-device, production-shaped options: the realize device is a GPU (`Cuda { gpu_id: 0 }`), CPU is
    /// the always-feasible fallback device, and a transfer estimator is present, so the placement DP
    /// runs and prunes every node's alternative set to its committed device (the single-device-set
    /// invariant). This is the shape `build_optimized_graph` builds on a Vulkan/CUDA realize; the
    /// co-located `two_backend_opts` above never opens a DP row and so never reaches this pruning.
    struct FlatTransfer;
    impl crate::ranker::cost::TransferEstimator for FlatTransfer {
        fn estimate_transfer_ns(
            &self,
            src: DeviceLocation,
            dst: DeviceLocation,
            _bytes: u64,
        ) -> u64 {
            if src == dst { 0 } else { 1_000 }
        }
    }
    /// A kernel cost of 10_000 flops (10 us at the caps' 1 flop/ns) on every node: a transfer of 1_000 ns
    /// is then a small fraction of a node, as on a real model, rather than infinitely worse than a
    /// zero-cost kernel (which `unknown_cost` would give).
    fn ten_us_cost(
        _: &[Shape],
        _: &[DType],
        _: &crate::kernel::OpParams,
        _: &fuel_ir::backend::BackendCapabilities,
    ) -> crate::fused::CostEstimate {
        crate::fused::CostEstimate {
            flops: 10_000,
            bytes_moved: 0,
            kernel_overhead_ns: 0,
        }
    }
    /// The same node on the GPU prior (`default_backend_rates`: 30 flops/ns) at 300_000 flops, i.e. also
    /// 10 us: the CPU arm is then within the competitive factor. Without this the CPU arm would be ~30x
    /// slower and correctly NOT competitive, which is itself what a real GPU model looks like.
    fn ten_us_cost_gpu(
        _: &[Shape],
        _: &[DType],
        _: &crate::kernel::OpParams,
        _: &fuel_ir::backend::BackendCapabilities,
    ) -> crate::fused::CostEstimate {
        crate::fused::CostEstimate {
            flops: 300_000,
            bytes_moved: 0,
            kernel_overhead_ns: 0,
        }
    }
    fn costed_two_placement_table() -> KernelBindingTable {
        let mut table = KernelBindingTable::new();
        for (op, n_in) in [
            (OpKind::ReluElementwise, 1),
            (OpKind::SiluElementwise, 1),
            (OpKind::TanhElementwise, 1),
            (OpKind::AddElementwise, 2),
        ] {
            let mut dtypes = vec![DType::F32; n_in];
            dtypes.push(DType::F32);
            for (backend, kernel, cost) in [
                (
                    BackendId::Cpu,
                    noop_kernel as crate::kernel::KernelRef,
                    ten_us_cost as crate::kernel::CostFn,
                ),
                (
                    BackendId::Cuda,
                    noop_kernel_b as crate::kernel::KernelRef,
                    ten_us_cost_gpu as crate::kernel::CostFn,
                ),
            ] {
                table.register_full(
                    op,
                    &dtypes,
                    backend,
                    kernel,
                    KernelCaps::empty(),
                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
                    cost,
                );
            }
        }
        table
    }
    fn gpu_placements(dev: DeviceLocation) -> Vec<BackendId> {
        match dev {
            DeviceLocation::Cuda { .. } => vec![BackendId::Cuda],
            DeviceLocation::Cpu => vec![BackendId::Cpu],
            _ => vec![],
        }
    }
    fn cpu_fallback(dev: DeviceLocation) -> Vec<(BackendId, DeviceLocation)> {
        if dev == DeviceLocation::Cpu {
            vec![]
        } else {
            vec![(BackendId::Cpu, DeviceLocation::Cpu)]
        }
    }

    /// ROW 157 / GAP-385, PRODUCTION ENTRY (born red). Live run, Vulkan tiny-Llama, ref `db0c1f7a2`: every
    /// optimize reported 0 live `Op::Branch`; the pathfinder saw 0 nodes with two placements because
    /// `compile_plan` pruned each set to the DP-committed device. Here the same options shape
    /// (GPU realize device + CPU fallback + transfer estimator) over a residual block must still yield
    /// one multi-node region.
    #[test]
    fn cross_device_residual_block_forks_through_the_production_options_shape() {
        let table = costed_two_placement_table();
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
        let q = f32_node(&mut g, Op::Silu, vec![n1]);
        let o = f32_node(&mut g, Op::Tanh, vec![q]);
        let res = f32_node(&mut g, Op::Add, vec![x, o]);

        let est = FlatTransfer;
        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
        let caps = fuel_ir::backend::BackendCapabilities {
            backend_id: BackendId::Cuda,
            device_location: gpu,
            op_dtype_support: std::collections::HashSet::new(),
            required_alignment: 64,
            access_granularity_bits: 8,
            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
            compute_throughput_flops_per_ns: 1.0,
            mem_bandwidth_bytes_per_ns: 4.0,
        };
        let caps_for = |_: BackendId| Some(&caps);
        let residency = |_: NodeId| Some(gpu);
        // Cost population stays ON (the default): `relaxed` merged enumeration, and with it the
        // placement DP, only runs when pricing is active, exactly as `build_optimized_graph` sets it.
        let opts = PlanOptions::new()
            .with_pinned_device(gpu)
            .with_placements_for_device(&gpu_placements)
            .with_fallback_placements_for(&cpu_fallback)
            .with_capabilities_for(&caps_for)
            .with_transfer_estimator(&est)
            .with_input_residency(&residency);
        let before = g.len();
        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
        assert!(
            optimized.branch_count(&g) >= 1,
            "a GPU realize with a CPU fallback must expose a cross-device region; branches={:?}",
            branches_after(&g, before)
        );
    }

    /// SIBLING of the test above: the same cross-device shape, but the GPU kernel is 30x cheaper than the
    /// CPU one (both at 10_000 flops, GPU prior 30 flops/ns). The CPU arm is not within the competitive
    /// factor, so NO region is recorded. This is what a real GPU model looks like; the test keeps the
    /// first one from passing by recording a region unconditionally.
    #[test]
    fn cross_device_cpu_arm_far_slower_than_the_gpu_is_not_competitive() {
        let mut table = KernelBindingTable::new();
        for (op, n_in) in [
            (OpKind::ReluElementwise, 1),
            (OpKind::SiluElementwise, 1),
            (OpKind::TanhElementwise, 1),
            (OpKind::AddElementwise, 2),
        ] {
            let mut dtypes = vec![DType::F32; n_in];
            dtypes.push(DType::F32);
            for (backend, kernel) in [
                (BackendId::Cpu, noop_kernel as crate::kernel::KernelRef),
                (BackendId::Cuda, noop_kernel_b as crate::kernel::KernelRef),
            ] {
                table.register_full(
                    op,
                    &dtypes,
                    backend,
                    kernel,
                    KernelCaps::empty(),
                    PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU,
                    ten_us_cost,
                );
            }
        }
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
        let q = f32_node(&mut g, Op::Silu, vec![n1]);
        let o = f32_node(&mut g, Op::Tanh, vec![q]);
        let res = f32_node(&mut g, Op::Add, vec![x, o]);
        let est = FlatTransfer;
        let gpu = DeviceLocation::Cuda { gpu_id: 0 };
        let caps = fuel_ir::backend::BackendCapabilities {
            backend_id: BackendId::Cuda,
            device_location: gpu,
            op_dtype_support: std::collections::HashSet::new(),
            required_alignment: 64,
            access_granularity_bits: 8,
            transfer_paths: vec![(gpu, fuel_ir::backend::TransferPath::SameDevice)],
            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
            compute_throughput_flops_per_ns: 1.0,
            mem_bandwidth_bytes_per_ns: 4.0,
        };
        let caps_for = |_: BackendId| Some(&caps);
        let residency = |_: NodeId| Some(gpu);
        let opts = PlanOptions::new()
            .with_pinned_device(gpu)
            .with_placements_for_device(&gpu_placements)
            .with_fallback_placements_for(&cpu_fallback)
            .with_capabilities_for(&caps_for)
            .with_transfer_estimator(&est)
            .with_input_residency(&residency);
        let optimized = optimize_graph(&mut g, &[res], &table, &opts).expect("optimize_graph");
        assert_eq!(
            optimized.branch_count(&g),
            0,
            "a CPU arm ~30x slower than the GPU is not competitive within the factor of 2"
        );
    }

    /// SABOTAGE SIBLING (row 157): a node read from outside the stretch must not sit inside a region.
    /// `n1` is read by `m` and by a second realize root `side`, so no region may contain it; `m` alone
    /// (diverge `n1`, reconverge `t`) is still a valid one-node region.
    #[test]
    fn a_node_read_from_outside_the_stretch_is_not_inside_a_region() {
        let table = two_placement_table();
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let n1 = f32_node(&mut g, Op::Relu, vec![x]);
        let m = f32_node(&mut g, Op::Silu, vec![n1]);
        let t = f32_node(&mut g, Op::Relu, vec![m]);
        let side = f32_node(&mut g, Op::Tanh, vec![n1]);
        let before = g.len();
        optimize_graph(&mut g, &[t, side], &table, &two_backend_opts()).expect("optimize_graph");
        let exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
        assert!(
            !exits.contains(&n1),
            "n1 is read by a second root and cannot be an arm exit"
        );
    }

    /// SABOTAGE SIBLING (row 157): a stretch is only as long as the nodes that have the alternative.
    /// `s` is CPU-only, so no region may span it; the two Relu nodes each fork alone.
    #[test]
    fn a_node_without_the_alternative_kernel_splits_the_region() {
        let mut table = KernelBindingTable::new();
        register_two_backend(&mut table, OpKind::ReluElementwise, 1);
        register_elementwise(&mut table, OpKind::SiluElementwise, 1); // CPU only
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let r1 = f32_node(&mut g, Op::Relu, vec![x]);
        let s = f32_node(&mut g, Op::Silu, vec![r1]);
        let r2 = f32_node(&mut g, Op::Relu, vec![s]);
        let t = f32_node(&mut g, Op::Relu, vec![r2]);
        let before = g.len();
        optimize_graph(&mut g, &[t], &table, &two_backend_opts()).expect("optimize_graph");
        let mut exits: Vec<NodeId> = branches_after(&g, before).iter().map(|b| b.1).collect();
        exits.sort_by_key(|n| n.0);
        assert!(
            !exits.contains(&s),
            "the CPU-only node is never an arm exit"
        );
        // r2 and t form one two-node stretch? t is the root, so only r1 and r2 can be interior.
        assert_eq!(
            exits,
            vec![r1, r2],
            "r1 forks alone, r2 forks alone, nothing spans s"
        );
    }

    /// SABOTAGE SIBLING (row 157): one placement per node means no region at all.
    #[test]
    fn a_single_placement_graph_gets_no_regions() {
        let mut table = KernelBindingTable::new();
        register_elementwise(&mut table, OpKind::ReluElementwise, 1);
        register_elementwise(&mut table, OpKind::SiluElementwise, 1);
        let mut g = Graph::new();
        let x = f32_node(&mut g, Op::Const, vec![]);
        let a = f32_node(&mut g, Op::Relu, vec![x]);
        let b = f32_node(&mut g, Op::Silu, vec![a]);
        let c = f32_node(&mut g, Op::Relu, vec![b]);
        let before = g.len();
        let optimized = optimize_graph(&mut g, &[c], &table, &cpu_opts()).expect("optimize_graph");
        assert_eq!(optimized.branch_count(&g), 0);
        assert_eq!(g.len(), before, "no clones are left behind");
    }

    // ===== Load-aware arm pick through the PRODUCTION realize entry
    //        (row 158 slice 2: estimated-completion, not queue-depth) =====

    /// Records the backend of every candidate the wrapped selector picks, so
    /// a test can read WHICH arm the production picking entry chose.
    #[derive(Debug)]
    struct RecordingSelector {
        inner: crate::ranker::ChainedSelector,
        picked: std::sync::Mutex<Vec<BackendId>>,
    }

    impl crate::ranker::RuntimeSelector for RecordingSelector {
        fn select<'a>(
            &self,
            set: &'a crate::ranker::AlternativeSet,
        ) -> Option<&'a crate::ranker::Candidate> {
            let picked = self.inner.select(set);
            if let Some(c) = picked {
                self.picked.lock().unwrap().push(c.backend);
            }
            picked
        }
    }

    /// Judge answering per BACKEND only. The pick enumerates candidates from
    /// the process-wide binding table (real `portable-cpu` kernel with a
    /// revision hash; a synthetic CUDA stand-in), so a cell-keyed judge would
    /// couple the test to those tags.
    struct BackendJudge {
        cuda_ns: u64,
        cpu_ns: u64,
    }

    impl crate::ranker::JudgeOracle for BackendJudge {
        fn measured_latency_ns(
            &self,
            _op: OpKind,
            _dtype: DType,
            _size_class: fuel_ir::dispatch::SizeClass,
            backend: BackendId,
            _kernel_source: &str,
            _kernel_revision_hash: u64,
        ) -> Option<u64> {
            match backend {
                BackendId::Cuda => Some(self.cuda_ns),
                BackendId::Cpu => Some(self.cpu_ns),
                _ => None,
            }
        }
    }

    /// Realize the single-fork graph through
    /// `PipelinedExecutor::realize_with_optimized_picking_env` (the entry the
    /// bridge calls) with a `ChainedSelector` over `lookup` and a Judge that
    /// measures the fork op at `cuda_ns` on CUDA and `cpu_ns` on CPU. Returns
    /// the backends the streaming pick chose for the (one) branch.
    ///
    /// Also returns the realize result (`"Ok"` or `Err(..)` as text), so a
    /// run with no pick names its cause instead of reading as "no pick".
    ///
    /// Holds `TOPOLOGY_TEST_GATE` for writing from before `optimize_graph`
    /// until the realize returns: the executor returns the typed
    /// `Error::TopologyChanged` when another test in this binary bumps the
    /// process-wide topology generation in between, and then the streaming
    /// walk never reaches the branch (ROADMAP row 165). The gate stops a
    /// sibling's bump from landing in that window; there is no retry.
    fn picked_backends_through_realize(
        lookup: crate::ranker::BackendRuntimeLookup,
        cuda_ns: u64,
        cpu_ns: u64,
    ) -> (Vec<BackendId>, String) {
        use crate::PipelinedExecutor;
        use crate::pipelined::StorageCache;
        use crate::ranker::ChainedSelector;
        use fuel_ir::SymEnv;

        // Build the lazily initialised process-wide tables BEFORE taking the
        // gate: their initialisation bumps the generation, and a bump under
        // our own write guard would wait on ourselves.
        drop(crate::dispatch::global_bindings());
        let _crate_gate = crate::dispatch::TOPOLOGY_TEST_GATE
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());

        let mut table = KernelBindingTable::new();
        let (mut g, _prod, _fork, _tail, root) = build_single_fork_graph(&mut table);
        let optimized = optimize_graph(&mut g, &[root], &table, &two_backend_opts())
            .expect("optimize_graph succeeds");
        assert_eq!(optimized.branch_count(&g), 1, "exactly one branch");

        let selector = Arc::new(RecordingSelector {
            inner: ChainedSelector::with_default_estimator(
                Some(Arc::new(BackendJudge { cuda_ns, cpu_ns })),
                Some(lookup.clone()),
            ),
            picked: std::sync::Mutex::new(Vec::new()),
        });

        let graph = Arc::new(RwLock::new(g));
        let mut cache = StorageCache::new();
        cache.insert(
            NodeId(0),
            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
                1.0_f32, 2.0, 3.0, 4.0,
            ]))),
        );
        // The CUDA arm has no device behind it in a CPU test, so a realize
        // that picked CUDA ends in a device error at the reconverge node; a
        // realize that picked CPU runs end to end. The result is returned, not
        // ignored, so the caller pins which.
        let result = PipelinedExecutor::realize_with_optimized_picking_env(
            graph,
            root,
            cache,
            &optimized,
            Some(selector.clone() as Arc<dyn crate::ranker::RuntimeSelector>),
            Some(lookup),
            SymEnv::default(),
        );
        let outcome = match result {
            Ok(_) => "Ok".to_string(),
            Err(e) => format!("Err({e:?})"),
        };
        let picks = selector.picked.lock().unwrap().clone();
        (picks, outcome)
    }

    /// Row 158 slice 2. CUDA measures 100 ns on the fork op, CPU 100 us.
    /// The device load must be read as estimated BACKLOG TIME, not as a
    /// queue-depth bucket:
    ///  - idle CUDA                      -> CUDA arm;
    ///  - CUDA with ONE op queued (the count bucket says "saturated") but
    ///    only 1 us of estimated backlog -> STILL the CUDA arm (1.1 us beats
    ///    CPU's 100 us); the count tier wrongly sends this to CPU;
    ///  - CUDA with a 1 hour backlog     -> the CPU arm.
    ///
    /// SHOWS: the streaming pick, reached through the production picking
    /// realize entry, ranks arms by backlog + measured latency.
    /// DOES NOT SHOW: that the executor's submit sites feed the backlog
    /// (the lookup here injects it), nor that kernels ran on either arm.
    #[test]
    fn load_aware_pick_ranks_by_estimated_completion_through_realize() {
        use crate::ranker::mock_backlog_lookup;
        const HOUR_NS: u64 = 3_600_000_000_000;

        let (idle, idle_r) = picked_backends_through_realize(
            mock_backlog_lookup(vec![(BackendId::Cuda, 0, 0)]),
            100,
            100_000,
        );
        assert_eq!(
            idle,
            vec![BackendId::Cuda],
            "idle GPU -> GPU arm; realize={idle_r}"
        );

        let (one_op, one_op_r) = picked_backends_through_realize(
            mock_backlog_lookup(vec![(BackendId::Cuda, 1, 1_000)]),
            100,
            100_000,
        );
        assert_eq!(
            one_op,
            vec![BackendId::Cuda],
            "1 op / 1 us backlog: GPU still finishes first (1.1 us vs 100 us); realize={one_op_r}",
        );

        let (hour, hour_r) = picked_backends_through_realize(
            mock_backlog_lookup(vec![(BackendId::Cuda, 1, HOUR_NS)]),
            100,
            100_000,
        );
        assert_eq!(
            hour,
            vec![BackendId::Cpu],
            "1 h GPU backlog -> CPU arm; realize={hour_r}"
        );
        assert_eq!(hour_r, "Ok", "the CPU arm realizes end to end");
    }
}