tenferro-runtime 0.7.0

Concrete tensor helpers, traced tensors, graph execution, and extension runtime support for tenferro.
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
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
//! Runtime-owned compiled-graph execution boundary.
//!
//! This module owns the private execution bridge used by
//! `Runtime::run_compiled*`.

use num_complex::{Complex32, Complex64};
use std::collections::{HashMap, HashSet};
use std::error::Error as StdError;
use std::fmt;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::{self, ThreadId};

use smallvec::SmallVec;
use tenferro_ops::shape_extent::ShapeExtent;
use tenferro_tensor::{
    AllocationGroup, DType, DescriptorSlot, GroupError, MemoryKind, Tensor, TensorBackend,
    TensorRead, TensorValue, TensorView,
};

use crate::error::ErrorPhase;
use crate::exec::{
    DispatchMode, ExecInstruction, ExecProgram, ExecSlot, ExtensionExecutionDispatch,
};
use crate::extension_cache::{ExtensionCacheSelector, ExtensionCacheStore};
use crate::graph::CompiledGraph;
use crate::runtime::schedule::{
    EventDependency, ExecutionLocation, ScheduledGraph, ScheduledNode, ScheduledNodeKind,
    ScheduledTransfer, UnsupportedScheduledNodeError,
};
use crate::runtime::{
    CacheOwnerError, CacheStats, EventDomainError, EventDomainOperation, EventDomainRun,
    EventToken, InputSignature, PrepareError, PrepareOptions, PreparedOperationPlan, Runtime,
    RuntimeCacheOwner, SubmissionError, TransferError, TransferProviderContractError,
    TransferRequest,
};
use crate::{Error, Result};

type RuntimeInputReads<'a> = SmallVec<[TensorRead<'a>; 8]>;
type RuntimeInputShapes<'a> = SmallVec<[&'a [usize]; 8]>;
type RuntimeShapeScratch = SmallVec<[usize; 8]>;

#[derive(Clone, Copy, Debug)]
pub(super) enum RuntimeOutputMode {
    Tensor,
    Value,
}

/// Runtime-prepared compiled graph execution handle.
///
/// This handle keeps the prepared execution staging and its direct provider
/// witnesses inside the immutable schedule. It is tied to the runtime epoch
/// that created it and becomes stale after runtime reconfiguration.
#[derive(Clone)]
pub struct PreparedCompiledGraph {
    runtime_id: super::RuntimeId,
    epoch: super::RuntimeEpoch,
    program: CompiledGraph,
    prepared: Arc<super::preparation::PreparedProgram>,
}

impl PreparedCompiledGraph {
    /// Number of planned elementwise regions and the instructions they cover,
    /// for execution-path parity tests.
    #[doc(hidden)]
    #[must_use]
    pub fn elementwise_region_summary(&self) -> (usize, usize) {
        super::region::region_summary(self.prepared.root().regions())
    }

    /// Number of planned elementwise regions executed as one fused command, and
    /// the number that fell back to per-instruction dispatch.
    #[doc(hidden)]
    #[must_use]
    pub fn elementwise_region_execution_counts(&self) -> (usize, usize) {
        let counters = self.prepared.root().region_counters();
        (counters.fused(), counters.fallbacks())
    }

    /// Number of successful scheduled event-domain submissions observed by this
    /// prepared program's production executor.
    ///
    /// This is runtime submission evidence, rather than a plan-derived census.
    #[doc(hidden)]
    #[must_use]
    pub fn execution_submission_count(&self) -> usize {
        self.prepared.root().region_counters().submissions()
    }

    /// Plan-derived command count for the production execution path, for
    /// execution-path tests: scheduled operations that no region covers, plus
    /// one command per planned region.
    ///
    /// This is a plan census, not a runtime submission count.
    #[doc(hidden)]
    #[must_use]
    pub fn execution_command_count(&self) -> usize {
        let root = self.prepared.root();
        super::region::command_count(root.schedule(), root.regions())
    }
}

/// Asynchronous runtime execution handle returned by [`Runtime::submit`].
pub struct ExecutionHandle {
    submission: Arc<InFlightSubmission>,
}

/// Move-only input package for detached runtime submission.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::runtime::ExecutionInputs;
///
/// let inputs = ExecutionInputs::new(Vec::new())?;
/// assert!(format!("{inputs:?}").contains("ExecutionInputs"));
/// # Ok::<(), tenferro_runtime::Error>(())
/// ```
pub struct ExecutionInputs {
    group: AllocationGroup,
    bindings: Box<[DescriptorSlot]>,
}

impl ExecutionInputs {
    /// Construct a package from already-owned tensors.
    ///
    /// # Errors
    ///
    /// Returns [`Error::RuntimeState`] when a tensor binding cannot be
    /// registered in the allocation group.
    pub fn new(tensors: Vec<Tensor>) -> Result<Self> {
        let (group, bindings) = AllocationGroup::from_tensors(tensors).map_err(|error| {
            Error::runtime_state(
                "ExecutionInputs::new",
                ErrorPhase::Execution,
                error.to_string(),
            )
        })?;
        Ok(Self { group, bindings })
    }

    pub(crate) fn as_reads(&self) -> Result<Vec<TensorRead<'_>>> {
        self.group.read_views(&self.bindings).map_err(|error| {
            Error::runtime_state(
                "ExecutionInputs::as_reads",
                ErrorPhase::Execution,
                error.to_string(),
            )
        })
    }
}

impl fmt::Debug for ExecutionInputs {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutionInputs")
            .field("len", &self.bindings.len())
            .finish()
    }
}

/// Borrowed immutable inputs for synchronous, retirement-before-return execution.
pub struct ScopedReadInputs<'env> {
    bindings: Box<[ScopedReadBinding<'env>]>,
}

impl<'env> ScopedReadInputs<'env> {
    /// Build a scoped input package from borrowed dtype-erased views.
    pub fn new(bindings: Vec<TensorView<'env>>) -> Self {
        Self {
            bindings: bindings
                .into_iter()
                .map(|tensor| ScopedReadBinding { tensor })
                .collect(),
        }
    }

    fn as_reads(&self) -> Vec<TensorRead<'env>> {
        self.bindings
            .iter()
            .map(|binding| TensorRead::from_view(binding.tensor.clone()))
            .collect()
    }

    fn has_non_host_provider(&self) -> bool {
        self.bindings.iter().any(|binding| {
            !matches!(
                binding.tensor.placement().memory_kind,
                MemoryKind::PinnedHost | MemoryKind::UnpinnedHost
            )
        })
    }

    /// Return the number of borrowed bindings.
    pub fn len(&self) -> usize {
        self.bindings.len()
    }

    /// Return whether no borrowed bindings were supplied.
    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty()
    }
}

/// One immutable borrowed binding in a scoped input package.
pub struct ScopedReadBinding<'env> {
    tensor: TensorView<'env>,
}

impl<'env> ScopedReadBinding<'env> {
    /// Wrap one immutable dtype-erased view.
    pub fn new(tensor: TensorView<'env>) -> Self {
        Self { tensor }
    }

    /// Borrow the binding's dtype-erased view.
    pub fn tensor(&self) -> &TensorView<'env> {
        &self.tensor
    }
}

impl fmt::Debug for ScopedReadInputs<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ScopedReadInputs")
            .field("len", &self.bindings.len())
            .finish()
    }
}

/// A synchronous scoped execution result.
// INVARIANT: these variants keep the borrowed execution contract allocation-free
// at the API boundary; boxing would add an avoidable ownership allocation.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum ScopedExecutionOutcome<'env> {
    /// All provider work retired before this call returned.
    Completed(ScopedExecutionBundle<'env>),
    /// Execution retired with an ordinary error and the original borrows remain available.
    RetiredFailed {
        error: Error,
        inputs: ScopedReadInputs<'env>,
    },
}

/// Metadata for a storage-free scoped output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputMetadata {
    /// Scalar dtype of the logical output.
    pub dtype: DType,
    /// Logical shape of the output.
    pub shape: Box<[usize]>,
}

/// Owned outputs and borrowed identity views from one completed scoped call.
pub struct ScopedExecutionBundle<'env> {
    owned: AllocationGroup,
    outputs: Box<[ScopedOutput<'env>]>,
}

impl fmt::Debug for ScopedExecutionBundle<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ScopedExecutionBundle")
            .field("len", &self.outputs.len())
            .finish()
    }
}

impl<'env> ScopedExecutionBundle<'env> {
    /// Borrow one completed output.
    ///
    /// # Errors
    ///
    /// Returns [`OutputAccessError::InvalidOutput`] for an invalid output
    /// index or [`OutputAccessError::Group`] when the completed descriptor
    /// group reports an output access failure.
    pub fn output(&self, index: usize) -> std::result::Result<OutputRef<'_>, OutputAccessError> {
        let output = self
            .outputs
            .get(index)
            .ok_or(OutputAccessError::InvalidOutput { index })?;
        match output {
            ScopedOutput::Borrowed(view) => Ok(OutputRef::Tensor(view.clone())),
            ScopedOutput::Owned(slot) => output_ref_from_group(&self.owned, *slot),
            ScopedOutput::Metadata(metadata) => Ok(OutputRef::Metadata(metadata)),
        }
    }

    /// Consume the bundle and extract a fresh owned output.
    ///
    /// # Errors
    ///
    /// Returns [`ScopedOutputExtractError::InvalidOutput`],
    /// [`ScopedOutputExtractError::BorrowedOutput`], or
    /// [`ScopedOutputExtractError::MetadataOutput`] for an output that cannot
    /// be consumed, and [`ScopedOutputExtractError::Output`] for a structural
    /// group extraction failure. Each error returns the unchanged bundle.
    #[allow(clippy::result_large_err)]
    pub fn into_owned_output(
        self,
        index: usize,
    ) -> std::result::Result<Tensor, (Self, ScopedOutputExtractError)> {
        let slot = match self.outputs.get(index) {
            Some(ScopedOutput::Owned(slot)) => *slot,
            Some(ScopedOutput::Borrowed(_)) => {
                return Err((self, ScopedOutputExtractError::BorrowedOutput))
            }
            Some(ScopedOutput::Metadata(_)) => {
                return Err((self, ScopedOutputExtractError::MetadataOutput))
            }
            None => return Err((self, ScopedOutputExtractError::InvalidOutput { index })),
        };
        let Self { owned, outputs } = self;
        match owned.into_tensor(slot) {
            Ok(tensor) => Ok(tensor),
            Err((owned, error)) => Err((
                Self { owned, outputs },
                ScopedOutputExtractError::Output(OutputExtractError::Group(error)),
            )),
        }
    }
}

/// Output classification used by scoped providers.
// INVARIANT: borrowed views stay inline so scoped output classification does
// not materialize an extra owner or heap allocation.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum ScopedOutput<'env> {
    /// A result that aliases an immutable caller input.
    Borrowed(TensorView<'env>),
    /// A fresh result owned by the scoped bundle's allocation group.
    Owned(DescriptorSlot),
    /// Metadata-only output with no tensor payload.
    Metadata(OutputMetadata),
}

/// Failure while consuming a scoped output.
#[derive(Debug, thiserror::Error)]
pub enum ScopedOutputExtractError {
    #[error("scoped output index {index} is outside the output set")]
    InvalidOutput { index: usize },
    #[error("scoped output is borrowed from the caller")]
    BorrowedOutput,
    #[error("scoped output contains metadata only")]
    MetadataOutput,
    #[error("scoped owned output cannot be extracted: {0}")]
    Output(#[from] OutputExtractError),
}

/// A pre-admission scoped submission rejection. The original borrows remain available.
#[derive(Debug)]
pub struct ScopedSubmitRejected<'env> {
    source: Box<Error>,
    inputs: ScopedReadInputs<'env>,
}

impl<'env> ScopedSubmitRejected<'env> {
    /// Consume the rejection and preserve its original environment lifetime.
    pub fn into_parts(self) -> (Error, ScopedReadInputs<'env>) {
        (*self.source, self.inputs)
    }
}

impl fmt::Display for ScopedSubmitRejected<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "scoped submission rejected before admission: {}",
            self.source
        )
    }
}

impl StdError for ScopedSubmitRejected<'_> {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(self.source.as_ref())
    }
}

/// A detached execution result retaining one allocation group for all outputs.
#[derive(Debug)]
pub struct ExecutionBundle {
    group: AllocationGroup,
    outputs: Box<[DescriptorSlot]>,
}

/// A borrowed output view from an [`ExecutionBundle`].
// INVARIANT: this read-only result is a zero-allocation projection of an
// already-prepared view; boxing would add work on the output hot path.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum OutputRef<'a> {
    Tensor(TensorView<'a>),
    Metadata(&'a OutputMetadata),
}

#[derive(Debug, thiserror::Error)]
pub enum OutputAccessError {
    #[error("execution output index {index} is outside the output set")]
    InvalidOutput { index: usize },
    #[error("execution output group is invalid: {0}")]
    Group(#[from] GroupError),
}

#[derive(Debug, thiserror::Error)]
pub enum OutputExtractError {
    #[error("execution output index {index} is outside the output set")]
    InvalidOutput { index: usize },
    #[error("execution output cannot be extracted: {0}")]
    Group(#[from] GroupError),
}

impl ExecutionBundle {
    fn from_inputs_and_outputs(inputs: ExecutionInputs, outputs: Vec<Tensor>) -> Result<Self> {
        let mut group = inputs.group;
        let mut output_slots = Vec::with_capacity(outputs.len());
        for output in outputs {
            let slot = group.append_tensor(output).map_err(|error| {
                Error::runtime_state(
                    "ExecutionBundle::from_inputs_and_outputs",
                    ErrorPhase::Execution,
                    error.to_string(),
                )
            })?;
            output_slots.push(slot);
        }
        Ok(Self {
            group,
            outputs: output_slots.into_boxed_slice(),
        })
    }

    #[cfg(test)]
    pub(super) fn from_outputs(outputs: Vec<Tensor>) -> Result<Self> {
        let (group, bindings) = AllocationGroup::from_tensors(outputs).map_err(|error| {
            Error::runtime_state(
                "ExecutionBundle::from_outputs",
                ErrorPhase::Execution,
                error.to_string(),
            )
        })?;
        Ok(Self {
            group,
            outputs: bindings,
        })
    }

    /// # Errors
    ///
    /// Returns [`OutputAccessError::InvalidOutput`] for an invalid output
    /// index or [`OutputAccessError::Group`] when the output descriptor group
    /// reports an access failure.
    pub fn output(&self, index: usize) -> std::result::Result<OutputRef<'_>, OutputAccessError> {
        let slot = *self
            .outputs
            .get(index)
            .ok_or(OutputAccessError::InvalidOutput { index })?;
        let mut views = self.group.read_views(std::slice::from_ref(&slot))?;
        let view = views
            .pop()
            .ok_or(OutputAccessError::InvalidOutput { index })?;
        match view {
            TensorRead::View(view) => Ok(OutputRef::Tensor(view)),
            TensorRead::Tensor(_) => Err(OutputAccessError::InvalidOutput { index }),
        }
    }

    // INVARIANT: extraction errors return the unchanged move-only bundle so
    // callers can retry or inspect it without a hidden copy.
    ///
    /// # Errors
    ///
    /// Returns [`OutputExtractError::InvalidOutput`] for an invalid index or
    /// [`OutputExtractError::Group`] for a structural group extraction
    /// failure. Each error returns the unchanged bundle without copying.
    #[allow(clippy::result_large_err)]
    pub fn into_output(
        self,
        index: usize,
    ) -> std::result::Result<Tensor, (Self, OutputExtractError)> {
        let slot = match self.outputs.get(index).copied() {
            Some(slot) => slot,
            None => return Err((self, OutputExtractError::InvalidOutput { index })),
        };
        let ExecutionBundle { group, outputs } = self;
        match group.into_tensor(slot) {
            Ok(tensor) => Ok(tensor),
            Err((group, error)) => Err((Self { group, outputs }, OutputExtractError::Group(error))),
        }
    }
}

/// The result of a detached submission after the provider retirement point.
#[derive(Debug)]
pub enum ExecutionOutcome {
    /// The scheduled graph completed and produced one alias-safe output bundle.
    Completed(Box<ExecutionBundle>),
    /// The graph retired with an ordinary execution error; the input owner is
    /// available again because retirement was observed.
    RetiredFailed {
        error: Error,
        inputs: Box<ExecutionInputs>,
    },
    /// Completion could not be proven. No owner is exposed and the private
    /// in-flight record retains all provider state permanently.
    CompletionUnproven {
        error: Error,
        diagnostic_keys: Box<[String]>,
    },
}

/// A detached submission failed before ownership could be transferred to the
/// in-flight worker.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{Error, runtime::{ExecutionInputs, SubmitError}};
///
/// let error = SubmitError::PreAdmission {
///     source: Box::new(Error::Internal("input rejected".into())),
///     inputs: Box::new(ExecutionInputs::new(Vec::new())?),
/// };
/// assert!(error.to_string().contains("before admission"));
/// # Ok::<(), tenferro_runtime::Error>(())
/// ```
#[derive(Debug)]
pub enum SubmitError {
    /// Preparation/admission rejected the request. The exact input package is
    /// returned unchanged to the caller.
    PreAdmission {
        source: Box<Error>,
        inputs: Box<ExecutionInputs>,
    },
}

impl SubmitError {
    /// Recover the unchanged package from a pre-admission rejection.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{Error, runtime::{ExecutionInputs, SubmitError}};
    ///
    /// let error = SubmitError::PreAdmission {
    ///     source: Box::new(Error::Internal("input rejected".into())),
    ///     inputs: Box::new(ExecutionInputs::new(Vec::new())?),
    /// };
    /// assert!(error.into_pre_admission().is_some());
    /// # Ok::<(), tenferro_runtime::Error>(())
    /// ```
    pub fn into_pre_admission(self) -> Option<(Error, ExecutionInputs)> {
        match self {
            Self::PreAdmission { source, inputs } => Some((*source, *inputs)),
        }
    }
}

impl fmt::Display for SubmitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PreAdmission { source, .. } => {
                write!(formatter, "submission rejected before admission: {source}")
            }
        }
    }
}

impl StdError for SubmitError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::PreAdmission { source, .. } => {
                // Keep the pre-admission typed source at the same depth as the
                // historical runtime error chain while the owner travels in
                // this wrapper.
                source.source().or(Some(source.as_ref()))
            }
        }
    }
}

impl From<SubmitError> for Error {
    fn from(error: SubmitError) -> Self {
        match error {
            SubmitError::PreAdmission { source, .. } => *source,
        }
    }
}

impl ExecutionHandle {
    /// Wait for submitted work to finish and return its tensor outputs.
    ///
    /// # Errors
    ///
    /// Returns the submitted runtime execution [`Error`], including
    /// [`ErrorKind::RuntimeState`](tenferro_tensor::ErrorKind::RuntimeState)
    /// when the handle was already consumed or the worker panicked.
    pub fn wait(self) -> Result<ExecutionOutcome> {
        self.submission.wait()
    }
}

impl fmt::Debug for ExecutionHandle {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExecutionHandle")
            .field("pending", &self.submission.is_pending())
            .finish_non_exhaustive()
    }
}

pub(super) struct InFlightSubmission {
    work: Mutex<Option<InFlightWork>>,
    completion: Mutex<Option<Result<ExecutionOutcome>>>,
    completed: Condvar,
}

struct AdmittedExecution {
    prepared: PreparedCompiledGraph,
    inputs: ExecutionInputs,
}

enum InFlightWork {
    Admitted(Box<AdmittedExecution>),
    #[cfg(test)]
    Test {
        inputs: Box<ExecutionInputs>,
        work: Box<dyn FnOnce() -> Result<Vec<Tensor>> + Send>,
    },
}

impl InFlightSubmission {
    fn new(prepared: PreparedCompiledGraph, inputs: ExecutionInputs) -> Self {
        Self {
            work: Mutex::new(Some(InFlightWork::Admitted(Box::new(AdmittedExecution {
                prepared,
                inputs,
            })))),
            completion: Mutex::new(None),
            completed: Condvar::new(),
        }
    }

    #[cfg(test)]
    pub(super) fn for_test(work: impl FnOnce() -> Result<Vec<Tensor>> + Send + 'static) -> Self {
        Self {
            work: Mutex::new(Some(InFlightWork::Test {
                inputs: Box::new(ExecutionInputs::new(Vec::new()).expect("empty test inputs")),
                work: Box::new(work),
            })),
            completion: Mutex::new(None),
            completed: Condvar::new(),
        }
    }

    fn into_unstarted_inputs(self) -> ExecutionInputs {
        let work = match self.work.into_inner() {
            Ok(work) => work,
            Err(poisoned) => poisoned.into_inner(),
        };
        match work {
            Some(InFlightWork::Admitted(admitted)) => admitted.inputs,
            #[cfg(test)]
            Some(InFlightWork::Test { inputs, .. }) => *inputs,
            None => unreachable!("unstarted submission must still contain its owner"),
        }
    }

    pub(super) fn run(&self) {
        let work = match self.work.lock() {
            Ok(mut work) => work.take(),
            Err(poisoned) => poisoned.into_inner().take(),
        };
        let result = match work {
            Some(InFlightWork::Admitted(admitted)) => run_admitted_work(admitted),
            #[cfg(test)]
            Some(InFlightWork::Test { work, .. }) => {
                let result = catch_unwind(AssertUnwindSafe(work));
                match result {
                    Ok(Ok(outputs)) => ExecutionBundle::from_outputs(outputs)
                        .map(|bundle| ExecutionOutcome::Completed(Box::new(bundle))),
                    Ok(Err(error)) => Err(error),
                    Err(payload) => Ok(ExecutionOutcome::CompletionUnproven {
                        error: Error::runtime_state(
                            "ExecutionHandle::wait",
                            ErrorPhase::Execution,
                            panic_payload_message(payload),
                        ),
                        diagnostic_keys: Box::from(["execution.retirement-unproven".to_owned()]),
                    }),
                }
            }
            None => Err(Error::runtime_state(
                "Runtime::submit",
                ErrorPhase::Execution,
                "in-flight submission work was already consumed",
            )),
        };
        match self.completion.lock() {
            Ok(mut completion) => {
                *completion = Some(result);
            }
            Err(poisoned) => {
                *poisoned.into_inner() = Some(Err(Error::runtime_state(
                    "ExecutionHandle::wait",
                    ErrorPhase::Execution,
                    "in-flight completion lock poisoned",
                )));
            }
        }
        self.completed.notify_all();
    }

    fn wait(&self) -> Result<ExecutionOutcome> {
        let mut completion = self.completion.lock().map_err(|_| {
            Error::runtime_state(
                "ExecutionHandle::wait",
                ErrorPhase::Execution,
                "in-flight completion lock poisoned",
            )
        })?;
        loop {
            if let Some(result) = completion.take() {
                return result;
            }
            completion = self.completed.wait(completion).map_err(|_| {
                Error::runtime_state(
                    "ExecutionHandle::wait",
                    ErrorPhase::Execution,
                    "in-flight completion lock poisoned while waiting",
                )
            })?;
        }
    }

    fn is_pending(&self) -> bool {
        self.completion
            .lock()
            .map_or(true, |completion| completion.is_none())
    }
}

fn run_admitted_work(admitted: Box<AdmittedExecution>) -> Result<ExecutionOutcome> {
    let execution = catch_unwind(AssertUnwindSafe(|| {
        let input_reads = admitted.inputs.as_reads()?;
        execute_admitted(&admitted.prepared, &input_reads)
    }));
    match execution {
        Ok(Ok(outputs)) => {
            let AdmittedExecution { inputs, .. } = *admitted;
            match ExecutionBundle::from_inputs_and_outputs(inputs, outputs) {
                Ok(bundle) => Ok(ExecutionOutcome::Completed(Box::new(bundle))),
                Err(error) => Ok(ExecutionOutcome::CompletionUnproven {
                    error,
                    diagnostic_keys: Box::from(["execution.bundle-build".to_owned()]),
                }),
            }
        }
        Ok(Err(error)) => {
            let AdmittedExecution { inputs, .. } = *admitted;
            Ok(ExecutionOutcome::RetiredFailed {
                error,
                inputs: Box::new(inputs),
            })
        }
        Err(payload) => {
            let error = Error::runtime_state(
                "ExecutionHandle::wait",
                ErrorPhase::Execution,
                panic_payload_message(payload),
            );
            // The completion witness was lost after admission. Leak the
            // private record deliberately: no owner or provider state may be
            // exposed while retirement is unproven.
            Box::leak(admitted);
            Ok(ExecutionOutcome::CompletionUnproven {
                error,
                diagnostic_keys: Box::from(["execution.retirement-unproven".to_owned()]),
            })
        }
    }
}

pub(super) trait SubmissionSpawner {
    fn spawn(&self, submission: Arc<InFlightSubmission>) -> std::io::Result<()>;
}

pub(super) fn spawn_in_flight(
    submission: Arc<InFlightSubmission>,
    spawner: &dyn SubmissionSpawner,
) -> std::result::Result<ExecutionHandle, Box<(ExecutionInputs, Error)>> {
    if let Err(source) = spawner.spawn(Arc::clone(&submission)) {
        // INVARIANT: a SubmissionSpawner error means it did not take or start
        // the submission, so the sole Arc can be unwrapped and the exact
        // pre-admission owner recovered.
        let submission = match Arc::try_unwrap(submission) {
            Ok(submission) => submission,
            Err(_) => unreachable!("failed spawner must not retain submission"),
        };
        let inputs = submission.into_unstarted_inputs();
        let error = Error::runtime_state_source(
            "Runtime::submit",
            ErrorPhase::Execution,
            SubmissionError::WorkerSpawn { source },
        );
        return Err(Box::new((inputs, error)));
    }
    Ok(ExecutionHandle { submission })
}

pub(super) struct OsThreadSpawner;

impl SubmissionSpawner for OsThreadSpawner {
    fn spawn(&self, submission: Arc<InFlightSubmission>) -> std::io::Result<()> {
        thread::Builder::new()
            .name("tenferro-runtime-submit".to_string())
            .spawn(move || submission.run())
            .map(drop)
    }
}

impl fmt::Debug for PreparedCompiledGraph {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PreparedCompiledGraph")
            .field("runtime_id", &self.runtime_id)
            .field("epoch", &self.epoch)
            .field("program", &self.program)
            .finish_non_exhaustive()
    }
}

fn panic_payload_message(payload: Box<dyn std::any::Any + Send + 'static>) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        format!("submitted execution panicked: {message}")
    } else if let Some(message) = payload.downcast_ref::<String>() {
        format!("submitted execution panicked: {message}")
    } else {
        "submitted execution panicked".to_string()
    }
}

#[allow(
    dead_code,
    reason = "Phase 5 runtime execution task adds erased dispatch methods"
)]
pub(super) trait ErasedTensorBackendExecutor: fmt::Debug + Send + Sync {
    fn backend_type_name(&self) -> &'static str;
    fn extension_cache_stats(&self) -> std::result::Result<CacheStats, CacheOwnerError>;
    fn clear_extension_caches(&self) -> std::result::Result<(), CacheOwnerError>;
    fn execute(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: Vec<Tensor>,
    ) -> Result<Vec<Tensor>>;
    fn execute_tensor_refs(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: &[&Tensor],
    ) -> Result<Vec<Tensor>>;
    fn execute_values(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: Vec<Tensor>,
    ) -> Result<Vec<TensorValue>>;
    fn execute_value_refs(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: &[&Tensor],
    ) -> Result<Vec<TensorValue>>;
    fn execute_slot_instruction<'input>(
        &self,
        instruction_index: usize,
        instruction: &ExecInstruction,
        operations: &[PreparedOperationPlan],
        slots: &mut [Option<ExecSlot<'input>>],
        output_mode: RuntimeOutputMode,
        terminal_slots: &[bool],
    ) -> Result<()>;
    /// Execute one planned elementwise region as a single fused command.
    ///
    /// Reads `input_slots` from `slots`, runs `plan`, and writes the fused
    /// outputs into `output_slots`. Returns `Ok(false)` when the backend
    /// rejects the fusion, in which case the caller executes the region's
    /// instructions one by one; nothing is written in that case.
    fn execute_elementwise_fusion_slots<'input>(
        &self,
        input_slots: &[usize],
        instruction_count: usize,
        plan: &tenferro_tensor::backend::ElementwiseFusionPlan,
        slots: &mut [Option<ExecSlot<'input>>],
        output_slots: &[usize],
    ) -> Result<bool>;
    fn materialize_slot<'input>(&self, slot: ExecSlot<'input>) -> Result<Tensor>;
    fn materialize_slot_value<'input>(&self, slot: ExecSlot<'input>) -> Result<TensorValue>;
}

pub(super) fn erased_tensor_backend_executor<B>(backend: B) -> Arc<dyn ErasedTensorBackendExecutor>
where
    B: TensorBackend + Send + Sync + 'static,
{
    Arc::new(TensorBackendExecutor::<B>::new(backend))
}

pub(super) fn extension_cache_owner(
    executor: Arc<dyn ErasedTensorBackendExecutor>,
) -> Arc<dyn RuntimeCacheOwner> {
    Arc::new(TensorBackendExtensionCacheOwner { executor })
}

#[derive(Debug)]
struct TensorBackendExtensionCacheOwner {
    executor: Arc<dyn ErasedTensorBackendExecutor>,
}

impl RuntimeCacheOwner for TensorBackendExtensionCacheOwner {
    fn cache_stats(&self) -> std::result::Result<CacheStats, CacheOwnerError> {
        self.executor.extension_cache_stats()
    }

    fn clear_caches(&self) -> std::result::Result<(), CacheOwnerError> {
        self.executor.clear_extension_caches()
    }
}

#[allow(
    dead_code,
    reason = "Phase 5 runtime execution task consumes backend execution state"
)]
struct TensorBackendExecutorState<B: TensorBackend + 'static> {
    backend: B,
    backend_cache: B::RuntimeCache,
    extension_caches: ExtensionCacheStore,
    slot_workspace: Vec<Option<ExecSlot<'static>>>,
    borrowed_slot_workspace_capacity: usize,
}

struct TensorBackendExecutor<B: TensorBackend + 'static> {
    state: Mutex<TensorBackendExecutorSlot<B>>,
    available: Condvar,
}

struct TensorBackendExecutorSlot<B: TensorBackend + 'static> {
    state: Option<TensorBackendExecutorState<B>>,
    active_thread: Option<ThreadId>,
    execution_poisoned: bool,
}

impl<B> TensorBackendExecutor<B>
where
    B: TensorBackend + Send + Sync + 'static,
{
    fn new(backend: B) -> Self {
        Self {
            state: Mutex::new(TensorBackendExecutorSlot {
                state: Some(TensorBackendExecutorState {
                    backend,
                    backend_cache: B::RuntimeCache::default(),
                    extension_caches: ExtensionCacheStore::new(),
                    slot_workspace: Vec::new(),
                    borrowed_slot_workspace_capacity: 0,
                }),
                active_thread: None,
                execution_poisoned: false,
            }),
            available: Condvar::new(),
        }
    }

    fn lease_state(&self, caller: &'static str) -> Result<TensorBackendExecutorLease<'_, B>> {
        let current = thread::current().id();
        let mut slot = self.lock_slot(caller)?;
        loop {
            if slot.execution_poisoned {
                return Err(Error::runtime_state(
                    caller,
                    ErrorPhase::Execution,
                    "tensor backend executor state poisoned by panic during prior execution",
                ));
            }
            if let Some(state) = slot.state.take() {
                slot.active_thread = Some(current);
                return Ok(TensorBackendExecutorLease {
                    executor: self,
                    state: Some(state),
                });
            }
            if slot.active_thread == Some(current) {
                return Err(Error::runtime_state(
                    caller,
                    ErrorPhase::Execution,
                    "reentrant tensor backend executor call would deadlock",
                ));
            }
            slot = self.available.wait(slot).map_err(|_| {
                Error::runtime_state(
                    caller,
                    ErrorPhase::Execution,
                    "tensor backend executor state lock poisoned while waiting",
                )
            })?;
        }
    }

    fn lock_slot(
        &self,
        caller: &'static str,
    ) -> Result<MutexGuard<'_, TensorBackendExecutorSlot<B>>> {
        self.state.lock().map_err(|_| {
            Error::runtime_state(
                caller,
                ErrorPhase::Execution,
                "tensor backend executor state lock poisoned",
            )
        })
    }
}

struct TensorBackendExecutorLease<'a, B: TensorBackend + 'static> {
    executor: &'a TensorBackendExecutor<B>,
    state: Option<TensorBackendExecutorState<B>>,
}

impl<B: TensorBackend + 'static> TensorBackendExecutorLease<'_, B> {
    fn state_mut(&mut self) -> &mut TensorBackendExecutorState<B> {
        self.state
            .as_mut()
            .expect("executor state lease always owns state before drop")
    }
}

impl<B: TensorBackend + 'static> Drop for TensorBackendExecutorLease<'_, B> {
    fn drop(&mut self) {
        let Some(state) = self.state.take() else {
            return;
        };
        let panicking = thread::panicking();
        let mut wake_all_waiters = panicking;
        match self.executor.state.lock() {
            Ok(mut slot) => {
                slot.state = Some(state);
                slot.active_thread = None;
                slot.execution_poisoned |= panicking;
            }
            Err(poisoned_lock) => {
                let mut slot = poisoned_lock.into_inner();
                slot.state = Some(state);
                slot.active_thread = None;
                slot.execution_poisoned = true;
                wake_all_waiters = true;
            }
        }
        if wake_all_waiters {
            self.executor.available.notify_all();
        } else {
            self.executor.available.notify_one();
        }
    }
}

impl<B: TensorBackend + 'static> fmt::Debug for TensorBackendExecutor<B> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TensorBackendExecutor")
            .field("backend_type", &std::any::type_name::<B>())
            .field("state_lock_poisoned", &self.state.is_poisoned())
            .finish_non_exhaustive()
    }
}

impl<B> ErasedTensorBackendExecutor for TensorBackendExecutor<B>
where
    B: TensorBackend + Send + Sync + 'static,
{
    fn backend_type_name(&self) -> &'static str {
        std::any::type_name::<B>()
    }

    fn extension_cache_stats(&self) -> std::result::Result<CacheStats, CacheOwnerError> {
        let lease = self
            .lease_state("Runtime::extension_cache_stats")
            .map_err(cache_owner_error)?;
        let state = lease
            .state
            .as_ref()
            .expect("executor state lease always owns state before drop");
        Ok(cache_stats_from_tensor_stats(
            state.extension_caches.stats(ExtensionCacheSelector::All),
        ))
    }

    fn clear_extension_caches(&self) -> std::result::Result<(), CacheOwnerError> {
        let mut lease = self
            .lease_state("Runtime::clear_extension_caches")
            .map_err(cache_owner_error)?;
        lease.state_mut().extension_caches.clear();
        Ok(())
    }

    fn execute(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: Vec<Tensor>,
    ) -> Result<Vec<Tensor>> {
        validate_exec_input_count(program, inputs.len())?;
        let mut lease = self.lease_state("Runtime::run_compiled")?;
        let TensorBackendExecutorState {
            backend,
            backend_cache,
            extension_caches,
            slot_workspace,
            borrowed_slot_workspace_capacity: _,
        } = lease.state_mut();
        let mut extension_dispatch = ExtensionExecutionDispatch {
            operations,
            caches: extension_caches,
        };
        crate::segment::eval_exec_segmented_with_cache_and_workspace(
            backend,
            program,
            inputs,
            slot_workspace,
            backend_cache,
            Some(&mut extension_dispatch),
        )
    }

    fn execute_tensor_refs(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: &[&Tensor],
    ) -> Result<Vec<Tensor>> {
        validate_exec_input_count(program, inputs.len())?;
        let inputs = inputs
            .iter()
            .map(|tensor| ExecSlot::Read(TensorRead::from_tensor(tensor)))
            .collect();
        let mut lease = self.lease_state("Runtime::run_compiled")?;
        let TensorBackendExecutorState {
            backend,
            backend_cache,
            extension_caches,
            borrowed_slot_workspace_capacity,
            ..
        } = lease.state_mut();
        let mut extension_dispatch = ExtensionExecutionDispatch {
            operations,
            caches: extension_caches,
        };
        let mut slot_workspace = Vec::with_capacity(*borrowed_slot_workspace_capacity);
        let result = crate::segment::eval_exec_segmented_slots_with_cache_and_workspace(
            backend,
            program,
            inputs,
            &mut slot_workspace,
            backend_cache,
            Some(&mut extension_dispatch),
        );
        *borrowed_slot_workspace_capacity = slot_workspace.capacity();
        result
    }

    fn execute_values(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: Vec<Tensor>,
    ) -> Result<Vec<TensorValue>> {
        validate_exec_input_count(program, inputs.len())?;
        let inputs = inputs.into_iter().map(ExecSlot::Owned).collect();
        let mut lease = self.lease_state("Runtime::run_compiled_values")?;
        let TensorBackendExecutorState {
            backend,
            backend_cache,
            extension_caches,
            slot_workspace,
            borrowed_slot_workspace_capacity: _,
        } = lease.state_mut();
        let mut extension_dispatch = ExtensionExecutionDispatch {
            operations,
            caches: extension_caches,
        };
        crate::segment::eval_exec_segmented_slot_values_with_cache_and_workspace(
            backend,
            program,
            inputs,
            slot_workspace,
            backend_cache,
            Some(&mut extension_dispatch),
        )
    }

    fn execute_value_refs(
        &self,
        program: &ExecProgram,
        operations: &[PreparedOperationPlan],
        inputs: &[&Tensor],
    ) -> Result<Vec<TensorValue>> {
        validate_exec_input_count(program, inputs.len())?;
        let inputs = inputs
            .iter()
            .map(|tensor| ExecSlot::Read(TensorRead::from_tensor(tensor)))
            .collect();
        let mut lease = self.lease_state("Runtime::run_compiled_values")?;
        let TensorBackendExecutorState {
            backend,
            backend_cache,
            extension_caches,
            borrowed_slot_workspace_capacity,
            ..
        } = lease.state_mut();
        let mut extension_dispatch = ExtensionExecutionDispatch {
            operations,
            caches: extension_caches,
        };
        let mut slot_workspace = Vec::with_capacity(*borrowed_slot_workspace_capacity);
        let result = crate::segment::eval_exec_segmented_slot_values_with_cache_and_workspace(
            backend,
            program,
            inputs,
            &mut slot_workspace,
            backend_cache,
            Some(&mut extension_dispatch),
        );
        *borrowed_slot_workspace_capacity = slot_workspace.capacity();
        result
    }

    fn execute_slot_instruction<'input>(
        &self,
        instruction_index: usize,
        instruction: &ExecInstruction,
        operations: &[PreparedOperationPlan],
        slots: &mut [Option<ExecSlot<'input>>],
        output_mode: RuntimeOutputMode,
        terminal_slots: &[bool],
    ) -> Result<()> {
        let mut lease = self.lease_state("Runtime::run_compiled scheduled instruction")?;
        let TensorBackendExecutorState {
            backend,
            backend_cache,
            extension_caches,
            ..
        } = lease.state_mut();
        let mut extension_dispatch = ExtensionExecutionDispatch {
            operations,
            caches: extension_caches,
        };

        if matches!(output_mode, RuntimeOutputMode::Value)
            && backend.with_backend_session(|exec| {
                crate::exec::try_execute_terminal_value_instruction(
                    exec,
                    slots,
                    instruction,
                    terminal_slots,
                )
            })?
        {
            // Already handled as a metadata-only TensorValue.
        } else if crate::exec::is_host_instruction(instruction) {
            crate::exec::execute_host_instruction(backend, slots, instruction)?;
        } else if crate::exec::is_ffi_instruction(instruction) {
            crate::exec::execute_ffi_instruction_cached(
                backend,
                backend_cache,
                slots,
                instruction,
                DispatchMode::Unsegmented,
                Some(instruction_index),
                Some(&mut extension_dispatch),
            )?;
        } else {
            let result = backend.with_backend_session(|exec| {
                crate::exec::execute_backend_op(exec, slots, instruction)
            })?;
            slots[instruction.output_slots[0]] = Some(ExecSlot::Owned(result));
        }
        crate::exec::reclaim_last_use_inputs_backend(slots, instruction, backend);
        Ok(())
    }

    fn execute_elementwise_fusion_slots<'input>(
        &self,
        input_slots: &[usize],
        instruction_count: usize,
        plan: &tenferro_tensor::backend::ElementwiseFusionPlan,
        slots: &mut [Option<ExecSlot<'input>>],
        output_slots: &[usize],
    ) -> Result<bool> {
        // The fused entry point takes owned tensors. A borrowed view input is
        // materialized once when the region is long enough to amortize that
        // copy; otherwise the per-instruction path, which resolves views itself,
        // stays in charge.
        let mut views: Vec<usize> = Vec::new();
        for &slot in input_slots {
            let value = slots
                .get(slot)
                .and_then(Option::as_ref)
                .ok_or_else(|| crate::Error::from(tenferro_tensor::Error::MissingValue { slot }))?;
            if value.as_tensor("elementwise_region").is_err() {
                views.push(slot);
            }
        }
        if !views.is_empty() {
            if instruction_count < super::region::VIEW_COPY_MIN_INSTRUCTIONS {
                return Ok(false);
            }
            let mut lease = self.lease_state("Runtime::run_prepared elementwise region copy")?;
            let backend = &mut lease.state_mut().backend;
            for &slot in &views {
                let tensor = {
                    let read = slots[slot].as_ref().map(ExecSlot::as_read).ok_or_else(|| {
                        crate::Error::from(tenferro_tensor::Error::MissingValue { slot })
                    })?;
                    backend.with_backend_session(|exec| exec.to_contiguous_read(read))?
                };
                slots[slot] = Some(ExecSlot::Owned(tensor));
            }
        }

        let mut inputs: Vec<&Tensor> = Vec::with_capacity(input_slots.len());
        for &slot in input_slots {
            let value = slots
                .get(slot)
                .and_then(Option::as_ref)
                .ok_or_else(|| crate::Error::from(tenferro_tensor::Error::MissingValue { slot }))?;
            inputs.push(value.as_tensor("elementwise_region")?);
        }

        if !crate::segment::plan_matches_input_dtypes(plan, &inputs) {
            return Ok(false);
        }

        let mut lease = self.lease_state("Runtime::run_prepared elementwise region")?;
        let backend = &mut lease.state_mut().backend;
        let outputs =
            backend.with_backend_session(|exec| exec.execute_elementwise_fusion(&inputs, plan))?;
        let Some(outputs) = outputs else {
            return Ok(false);
        };
        if outputs.len() != output_slots.len() {
            return Err(crate::Error::Internal(format!(
                "fused elementwise region produced {} outputs for {} slots",
                outputs.len(),
                output_slots.len()
            )));
        }
        for (&slot, tensor) in output_slots.iter().zip(outputs) {
            slots[slot] = Some(ExecSlot::Owned(tensor));
        }
        Ok(true)
    }

    fn materialize_slot<'input>(&self, slot: ExecSlot<'input>) -> Result<Tensor> {
        let mut lease = self.lease_state("Runtime::run_compiled collect outputs")?;
        let backend = &mut lease.state_mut().backend;
        backend.with_backend_session(|exec| slot.into_tensor(exec))
    }

    fn materialize_slot_value<'input>(&self, slot: ExecSlot<'input>) -> Result<TensorValue> {
        let mut lease = self.lease_state("Runtime::run_compiled_values collect outputs")?;
        let backend = &mut lease.state_mut().backend;
        backend.with_backend_session(|exec| slot.into_value(exec))
    }
}

fn cache_owner_error(error: Error) -> CacheOwnerError {
    CacheOwnerError::new(Arc::new(error))
}

fn cache_stats_from_tensor_stats(stats: tenferro_tensor::CacheStats) -> CacheStats {
    CacheStats {
        entries: stats.entries,
        retained_bytes: stats.retained_bytes,
        hits: stats.hits,
        misses: stats.misses,
        evictions: stats.evictions,
        clears: stats.clears,
    }
}

pub(super) fn run_compiled(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[&Tensor],
) -> Result<Vec<Tensor>> {
    let inputs = resolve_input_refs(program, inputs)?;
    let signature = input_signature_reads(&inputs)?;
    let prepared = prepare(runtime, program, &signature)?;
    validate_prepared_epoch(runtime, prepared.root().epoch(), "Runtime::run_compiled")?;
    execute_scheduled_reads(
        prepared.root().staging(),
        prepared.root().schedule(),
        prepared.root().regions(),
        prepared.root().region_counters(),
        prepared.operations(),
        &inputs,
    )
}

/// Execute one immutable borrowed package synchronously through provider retirement.
///
/// Asynchronous or non-host providers are rejected before preparation can enqueue
/// work. CPU/host execution returns only after the schedule has retired.
pub(super) fn execute_scoped_read_only<'env>(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: ScopedReadInputs<'env>,
) -> std::result::Result<ScopedExecutionOutcome<'env>, ScopedSubmitRejected<'env>> {
    if inputs.has_non_host_provider() {
        return Err(ScopedSubmitRejected {
            source: Box::new(Error::unsupported(
                "Runtime::execute_scoped_read_only",
                ErrorPhase::Execution,
                "scoped borrowed execution requires host/CPU storage",
            )),
            inputs,
        });
    }

    let reads = inputs.as_reads();
    let prepared = match prepare_compiled_reads(runtime, program, &reads) {
        Ok(prepared) => prepared,
        Err(source) => {
            return Err(ScopedSubmitRejected {
                source: Box::new(source),
                inputs,
            })
        }
    };
    if !schedule_supports_scoped_execution(prepared.prepared.root().schedule()) {
        return Err(ScopedSubmitRejected {
            source: Box::new(Error::unsupported(
                "Runtime::execute_scoped_read_only",
                ErrorPhase::Execution,
                "the selected provider does not prove retirement before scoped return",
            )),
            inputs,
        });
    }

    match execute_scoped_admitted(
        prepared.prepared.root().staging(),
        prepared.prepared.root().schedule(),
        prepared.prepared.operations(),
        &reads,
    ) {
        Ok(bundle) => Ok(ScopedExecutionOutcome::Completed(bundle)),
        Err(error) => Ok(ScopedExecutionOutcome::RetiredFailed { error, inputs }),
    }
}

fn execute_scoped_admitted<'env>(
    program: &ExecProgram,
    schedule: &ScheduledGraph,
    operations: &[PreparedOperationPlan],
    inputs: &[TensorRead<'env>],
) -> Result<ScopedExecutionBundle<'env>> {
    validate_exec_input_count(program, inputs.len())?;
    crate::exec::validate_exec_program(program, "scoped tensor executor")?;
    let input_slots = inputs.iter().cloned().map(ExecSlot::Read).collect();
    let mut located = execute_scheduled_slots(
        program,
        schedule,
        &[],
        &super::region::RegionExecutionCounters::default(),
        operations,
        input_slots,
        RuntimeOutputMode::Tensor,
    )?;
    collect_scoped_outputs(program, &mut located)
}

pub(crate) fn collect_scoped_outputs<'env>(
    program: &ExecProgram,
    outputs: &mut [Option<LocatedExecSlot<'env>>],
) -> Result<ScopedExecutionBundle<'env>> {
    let mut owned = AllocationGroup::from_tensors(Vec::new())
        .map(|(group, _)| group)
        .map_err(|error| {
            Error::runtime_state(
                "Runtime::collect_scoped_outputs",
                ErrorPhase::Execution,
                error.to_string(),
            )
        })?;
    let mut scoped = Vec::with_capacity(program.output_slots.len());
    for &slot in &program.output_slots {
        let located = outputs
            .get_mut(slot)
            .and_then(Option::take)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        let output = match located.value {
            ExecSlot::Read(read) => ScopedOutput::Borrowed(read.tensor_view()),
            ExecSlot::Owned(tensor) => {
                let slot = owned.append_tensor(tensor).map_err(|error| {
                    Error::runtime_state(
                        "Runtime::collect_scoped_outputs",
                        ErrorPhase::Execution,
                        error.to_string(),
                    )
                })?;
                ScopedOutput::Owned(slot)
            }
            ExecSlot::Value(value) => {
                let (group, slot, dtype, shape) = value.try_into_group_parts().map_err(|_| {
                    Error::runtime_state(
                        "Runtime::collect_scoped_outputs",
                        ErrorPhase::Execution,
                        "scoped value output was retained by another owner",
                    )
                })?;
                let slot = owned.append_group(group, slot).map_err(|error| {
                    Error::runtime_state(
                        "Runtime::collect_scoped_outputs",
                        ErrorPhase::Execution,
                        error.to_string(),
                    )
                })?;
                let _ = (dtype, shape);
                ScopedOutput::Owned(slot)
            }
        };
        scoped.push(output);
    }
    outputs.iter_mut().for_each(|output| *output = None);
    Ok(ScopedExecutionBundle {
        owned,
        outputs: scoped.into_boxed_slice(),
    })
}

fn output_ref_from_group<'a>(
    group: &'a AllocationGroup,
    slot: DescriptorSlot,
) -> std::result::Result<OutputRef<'a>, OutputAccessError> {
    let mut views = group.read_views(std::slice::from_ref(&slot))?;
    match views.pop() {
        Some(TensorRead::View(view)) => Ok(OutputRef::Tensor(view)),
        Some(TensorRead::Tensor(_)) | None => Err(OutputAccessError::InvalidOutput {
            index: slot.index(),
        }),
    }
}

fn schedule_supports_scoped_execution(schedule: &ScheduledGraph) -> bool {
    let supports = |location: &ExecutionLocation| {
        location
            .witness()
            .event_domain_driver()
            .supports_scoped_read_only()
    };
    supports(schedule.root_location())
        && schedule.input_locations().iter().all(supports)
        && schedule.operation_locations().iter().all(supports)
        && schedule.nodes().iter().all(|node| {
            node.event_domain_witness()
                .event_domain_driver()
                .supports_scoped_read_only()
        })
}

pub(super) fn prepare_compiled(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[&Tensor],
) -> Result<PreparedCompiledGraph> {
    let inputs = resolve_input_refs(program, inputs)?;
    let signature = input_signature_reads(&inputs)?;
    let prepared = prepare(runtime, program, &signature)?;
    validate_prepared_epoch(
        runtime,
        prepared.root().epoch(),
        "Runtime::prepare_compiled",
    )?;
    Ok(PreparedCompiledGraph {
        runtime_id: runtime.id(),
        epoch: prepared.root().epoch(),
        program: program.clone(),
        prepared,
    })
}

pub(super) fn submit(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: ExecutionInputs,
) -> std::result::Result<ExecutionHandle, SubmitError> {
    submit_with_spawner(runtime, program, inputs, &OsThreadSpawner)
}

pub(super) fn submit_with_spawner(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: ExecutionInputs,
    spawner: &dyn SubmissionSpawner,
) -> std::result::Result<ExecutionHandle, SubmitError> {
    let prepared = match prepare_submission(runtime, program, &inputs) {
        Ok(prepared) => prepared,
        Err(source) => {
            return Err(SubmitError::PreAdmission {
                source: Box::new(source),
                inputs: Box::new(inputs),
            })
        }
    };
    let submission = Arc::new(InFlightSubmission::new(prepared, inputs));
    match spawn_in_flight(submission, spawner) {
        Ok(handle) => Ok(handle),
        Err(failure) => {
            let (inputs, source) = *failure;
            Err(SubmitError::PreAdmission {
                source: Box::new(source),
                inputs: Box::new(inputs),
            })
        }
    }
}

pub(super) fn run_prepared(
    runtime: &Runtime,
    prepared: &PreparedCompiledGraph,
    inputs: &[&Tensor],
) -> Result<Vec<Tensor>> {
    validate_prepared_runtime(runtime, prepared, "Runtime::run_prepared")?;
    let inputs = resolve_input_refs(&prepared.program, inputs)?;
    execute_scheduled_reads(
        prepared.prepared.root().staging(),
        prepared.prepared.root().schedule(),
        prepared.prepared.root().regions(),
        prepared.prepared.root().region_counters(),
        prepared.prepared.operations(),
        &inputs,
    )
}

fn prepare_submission(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &ExecutionInputs,
) -> Result<PreparedCompiledGraph> {
    let input_reads = inputs.as_reads()?;
    prepare_compiled_reads(runtime, program, &input_reads)
}

fn prepare_compiled_reads(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[TensorRead<'_>],
) -> Result<PreparedCompiledGraph> {
    validate_ordered_input_metadata_reads(program, inputs)?;
    let signature = input_signature_reads(inputs)?;
    let prepared = prepare(runtime, program, &signature)?;
    validate_prepared_epoch(runtime, prepared.root().epoch(), "Runtime::submit")?;
    Ok(PreparedCompiledGraph {
        runtime_id: runtime.id(),
        epoch: prepared.root().epoch(),
        program: program.clone(),
        prepared,
    })
}

fn execute_admitted(
    prepared: &PreparedCompiledGraph,
    inputs: &[TensorRead<'_>],
) -> Result<Vec<Tensor>> {
    execute_scheduled_reads(
        prepared.prepared.root().staging(),
        prepared.prepared.root().schedule(),
        prepared.prepared.root().regions(),
        prepared.prepared.root().region_counters(),
        prepared.prepared.operations(),
        inputs,
    )
}

pub(super) fn run_compiled_values(
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[&Tensor],
) -> Result<Vec<TensorValue>> {
    let inputs = resolve_input_refs(program, inputs)?;
    let signature = input_signature_reads(&inputs)?;
    let prepared = prepare(runtime, program, &signature)?;
    validate_prepared_epoch(
        runtime,
        prepared.root().epoch(),
        "Runtime::run_compiled_values",
    )?;
    execute_scheduled_value_reads(
        prepared.root().staging(),
        prepared.root().schedule(),
        prepared.operations(),
        &inputs,
    )
}

fn validate_prepared_runtime(
    runtime: &Runtime,
    prepared: &PreparedCompiledGraph,
    caller: &'static str,
) -> Result<()> {
    if runtime.id() != prepared.runtime_id {
        return Err(Error::runtime_state(
            caller,
            ErrorPhase::Execution,
            "prepared compiled graph belongs to a different runtime",
        ));
    }
    let epoch = runtime
        .epoch()
        .map_err(|source| Error::runtime_state_source(caller, ErrorPhase::Execution, source))?;
    if epoch != prepared.epoch {
        return Err(Error::runtime_state(
            caller,
            ErrorPhase::Execution,
            format!(
                "prepared epoch {:?} does not match current epoch {:?}",
                prepared.epoch, epoch
            ),
        ));
    }
    Ok(())
}

fn prepare(
    runtime: &Runtime,
    program: &CompiledGraph,
    signature: &InputSignature,
) -> Result<Arc<super::preparation::PreparedProgram>> {
    runtime
        .prepare_compiled_for(program, signature, &PrepareOptions::new())
        .map_err(prepare_error)
}

fn validate_prepared_epoch(
    runtime: &Runtime,
    prepared_epoch: super::RuntimeEpoch,
    caller: &'static str,
) -> Result<()> {
    let epoch = runtime
        .epoch()
        .map_err(|source| Error::runtime_state_source(caller, ErrorPhase::Execution, source))?;
    if epoch != prepared_epoch {
        return Err(Error::runtime_state(
            caller,
            ErrorPhase::Execution,
            format!(
                "prepared epoch {:?} does not match current epoch {:?}",
                prepared_epoch, epoch
            ),
        ));
    }
    Ok(())
}

fn execute_scheduled_reads(
    program: &ExecProgram,
    schedule: &ScheduledGraph,
    regions: &[super::region::ElementwiseRegion],
    region_counters: &super::region::RegionExecutionCounters,
    operations: &[PreparedOperationPlan],
    inputs: &[TensorRead<'_>],
) -> Result<Vec<Tensor>> {
    validate_exec_input_count(program, inputs.len())?;
    crate::exec::validate_exec_program(program, "scheduled tensor executor")?;
    let inputs = inputs.iter().cloned().map(ExecSlot::Read).collect();
    execute_scheduled_slots(
        program,
        schedule,
        regions,
        region_counters,
        operations,
        inputs,
        RuntimeOutputMode::Tensor,
    )
    .and_then(|mut slots| {
        collect_tensor_outputs_with(program, &mut slots, |location, slot| {
            location.witness().executor().materialize_slot(slot)
        })
    })
}

fn execute_scheduled_value_reads(
    program: &ExecProgram,
    schedule: &ScheduledGraph,
    operations: &[PreparedOperationPlan],
    inputs: &[TensorRead<'_>],
) -> Result<Vec<TensorValue>> {
    validate_exec_input_count(program, inputs.len())?;
    crate::exec::validate_exec_program(program, "scheduled value executor")?;
    let inputs = inputs.iter().cloned().map(ExecSlot::Read).collect();
    execute_scheduled_slots(
        program,
        schedule,
        &[],
        &super::region::RegionExecutionCounters::default(),
        operations,
        inputs,
        RuntimeOutputMode::Value,
    )
    .and_then(|mut slots| {
        collect_value_outputs_with(program, &mut slots, |location, slot| {
            location.witness().executor().materialize_slot_value(slot)
        })
    })
}

fn execute_scheduled_slots<'input>(
    program: &ExecProgram,
    schedule: &ScheduledGraph,
    regions: &[super::region::ElementwiseRegion],
    region_counters: &super::region::RegionExecutionCounters,
    operations: &[PreparedOperationPlan],
    inputs: Vec<ExecSlot<'input>>,
    output_mode: RuntimeOutputMode,
) -> Result<Vec<Option<LocatedExecSlot<'input>>>> {
    let terminal_slots = if matches!(output_mode, RuntimeOutputMode::Value) {
        crate::exec::terminal_output_slots(program)
    } else {
        Vec::new()
    };
    let mut staged = Vec::new();
    let mut located = (0..program.n_slots)
        .map(|_| Vec::new())
        .collect::<Vec<Vec<LocatedExecSlot<'input>>>>();
    // INVARIANT: the immutable schedule was validated during preparation;
    // runs are declared after the value stores so unwinding drops
    // and drains native domain work before any tensor storage is released.
    // Driver preflight completes before input ingress or any operation launch.
    // Planned elementwise regions: the start node executes the whole region as
    // one fused command and the covered nodes are skipped. Regions apply to
    // tensor output mode; value mode keeps the per-instruction path.
    let regions_applicable = matches!(output_mode, RuntimeOutputMode::Tensor);
    let mut region_starts: HashMap<usize, usize> = HashMap::new();
    let mut region_covered: HashSet<usize> = HashSet::new();
    if regions_applicable {
        for (region_index, region) in regions.iter().enumerate() {
            if let Some(&first) = region.node_indices.first() {
                region_starts.insert(first, region_index);
            }
            region_covered.extend(region.node_indices.iter().copied());
        }
    }

    let mut event_domains = ScheduledEventDomains::new(schedule)?;
    let result = (|| {
        crate::exec::initialize_exec_slots_in(program, inputs, &mut staged)?;
        if schedule.input_locations().len() != program.input_slots.len() {
            return Err(Error::runtime_state(
                "Runtime::run_compiled",
                ErrorPhase::Execution,
                format!(
                    "prepared schedule has {} input locations for {} inputs",
                    schedule.input_locations().len(),
                    program.input_slots.len()
                ),
            ));
        }
        for (&slot, location) in program.input_slots.iter().zip(schedule.input_locations()) {
            let value = staged
                .get_mut(slot)
                .and_then(Option::take)
                .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
            validate_runtime_input_ingress(location, &value.as_read(), slot)?;
            located[slot].push(LocatedExecSlot {
                location: location.clone(),
                value,
            });
        }
        for (node_index, node) in schedule.nodes().iter().enumerate() {
            match node {
                ScheduledNode::Operation(operation_node) => {
                    if let Some(&region_index) = region_starts.get(&node_index) {
                        let region = &regions[region_index];
                        let first_instruction = program
                            .instructions
                            .get(region.instruction_range.start)
                            .ok_or_else(|| {
                                Error::runtime_state(
                                    "Runtime::run_prepared",
                                    ErrorPhase::Execution,
                                    format!(
                                        "elementwise region references instruction {}, but the                                          execution program has {} instructions",
                                        region.instruction_range.start,
                                        program.instructions.len()
                                    ),
                                )
                            })?;
                        let operation = instruction_execution(schedule, first_instruction)?;
                        if operation.location() != operation_node.location() {
                            return Err(Error::runtime_state(
                                "Runtime::run_prepared",
                                ErrorPhase::Execution,
                                "elementwise region location does not match its first prepared                                  operation"
                                    .to_string(),
                            ));
                        }
                        let location = operation.location().clone();
                        let mut launch = || {
                            for &slot in &region.input_slots {
                                stage_slot_input(slot, &location, &mut located, &mut staged)?;
                            }
                            let applied = operation.executor().execute_elementwise_fusion_slots(
                                &region.input_slots,
                                region.instructions.len(),
                                &region.plan,
                                &mut staged,
                                &region.output_slots,
                            )?;
                            if applied {
                                region_counters.record_fused();
                                validate_region_outputs(region, &location, &staged)?;
                                return retain_region_results(
                                    region,
                                    &location,
                                    &mut located,
                                    &mut staged,
                                );
                            }
                            // The backend rejected the fusion: execute the
                            // region's instructions one by one.
                            region_counters.record_fallback();
                            for (offset, instruction) in region.instructions.iter().enumerate() {
                                let instruction_index = region.instruction_range.start + offset;
                                let member = instruction_execution(schedule, instruction)?;
                                if member.location() != operation_node.location() {
                                    return Err(Error::runtime_state(
                                        "Runtime::run_prepared",
                                        ErrorPhase::Execution,
                                        "elementwise region member location does not match the                                          region location"
                                            .to_string(),
                                    ));
                                }
                                stage_instruction_inputs(
                                    instruction,
                                    member.location(),
                                    &mut located,
                                    &mut staged,
                                )?;
                                member.executor().execute_slot_instruction(
                                    instruction_index,
                                    instruction,
                                    operations,
                                    &mut staged,
                                    output_mode,
                                    &terminal_slots,
                                )?;
                                validate_instruction_outputs(
                                    instruction_index,
                                    instruction,
                                    member.location(),
                                    &staged,
                                )?;
                                retain_instruction_results(
                                    instruction,
                                    member.location(),
                                    &mut located,
                                    &mut staged,
                                )?;
                            }
                            Ok(())
                        };
                        event_domains.enqueue(node_index, node, &mut launch)?;
                        region_counters.record_submission();
                        // Every covered node's completion resolves to the region's
                        // completion token, which was recorded after the region's
                        // last command.
                        let completion = EventDependency::from_completion(node.completion());
                        if let Some(token) = event_domains.completions.get(&completion).cloned() {
                            for &covered in &region.node_indices {
                                if covered == node_index {
                                    continue;
                                }
                                let covered_node = schedule.nodes().get(covered).ok_or_else(|| {
                                    Error::runtime_state(
                                        "Runtime::run_prepared",
                                        ErrorPhase::Execution,
                                        format!(
                                            "elementwise region references schedule node {covered},                                              but the schedule has {} nodes",
                                            schedule.nodes().len()
                                        ),
                                    )
                                })?;
                                event_domains.completions.insert(
                                    EventDependency::from_completion(covered_node.completion()),
                                    Arc::clone(&token),
                                );
                            }
                        }
                        continue;
                    }
                    if region_covered.contains(&node_index) {
                        // Executed as part of its region.
                        continue;
                    }
                    let mut launch = || {
                        let instruction_index = operation_node.instruction_index();
                        let instruction =
                            program.instructions.get(instruction_index).ok_or_else(|| {
                                Error::runtime_state(
                                    "Runtime::run_compiled",
                                    ErrorPhase::Execution,
                                    format!(
                                        "scheduled operation references instruction \
                                         {instruction_index}, but the execution program has {} \
                                         instructions",
                                        program.instructions.len()
                                    ),
                                )
                            })?;
                        let operation = instruction_execution(schedule, instruction)?;
                        if operation.location() != operation_node.location() {
                            return Err(Error::runtime_state(
                                "Runtime::run_compiled",
                                ErrorPhase::Execution,
                                format!(
                                    "scheduled instruction {instruction_index} location does not \
                                     match its prepared executor"
                                ),
                            ));
                        }
                        stage_instruction_inputs(
                            instruction,
                            operation.location(),
                            &mut located,
                            &mut staged,
                        )?;
                        operation.executor().execute_slot_instruction(
                            instruction_index,
                            instruction,
                            operations,
                            &mut staged,
                            output_mode,
                            &terminal_slots,
                        )?;
                        validate_instruction_outputs(
                            instruction_index,
                            instruction,
                            operation.location(),
                            &staged,
                        )?;
                        retain_instruction_results(
                            instruction,
                            operation.location(),
                            &mut located,
                            &mut staged,
                        )
                    };
                    event_domains.enqueue(node_index, node, &mut launch)?;
                    region_counters.record_submission();
                }
                ScheduledNode::Transfer(transfer) => {
                    let mut launch = || execute_scheduled_transfer(transfer, &mut located);
                    event_domains.enqueue(node_index, node, &mut launch)?;
                    region_counters.record_submission();
                }
                ScheduledNode::Collective(_) => {
                    return Err(Error::runtime_state_source(
                        "Runtime::run_compiled",
                        ErrorPhase::Execution,
                        UnsupportedScheduledNodeError {
                            node_index,
                            node_kind: ScheduledNodeKind::Collective,
                        },
                    ));
                }
                ScheduledNode::Barrier(_) => {
                    let mut launch = || Ok(());
                    event_domains.enqueue(node_index, node, &mut launch)?;
                    region_counters.record_submission();
                }
            }
        }
        Ok(())
    })();
    let drain = event_domains.drain();
    match (result, drain) {
        (Ok(()), Ok(())) => collect_located_outputs(program, &mut located),
        (Err(error), Ok(())) | (Ok(()), Err(error)) => {
            staged.clear();
            located.clear();
            Err(error)
        }
        (Err(primary), Err(cleanup)) => {
            staged.clear();
            located.clear();
            Err(scheduled_execution_cleanup_error(primary, cleanup))
        }
    }
}

#[derive(Debug)]
pub(crate) struct ScheduledEventDomains {
    runs: Vec<RuntimeOwnedEventDomainRun>,
    completions: HashMap<EventDependency, Arc<dyn EventToken>>,
}

#[derive(Debug, thiserror::Error)]
#[error(
    "scheduled node {node_index} depends on completion {dependency:?}, but no completion token was recorded"
)]
pub(crate) struct MissingScheduledDependencyCompletionError {
    pub(crate) dependency: EventDependency,
    pub(crate) node_index: usize,
}

#[derive(Debug, thiserror::Error)]
#[error("scheduled transfer destination {destination:?} already contains value slot {value_slot}")]
pub(crate) struct DuplicateTransferDestinationError {
    pub(crate) value_slot: usize,
    pub(crate) destination: ExecutionLocation,
}

impl ScheduledEventDomains {
    pub(crate) fn new(schedule: &ScheduledGraph) -> Result<Self> {
        schedule.preflight().map_err(|source| {
            Error::runtime_state_source("Runtime::run_compiled", ErrorPhase::Execution, source)
        })?;
        let mut drivers = Vec::new();
        let mut seen_domains = HashSet::new();
        for node in schedule.nodes() {
            let domain = node.completion().domain();
            if !seen_domains.insert(domain) {
                continue;
            }
            let witness = node.event_domain_witness();
            debug_assert_eq!(witness.event_domain_id(), domain);
            drivers.push((domain, witness.event_domain_driver().clone()));
        }
        let mut runs = Vec::with_capacity(drivers.len());
        for (domain, driver) in drivers {
            let run = RuntimeOwnedEventDomainRun::new(domain, driver.begin_run(domain)?);
            let actual = run.domain(EventDomainOperation::BeginRun)?;
            if actual != domain {
                return Err(event_domain_error(EventDomainError::RunDomainMismatch {
                    operation: EventDomainOperation::BeginRun,
                    node_index: None,
                    expected: domain,
                    actual,
                }));
            }
            runs.push(run);
        }
        Ok(Self {
            runs,
            completions: HashMap::new(),
        })
    }

    #[cfg(test)]
    pub(crate) fn for_test(
        drivers: Vec<(super::EventDomainId, Arc<dyn super::EventDomainDriver>)>,
    ) -> Result<Self> {
        let mut runs = Vec::with_capacity(drivers.len());
        for (domain, driver) in drivers {
            let run = RuntimeOwnedEventDomainRun::new(domain, driver.begin_run(domain)?);
            let actual = run.domain(EventDomainOperation::BeginRun)?;
            if actual != domain {
                return Err(event_domain_error(EventDomainError::RunDomainMismatch {
                    operation: EventDomainOperation::BeginRun,
                    node_index: None,
                    expected: domain,
                    actual,
                }));
            }
            runs.push(run);
        }
        Ok(Self {
            runs,
            completions: HashMap::new(),
        })
    }

    pub(crate) fn enqueue(
        &mut self,
        node_index: usize,
        node: &ScheduledNode,
        launch: &mut dyn FnMut() -> Result<()>,
    ) -> Result<()> {
        let completion = node.completion();
        let destination = completion.domain();
        let run_index = self.run_index(completion.domain())?;
        let actual_preflight_domain = self.runs[run_index].domain(EventDomainOperation::Enqueue)?;
        if actual_preflight_domain != destination {
            return Err(event_domain_error(EventDomainError::RunDomainMismatch {
                operation: EventDomainOperation::Enqueue,
                node_index: Some(node_index),
                expected: destination,
                actual: actual_preflight_domain,
            }));
        }
        let dependencies = self.classify_dependencies(node_index, node, destination)?;
        let actual_run_domain = self.runs[run_index].domain(EventDomainOperation::Enqueue)?;
        if actual_run_domain != destination {
            return Err(event_domain_error(EventDomainError::RunDomainMismatch {
                operation: EventDomainOperation::Enqueue,
                node_index: Some(node_index),
                expected: destination,
                actual: actual_run_domain,
            }));
        }
        let completion_event = self.runs[run_index].enqueue(&dependencies, launch)?;
        let actual = completion_event.origin();
        if actual != completion.domain() {
            return Err(event_domain_error(
                EventDomainError::CompletionTokenDomainMismatch {
                    operation: EventDomainOperation::ValidateCompletion,
                    node_index: Some(node_index),
                    expected: completion.domain(),
                    actual,
                },
            ));
        }
        self.completions.insert(
            EventDependency::from_completion(completion),
            completion_event,
        );
        Ok(())
    }

    fn classify_dependencies(
        &self,
        node_index: usize,
        node: &ScheduledNode,
        destination: super::EventDomainId,
    ) -> Result<SmallVec<[Arc<dyn EventToken>; 4]>> {
        let mut admitted = SmallVec::with_capacity(node.dependencies().len());
        for dependency in node.dependencies() {
            let dependency_completion =
                self.completions.get(dependency).cloned().ok_or_else(|| {
                    Error::runtime_state_source(
                        "Runtime::run_compiled",
                        ErrorPhase::Execution,
                        MissingScheduledDependencyCompletionError {
                            dependency: *dependency,
                            node_index,
                        },
                    )
                })?;
            let actual = dependency_completion.origin();
            if actual != dependency.domain() {
                return Err(event_domain_error(
                    EventDomainError::DependencyDomainMismatch {
                        operation: match node {
                            ScheduledNode::Transfer(_) => EventDomainOperation::TransferBridge,
                            ScheduledNode::Operation(_)
                            | ScheduledNode::Collective(_)
                            | ScheduledNode::Barrier(_) => EventDomainOperation::Enqueue,
                        },
                        node_index: Some(node_index),
                        expected: dependency.domain(),
                        actual,
                    },
                ));
            }
            match node {
                ScheduledNode::Transfer(transfer) => {
                    let source = transfer.source_event_domain();
                    if actual == destination {
                        admitted.push(dependency_completion);
                    } else if actual == source {
                        dependency_completion.wait().map_err(|source_error| {
                            event_domain_error(EventDomainError::DependencyWaitFailed {
                                operation: EventDomainOperation::TransferBridge,
                                node_index: Some(node_index),
                                expected: destination,
                                actual,
                                source: Box::new(source_error),
                            })
                        })?;
                    } else {
                        return Err(event_domain_error(
                            EventDomainError::DependencyDomainMismatch {
                                operation: EventDomainOperation::TransferBridge,
                                node_index: Some(node_index),
                                expected: source,
                                actual,
                            },
                        ));
                    }
                }
                ScheduledNode::Operation(_)
                | ScheduledNode::Collective(_)
                | ScheduledNode::Barrier(_) => {
                    if actual != destination {
                        return Err(event_domain_error(
                            EventDomainError::DependencyDomainMismatch {
                                operation: EventDomainOperation::Enqueue,
                                node_index: Some(node_index),
                                expected: destination,
                                actual,
                            },
                        ));
                    }
                    admitted.push(dependency_completion);
                }
            }
        }
        Ok(admitted)
    }

    fn run_index(&self, domain: super::EventDomainId) -> Result<usize> {
        if let Some(index) = self
            .runs
            .iter()
            .position(|run| run.requested_domain() == domain)
        {
            return Ok(index);
        }
        Err(missing_event_domain_driver(domain))
    }

    pub(crate) fn drain(&mut self) -> Result<()> {
        let mut failures = Vec::new();
        for run in &mut self.runs {
            if let Err(error) = run.drain() {
                failures.push(error);
            }
        }
        let mut failures = failures.into_iter();
        let Some(mut error) = failures.next() else {
            return Ok(());
        };
        for failure in failures {
            error = Error::with_suppressed(error, failure);
        }
        Err(error)
    }
}

#[derive(Debug)]
enum RuntimeOwnedEventDomainRunState {
    Pending(Box<dyn EventDomainRun>),
    Retired,
    Failed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EventDomainRunTerminalState {
    Retired,
    Failed,
}

impl fmt::Display for EventDomainRunTerminalState {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Retired => formatter.write_str("retired"),
            Self::Failed => formatter.write_str("failed"),
        }
    }
}

#[derive(Debug)]
struct RuntimeOwnedEventDomainRun {
    requested_domain: super::EventDomainId,
    state: RuntimeOwnedEventDomainRunState,
}

impl RuntimeOwnedEventDomainRun {
    fn new(requested_domain: super::EventDomainId, inner: Box<dyn EventDomainRun>) -> Self {
        Self {
            requested_domain,
            state: RuntimeOwnedEventDomainRunState::Pending(inner),
        }
    }

    fn requested_domain(&self) -> super::EventDomainId {
        self.requested_domain
    }

    fn domain(&self, operation: EventDomainOperation) -> Result<super::EventDomainId> {
        match &self.state {
            RuntimeOwnedEventDomainRunState::Pending(run) => Ok(run.domain()),
            RuntimeOwnedEventDomainRunState::Retired => Err(event_domain_run_state_error(
                operation,
                self.requested_domain,
                EventDomainRunTerminalState::Retired,
            )),
            RuntimeOwnedEventDomainRunState::Failed => Err(event_domain_run_state_error(
                operation,
                self.requested_domain,
                EventDomainRunTerminalState::Failed,
            )),
        }
    }

    fn enqueue(
        &mut self,
        dependencies: &[Arc<dyn EventToken>],
        launch: &mut dyn FnMut() -> Result<()>,
    ) -> Result<Arc<dyn EventToken>> {
        match &mut self.state {
            RuntimeOwnedEventDomainRunState::Pending(run) => run.enqueue(dependencies, launch),
            RuntimeOwnedEventDomainRunState::Retired => Err(event_domain_run_state_error(
                EventDomainOperation::Enqueue,
                self.requested_domain,
                EventDomainRunTerminalState::Retired,
            )),
            RuntimeOwnedEventDomainRunState::Failed => Err(event_domain_run_state_error(
                EventDomainOperation::Enqueue,
                self.requested_domain,
                EventDomainRunTerminalState::Failed,
            )),
        }
    }

    fn drain(&mut self) -> Result<()> {
        let run = match std::mem::replace(&mut self.state, RuntimeOwnedEventDomainRunState::Failed)
        {
            RuntimeOwnedEventDomainRunState::Pending(run) => run,
            RuntimeOwnedEventDomainRunState::Retired => {
                self.state = RuntimeOwnedEventDomainRunState::Retired;
                return Err(event_domain_run_state_error(
                    EventDomainOperation::Drain,
                    self.requested_domain,
                    EventDomainRunTerminalState::Retired,
                ));
            }
            RuntimeOwnedEventDomainRunState::Failed => {
                self.state = RuntimeOwnedEventDomainRunState::Failed;
                return Err(event_domain_run_state_error(
                    EventDomainOperation::Drain,
                    self.requested_domain,
                    EventDomainRunTerminalState::Failed,
                ));
            }
        };
        let domain = self.requested_domain;
        let mut run = run;
        let drain_result = catch_unwind(AssertUnwindSafe(|| run.drain()));
        drop_event_domain_run(run);
        match drain_result {
            Ok(Ok(())) => {
                self.state = RuntimeOwnedEventDomainRunState::Retired;
                Ok(())
            }
            Ok(Err(error)) => {
                self.state = RuntimeOwnedEventDomainRunState::Failed;
                Err(error)
            }
            Err(payload) => {
                self.state = RuntimeOwnedEventDomainRunState::Failed;
                Err(event_domain_error(EventDomainError::DrainPanicked {
                    operation: EventDomainOperation::Drain,
                    domain,
                    message: safe_event_domain_panic_message(payload),
                }))
            }
        }
    }
}

/// Internal error returned when a runtime-owned event run is used after
/// explicit retirement or failure.
#[derive(Debug, thiserror::Error)]
#[error("{operation} used event-domain run {domain:?} after it reached terminal state {state}")]
pub(crate) struct EventDomainRunLifecycleError {
    operation: EventDomainOperation,
    domain: super::EventDomainId,
    state: EventDomainRunTerminalState,
}

fn event_domain_run_state_error(
    operation: EventDomainOperation,
    domain: super::EventDomainId,
    state: EventDomainRunTerminalState,
) -> Error {
    Error::runtime_state_source(
        "Runtime::run_compiled",
        ErrorPhase::Execution,
        EventDomainRunLifecycleError {
            operation,
            domain,
            state,
        },
    )
}

fn drop_event_domain_run(run: Box<dyn EventDomainRun>) {
    if catch_unwind(AssertUnwindSafe(|| drop(run))).is_err() {
        // The provider run has been consumed; its cleanup panic is contained.
    }
}

impl Drop for RuntimeOwnedEventDomainRun {
    fn drop(&mut self) {
        let state = std::mem::replace(&mut self.state, RuntimeOwnedEventDomainRunState::Failed);
        if let RuntimeOwnedEventDomainRunState::Pending(run) = state {
            drop_event_domain_run(run);
        }
    }
}

fn missing_event_domain_driver(domain: super::EventDomainId) -> Error {
    Error::from(EventDomainError::MissingDriver { domain })
}

fn event_domain_error(source: EventDomainError) -> Error {
    Error::from(source)
}

fn safe_event_domain_panic_message(payload: Box<dyn std::any::Any + Send + 'static>) -> String {
    match payload.downcast::<&'static str>() {
        Ok(message) => (*message).to_owned(),
        Err(payload) => match payload.downcast::<String>() {
            Ok(message) => *message,
            Err(_) => "non-string panic payload".to_owned(),
        },
    }
}

fn scheduled_execution_cleanup_error(primary: Error, cleanup: Error) -> Error {
    Error::with_suppressed(primary, cleanup)
}

fn instruction_execution<'a>(
    schedule: &'a ScheduledGraph,
    instruction: &ExecInstruction,
) -> Result<InstructionExecution<'a>> {
    let Some(operation_index) = instruction.semantic_operation_index else {
        let location = schedule.root_location();
        return Ok(InstructionExecution {
            witness: location.witness(),
            location,
        });
    };
    let location = schedule
        .operation_locations()
        .get(operation_index)
        .ok_or_else(|| {
            Error::runtime_state(
                "Runtime::run_compiled",
                ErrorPhase::Execution,
                format!(
                    "instruction references semantic operation {operation_index}, but prepared schedule has {} operations",
                    schedule.operation_locations().len()
                ),
            )
        })?;
    Ok(InstructionExecution {
        witness: location.witness(),
        location,
    })
}

struct InstructionExecution<'a> {
    witness: &'a super::snapshot::ExecutableEngineSnapshot,
    location: &'a ExecutionLocation,
}

impl InstructionExecution<'_> {
    fn executor(&self) -> &Arc<dyn ErasedTensorBackendExecutor> {
        self.witness.executor()
    }

    fn location(&self) -> &ExecutionLocation {
        self.location
    }
}

pub(crate) struct LocatedExecSlot<'input> {
    pub(crate) location: ExecutionLocation,
    pub(crate) value: ExecSlot<'input>,
}

fn stage_instruction_inputs<'input>(
    instruction: &ExecInstruction,
    location: &ExecutionLocation,
    located: &mut [Vec<LocatedExecSlot<'input>>],
    staged: &mut [Option<ExecSlot<'input>>],
) -> Result<()> {
    for &slot in &instruction.input_slots {
        stage_slot_input(slot, location, located, staged)?;
    }
    Ok(())
}

/// Move one slot's value from `located` into `staged`.
fn stage_slot_input<'input>(
    slot: usize,
    location: &ExecutionLocation,
    located: &mut [Vec<LocatedExecSlot<'input>>],
    staged: &mut [Option<ExecSlot<'input>>],
) -> Result<()> {
    if staged
        .get(slot)
        .ok_or(tenferro_tensor::Error::MissingValue { slot })?
        .is_some()
    {
        return Ok(());
    }
    let values = located
        .get_mut(slot)
        .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
    let value_index = values
        .iter()
        .position(|value| &value.location == location)
        .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
    staged[slot] = Some(values.swap_remove(value_index).value);
    Ok(())
}

/// Validate every live-out of a fused elementwise region: present and resident
/// on the region's location.
fn validate_region_outputs(
    region: &super::region::ElementwiseRegion,
    location: &ExecutionLocation,
    staged: &[Option<ExecSlot<'_>>],
) -> Result<()> {
    for &output_slot in &region.output_slots {
        let output = staged
            .get(output_slot)
            .and_then(Option::as_ref)
            .ok_or(tenferro_tensor::Error::MissingValue { slot: output_slot })?;
        let output = output.as_read();
        if !location
            .witness()
            .owns_resident_tensor(&output, location.storage_class())
        {
            return Err(Error::runtime_state_source(
                "Runtime::run_prepared",
                ErrorPhase::Execution,
                super::EngineExecutionContractError::OutputResidencyMismatch {
                    instruction_index: region.instruction_range.start,
                    output_slot,
                    engine_id: location.engine_id().clone(),
                    storage_class: location.storage_class().clone(),
                    backend_family: output.backend_family(),
                    allocation_domain: output.allocation_domain(),
                },
            ));
        }
    }
    Ok(())
}

/// Publish a fused region's results: release region inputs whose last use is
/// inside the region and move every live-out into `located`.
fn retain_region_results<'input>(
    region: &super::region::ElementwiseRegion,
    location: &ExecutionLocation,
    located: &mut [Vec<LocatedExecSlot<'input>>],
    staged: &mut [Option<ExecSlot<'input>>],
) -> Result<()> {
    for (&slot, &last_use) in region.input_slots.iter().zip(region.input_last_use.iter()) {
        if last_use {
            located[slot].clear();
            staged[slot].take();
        }
    }
    for &slot in &region.output_slots {
        let value = staged
            .get_mut(slot)
            .and_then(Option::take)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        let values = located
            .get_mut(slot)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        values.clear();
        values.push(LocatedExecSlot {
            location: location.clone(),
            value,
        });
    }
    Ok(())
}

fn validate_instruction_outputs(
    instruction_index: usize,
    instruction: &ExecInstruction,
    location: &ExecutionLocation,
    staged: &[Option<ExecSlot<'_>>],
) -> Result<()> {
    for &output_slot in &instruction.output_slots {
        let output = staged
            .get(output_slot)
            .and_then(Option::as_ref)
            .ok_or(tenferro_tensor::Error::MissingValue { slot: output_slot })?;
        let output = output.as_read();
        if !location
            .witness()
            .owns_resident_tensor(&output, location.storage_class())
        {
            return Err(Error::runtime_state_source(
                "Runtime::run_compiled",
                ErrorPhase::Execution,
                super::EngineExecutionContractError::OutputResidencyMismatch {
                    instruction_index,
                    output_slot,
                    engine_id: location.engine_id().clone(),
                    storage_class: location.storage_class().clone(),
                    backend_family: output.backend_family(),
                    allocation_domain: output.allocation_domain(),
                },
            ));
        }
    }
    Ok(())
}

pub(crate) fn retain_instruction_results<'input>(
    instruction: &ExecInstruction,
    location: &ExecutionLocation,
    located: &mut [Vec<LocatedExecSlot<'input>>],
    staged: &mut [Option<ExecSlot<'input>>],
) -> Result<()> {
    for &slot in &instruction.input_slots {
        let is_output = instruction.output_slots.contains(&slot);
        let is_last_use = instruction
            .input_slots
            .iter()
            .enumerate()
            .any(|(index, &candidate)| {
                candidate == slot && instruction.last_use.get(index).copied().unwrap_or(false)
            });
        if is_last_use {
            located[slot].clear();
            if !is_output {
                staged[slot].take();
            }
        } else if !is_output && let Some(value) = staged[slot].take() {
            located[slot].push(LocatedExecSlot {
                location: location.clone(),
                value,
            });
        }
    }

    for &slot in &instruction.output_slots {
        let value = staged
            .get_mut(slot)
            .and_then(Option::take)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        let values = located
            .get_mut(slot)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        values.clear();
        values.push(LocatedExecSlot {
            location: location.clone(),
            value,
        });
    }
    Ok(())
}

fn validate_runtime_input_ingress(
    location: &ExecutionLocation,
    input: &TensorRead<'_>,
    slot: usize,
) -> Result<()> {
    let accepted = location
        .witness()
        .accepts_runtime_input(input, location.storage_class());
    if accepted {
        return Ok(());
    }
    Err(Error::runtime_state_source(
        "Runtime::run_compiled",
        ErrorPhase::Execution,
        super::InputIngressContractError::ResidencyMismatch {
            input_slot: slot,
            ingress_engine_id: location.engine_id().clone(),
            ingress_storage_class: location.storage_class().clone(),
            placement: input.placement().clone(),
            backend_family: input.backend_family(),
            allocation_domain: input.allocation_domain(),
        },
    ))
}

fn execute_scheduled_transfer<'input>(
    transfer: &ScheduledTransfer,
    located: &mut [Vec<LocatedExecSlot<'input>>],
) -> Result<()> {
    let source = transfer.source_location();
    let destination = transfer.destination_location();
    let provider = transfer.provider();
    let values =
        located
            .get_mut(transfer.value_slot())
            .ok_or(tenferro_tensor::Error::MissingValue {
                slot: transfer.value_slot(),
            })?;
    if values.iter().any(|value| &value.location == destination) {
        return Err(Error::runtime_state_source(
            "Runtime::run_compiled",
            ErrorPhase::Execution,
            DuplicateTransferDestinationError {
                value_slot: transfer.value_slot(),
                destination: destination.clone(),
            },
        ));
    }
    let transferred = {
        let source_value = values
            .iter()
            .find(|value| &value.location == source)
            .ok_or(tenferro_tensor::Error::MissingValue {
                slot: transfer.value_slot(),
            })?;
        let source_read = source_value.value.as_read();
        let expected_dtype = source_read.dtype();
        let expected_shape = source_read.shape().to_vec();
        let transferred =
            provider.transfer_blocking(TransferRequest::new(source, destination, source_read))?;
        validate_transfer_output(destination, expected_dtype, &expected_shape, &transferred)?;
        transferred
    };
    values.push(LocatedExecSlot {
        location: destination.clone(),
        value: ExecSlot::Owned(transferred),
    });
    Ok(())
}

fn validate_transfer_output(
    destination: &ExecutionLocation,
    expected_dtype: tenferro_tensor::DType,
    expected_shape: &[usize],
    output: &Tensor,
) -> Result<()> {
    let expected_elements = checked_transfer_element_count(expected_shape).map_err(|source| {
        Error::runtime_state_source(
            "Runtime::run_compiled",
            ErrorPhase::Execution,
            TransferError::ProviderContract { source },
        )
    })?;
    let contract_error = if output.dtype() != expected_dtype {
        Some(TransferProviderContractError::DTypeMismatch {
            expected: expected_dtype,
            actual: output.dtype(),
        })
    } else if output.shape() != expected_shape {
        Some(TransferProviderContractError::ShapeMismatch {
            expected: expected_shape.to_vec(),
            actual: output.shape().to_vec(),
        })
    } else if tensor_buffer_len(output) != expected_elements {
        Some(TransferProviderContractError::InvalidBufferLength {
            expected: expected_elements,
            actual: tensor_buffer_len(output),
        })
    } else if !destination
        .witness()
        .accepts_input_placement(output.placement(), destination.storage_class())
    {
        Some(
            TransferProviderContractError::DestinationPlacementMismatch {
                destination_engine_id: destination.engine_id().clone(),
                destination_storage_class: destination.storage_class().clone(),
                actual: output.placement().clone(),
            },
        )
    } else if !destination.witness().owns_resident_tensor(
        &TensorRead::from_tensor(output),
        destination.storage_class(),
    ) {
        Some(
            TransferProviderContractError::DestinationResidencyMismatch {
                destination_engine_id: destination.engine_id().clone(),
                destination_storage_class: destination.storage_class().clone(),
                actual_backend_family: TensorRead::from_tensor(output).backend_family(),
                actual_allocation_domain: TensorRead::from_tensor(output).allocation_domain(),
            },
        )
    } else {
        None
    };
    match contract_error {
        None => Ok(()),
        Some(source) => Err(Error::runtime_state_source(
            "Runtime::run_compiled",
            ErrorPhase::Execution,
            TransferError::ProviderContract { source },
        )),
    }
}

fn checked_transfer_element_count(
    shape: &[usize],
) -> std::result::Result<usize, TransferProviderContractError> {
    tenferro_tensor::validate::checked_shape_product(
        "Runtime::run_compiled",
        "transfer source shape",
        shape,
    )
    .map_err(|source| TransferProviderContractError::LogicalElementCount { source })
}

fn tensor_buffer_len(tensor: &Tensor) -> usize {
    match tensor.dtype() {
        DType::F32 => tensor.as_typed::<f32>().map_or(0, |t| t.buffer().len()),
        DType::F64 => tensor.as_typed::<f64>().map_or(0, |t| t.buffer().len()),
        DType::I32 => tensor.as_typed::<i32>().map_or(0, |t| t.buffer().len()),
        DType::I64 => tensor.as_typed::<i64>().map_or(0, |t| t.buffer().len()),
        DType::Bool => tensor.as_typed::<bool>().map_or(0, |t| t.buffer().len()),
        DType::C32 => tensor
            .as_typed::<Complex32>()
            .map_or(0, |t| t.buffer().len()),
        DType::C64 => tensor
            .as_typed::<Complex64>()
            .map_or(0, |t| t.buffer().len()),
        // A caller-owned payload has no runtime buffer length to report, which is
        // also what the accessor falls back to when the tag table and the runtime
        // dtype disagree.
        DType::External(_) => 0,
    }
}

#[cfg(test)]
mod transfer_validation_tests {
    use std::error::Error as _;

    use super::checked_transfer_element_count;
    use crate::TransferProviderContractError;

    #[test]
    fn transfer_element_count_overflow_is_typed_and_preserves_source() {
        let error = checked_transfer_element_count(&[usize::MAX, 2]).unwrap_err();

        assert!(matches!(
            error,
            TransferProviderContractError::LogicalElementCount { .. }
        ));
        assert!(error.source().is_some());
    }
}

fn collect_located_outputs<'input>(
    program: &ExecProgram,
    located: &mut [Vec<LocatedExecSlot<'input>>],
) -> Result<Vec<Option<LocatedExecSlot<'input>>>> {
    let mut outputs = (0..program.n_slots).map(|_| None).collect::<Vec<_>>();
    for &slot in &program.output_slots {
        if outputs[slot].is_some() {
            continue;
        }
        let values = located
            .get_mut(slot)
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        let value = values
            .pop()
            .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
        values.clear();
        outputs[slot] = Some(value);
    }
    located.iter_mut().for_each(Vec::clear);
    Ok(outputs)
}

pub(super) fn collect_tensor_outputs_with<'input>(
    program: &ExecProgram,
    outputs: &mut [Option<LocatedExecSlot<'input>>],
    mut materialize: impl FnMut(&ExecutionLocation, ExecSlot<'input>) -> Result<Tensor>,
) -> Result<Vec<Tensor>> {
    program
        .output_slots
        .iter()
        .map(|&slot| {
            let located = outputs
                .get_mut(slot)
                .and_then(Option::take)
                .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
            materialize(&located.location, located.value)
        })
        .collect()
}

fn collect_value_outputs_with<'input>(
    program: &ExecProgram,
    outputs: &mut [Option<LocatedExecSlot<'input>>],
    mut materialize: impl FnMut(&ExecutionLocation, ExecSlot<'input>) -> Result<TensorValue>,
) -> Result<Vec<TensorValue>> {
    program
        .output_slots
        .iter()
        .map(|&slot| {
            let located = outputs
                .get_mut(slot)
                .and_then(Option::take)
                .ok_or(tenferro_tensor::Error::MissingValue { slot })?;
            materialize(&located.location, located.value)
        })
        .collect()
}

fn input_signature_reads(inputs: &[TensorRead<'_>]) -> Result<InputSignature> {
    InputSignature::from_reads(inputs).map_err(|source| prepare_error(Arc::new(source)))
}

fn resolve_input_refs<'a>(
    program: &'a CompiledGraph,
    inputs: &'a [&'a Tensor],
) -> Result<RuntimeInputReads<'a>> {
    let expected = program.program().inputs().len();
    if inputs.len() > expected {
        return Err(Error::GraphInputCountMismatch {
            expected,
            actual: inputs.len(),
        });
    }
    let resolved = if inputs.is_empty() {
        semantic_default_inputs(program)?
    } else if inputs.len() == expected {
        inputs
            .iter()
            .map(|tensor| TensorRead::from_tensor(tensor))
            .collect()
    } else {
        let mut explicit = inputs.iter();
        let mut resolved = RuntimeInputReads::new();
        for value in program.program().inputs() {
            if let Some(retained) = program.bindings().tensor_ref_for_input(*value) {
                resolved.push(retained.tensor_read()?);
            } else {
                let tensor = explicit.next().ok_or_else(|| {
                    Error::invalid_argument(
                        "Runtime::resolve_input_refs",
                        ErrorPhase::Execution,
                        "inputs",
                        format!(
                            "expected {expected} inputs, or one explicit input for each unbound placeholder"
                        ),
                    )
                })?;
                resolved.push(TensorRead::from_tensor(tensor));
            }
        }
        if explicit.next().is_some() {
            return Err(Error::invalid_argument(
                "Runtime::resolve_input_refs",
                ErrorPhase::Execution,
                "inputs",
                format!("expected {expected} inputs, received {}", inputs.len()),
            ));
        }
        resolved
    };
    validate_ordered_input_metadata_reads(program, &resolved)?;
    Ok(resolved)
}

fn semantic_default_inputs(program: &CompiledGraph) -> Result<RuntimeInputReads<'_>> {
    program
        .program()
        .inputs()
        .iter()
        .enumerate()
        .map(|(input_index, value)| {
            let retained = program
                .bindings()
                .tensor_ref_for_input(*value)
                .ok_or_else(|| Error::UnboundPlaceholder {
                    input_key: format!("semantic input {input_index}"),
                })?;
            retained.tensor_read()
        })
        .collect()
}

fn validate_ordered_input_metadata_reads(
    program: &CompiledGraph,
    inputs: &[TensorRead<'_>],
) -> Result<()> {
    let actuals = inputs
        .iter()
        .map(|input| (input.dtype(), input.shape().to_vec()))
        .collect::<Vec<_>>();
    validate_ordered_input_metadata_values(program, &actuals, "Runtime::submit")
}

fn validate_ordered_input_metadata_values(
    program: &CompiledGraph,
    actuals: &[(tenferro_tensor::DType, Vec<usize>)],
    caller: &'static str,
) -> Result<()> {
    let expected = program.input_count();
    if actuals.len() != expected {
        return Err(Error::GraphInputCountMismatch {
            expected,
            actual: actuals.len(),
        });
    }
    let input_shapes: RuntimeInputShapes<'_> =
        actuals.iter().map(|(_, shape)| shape.as_slice()).collect();
    for (input_value, (actual_dtype, actual_shape)) in
        program.program().inputs().iter().zip(actuals)
    {
        let metadata = program
            .program()
            .value_metadata(*input_value)
            .map_err(|source| Error::runtime_state_source(caller, ErrorPhase::Execution, source))?;
        if metadata.dtype() != *actual_dtype {
            return Err(Error::PlaceholderDtypeMismatch {
                expected: metadata.dtype(),
                actual: *actual_dtype,
            });
        }
        if metadata.shape().len() != actual_shape.len() {
            return Err(Error::PlaceholderRankMismatch {
                expected: metadata.shape().len(),
                actual: actual_shape.len(),
            });
        }
        let mut expected_shape: RuntimeShapeScratch = actual_shape.iter().copied().collect();
        let mut exact_mismatch = false;
        for (axis, (extent, actual_size)) in metadata.shape().iter().zip(actual_shape).enumerate() {
            match extent {
                ShapeExtent::Exact(expression) => {
                    let expected = expression.eval(&input_shapes).map_err(|source| {
                        Error::runtime_state_source(caller, ErrorPhase::Execution, source)
                    })?;
                    expected_shape[axis] = expected;
                    exact_mismatch |= expected != *actual_size;
                }
                ShapeExtent::UpperBound(expression) => {
                    let bound = expression.eval(&input_shapes).map_err(|source| {
                        Error::runtime_state_source(caller, ErrorPhase::Execution, source)
                    })?;
                    if *actual_size > bound {
                        return Err(Error::PlaceholderShapeBoundExceeded {
                            axis,
                            bound,
                            actual: *actual_size,
                        });
                    }
                }
                ShapeExtent::Unknown => {}
            }
        }
        if exact_mismatch {
            return Err(Error::PlaceholderShapeMismatch {
                expected: expected_shape.into_vec(),
                actual: actual_shape.clone(),
            });
        }
    }
    Ok(())
}

fn validate_exec_input_count(program: &ExecProgram, actual: usize) -> Result<()> {
    let expected = program.input_slots.len();
    if actual != expected {
        return Err(Error::runtime_state(
            "Runtime::run_compiled",
            ErrorPhase::Execution,
            format!("expected {expected} inputs for execution program, got {actual}"),
        ));
    }
    Ok(())
}

fn prepare_error(source: Arc<PrepareError>) -> Error {
    Error::runtime_state_source(
        "Runtime::run_compiled",
        ErrorPhase::Execution,
        SharedPrepareError(source),
    )
}

#[derive(Clone, Debug)]
struct SharedPrepareError(Arc<PrepareError>);

impl fmt::Display for SharedPrepareError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

impl StdError for SharedPrepareError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(self.0.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use std::any::Any;
    use std::error::Error as StdError;
    use std::hash::Hasher;
    use std::num::NonZeroU64;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, TryLockError, Weak};

    use tenferro_cpu::CpuBackend;
    use tenferro_ops::dim_expr::DimExpr;
    use tenferro_ops::ext_op::ExtensionOp;
    use tenferro_ops::SymDim;
    use tenferro_tensor::{
        BackendSession, BackendSessionHost, DType, Tensor, TensorBackend, TensorRead, TypedTensor,
    };

    use crate::exec::{ExecInstruction, ExecOp, ExecProgram, ExecSlot};
    use crate::runtime::{
        CoreCapabilityBundle, EngineId, ErasedExecutionContext, EventDomainDriver, EventDomainId,
        ExecutableEngineContract, ExecutionContextIdentity, HardwareClassId, InputIngressContract,
        InputSignature, PreparedOperation, PreparedOperationBinding, PreparedOperationExecutor,
        PreparedOperationPlan, ProviderDeviceIdentity, ProviderId, RegistrationIdentity,
        RuntimeCacheOwner, RuntimeEpoch, RuntimeId, SpecializationProjection,
        SpecializationRequirements, StorageClass,
    };
    use crate::{Error, ErrorPhase, ExtensionCacheStore, Result};

    use super::{
        DuplicateTransferDestinationError, ErasedTensorBackendExecutor, LocatedExecSlot,
        TensorBackendExecutor,
    };
    use crate::runtime::schedule::{
        EventCompletion, EventSlotId, ExecutionLocation, ScheduledTransfer,
    };

    const LOCK_PROBE_FAMILY: &str = "runtime.lock-probe.v1";
    const REENTRANT_PROBE_FAMILY: &str = "runtime.reentrant-probe.v1";

    #[derive(Clone, Debug)]
    struct LockProbeOp;

    impl ExtensionOp for LockProbeOp {
        fn family_id(&self) -> &'static str {
            LOCK_PROBE_FAMILY
        }

        fn payload_hash(&self, _hasher: &mut dyn Hasher) {}

        fn payload_eq(&self, other: &dyn ExtensionOp) -> bool {
            other.as_any().downcast_ref::<Self>().is_some()
        }

        fn clone_arc(&self) -> Arc<dyn ExtensionOp> {
            Arc::new(self.clone())
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn input_count(&self) -> usize {
            1
        }

        fn output_count(&self) -> usize {
            1
        }

        fn infer_output_meta(
            &self,
            ctx: &mut tenferro_ops::ExtensionShapeContext<'_>,
        ) -> tenferro_tensor::Result<Vec<(DType, Vec<SymDim>)>> {
            Ok(vec![(ctx.input_dtype(0)?, ctx.input_shape(0)?.to_vec())])
        }
    }

    #[derive(Clone, Debug)]
    struct ReentrantProbeOp;

    impl ExtensionOp for ReentrantProbeOp {
        fn family_id(&self) -> &'static str {
            REENTRANT_PROBE_FAMILY
        }

        fn payload_hash(&self, _hasher: &mut dyn Hasher) {}

        fn payload_eq(&self, other: &dyn ExtensionOp) -> bool {
            other.as_any().downcast_ref::<Self>().is_some()
        }

        fn clone_arc(&self) -> Arc<dyn ExtensionOp> {
            Arc::new(self.clone())
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn input_count(&self) -> usize {
            1
        }

        fn output_count(&self) -> usize {
            1
        }

        fn infer_output_meta(
            &self,
            ctx: &mut tenferro_ops::ExtensionShapeContext<'_>,
        ) -> tenferro_tensor::Result<Vec<(DType, Vec<SymDim>)>> {
            Ok(vec![(ctx.input_dtype(0)?, ctx.input_shape(0)?.to_vec())])
        }
    }

    #[derive(Debug)]
    struct LockProbePreparedOperation {
        binding: PreparedOperationBinding,
        specialization: SpecializationProjection,
        executor: Weak<TensorBackendExecutor<CpuBackend>>,
        observed_unlocked_state: Arc<AtomicBool>,
    }

    impl PreparedOperation for LockProbePreparedOperation {
        fn binding(&self) -> &PreparedOperationBinding {
            &self.binding
        }

        fn specialization(&self) -> &SpecializationProjection {
            &self.specialization
        }

        fn retained_bytes(&self) -> usize {
            0
        }
    }

    impl PreparedOperationExecutor for LockProbePreparedOperation {
        fn execute(
            &self,
            context: &mut ErasedExecutionContext<'_>,
            _extension_caches: &mut ExtensionCacheStore,
            inputs: &[TensorRead<'_>],
        ) -> Result<Vec<Tensor>> {
            let executor = self.executor.upgrade().expect("executor still alive");
            let unlocked = match executor.state.try_lock() {
                Ok(_guard) => true,
                Err(TryLockError::WouldBlock) => false,
                Err(TryLockError::Poisoned(_)) => false,
            };
            self.observed_unlocked_state
                .store(unlocked, Ordering::SeqCst);
            let backend = context
                .downcast_mut::<CpuBackend>(self.binding.context_identity())
                .map_err(|source| {
                    Error::runtime_state_source("lock_probe", ErrorPhase::Execution, source)
                })?;
            Ok(vec![backend.with_backend_session(|exec| {
                exec.to_contiguous_read(inputs[0].clone())
            })?])
        }
    }

    #[derive(Debug)]
    struct ReentrantProbePreparedOperation {
        binding: PreparedOperationBinding,
        specialization: SpecializationProjection,
        executor: Weak<TensorBackendExecutor<CpuBackend>>,
        observed_reentrant_error: Arc<AtomicBool>,
    }

    #[derive(Debug)]
    struct SessionProbePreparedOperation {
        binding: PreparedOperationBinding,
        specialization: SpecializationProjection,
        observed_session: Arc<AtomicBool>,
    }

    impl PreparedOperation for SessionProbePreparedOperation {
        fn binding(&self) -> &PreparedOperationBinding {
            &self.binding
        }

        fn specialization(&self) -> &SpecializationProjection {
            &self.specialization
        }

        fn retained_bytes(&self) -> usize {
            0
        }
    }

    impl PreparedOperationExecutor for SessionProbePreparedOperation {
        fn execute(
            &self,
            _context: &mut ErasedExecutionContext<'_>,
            _extension_caches: &mut ExtensionCacheStore,
            _inputs: &[TensorRead<'_>],
        ) -> Result<Vec<Tensor>> {
            Err(Error::unsupported(
                "session_probe",
                ErrorPhase::Execution,
                "session probe must use the scheduler-owned session path",
            ))
        }

        fn supports_session(&self) -> bool {
            true
        }

        fn execute_in_session(
            &self,
            session: &mut dyn BackendSession,
            _extension_caches: &mut ExtensionCacheStore,
            inputs: &[TensorRead<'_>],
        ) -> Result<Vec<Tensor>> {
            self.observed_session.store(true, Ordering::SeqCst);
            Ok(vec![session.to_contiguous_read(inputs[0].clone())?])
        }
    }

    impl ReentrantProbePreparedOperation {
        fn probe_reentrant_call(&self, input: Tensor) {
            let executor = self.executor.upgrade().expect("executor still alive");
            let nested = ErasedTensorBackendExecutor::execute(
                executor.as_ref(),
                &passthrough_program(),
                &[],
                vec![input],
            );
            let observed = nested.is_err_and(|error| {
                error
                    .to_string()
                    .contains("reentrant tensor backend executor call would deadlock")
            });
            self.observed_reentrant_error
                .store(observed, Ordering::SeqCst);
        }
    }

    impl PreparedOperation for ReentrantProbePreparedOperation {
        fn binding(&self) -> &PreparedOperationBinding {
            &self.binding
        }

        fn specialization(&self) -> &SpecializationProjection {
            &self.specialization
        }

        fn retained_bytes(&self) -> usize {
            0
        }
    }

    impl PreparedOperationExecutor for ReentrantProbePreparedOperation {
        fn execute(
            &self,
            context: &mut ErasedExecutionContext<'_>,
            _extension_caches: &mut ExtensionCacheStore,
            inputs: &[TensorRead<'_>],
        ) -> Result<Vec<Tensor>> {
            let backend = context
                .downcast_mut::<CpuBackend>(self.binding.context_identity())
                .map_err(|source| {
                    Error::runtime_state_source("reentrant_probe", ErrorPhase::Execution, source)
                })?;
            let materialized =
                backend.with_backend_session(|exec| exec.to_contiguous_read(inputs[0].clone()))?;
            self.probe_reentrant_call(materialized.duplicate()?);
            Ok(vec![materialized])
        }
    }

    fn lock_probe_program() -> ExecProgram {
        ExecProgram {
            instructions: vec![ExecInstruction {
                op: ExecOp::Extension(Arc::new(LockProbeOp)),
                semantic_operation_index: Some(0),
                input_slots: vec![0],
                output_slots: vec![1],
                dtype: DType::F64,
                output_shapes: vec![vec![DimExpr::InputDim {
                    input_idx: 0,
                    axis: 0,
                }]]
                .into(),
                output_extents: vec![vec![]].into(),
                last_use: vec![false],
            }],
            input_slots: vec![0],
            output_slots: vec![1],
            n_slots: 2,
            shape_guards: vec![],
        }
    }

    fn partial_session_probe_program() -> ExecProgram {
        let output_shape = || {
            vec![DimExpr::InputDim {
                input_idx: 0,
                axis: 0,
            }]
        };
        ExecProgram {
            instructions: vec![
                ExecInstruction {
                    op: ExecOp::Extension(Arc::new(LockProbeOp)),
                    semantic_operation_index: Some(0),
                    input_slots: vec![0],
                    output_slots: vec![1],
                    dtype: DType::F64,
                    output_shapes: vec![output_shape()].into(),
                    output_extents: vec![vec![]].into(),
                    last_use: vec![false],
                },
                ExecInstruction {
                    op: ExecOp::Extension(Arc::new(LockProbeOp)),
                    semantic_operation_index: Some(1),
                    input_slots: vec![1],
                    output_slots: vec![2],
                    dtype: DType::F64,
                    output_shapes: vec![output_shape()].into(),
                    output_extents: vec![vec![]].into(),
                    last_use: vec![false],
                },
            ],
            input_slots: vec![0],
            output_slots: vec![2],
            n_slots: 3,
            shape_guards: vec![],
        }
    }

    fn reentrant_probe_program() -> ExecProgram {
        ExecProgram {
            instructions: vec![ExecInstruction {
                op: ExecOp::Extension(Arc::new(ReentrantProbeOp)),
                semantic_operation_index: Some(0),
                input_slots: vec![0],
                output_slots: vec![1],
                dtype: DType::F64,
                output_shapes: vec![vec![DimExpr::InputDim {
                    input_idx: 0,
                    axis: 0,
                }]]
                .into(),
                output_extents: vec![vec![]].into(),
                last_use: vec![false],
            }],
            input_slots: vec![0],
            output_slots: vec![1],
            n_slots: 2,
            shape_guards: vec![],
        }
    }

    fn passthrough_program() -> ExecProgram {
        ExecProgram {
            instructions: vec![],
            input_slots: vec![0],
            output_slots: vec![0],
            n_slots: 1,
            shape_guards: vec![],
        }
    }

    fn f64_zeros(shape: Vec<usize>) -> Tensor {
        Tensor::from_typed::<f64>(TypedTensor::zeros(shape).unwrap())
    }

    fn nz(value: u64) -> NonZeroU64 {
        NonZeroU64::new(value).unwrap_or(NonZeroU64::MIN)
    }

    fn probe_binding() -> PreparedOperationBinding {
        PreparedOperationBinding::new(
            RuntimeId::from_nonzero(nz(1)),
            RuntimeEpoch::from_nonzero(nz(2)),
            EngineId::new("tenferro.cpu").unwrap(),
            RegistrationIdentity::new(nz(3), nz(4)),
            ExecutionContextIdentity::of::<CpuBackend>(),
            HardwareClassId::new("tenferro.cpu.host").unwrap(),
        )
    }

    fn probe_specialization() -> SpecializationProjection {
        SpecializationRequirements::polymorphic(0)
            .project(&InputSignature::new(Vec::new()))
            .unwrap()
    }

    #[test]
    fn tensor_backend_executor_releases_state_lock_during_extension_execution() {
        let executor = Arc::new(TensorBackendExecutor::<CpuBackend>::new(CpuBackend::new()));
        let observed_unlocked_state = Arc::new(AtomicBool::new(false));
        let prepared = Arc::new(LockProbePreparedOperation {
            binding: probe_binding(),
            specialization: probe_specialization(),
            executor: Arc::downgrade(&executor),
            observed_unlocked_state: Arc::clone(&observed_unlocked_state),
        });
        let operations = vec![PreparedOperationPlan::executable(
            prepared.clone(),
            prepared,
        )];

        let output = ErasedTensorBackendExecutor::execute(
            executor.as_ref(),
            &lock_probe_program(),
            &operations,
            vec![f64_zeros(vec![2])],
        )
        .expect("extension executes");

        assert_eq!(output[0].shape(), &[2]);
        assert!(
            observed_unlocked_state.load(Ordering::SeqCst),
            "executor state lock must not be held while extension runtime callbacks execute"
        );
    }

    #[test]
    fn scheduled_execution_cleanup_error_preserves_primary_error() {
        let primary = Error::runtime_state(
            "primary-execution",
            ErrorPhase::Execution,
            "primary execution failure",
        );
        let cleanup = Error::runtime_state(
            "event-domain-cleanup",
            ErrorPhase::Execution,
            "cleanup failure",
        );
        let primary_display = primary.to_string();

        let combined = super::scheduled_execution_cleanup_error(primary, cleanup);
        let primary_error = combined.primary().expect("primary execution error");
        let cleanup_error = combined.suppressed().expect("cleanup error");
        assert_eq!(primary_error.to_string(), primary_display);
        assert_eq!(
            cleanup_error.to_string(),
            "event-domain-cleanup (Execution): runtime state failure: cleanup failure"
        );
        assert_eq!(
            StdError::source(&combined)
                .expect("primary error in the standard source chain")
                .to_string(),
            primary_display
        );
    }

    #[test]
    fn duplicate_scheduled_transfer_destination_reports_typed_fields() {
        let domain = EventDomainId::runtime_created_for_test(
            RuntimeId::from_nonzero(nz(1)),
            RuntimeEpoch::from_nonzero(nz(1)),
            RegistrationIdentity::new(nz(1), nz(1)),
        );
        let source = ExecutionLocation::new(
            EngineId::new("tenferro-test.transfer-source").expect("source engine"),
            ProviderDeviceIdentity::new(
                ProviderId::new("tenferro-test.transfer").expect("provider id"),
                "source",
            )
            .expect("source provider target"),
            domain,
            StorageClass::new("tenferro-test.transfer-source").expect("source storage"),
        );
        let destination = ExecutionLocation::new(
            EngineId::new("tenferro-test.transfer-destination").expect("destination engine"),
            ProviderDeviceIdentity::new(
                ProviderId::new("tenferro-test.transfer").expect("provider id"),
                "destination",
            )
            .expect("destination provider target"),
            domain,
            StorageClass::new("tenferro-test.transfer-destination").expect("destination storage"),
        );
        let transfer = ScheduledTransfer::new(
            3,
            source,
            destination.clone(),
            [],
            EventCompletion::new(domain, EventSlotId::new(0), 0),
        );
        let mut located = vec![
            Vec::new(),
            Vec::new(),
            Vec::new(),
            vec![LocatedExecSlot {
                location: destination.clone(),
                value: ExecSlot::Owned(f64_zeros(vec![1])),
            }],
        ];

        let error = super::execute_scheduled_transfer(&transfer, &mut located)
            .expect_err("duplicate transfer destination");
        let Error::RuntimeStateSource { source, .. } = error else {
            panic!("duplicate transfer destination must retain a typed source");
        };
        let duplicate = source
            .downcast_ref::<DuplicateTransferDestinationError>()
            .expect("typed duplicate transfer destination source");
        assert_eq!(duplicate.value_slot, 3);
        assert_eq!(duplicate.destination, destination);
    }

    #[test]
    fn tensor_backend_executor_reentrant_call_returns_error_instead_of_deadlocking() {
        let executor = Arc::new(TensorBackendExecutor::<CpuBackend>::new(CpuBackend::new()));
        let observed_reentrant_error = Arc::new(AtomicBool::new(false));
        let prepared = Arc::new(ReentrantProbePreparedOperation {
            binding: probe_binding(),
            specialization: probe_specialization(),
            executor: Arc::downgrade(&executor),
            observed_reentrant_error: Arc::clone(&observed_reentrant_error),
        });
        let operations = vec![PreparedOperationPlan::executable(
            prepared.clone(),
            prepared,
        )];

        let output = ErasedTensorBackendExecutor::execute(
            executor.as_ref(),
            &reentrant_probe_program(),
            &operations,
            vec![f64_zeros(vec![2])],
        )
        .expect("outer extension executes");

        assert_eq!(output[0].shape(), &[2]);
        assert!(
            observed_reentrant_error.load(Ordering::SeqCst),
            "same-thread reentrant executor call must fail immediately instead of deadlocking"
        );
    }

    #[test]
    fn tensor_backend_executor_dispatches_session_capable_extension_in_one_session_path() {
        let executor = TensorBackendExecutor::<CpuBackend>::new(CpuBackend::new());
        let observed_session = Arc::new(AtomicBool::new(false));
        let prepared = Arc::new(SessionProbePreparedOperation {
            binding: probe_binding(),
            specialization: probe_specialization(),
            observed_session: Arc::clone(&observed_session),
        });
        let operations = vec![PreparedOperationPlan::executable(
            prepared.clone(),
            prepared,
        )];

        let output = ErasedTensorBackendExecutor::execute(
            &executor,
            &lock_probe_program(),
            &operations,
            vec![f64_zeros(vec![2])],
        )
        .expect("session-capable extension executes");

        assert_eq!(output[0].shape(), &[2]);
        assert!(observed_session.load(Ordering::SeqCst));
    }

    #[test]
    fn tensor_backend_executor_batches_session_capable_region_after_boundary() {
        let executor = Arc::new(TensorBackendExecutor::<CpuBackend>::new(CpuBackend::new()));
        let observed_unlocked_state = Arc::new(AtomicBool::new(false));
        let observed_session = Arc::new(AtomicBool::new(false));
        let ordinary = Arc::new(LockProbePreparedOperation {
            binding: probe_binding(),
            specialization: probe_specialization(),
            executor: Arc::downgrade(&executor),
            observed_unlocked_state: Arc::clone(&observed_unlocked_state),
        });
        let session = Arc::new(SessionProbePreparedOperation {
            binding: probe_binding(),
            specialization: probe_specialization(),
            observed_session: Arc::clone(&observed_session),
        });
        let operations = vec![
            PreparedOperationPlan::executable(ordinary.clone(), ordinary),
            PreparedOperationPlan::executable(session.clone(), session),
        ];

        let output = ErasedTensorBackendExecutor::execute(
            executor.as_ref(),
            &partial_session_probe_program(),
            &operations,
            vec![f64_zeros(vec![2])],
        )
        .expect("mixed session regions execute");

        assert_eq!(output[0].shape(), &[2]);
        assert!(observed_unlocked_state.load(Ordering::SeqCst));
        assert!(observed_session.load(Ordering::SeqCst));

        let values = ErasedTensorBackendExecutor::execute_values(
            executor.as_ref(),
            &partial_session_probe_program(),
            &operations,
            vec![f64_zeros(vec![2])],
        )
        .expect("mixed session regions execute in value mode");
        assert_eq!(values[0].shape(), &[2]);
    }

    #[test]
    fn tensor_backend_executor_bridge_does_not_require_clone_source_contract() {
        type ContractConstructor<B> = fn(
            ProviderDeviceIdentity,
            CoreCapabilityBundle,
            B,
            Arc<dyn EventDomainDriver>,
            InputIngressContract,
            Option<Arc<dyn RuntimeCacheOwner>>,
        ) -> ExecutableEngineContract;

        fn factory_accepts_backend_without_clone_bound<B>()
        where
            B: TensorBackend + Send + Sync + 'static,
        {
            let _factory: fn(B) -> Arc<dyn ErasedTensorBackendExecutor> =
                super::erased_tensor_backend_executor::<B>;
        }

        fn contract_accepts_backend_without_clone_bound<B>()
        where
            B: TensorBackend + Send + Sync + 'static,
        {
            let _constructor: ContractConstructor<B> = ExecutableEngineContract::new::<B>;
        }

        factory_accepts_backend_without_clone_bound::<CpuBackend>();
        contract_accepts_backend_without_clone_bound::<CpuBackend>();
    }
}