eredu-runtime 0.5.0

Backend-neutral model execution runtime for Eredu
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
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
//! Selection contracts for replicated text architectures.

use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
};

use eredu_checkpoint::{LinearFormat, SourceTensorEncoding, StoredDtype};
use eredu_core::{
    cache::{StateComponentPolicy, StateTensorDtype},
    checkpoint::TensorDtype,
    ParallelTopology, QuantizationRequest, SessionCapabilities,
};
use eredu_nn::{NeuralBackend, NeuralOperatorCapabilities};

use crate::{
    ArchitectureGroupTransport, ArchitectureParameterDescription, ArchitecturePartition,
    CacheResidencyPolicy, ExecutionGraph, ExecutionGroupId, ExecutionUnitLayout,
    LayerWeightResidency, LayeredArchitecture, ParameterGroupOwner, ParameterGroupSpec,
    RuntimeState, StateLayout,
};

/// Statically dispatched text-input seam for a layered decoder.
///
/// Routed, composite, partitioned, prediction, and realtime execution use
/// separate extension contracts rather than adding requirements here.
pub trait ReplicatedTextArchitecture<B, S>: LayeredArchitecture<B, S>
where
    B: NeuralBackend,
    S: RuntimeState<B>,
{
    /// Forms the architecture-owned borrowed input for one text pass.
    fn text_input<'a>(tokens: &'a B::Tensor, mask: Option<&'a B::Tensor>) -> Self::Input<'a>;

    /// Declares how a causal-text session projects a complete architecture output.
    fn text_output_selection(&self) -> ReplicatedTextOutputSelection {
        ReplicatedTextOutputSelection::LastSequencePosition
    }
}

/// Architecture-declared projection from complete logits to one causal-text output.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum ReplicatedTextOutputSelection {
    /// Selects the final position on the architecture's sequence axis.
    LastSequencePosition,
}

impl ReplicatedTextOutputSelection {
    /// Returns the mechanical sequence-axis index requested from a backend tensor.
    pub const fn sequence_index(self) -> i32 {
        match self {
            Self::LastSequencePosition => -1,
        }
    }
}

/// Backend implementation route for one source-to-executable weight lowering.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum WeightLoweringKind {
    /// The admitted source encoding is retained by the executable operator.
    Direct,
    /// An architecture-owned recipe derives the executable tensor from the admitted source.
    Derived,
    /// Payload materialization performs an admitted transformation.
    Transform,
    /// An architecture recipe derives a tensor that payload materialization then transforms.
    DerivedTransform,
}

/// One exact weight lowering implemented by a backend.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct WeightLoweringCapability {
    /// Exact neutral lowering request implemented by this capability.
    descriptor: WeightLoweringDescriptor,
    /// Whether the lowering is direct or transforming.
    kind: WeightLoweringKind,
}

impl WeightLoweringCapability {
    /// Creates one exact backend lowering mechanism.
    pub fn new(descriptor: WeightLoweringDescriptor, kind: WeightLoweringKind) -> Self {
        Self { descriptor, kind }
    }

    /// Returns the admitted source encoding.
    pub const fn source(&self) -> &SourceTensorEncoding {
        self.descriptor.source()
    }

    /// Returns the executable format produced by this mechanism.
    pub const fn executable(&self) -> LinearFormat {
        self.descriptor.executable()
    }

    /// Returns whether materialization retains or transforms the source.
    pub const fn kind(&self) -> WeightLoweringKind {
        self.kind
    }

    /// Returns the exact geometry-bearing lowering request.
    pub const fn descriptor(&self) -> &WeightLoweringDescriptor {
        &self.descriptor
    }
}

/// Exact source-to-executable lowering query presented to a backend.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct WeightLoweringDescriptor {
    source: SourceTensorEncoding,
    executable: LinearFormat,
    physical_shape: Vec<usize>,
    logical_shape: Vec<usize>,
    packed_axis: Option<usize>,
}

impl WeightLoweringDescriptor {
    /// Creates a geometry-bearing lowering query.
    pub fn new(
        source: SourceTensorEncoding,
        executable: LinearFormat,
        physical_shape: Vec<usize>,
        logical_shape: Vec<usize>,
        packed_axis: Option<usize>,
    ) -> Result<Self, ReplicatedTextContractError> {
        if physical_shape.contains(&0)
            || logical_shape.contains(&0)
            || physical_shape.len() != logical_shape.len()
        {
            return Err(ReplicatedTextContractError::invalid(
                "weight lowering requires positive extents and equal physical and logical ranks",
            ));
        }
        if packed_axis.is_some_and(|axis| axis >= logical_shape.len()) {
            return Err(ReplicatedTextContractError::invalid(
                "weight lowering packed axis is outside the logical shape",
            ));
        }
        Ok(Self {
            source,
            executable,
            physical_shape,
            logical_shape,
            packed_axis,
        })
    }

    /// Returns the admitted source encoding.
    pub const fn source(&self) -> &SourceTensorEncoding {
        &self.source
    }

    /// Returns the selected executable format.
    pub const fn executable(&self) -> LinearFormat {
        self.executable
    }

    /// Returns the admitted physical source shape.
    pub fn physical_shape(&self) -> &[usize] {
        &self.physical_shape
    }

    /// Returns the architecture-declared logical shape.
    pub fn logical_shape(&self) -> &[usize] {
        &self.logical_shape
    }

    /// Returns the executable packing axis, when the parameter is packable.
    pub const fn packed_axis(&self) -> Option<usize> {
        self.packed_axis
    }

    /// Returns the exact extent along the packing axis.
    pub fn packed_extent(&self) -> Option<usize> {
        self.packed_axis.map(|axis| self.logical_shape[axis])
    }
}

/// Weight-residency mechanism implemented by a backend.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum WeightResidencyMechanism {
    /// All parameters remain device resident.
    Resident,
    /// A bounded device window is staged from host storage.
    Windowed,
    /// Bounded host and device windows are populated from disk.
    DiskStreamed,
}

/// Physical placement selected for one semantic mutable-state component.
#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum StateComponentPlacement {
    /// The mutable component remains on the execution device.
    Device,
    /// The append-only component is managed by bounded paged storage.
    Paged,
}

/// Physical scalar representation selected for native mutable state.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum StateStorageDtype {
    /// IEEE half precision.
    F16,
    /// Brain floating point.
    Bf16,
    /// IEEE single precision.
    F32,
    /// IEEE double precision.
    F64,
    /// Two IEEE single-precision components.
    Complex64,
    /// Signed 32-bit integer.
    I32,
    /// Unsigned 32-bit integer.
    U32,
}

impl StateStorageDtype {
    /// Exact bytes occupied by one native state element.
    pub const fn bytes(self) -> std::num::NonZeroU8 {
        let bytes = match self {
            Self::F16 | Self::Bf16 => 2,
            Self::F32 | Self::I32 | Self::U32 => 4,
            Self::F64 | Self::Complex64 => 8,
        };
        std::num::NonZeroU8::new(bytes).unwrap()
    }

    /// Whether this representation belongs to the model's floating state family.
    pub const fn is_floating(self) -> bool {
        !matches!(self, Self::I32 | Self::U32)
    }

    /// Resolves an architecture dtype policy without overriding fixed-width tensors.
    pub const fn resolve(policy: StateTensorDtype, floating: Option<Self>) -> Option<Self> {
        match policy {
            StateTensorDtype::Floating => match floating {
                Some(dtype) if dtype.is_floating() => Some(dtype),
                _ => None,
            },
            StateTensorDtype::Float32 => Some(Self::F32),
            StateTensorDtype::Int32 => Some(Self::I32),
            StateTensorDtype::Uint32 => Some(Self::U32),
        }
    }
}

/// Exact state component and placements implemented by a backend mechanism.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct StateComponentMechanism {
    layer: usize,
    component: StateComponentPolicy,
    device_placement: Option<StateComponentPlacement>,
    paged_placement: Option<StateComponentPlacement>,
}

impl StateComponentMechanism {
    /// Describes support for one exact architecture-declared component.
    pub fn new(
        layer: usize,
        component: StateComponentPolicy,
        device_placement: Option<StateComponentPlacement>,
        paged_placement: Option<StateComponentPlacement>,
    ) -> Self {
        Self {
            layer,
            component,
            device_placement,
            paged_placement,
        }
    }

    /// Returns the architecture-global state layer.
    pub const fn layer(&self) -> usize {
        self.layer
    }

    /// Returns the exact semantic component contract.
    pub const fn component(&self) -> &StateComponentPolicy {
        &self.component
    }

    /// Returns the placement used for a requested state policy.
    pub const fn placement(
        &self,
        policy: &CacheResidencyPolicy,
    ) -> Option<StateComponentPlacement> {
        match policy {
            CacheResidencyPolicy::Device => self.device_placement,
            CacheResidencyPolicy::Paged(_) => self.paged_placement,
        }
    }
}

/// Exact, family-neutral mutable-state mechanisms reported by a backend.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct StateMechanismCapabilities {
    floating_state: Option<(TensorDtype, StateStorageDtype)>,
    components: Vec<StateComponentMechanism>,
    checkpoint: bool,
    rollback: bool,
    reset: bool,
    prompt_cache: bool,
    observation_retention: bool,
}

impl StateMechanismCapabilities {
    /// Creates a fail-closed report for exact architecture-declared components.
    pub fn new(components: impl IntoIterator<Item = StateComponentMechanism>) -> Self {
        Self {
            floating_state: None,
            components: components.into_iter().collect(),
            checkpoint: false,
            rollback: false,
            reset: false,
            prompt_cache: false,
            observation_retention: false,
        }
    }

    /// Binds floating-state support to the exact architecture-selected source dtype.
    pub fn with_floating_state_dtype(
        mut self,
        source: TensorDtype,
        dtype: StateStorageDtype,
    ) -> Self {
        self.floating_state = Some((source, dtype));
        self
    }

    /// Returns the source and native representation used for floating-state support queries.
    pub fn floating_state_dtype(&self) -> Option<(&TensorDtype, StateStorageDtype)> {
        self.floating_state
            .as_ref()
            .map(|(source, dtype)| (source, *dtype))
    }

    /// Declares transactional checkpoint and rollback facilities.
    pub const fn with_transactions(mut self, checkpoint: bool, rollback: bool) -> Self {
        self.checkpoint = checkpoint;
        self.rollback = rollback;
        self
    }

    /// Declares complete state reset support.
    pub const fn with_reset(mut self, supported: bool) -> Self {
        self.reset = supported;
        self
    }

    /// Declares prompt-cache persistence and restoration support.
    pub const fn with_prompt_cache(mut self, supported: bool) -> Self {
        self.prompt_cache = supported;
        self
    }

    /// Declares that observed submissions retain every live component.
    pub const fn with_observation_retention(mut self, supported: bool) -> Self {
        self.observation_retention = supported;
        self
    }

    /// Returns exact supported component mechanisms.
    pub fn components(&self) -> &[StateComponentMechanism] {
        &self.components
    }

    /// Returns whether state checkpoints are implemented.
    pub const fn checkpoint(&self) -> bool {
        self.checkpoint
    }

    /// Returns whether checkpoint rollback is implemented.
    pub const fn rollback(&self) -> bool {
        self.rollback
    }

    /// Returns whether complete reset is implemented.
    pub const fn reset(&self) -> bool {
        self.reset
    }

    /// Returns whether prompt-cache persistence is implemented.
    pub const fn prompt_cache(&self) -> bool {
        self.prompt_cache
    }

    /// Returns whether observation retains every live component.
    pub const fn observation_retention(&self) -> bool {
        self.observation_retention
    }
}

/// Architecture-valid transform target for one linear parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParameterTransformTarget {
    /// Requested load-time transform.
    request: QuantizationRequest,
    /// Executable format produced for this parameter.
    executable: LinearFormat,
    /// Exact geometry that the backend lowering must accept.
    descriptor: WeightLoweringDescriptor,
}

impl ParameterTransformTarget {
    /// Creates one architecture-admitted load-time transform target.
    fn new(
        request: QuantizationRequest,
        executable: LinearFormat,
        descriptor: WeightLoweringDescriptor,
    ) -> Self {
        Self {
            request,
            executable,
            descriptor,
        }
    }

    /// Returns the caller request selecting this transform.
    pub const fn request(&self) -> QuantizationRequest {
        self.request
    }

    /// Returns the architecture-admitted executable format.
    pub const fn executable(&self) -> LinearFormat {
        self.executable
    }

    /// Returns the exact neutral lowering query.
    pub const fn descriptor(&self) -> &WeightLoweringDescriptor {
        &self.descriptor
    }
}

/// Architecture declaration of whether and how a parameter may be transformed.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum ParameterTransformConstraint {
    /// This parameter is not an executable affine projection weight.
    None,
    /// The declared axis is the input/packing axis of a linear parameter.
    Linear {
        /// Axis whose extent is grouped or blocked by executable packing.
        packed_axis: usize,
    },
}

/// Architecture-owned semantic role of one logical parameter.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum ReplicatedTextParameterRole {
    /// Token lookup table.
    Embedding,
    /// Executable affine projection weight.
    LinearWeight,
    /// Learned affine projection bias.
    LinearBias,
    /// Learned normalization scale or offset.
    Normalization,
    /// Physical scale, zero-point, or packed-format companion.
    FormatCompanion,
    /// Another architecture-declared non-linear parameter.
    Other,
}

/// Architecture-owned location of one replicated-text parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum ReplicatedTextParameterOwner {
    /// Pinned module selected by a stable architecture role.
    StaticRole(String),
    /// One architecture-global execution unit.
    ExecutionUnit {
        /// Stable execution-group identity.
        group: String,
        /// Group-local architecture-global unit index.
        unit: usize,
    },
}

/// Exact admitted presence or derivation of one logical parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum ReplicatedTextParameterPresence {
    /// A required physical source was selected.
    Required,
    /// An optional physical source was present and selected.
    OptionalPresent,
    /// An optional architecture parameter is absent from this artifact.
    OptionalAbsent,
    /// The value is tied to another canonical logical parameter.
    Tied {
        /// Canonical identity supplying the value.
        target: String,
    },
    /// The value is produced by an architecture-owned recipe.
    Derived {
        /// Stable recipe identity.
        recipe: String,
    },
}

impl ReplicatedTextParameterPresence {
    /// Returns whether selection must choose a backend lowering.
    pub fn has_physical_source(&self) -> bool {
        matches!(self, Self::Required | Self::OptionalPresent)
    }
}

/// Exact admitted source and executable constraints for one logical parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextPhysicalSource {
    catalog_key: String,
    tensor: String,
    shard: PathBuf,
    output: String,
    source_encoding: SourceTensorEncoding,
    encoded_byte_len: u64,
}

impl ReplicatedTextPhysicalSource {
    /// Records one exact physical tensor, admitted shard, and selected output.
    pub fn new(
        catalog_key: impl Into<String>,
        tensor: impl Into<String>,
        shard: impl Into<PathBuf>,
        output: impl Into<String>,
        source_encoding: SourceTensorEncoding,
        encoded_byte_len: u64,
    ) -> Result<Self, ReplicatedTextContractError> {
        let catalog_key = catalog_key.into();
        let tensor = tensor.into();
        let shard = shard.into();
        let output = output.into();
        if catalog_key.trim().is_empty()
            || tensor.trim().is_empty()
            || shard.as_os_str().is_empty()
            || output.trim().is_empty()
            || encoded_byte_len == 0
        {
            return Err(ReplicatedTextContractError::invalid(
                "physical source key, tensor, shard, output, and byte length must be valid",
            ));
        }
        Ok(Self {
            catalog_key,
            tensor,
            shard,
            output,
            source_encoding,
            encoded_byte_len,
        })
    }

    /// Logical key selecting this exact output from the admitted catalog.
    pub fn catalog_key(&self) -> &str {
        &self.catalog_key
    }

    /// Physical tensor identity in the admitted container.
    pub fn tensor(&self) -> &str {
        &self.tensor
    }
    /// Canonical admitted payload shard.
    pub fn shard(&self) -> &Path {
        &self.shard
    }
    /// Exact logical output selected from the physical tensor.
    pub fn output(&self) -> &str {
        &self.output
    }
    /// Exact physical container encoding for this catalog output.
    pub const fn source_encoding(&self) -> &SourceTensorEncoding {
        &self.source_encoding
    }
    /// Encoded bytes selected for this catalog output.
    pub const fn encoded_byte_len(&self) -> u64 {
        self.encoded_byte_len
    }
}

/// Exact admitted source and executable constraints for one logical parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextParameterRequirement {
    /// Canonical logical parameter identity.
    name: String,
    /// Physical outputs admitted as sources for this logical parameter.
    sources: Vec<String>,
    /// Exact shard and multi-output provenance for the physical input.
    physical_sources: Vec<ReplicatedTextPhysicalSource>,
    /// All admitted aliases for the logical parameter.
    aliases: Vec<String>,
    /// Encoding of the selected physical source, when present.
    source_encoding: Option<SourceTensorEncoding>,
    /// Exact selected physical source shape, when present.
    physical_shape: Option<Vec<usize>>,
    /// Architecture-declared logical tensor shape.
    logical_shape: Vec<usize>,
    /// Architecture-owned semantic parameter role.
    role: ReplicatedTextParameterRole,
    /// Architecture-owned static/group/unit location.
    owner: ReplicatedTextParameterOwner,
    /// Exact artifact presence, tie, or derivation.
    presence: ReplicatedTextParameterPresence,
    /// Architecture-selected native executable format.
    native_executable: LinearFormat,
    /// Exact architecture-owned transform eligibility and packing axis.
    transform: ParameterTransformConstraint,
    /// Exact encoded-linear primary relationship for a physical companion.
    linear_companion: Option<(eredu_nn::LinearCompanionRole, String)>,
    /// Exact architecture output names used when this weight is transformed.
    transform_companions: Option<(String, String)>,
    /// Exact stored dtypes which the architecture permits a native companion
    /// slot to accept during binding.
    permitted_native_source_dtypes: Vec<eredu_checkpoint::recipe::RecipeDtype>,
}

impl ReplicatedTextParameterRequirement {
    /// Creates one exact logical-parameter requirement.
    #[allow(
        clippy::too_many_arguments,
        reason = "the constructor validates one complete immutable catalog record"
    )]
    pub fn new(
        name: impl Into<String>,
        sources: Vec<String>,
        physical_sources: Vec<ReplicatedTextPhysicalSource>,
        aliases: Vec<String>,
        source_encoding: Option<SourceTensorEncoding>,
        physical_shape: Option<Vec<usize>>,
        logical_shape: Vec<usize>,
        native_executable: LinearFormat,
        role: ReplicatedTextParameterRole,
        owner: ReplicatedTextParameterOwner,
        presence: ReplicatedTextParameterPresence,
        transform: ParameterTransformConstraint,
    ) -> Result<Self, ReplicatedTextContractError> {
        let name = name.into();
        native_executable
            .validate()
            .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))?;
        if name.trim().is_empty() {
            return Err(ReplicatedTextContractError::invalid(
                "logical parameter identity is empty",
            ));
        }
        if sources.iter().any(|source| source.trim().is_empty())
            || aliases.iter().any(|alias| alias.trim().is_empty())
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has an empty physical identity"
            )));
        }
        let has_source = !sources.is_empty();
        let has_physical_facts = source_encoding.is_some() && physical_shape.is_some();
        if source_encoding.is_some() != physical_shape.is_some()
            || (has_source && !has_physical_facts)
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has inconsistent source presence"
            )));
        }
        match presence {
            ReplicatedTextParameterPresence::Required
            | ReplicatedTextParameterPresence::OptionalPresent
                if !has_source =>
            {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "physical logical parameter {name:?} has no lowering source"
                )));
            }
            ReplicatedTextParameterPresence::OptionalAbsent
            | ReplicatedTextParameterPresence::Tied { .. }
                if has_source =>
            {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "source-free logical parameter {name:?} has a lowering source"
                )));
            }
            _ => {}
        }
        let provenance_required =
            has_source || matches!(presence, ReplicatedTextParameterPresence::Derived { .. });
        if provenance_required != !physical_sources.is_empty() {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has inconsistent physical provenance"
            )));
        }
        if physical_sources.is_empty() && has_physical_facts {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has physical facts without provenance"
            )));
        }
        if physical_shape
            .as_ref()
            .is_some_and(|shape| shape.contains(&0))
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has an invalid physical shape"
            )));
        }
        if logical_shape.contains(&0) {
            return Err(ReplicatedTextContractError::invalid(format!(
                "logical parameter {name:?} has an invalid shape {logical_shape:?}"
            )));
        }
        if let ParameterTransformConstraint::Linear { packed_axis } = transform {
            if packed_axis >= logical_shape.len() {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "logical parameter {name:?} has packing axis {packed_axis} outside shape {logical_shape:?}"
                )));
            }
        }
        let requirement = Self {
            name,
            sources,
            physical_sources,
            aliases,
            source_encoding,
            physical_shape,
            logical_shape,
            role,
            owner,
            presence,
            native_executable,
            transform,
            linear_companion: None,
            transform_companions: None,
            permitted_native_source_dtypes: Vec::new(),
        };
        Ok(requirement)
    }

    /// Explicitly permits exact source dtypes for this architecture parameter.
    pub fn with_permitted_native_source_dtypes(
        mut self,
        dtypes: Vec<eredu_checkpoint::recipe::RecipeDtype>,
    ) -> Self {
        self.permitted_native_source_dtypes =
            dtypes.into_iter().fold(Vec::new(), |mut out, dtype| {
                if !out.contains(&dtype) {
                    out.push(dtype);
                }
                out
            });
        self
    }

    /// Attaches the exact encoded-linear primary relationship selected by the architecture.
    pub fn with_linear_companion(
        mut self,
        role: eredu_nn::LinearCompanionRole,
        primary: impl Into<String>,
    ) -> Result<Self, ReplicatedTextContractError> {
        let primary = primary.into();
        if self.role != ReplicatedTextParameterRole::FormatCompanion
            || primary.trim().is_empty()
            || primary == self.name
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "parameter {:?} has an invalid encoded-linear companion relationship",
                self.name
            )));
        }
        self.linear_companion = Some((role, primary));
        Ok(self)
    }

    /// Attaches exact scale and affine-bias output identities for load-time transforms.
    pub fn with_transform_companions(
        mut self,
        scale: impl Into<String>,
        affine_bias: impl Into<String>,
    ) -> Result<Self, ReplicatedTextContractError> {
        let scale = scale.into();
        let affine_bias = affine_bias.into();
        if !matches!(self.transform, ParameterTransformConstraint::Linear { .. })
            || scale.trim().is_empty()
            || affine_bias.trim().is_empty()
            || scale == affine_bias
            || scale == self.name
            || affine_bias == self.name
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "parameter {:?} has invalid transform companion identities",
                self.name
            )));
        }
        self.transform_companions = Some((scale, affine_bias));
        Ok(self)
    }

    /// Returns the canonical logical identity.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns exact admitted physical source identities.
    pub fn sources(&self) -> &[String] {
        &self.sources
    }

    /// Returns exact admitted shard and multi-output provenance.
    pub fn physical_sources(&self) -> &[ReplicatedTextPhysicalSource] {
        &self.physical_sources
    }

    /// Returns all architecture-admitted alternative source identities.
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }

    /// Returns the admitted physical source encoding.
    pub const fn source_encoding(&self) -> Option<&SourceTensorEncoding> {
        self.source_encoding.as_ref()
    }

    /// Returns the selected physical shape, when a source is present.
    pub fn physical_shape(&self) -> Option<&[usize]> {
        self.physical_shape.as_deref()
    }

    /// Returns the architecture-declared logical shape.
    pub fn logical_shape(&self) -> &[usize] {
        &self.logical_shape
    }

    /// Returns the architecture-owned semantic role.
    pub const fn role(&self) -> ReplicatedTextParameterRole {
        self.role
    }

    /// Returns the architecture-owned static/group/unit location.
    pub const fn owner(&self) -> &ReplicatedTextParameterOwner {
        &self.owner
    }

    /// Returns exact artifact presence, tie, or derivation.
    pub const fn presence(&self) -> &ReplicatedTextParameterPresence {
        &self.presence
    }

    /// Returns whether this logical value selects a physical source lowering.
    ///
    /// Architecture-derived values may retain a physical lowering source when
    /// a recipe splits one encoded tensor into several logical parameters.
    pub fn has_lowering_source(&self) -> bool {
        !self.sources.is_empty() || !self.physical_sources.is_empty()
    }

    /// Returns exact transform eligibility and packing geometry.
    pub const fn transform_constraint(&self) -> ParameterTransformConstraint {
        self.transform
    }

    /// Returns the exact encoded-linear primary relationship.
    pub fn linear_companion(&self) -> Option<(eredu_nn::LinearCompanionRole, &str)> {
        self.linear_companion
            .as_ref()
            .map(|(role, primary)| (*role, primary.as_str()))
    }

    /// Returns exact scale and affine-bias identities for load-time transforms.
    pub fn transform_companions(&self) -> Option<(&str, &str)> {
        self.transform_companions
            .as_ref()
            .map(|(scale, bias)| (scale.as_str(), bias.as_str()))
    }

    /// Returns explicitly permitted native source dtypes.
    pub fn permitted_native_source_dtypes(&self) -> &[eredu_checkpoint::recipe::RecipeDtype] {
        &self.permitted_native_source_dtypes
    }

    /// Returns the architecture-native executable format.
    pub const fn native_executable(&self) -> LinearFormat {
        self.native_executable
    }

    /// Resolves a caller transform through architecture-owned constraints.
    pub fn transform_target(
        &self,
        request: QuantizationRequest,
    ) -> Result<Option<ParameterTransformTarget>, ReplicatedTextContractError> {
        let packed_axis = match self.transform {
            ParameterTransformConstraint::None => return Ok(None),
            ParameterTransformConstraint::Linear { packed_axis } => packed_axis,
        };
        let extent = self.logical_shape[packed_axis];
        let executable = match request {
            QuantizationRequest::Affine { group_size, bits } => {
                let group_size = i32::try_from(group_size).map_err(|_| {
                    ReplicatedTextContractError::invalid("affine group size exceeds i32")
                })?;
                let format = eredu_checkpoint::AffineQuantization::new(group_size, i32::from(bits))
                    .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))?;
                let group_size = usize::try_from(format.group_size).map_err(|_| {
                    ReplicatedTextContractError::invalid("affine group size is negative")
                })?;
                if group_size > extent || !extent.is_multiple_of(group_size) {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "affine group size {group_size} does not divide packed extent {extent}"
                    )));
                }
                LinearFormat::Affine(format)
            }
            QuantizationRequest::MxFp4 => {
                const MXFP4_BLOCK_SIZE: usize = 32;
                if !extent.is_multiple_of(MXFP4_BLOCK_SIZE) {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "MXFP4 packed extent {extent} is not divisible by block size {MXFP4_BLOCK_SIZE}"
                    )));
                }
                LinearFormat::MxFp4
            }
            _ => {
                return Err(ReplicatedTextContractError::invalid(
                    "unknown load-time transform request",
                ))
            }
        };
        let descriptor = self.lowering_descriptor(executable)?;
        Ok(Some(ParameterTransformTarget::new(
            request, executable, descriptor,
        )))
    }

    /// Forms the exact backend lowering query for one admitted executable format.
    pub fn lowering_descriptor(
        &self,
        executable: LinearFormat,
    ) -> Result<WeightLoweringDescriptor, ReplicatedTextContractError> {
        let packed_axis = match self.transform {
            ParameterTransformConstraint::None => None,
            ParameterTransformConstraint::Linear { packed_axis } => Some(packed_axis),
        };
        let packed_axis = packed_axis
            .or_else(|| {
                (self.role == ReplicatedTextParameterRole::Embedding
                    && executable != LinearFormat::Dense)
                    .then(|| self.logical_shape.len().checked_sub(1))
                    .flatten()
            })
            .or_else(|| {
                (matches!(
                    self.presence,
                    ReplicatedTextParameterPresence::Derived { .. }
                ) && executable != LinearFormat::Dense)
                    .then(|| {
                        self.physical_shape
                            .as_ref()
                            .and_then(|shape| shape.len().checked_sub(1))
                    })
                    .flatten()
            });
        let alias_backed_packed_output = matches!(
            self.source_encoding,
            Some(
                SourceTensorEncoding::Safetensors(StoredDtype::U32)
                    | SourceTensorEncoding::RecipeOutput(StoredDtype::U32)
            )
        );
        let lowering_shape = if matches!(
            self.presence,
            ReplicatedTextParameterPresence::Derived { .. }
        ) && !alias_backed_packed_output
        {
            self.physical_shape.as_ref().unwrap_or(&self.logical_shape)
        } else {
            &self.logical_shape
        };
        WeightLoweringDescriptor::new(
            self.source_encoding.clone().ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "logical parameter {:?} has no physical lowering source",
                    self.name
                ))
            })?,
            executable,
            self.physical_shape.clone().ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "logical parameter {:?} has no physical source shape",
                    self.name
                ))
            })?,
            lowering_shape.clone(),
            packed_axis,
        )
    }
}

/// Invalid public replicated-text contract construction.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error("invalid replicated text contract: {message}")]
pub struct ReplicatedTextContractError {
    message: String,
}

/// Static state-access semantics required by an admitted replicated text graph.
#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum ReplicatedTextStateAccess {
    /// No mutable token state.
    Stateless,
    /// Ordinary key/value attention state.
    KeyValue,
    /// Architecture-declared recurrent or convolutional components only.
    Fixed,
    /// Key/value attention plus architecture-declared fixed components.
    AttentionWithFixed,
    /// Compressed-latent attention state without fixed components.
    CompressedAttention,
    /// Compressed-latent attention plus architecture-declared fixed components.
    CompressedAttentionWithFixed,
}

impl ReplicatedTextContractError {
    fn invalid(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Returns the stable semantic diagnostic.
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Exact architecture and artifact requirements for replicated text execution.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextRequirements {
    floating_state_source: Option<TensorDtype>,
    architecture_identity: String,
    /// Optional neural operations required by the architecture equations.
    operators: NeuralOperatorCapabilities,
    /// Stable architecture-owned execution graph.
    execution_graph: ExecutionGraph,
    /// Exact group-major execution-unit geometry.
    execution_units: ExecutionUnitLayout,
    /// Architecture-owned transport semantics in graph-group order.
    group_transports: Vec<ArchitectureGroupTransport>,
    /// Complete architecture-owned mutable-state geometry.
    state_layout: StateLayout,
    /// Static state-access semantics used by architecture traversal.
    state_access: ReplicatedTextStateAccess,
    /// Canonical logical parameter requirements.
    parameters: Vec<ReplicatedTextParameterRequirement>,
    /// Exact additive prediction/auxiliary parameters selected with this target.
    auxiliary_parameters: Vec<ReplicatedTextParameterRequirement>,
    derived_recipes: BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe>,
    derived_recipe_outputs: BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata>,
    shared_source_keys: BTreeSet<String>,
    grouped_operations: Vec<GroupedOperationRequirement>,
}

impl ReplicatedTextRequirements {
    /// Creates exact requirements from architecture and admitted-artifact facts only.
    #[allow(
        clippy::too_many_arguments,
        reason = "the constructor validates one complete immutable architecture contract"
    )]
    pub fn new(
        architecture_identity: impl Into<String>,
        operators: NeuralOperatorCapabilities,
        execution_graph: ExecutionGraph,
        execution_units: ExecutionUnitLayout,
        group_transports: Vec<ArchitectureGroupTransport>,
        state_layout: StateLayout,
        state_access: ReplicatedTextStateAccess,
        parameters: Vec<ReplicatedTextParameterRequirement>,
    ) -> Result<Self, ReplicatedTextContractError> {
        let architecture_identity = architecture_identity.into();
        if architecture_identity.trim().is_empty() {
            return Err(ReplicatedTextContractError::invalid(
                "architecture identity is empty",
            ));
        }
        if group_transports.len() != execution_graph.groups().len() {
            return Err(ReplicatedTextContractError::invalid(format!(
                "{} group transports do not match {} execution groups",
                group_transports.len(),
                execution_graph.groups().len()
            )));
        }
        if execution_units.group_count() != execution_graph.groups().len()
            || execution_graph
                .groups()
                .iter()
                .enumerate()
                .any(|(index, group)| {
                    execution_units
                        .group_id(index)
                        .is_none_or(|id| id.as_str() != group.id())
                })
        {
            return Err(ReplicatedTextContractError::invalid(
                "execution-unit layout group identities differ from the execution graph",
            ));
        }
        validate_state_access_profile(&state_layout, state_access)?;
        let mut names = BTreeSet::new();
        if parameters
            .iter()
            .any(|parameter| !names.insert(parameter.name()))
        {
            return Err(ReplicatedTextContractError::invalid(
                "logical parameter identities are not unique",
            ));
        }
        Ok(Self {
            floating_state_source: None,
            architecture_identity,
            operators,
            execution_graph,
            execution_units,
            group_transports,
            state_layout,
            state_access,
            parameters,
            auxiliary_parameters: Vec::new(),
            derived_recipes: BTreeMap::new(),
            derived_recipe_outputs: BTreeMap::new(),
            shared_source_keys: BTreeSet::new(),
            grouped_operations: Vec::new(),
        })
    }

    /// Records the dtype of the architecture-declared activation source before native selection.
    /// This is source metadata, not a request to convert checkpoint weights.
    pub fn with_floating_state_source(mut self, dtype: TensorDtype) -> Self {
        self.floating_state_source = Some(dtype);
        self
    }

    /// Returns the exact source dtype used to resolve generic floating state.
    pub fn floating_state_source(&self) -> Option<&TensorDtype> {
        self.floating_state_source.as_ref()
    }

    /// Attaches exact additive auxiliary parameter requirements before backend selection.
    pub fn with_auxiliary_parameters(
        mut self,
        parameters: Vec<ReplicatedTextParameterRequirement>,
        recipes: BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe>,
        outputs: BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata>,
    ) -> Result<Self, ReplicatedTextContractError> {
        let primary = self
            .parameters
            .iter()
            .map(|parameter| parameter.name())
            .collect::<BTreeSet<_>>();
        let mut names = BTreeSet::new();
        if parameters
            .iter()
            .any(|parameter| primary.contains(parameter.name()) || !names.insert(parameter.name()))
        {
            return Err(ReplicatedTextContractError::invalid(
                "auxiliary parameter identities overlap or are not unique",
            ));
        }
        if recipes.keys().ne(outputs.keys())
            || recipes
                .keys()
                .any(|target| !names.contains(target.as_str()))
            || recipes
                .keys()
                .any(|target| self.derived_recipes.contains_key(target))
        {
            return Err(ReplicatedTextContractError::invalid(
                "auxiliary derivations do not match auxiliary parameters",
            ));
        }
        self.derived_recipes.extend(recipes);
        self.derived_recipe_outputs.extend(outputs);
        self.auxiliary_parameters = parameters;
        Ok(self)
    }

    /// Attaches the exact architecture-owned derivations selected for this artifact.
    pub fn with_derived_recipes(
        mut self,
        recipes: BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe>,
        outputs: BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata>,
    ) -> Result<Self, ReplicatedTextContractError> {
        self.set_derived_recipes(recipes, outputs, BTreeSet::new())?;
        Ok(self)
    }

    /// Attaches exact derivations together with architecture-declared physical
    /// sources which intentionally feed more than one logical destination.
    pub fn with_derived_recipes_and_shared_sources(
        mut self,
        recipes: BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe>,
        outputs: BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata>,
        shared_source_keys: BTreeSet<String>,
    ) -> Result<Self, ReplicatedTextContractError> {
        self.set_derived_recipes(recipes, outputs, shared_source_keys)?;
        Ok(self)
    }

    fn set_derived_recipes(
        &mut self,
        recipes: BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe>,
        outputs: BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata>,
        shared_source_keys: BTreeSet<String>,
    ) -> Result<(), ReplicatedTextContractError> {
        if recipes.keys().ne(outputs.keys()) {
            return Err(ReplicatedTextContractError::invalid(
                "derived recipe targets and inferred outputs differ",
            ));
        }
        for source in &shared_source_keys {
            let claims = recipes
                .values()
                .filter(|recipe| recipe.source_keys().contains(&source.as_str()))
                .count();
            if claims < 2 {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "declared shared source {source:?} is not claimed by multiple derived targets"
                )));
            }
        }
        for target in recipes.keys() {
            let recipe = recipes
                .get(target)
                .expect("recipe target came from the same map");
            let parameter = self
                .parameters
                .iter_mut()
                .find(|parameter| parameter.name == *target)
                .ok_or_else(|| {
                    ReplicatedTextContractError::invalid(format!(
                        "derived recipe target {target:?} is not a declared parameter"
                    ))
                })?;
            if matches!(
                parameter.presence,
                ReplicatedTextParameterPresence::OptionalAbsent
                    | ReplicatedTextParameterPresence::Tied { .. }
            ) {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "derived recipe target {target:?} has no independent artifact value"
                )));
            }
            parameter.presence = ReplicatedTextParameterPresence::Derived {
                recipe: "architecture.recipe".into(),
            };
            parameter.sources = recipe
                .source_keys()
                .into_iter()
                .map(str::to_owned)
                .collect();
        }
        self.derived_recipes = recipes;
        self.derived_recipe_outputs = outputs;
        self.shared_source_keys = shared_source_keys;
        Ok(())
    }

    /// Returns the normalized architecture identity bound during admission.
    pub fn architecture_identity(&self) -> &str {
        &self.architecture_identity
    }

    /// Rebinds an admitted physical schema to a new architecture identity which
    /// deliberately implements the same complete neutral topology.
    pub fn with_extension_architecture_identity(
        mut self,
        architecture_identity: impl Into<String>,
    ) -> Result<Self, ReplicatedTextContractError> {
        let architecture_identity = architecture_identity.into();
        if architecture_identity.trim().is_empty() {
            return Err(ReplicatedTextContractError::invalid(
                "extension architecture identity is empty",
            ));
        }
        self.architecture_identity = architecture_identity;
        Ok(self)
    }

    /// Declares exact grouped operations required by this architecture path.
    pub fn with_grouped_operations(
        mut self,
        operations: impl IntoIterator<Item = GroupedOperationRequirement>,
    ) -> Self {
        self.grouped_operations = operations.into_iter().collect();
        self
    }

    /// Returns required optional neural-operation semantics.
    pub const fn operators(&self) -> NeuralOperatorCapabilities {
        self.operators
    }
    /// Returns the architecture-owned execution graph.
    pub const fn execution_graph(&self) -> &ExecutionGraph {
        &self.execution_graph
    }
    /// Returns group-major execution-unit geometry.
    pub const fn execution_units(&self) -> &ExecutionUnitLayout {
        &self.execution_units
    }
    /// Returns architecture-owned group transports.
    pub fn group_transports(&self) -> &[ArchitectureGroupTransport] {
        &self.group_transports
    }
    /// Returns complete mutable-state geometry.
    pub const fn state_layout(&self) -> &StateLayout {
        &self.state_layout
    }
    /// Returns the state-access semantics used by typed traversal.
    pub const fn state_access(&self) -> ReplicatedTextStateAccess {
        self.state_access
    }
    /// Returns canonical logical parameter requirements.
    pub fn parameters(&self) -> &[ReplicatedTextParameterRequirement] {
        &self.parameters
    }

    /// Returns exact additive auxiliary parameter requirements.
    pub fn auxiliary_parameters(&self) -> &[ReplicatedTextParameterRequirement] {
        &self.auxiliary_parameters
    }
    /// Returns exact derivations that are part of the selected artifact contract.
    pub fn derived_recipes(
        &self,
    ) -> &BTreeMap<String, eredu_checkpoint::recipe::DerivedWeightRecipe> {
        &self.derived_recipes
    }
    /// Returns admission-time output metadata for every exact derivation.
    pub fn derived_recipe_outputs(
        &self,
    ) -> &BTreeMap<String, eredu_checkpoint::recipe::RecipeMetadata> {
        &self.derived_recipe_outputs
    }
    /// Returns physical sources explicitly declared as shared by the architecture.
    pub fn shared_source_keys(&self) -> &BTreeSet<String> {
        &self.shared_source_keys
    }
    /// Returns exact grouped operations required before construction.
    pub fn grouped_operations(&self) -> &[GroupedOperationRequirement] {
        &self.grouped_operations
    }
}

fn validate_state_access_profile(
    layout: &StateLayout,
    access: ReplicatedTextStateAccess,
) -> Result<(), ReplicatedTextContractError> {
    use eredu_core::cache::StateComponentRole;

    let roles = (0..layout.len())
        .flat_map(|layer| {
            layout
                .components(layer)
                .expect("validated state layout exposes every layer")
        })
        .map(StateComponentPolicy::role)
        .collect::<Vec<_>>();
    let ordinary = |role| {
        matches!(
            role,
            StateComponentRole::AttentionKeys | StateComponentRole::AttentionValues
        )
    };
    let compressed = |role| {
        matches!(
            role,
            StateComponentRole::CompressedLatent | StateComponentRole::RotaryKeys
        )
    };
    let fixed = |role| matches!(role, StateComponentRole::Fixed(_));
    let has_ordinary = roles.iter().copied().any(ordinary);
    let has_compressed = roles.iter().copied().any(compressed);
    let has_fixed = roles.iter().copied().any(fixed);
    let coherent = match access {
        ReplicatedTextStateAccess::Stateless => roles.is_empty(),
        ReplicatedTextStateAccess::KeyValue => roles.iter().copied().all(ordinary) && has_ordinary,
        ReplicatedTextStateAccess::Fixed => roles.iter().copied().all(fixed) && has_fixed,
        ReplicatedTextStateAccess::AttentionWithFixed => {
            roles
                .iter()
                .copied()
                .all(|role| ordinary(role) || fixed(role))
                && has_ordinary
                && has_fixed
        }
        ReplicatedTextStateAccess::CompressedAttention => {
            roles.iter().copied().all(compressed) && has_compressed
        }
        ReplicatedTextStateAccess::CompressedAttentionWithFixed => {
            roles
                .iter()
                .copied()
                .all(|role| compressed(role) || fixed(role))
                && has_compressed
                && has_fixed
        }
    };
    if !coherent {
        return Err(ReplicatedTextContractError::invalid(format!(
            "state access profile {access:?} does not match component roles {roles:?}"
        )));
    }
    Ok(())
}

/// One required grouped-compute mechanism.
#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum GroupedOperationRequirement {
    /// Ordinary grouped gated-product output.
    GatedProduct,
    /// Rank-local gated-product partial with an explicit post-reduce term.
    GatedProductTensorParallelPartial,
    /// Ordinary grouped ReLU-squared output.
    Relu2,
    /// Rank-local ReLU-squared partial with an explicit post-reduce term.
    Relu2TensorParallelPartial,
}

/// Generic independently addressable storage facilities implemented by a backend.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct AddressableStorageCapabilities {
    bulk_access: bool,
    incremental_access: bool,
    lease_completion: bool,
    maximum_compact_bytes: u64,
    tiers: AddressableStorageTiers,
}

/// Generic storage tiers usable by an independently addressable bank.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct AddressableStorageTiers {
    device: bool,
    host: bool,
    disk: bool,
}

impl AddressableStorageTiers {
    /// Creates one exact tier capability set.
    pub const fn new(device: bool, host: bool, disk: bool) -> Self {
        Self { device, host, disk }
    }

    /// Returns whether executable device storage is available.
    pub const fn device(self) -> bool {
        self.device
    }

    /// Returns whether host staging storage is available.
    pub const fn host(self) -> bool {
        self.host
    }

    /// Returns whether lazy checkpoint-backed storage is available.
    pub const fn disk(self) -> bool {
        self.disk
    }
}

impl AddressableStorageCapabilities {
    /// Creates an exact addressable-storage capability report.
    pub const fn new(
        bulk_access: bool,
        incremental_access: bool,
        lease_completion: bool,
        maximum_compact_bytes: u64,
    ) -> Self {
        Self {
            bulk_access,
            incremental_access,
            lease_completion,
            maximum_compact_bytes,
            tiers: AddressableStorageTiers::new(true, true, true),
        }
    }

    /// Replaces the exact supported storage-tier set.
    pub const fn with_tiers(mut self, tiers: AddressableStorageTiers) -> Self {
        self.tiers = tiers;
        self
    }

    /// Returns whether bounded multi-row access is implemented.
    pub const fn bulk_access(self) -> bool {
        self.bulk_access
    }

    /// Returns whether latency-sensitive incremental access is implemented.
    pub const fn incremental_access(self) -> bool {
        self.incremental_access
    }

    /// Returns whether acquisitions remain leased through native completion.
    pub const fn lease_completion(self) -> bool {
        self.lease_completion
    }

    /// Returns the largest supported per-acquisition compact bank.
    pub const fn maximum_compact_bytes(self) -> u64 {
        self.maximum_compact_bytes
    }

    /// Returns the exact independently addressable storage tiers.
    pub const fn tiers(self) -> AddressableStorageTiers {
        self.tiers
    }
}

/// Family- and execution-class-neutral backend mechanism report.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BackendMechanismCapabilities {
    /// Optional neural operations implemented by the backend.
    operators: NeuralOperatorCapabilities,
    /// Exact admitted source-to-executable lowerings.
    weight_lowerings: Vec<WeightLoweringCapability>,
    /// Ordinary parameter residency mechanisms.
    weight_residencies: Vec<WeightResidencyMechanism>,
    /// Exact mutable-state component and lifecycle mechanisms.
    state: StateMechanismCapabilities,
    /// Exact session facilities implemented by the constructed session.
    session: SessionCapabilities,
    /// Prompt-cache persistence mechanism is available.
    prompt_cache: bool,
    /// Exact completion ownership is implemented for submitted work.
    exact_completion: bool,
    grouped_operations: Vec<GroupedOperationRequirement>,
    indexed_movement: bool,
    addressable_storage: Option<AddressableStorageCapabilities>,
}

impl BackendMechanismCapabilities {
    /// Creates a fail-closed mechanism report.
    pub fn new(
        operators: NeuralOperatorCapabilities,
        weight_lowerings: Vec<WeightLoweringCapability>,
        weight_residencies: Vec<WeightResidencyMechanism>,
        state: StateMechanismCapabilities,
    ) -> Self {
        Self {
            operators,
            weight_lowerings,
            weight_residencies,
            state,
            session: SessionCapabilities::default(),
            prompt_cache: false,
            exact_completion: false,
            grouped_operations: Vec::new(),
            indexed_movement: false,
            addressable_storage: None,
        }
    }

    /// Adds supported session-observation and persistence mechanisms.
    pub const fn with_session(mut self, session: SessionCapabilities) -> Self {
        self.session = session;
        self
    }
    /// Declares prompt-cache persistence support.
    pub const fn with_prompt_cache(mut self, supported: bool) -> Self {
        self.prompt_cache = supported;
        self
    }
    /// Declares exact native-completion ownership support.
    pub const fn with_exact_completion(mut self, supported: bool) -> Self {
        self.exact_completion = supported;
        self
    }
    /// Declares exact grouped operation mechanisms.
    pub fn with_grouped_operations(
        mut self,
        operations: impl IntoIterator<Item = GroupedOperationRequirement>,
    ) -> Self {
        self.grouped_operations = operations.into_iter().collect();
        self
    }
    /// Declares generic indexed discovery, slicing, remapping, and concatenation.
    pub const fn with_indexed_movement(mut self, supported: bool) -> Self {
        self.indexed_movement = supported;
        self
    }
    /// Declares generic independently addressable storage facilities.
    pub const fn with_addressable_storage(
        mut self,
        capabilities: AddressableStorageCapabilities,
    ) -> Self {
        self.addressable_storage = Some(capabilities);
        self
    }
    /// Returns neural-operation mechanisms.
    pub const fn operators(&self) -> NeuralOperatorCapabilities {
        self.operators
    }
    /// Returns source-to-executable weight-lowering mechanisms.
    pub fn weight_lowerings(&self) -> &[WeightLoweringCapability] {
        &self.weight_lowerings
    }
    /// Returns weight-residency mechanisms.
    pub fn weight_residencies(&self) -> &[WeightResidencyMechanism] {
        &self.weight_residencies
    }
    /// Returns exact mutable-state component and lifecycle mechanisms.
    pub const fn state(&self) -> &StateMechanismCapabilities {
        &self.state
    }
    /// Returns session-observation and persistence mechanisms.
    pub const fn session(&self) -> SessionCapabilities {
        self.session
    }
    /// Returns whether prompt-cache persistence is supported.
    pub const fn prompt_cache(&self) -> bool {
        self.prompt_cache
    }
    /// Returns whether exact native-completion ownership is supported.
    pub const fn exact_completion(&self) -> bool {
        self.exact_completion
    }
    /// Returns exact grouped operation mechanisms.
    pub fn grouped_operations(&self) -> &[GroupedOperationRequirement] {
        &self.grouped_operations
    }
    /// Returns whether generic indexed movement is implemented.
    pub const fn indexed_movement(&self) -> bool {
        self.indexed_movement
    }
    /// Returns independently addressable storage facilities, when implemented.
    pub const fn addressable_storage(&self) -> Option<AddressableStorageCapabilities> {
        self.addressable_storage
    }
}

/// Caller choices resolved while selecting one replicated text realization.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextSelectionRequest {
    max_cached_shards: usize,
    /// Requested execution topology.
    topology: Option<ParallelTopology>,
    /// Requested ordinary parameter residency.
    residency: LayerWeightResidency,
    /// Requested mutable-state implementation and its exact residency policy.
    state: CacheResidencyPolicy,
    /// Optional load-time transform.
    quantization: Option<QuantizationRequest>,
    /// Requested optional session facilities.
    session: SessionCapabilities,
    /// Whether prompt-cache persistence is requested.
    prompt_cache: bool,
    /// Whether exact completion ownership is requested.
    exact_completion: bool,
}

impl ReplicatedTextSelectionRequest {
    /// Creates a replicated request with fail-closed optional facilities.
    pub fn new(residency: LayerWeightResidency, state: CacheResidencyPolicy) -> Self {
        Self {
            max_cached_shards: residency.max_cached_shards(),
            topology: None,
            residency,
            state,
            quantization: None,
            session: SessionCapabilities::default(),
            prompt_cache: false,
            exact_completion: false,
        }
    }
    /// Sets the exact source reader-cache limit independently of weight placement.
    pub const fn with_max_cached_shards(mut self, maximum: std::num::NonZeroUsize) -> Self {
        self.max_cached_shards = maximum.get();
        self
    }
    /// Returns the exact selected source reader-cache limit.
    pub const fn max_cached_shards(&self) -> usize {
        self.max_cached_shards
    }
    /// Sets the requested topology.
    pub const fn with_topology(mut self, topology: ParallelTopology) -> Self {
        self.topology = Some(topology);
        self
    }
    /// Sets the optional load-time transform.
    pub const fn with_quantization(mut self, quantization: QuantizationRequest) -> Self {
        self.quantization = Some(quantization);
        self
    }
    /// Sets requested session facilities.
    pub const fn with_session(mut self, session: SessionCapabilities) -> Self {
        self.session = session;
        self
    }
    /// Requests prompt-cache persistence.
    pub const fn with_prompt_cache(mut self, required: bool) -> Self {
        self.prompt_cache = required;
        self
    }
    /// Requests exact completion ownership.
    pub const fn with_exact_completion(mut self, required: bool) -> Self {
        self.exact_completion = required;
        self
    }
    /// Returns the requested topology, where `None` means replicated.
    pub const fn topology(&self) -> Option<ParallelTopology> {
        self.topology
    }
    /// Returns the requested weight residency.
    pub const fn residency(&self) -> LayerWeightResidency {
        self.residency
    }
    /// Returns the requested state policy.
    pub const fn state(&self) -> &CacheResidencyPolicy {
        &self.state
    }
    /// Returns the requested transform.
    pub const fn quantization(&self) -> Option<QuantizationRequest> {
        self.quantization
    }
    /// Returns requested session facilities.
    pub const fn session(&self) -> SessionCapabilities {
        self.session
    }
    /// Returns whether prompt-cache persistence is requested.
    pub const fn prompt_cache(&self) -> bool {
        self.prompt_cache
    }
    /// Returns whether exact completion ownership is requested.
    pub const fn exact_completion(&self) -> bool {
        self.exact_completion
    }
}

/// Selected lowering for one canonical logical parameter.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SelectedParameterRealization {
    /// Canonical logical parameter identity.
    name: String,
    /// Physical outputs admitted as sources for this logical parameter.
    sources: Vec<String>,
    physical_sources: Vec<ReplicatedTextPhysicalSource>,
    /// Admitted physical encoding.
    source_encoding: SourceTensorEncoding,
    /// Exact executable format used to construct the architecture module.
    executable: LinearFormat,
    /// Backend lowering selected for materialization.
    lowering: WeightLoweringKind,
}

/// Exact backend work item for one selected logical parameter.
///
/// This value joins architecture-owned topology and artifact facts with the
/// authoritative selected lowering. A materializer may batch these tasks, but
/// it must not replace them with one model-wide transform choice.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextMaterializationTask {
    name: String,
    sources: Vec<String>,
    physical_sources: Vec<ReplicatedTextPhysicalSource>,
    aliases: Vec<String>,
    source_encoding: SourceTensorEncoding,
    physical_shape: Vec<usize>,
    logical_shape: Vec<usize>,
    role: ReplicatedTextParameterRole,
    owner: ReplicatedTextParameterOwner,
    presence: ReplicatedTextParameterPresence,
    executable: LinearFormat,
    lowering: WeightLoweringKind,
    lowering_descriptor: WeightLoweringDescriptor,
    derived_recipe: Option<eredu_checkpoint::recipe::DerivedWeightRecipe>,
    derived_output: Option<eredu_checkpoint::recipe::RecipeMetadata>,
    shared_source_keys: BTreeSet<String>,
    permitted_native_source_dtypes: Vec<eredu_checkpoint::recipe::RecipeDtype>,
    output_companions: Vec<ReplicatedTextOutputCompanion>,
}

/// Index-based partition of exact materialization tasks by construction owner.
///
/// Indices refer to the input task slice used to create the plan. Keeping the
/// plan free of borrowed or erased task values lets concrete backends retain
/// their own statically dispatched construction path.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextMaterializationPartitionPlan {
    task_count: usize,
    static_tasks: Vec<usize>,
    unit_tasks: Vec<Vec<usize>>,
}

impl ReplicatedTextMaterializationPartitionPlan {
    /// Returns the number of tasks from which this plan was derived.
    pub const fn task_count(&self) -> usize {
        self.task_count
    }

    /// Returns indices owned by architecture-static modules.
    pub fn static_task_indices(&self) -> &[usize] {
        &self.static_tasks
    }

    /// Returns task-index partitions in local flattened execution-unit order.
    pub fn unit_task_indices(&self) -> &[Vec<usize>] {
        &self.unit_tasks
    }

    /// Borrows static tasks from the exact slice used to construct this plan.
    pub fn static_tasks<'a>(
        &self,
        tasks: &'a [ReplicatedTextMaterializationTask],
    ) -> Result<Vec<&'a ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
        self.validate_task_slice(tasks)?;
        Ok(self
            .static_tasks
            .iter()
            .map(|index| &tasks[*index])
            .collect())
    }

    /// Borrows unit tasks from the exact slice used to construct this plan.
    pub fn unit_tasks<'a>(
        &self,
        tasks: &'a [ReplicatedTextMaterializationTask],
    ) -> Result<Vec<Vec<&'a ReplicatedTextMaterializationTask>>, ReplicatedTextContractError> {
        self.validate_task_slice(tasks)?;
        Ok(self
            .unit_tasks
            .iter()
            .map(|indices| indices.iter().map(|index| &tasks[*index]).collect())
            .collect())
    }

    fn validate_task_slice(
        &self,
        tasks: &[ReplicatedTextMaterializationTask],
    ) -> Result<(), ReplicatedTextContractError> {
        if tasks.len() != self.task_count {
            return Err(ReplicatedTextContractError::invalid(format!(
                "materialization partition plan expects {} tasks, got {}",
                self.task_count,
                tasks.len()
            )));
        }
        Ok(())
    }
}

/// One executable-format group of transforming task indices.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextTransformGroup {
    quantization: eredu_checkpoint::WeightQuantization,
    task_indices: Vec<usize>,
}

impl ReplicatedTextTransformGroup {
    /// Returns the packed output format shared by every task in this group.
    pub const fn quantization(&self) -> eredu_checkpoint::WeightQuantization {
        self.quantization
    }

    /// Returns transforming task indices in original task order.
    pub fn task_indices(&self) -> &[usize] {
        &self.task_indices
    }

    /// Borrows this group's tasks from the original task slice.
    pub fn tasks<'a>(
        &self,
        tasks: &'a [ReplicatedTextMaterializationTask],
    ) -> Result<Vec<&'a ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
        self.task_indices
            .iter()
            .map(|index| {
                tasks.get(*index).ok_or_else(|| {
                    ReplicatedTextContractError::invalid(
                        "transform group was applied to a different materialization task slice",
                    )
                })
            })
            .collect()
    }
}

/// Architecture-declared output companion for one materialized linear weight.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ReplicatedTextOutputCompanion {
    name: String,
    role: eredu_nn::LinearCompanionRole,
    logical_shape: Vec<usize>,
    owner: ParameterGroupOwner,
    materialization_task: Option<Box<ReplicatedTextMaterializationTask>>,
    catalog_source: Option<ReplicatedTextPhysicalSource>,
    derived_recipe: Option<eredu_checkpoint::recipe::DerivedWeightRecipe>,
    derived_output: Option<eredu_checkpoint::recipe::RecipeMetadata>,
}

impl ReplicatedTextOutputCompanion {
    /// Creates one exact output companion identity and semantic role.
    pub fn new(
        name: impl Into<String>,
        role: eredu_nn::LinearCompanionRole,
        logical_shape: Vec<usize>,
        owner: ParameterGroupOwner,
    ) -> Result<Self, ReplicatedTextContractError> {
        let name = name.into();
        if name.trim().is_empty() || logical_shape.is_empty() || logical_shape.contains(&0) {
            return Err(ReplicatedTextContractError::invalid(
                "materialization output companion identity or geometry is invalid",
            ));
        }
        Ok(Self {
            name,
            role,
            logical_shape,
            owner,
            materialization_task: None,
            catalog_source: None,
            derived_recipe: None,
            derived_output: None,
        })
    }

    pub(crate) fn with_derived_recipe(
        mut self,
        recipe: eredu_checkpoint::recipe::DerivedWeightRecipe,
        output: eredu_checkpoint::recipe::RecipeMetadata,
    ) -> Self {
        self.derived_recipe = Some(recipe);
        self.derived_output = Some(output);
        self
    }

    /// Returns the exact architecture-declared parameter identity.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the companion's role in the encoded linear parameter.
    pub const fn role(&self) -> eredu_nn::LinearCompanionRole {
        self.role
    }

    /// Returns the exact architecture-declared companion geometry.
    pub fn logical_shape(&self) -> &[usize] {
        &self.logical_shape
    }

    /// Returns the exact architecture-declared companion owner.
    pub const fn owner(&self) -> &ParameterGroupOwner {
        &self.owner
    }

    pub(crate) fn with_materialization_task(
        mut self,
        task: ReplicatedTextMaterializationTask,
    ) -> Result<Self, ReplicatedTextContractError> {
        let names_output =
            task.name() == self.name || task.aliases().iter().any(|alias| alias == &self.name);
        if !names_output || !task.output_companions().is_empty() {
            return Err(ReplicatedTextContractError::invalid(format!(
                "companion {:?} has an inconsistent standalone materialization task",
                self.name
            )));
        }
        self.materialization_task = Some(Box::new(task));
        Ok(self)
    }

    /// Retains exact translated-catalog provenance for a directly loaded companion.
    pub fn with_catalog_source(mut self, source: ReplicatedTextPhysicalSource) -> Self {
        self.catalog_source = Some(source);
        self
    }

    /// Returns the standalone selected materialization task, when one exists.
    ///
    /// Generated transform outputs and translated checkpoint catalog outputs
    /// instead retain their causal source on the primary task or companion.
    pub fn materialization_task(&self) -> Option<&ReplicatedTextMaterializationTask> {
        self.materialization_task.as_deref()
    }

    /// Returns exact translated-catalog provenance for this companion.
    pub const fn catalog_source(&self) -> Option<&ReplicatedTextPhysicalSource> {
        self.catalog_source.as_ref()
    }

    /// Returns the architecture-owned companion derivation, when required.
    pub const fn derived_recipe(&self) -> Option<&eredu_checkpoint::recipe::DerivedWeightRecipe> {
        self.derived_recipe.as_ref()
    }

    /// Returns admission-time metadata for the derived companion output.
    pub const fn derived_output(&self) -> Option<&eredu_checkpoint::recipe::RecipeMetadata> {
        self.derived_output.as_ref()
    }
}

impl ReplicatedTextMaterializationTask {
    /// Creates one exact, source-backed materialization task selected outside
    /// the ordinary replicated-text session lifecycle.
    ///
    /// This is used by architecture-owned auxiliary modules which share the
    /// same physical lowering contract but do not own a text session.
    #[allow(clippy::too_many_arguments)]
    pub fn from_exact_source(
        name: impl Into<String>,
        physical_source: ReplicatedTextPhysicalSource,
        aliases: Vec<String>,
        physical_shape: Vec<usize>,
        logical_shape: Vec<usize>,
        role: ReplicatedTextParameterRole,
        owner: ReplicatedTextParameterOwner,
        executable: LinearFormat,
        lowering: WeightLoweringKind,
        lowering_descriptor: WeightLoweringDescriptor,
    ) -> Result<Self, ReplicatedTextContractError> {
        let name = name.into();
        if name.trim().is_empty()
            || physical_shape.is_empty()
            || logical_shape.is_empty()
            || physical_shape.contains(&0)
            || logical_shape.contains(&0)
            || lowering_descriptor.source() != physical_source.source_encoding()
            || lowering_descriptor.executable() != executable
            || lowering_descriptor.physical_shape() != physical_shape
            || lowering_descriptor.logical_shape() != logical_shape
        {
            return Err(ReplicatedTextContractError::invalid(
                "exact auxiliary materialization task is internally inconsistent",
            ));
        }
        let source = physical_source.catalog_key().to_owned();
        Ok(Self {
            name,
            sources: vec![source],
            physical_sources: vec![physical_source],
            aliases,
            source_encoding: lowering_descriptor.source().clone(),
            physical_shape,
            logical_shape,
            role,
            owner,
            presence: ReplicatedTextParameterPresence::Required,
            executable,
            lowering,
            lowering_descriptor,
            derived_recipe: None,
            derived_output: None,
            shared_source_keys: BTreeSet::new(),
            permitted_native_source_dtypes: Vec::new(),
            output_companions: Vec::new(),
        })
    }

    pub(crate) fn set_output_companions(
        &mut self,
        mut companions: Vec<ReplicatedTextOutputCompanion>,
    ) -> Result<(), ReplicatedTextContractError> {
        companions.sort_by(|left, right| {
            left.role
                .cmp(&right.role)
                .then_with(|| left.name.cmp(&right.name))
        });
        if companions
            .windows(2)
            .any(|pair| pair[0].name == pair[1].name || pair[0].role == pair[1].role)
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "materialization task {:?} has duplicate output companions",
                self.name
            )));
        }
        let roles = companions
            .iter()
            .map(|companion| companion.role)
            .collect::<Vec<_>>();
        let expected = if companions.is_empty()
            && matches!(
                self.lowering,
                WeightLoweringKind::Direct | WeightLoweringKind::Derived
            ) {
            Vec::new()
        } else {
            match self.executable {
                LinearFormat::Dense | LinearFormat::GgufIQuant { .. } => Vec::new(),
                LinearFormat::MxFp4 | LinearFormat::E4M3BlockFp8(_) => {
                    vec![eredu_nn::LinearCompanionRole::Scale]
                }
                LinearFormat::Affine(_) => vec![
                    eredu_nn::LinearCompanionRole::Scale,
                    eredu_nn::LinearCompanionRole::AffineBias,
                ],
            }
        };
        let mut expected = expected;
        expected.sort();
        if roles != expected {
            return Err(ReplicatedTextContractError::invalid(format!(
                "materialization task {:?} executable {:?} requires companion roles {:?}, got {:?}",
                self.name, self.executable, expected, roles
            )));
        }
        self.output_companions = companions;
        Ok(())
    }

    /// Attaches the architecture's exact selected packed-output companions.
    pub fn with_output_companions(
        mut self,
        companions: Vec<ReplicatedTextOutputCompanion>,
    ) -> Result<Self, ReplicatedTextContractError> {
        self.set_output_companions(companions)?;
        Ok(self)
    }

    /// Returns the canonical logical parameter identity.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns every admitted physical source identity.
    pub fn sources(&self) -> &[String] {
        &self.sources
    }

    /// Returns exact shard and translated-output provenance.
    pub fn physical_sources(&self) -> &[ReplicatedTextPhysicalSource] {
        &self.physical_sources
    }

    /// Returns every architecture-admitted alias.
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }

    /// Returns architecture-declared physical sources shared by logical outputs.
    pub fn shared_source_keys(&self) -> &BTreeSet<String> {
        &self.shared_source_keys
    }

    /// Returns exact source dtypes explicitly permitted for native binding.
    pub fn permitted_native_source_dtypes(&self) -> &[eredu_checkpoint::recipe::RecipeDtype] {
        &self.permitted_native_source_dtypes
    }

    /// Returns the exact admitted source encoding.
    pub const fn source_encoding(&self) -> &SourceTensorEncoding {
        &self.source_encoding
    }

    /// Returns the admitted physical source geometry.
    pub fn physical_shape(&self) -> &[usize] {
        &self.physical_shape
    }

    /// Returns the architecture-declared logical geometry.
    pub fn logical_shape(&self) -> &[usize] {
        &self.logical_shape
    }

    /// Returns the architecture-owned semantic parameter role.
    pub const fn role(&self) -> ReplicatedTextParameterRole {
        self.role
    }

    /// Returns the architecture-owned module location.
    pub const fn owner(&self) -> &ReplicatedTextParameterOwner {
        &self.owner
    }

    /// Returns the exact admitted presence or derivation.
    pub const fn presence(&self) -> &ReplicatedTextParameterPresence {
        &self.presence
    }

    /// Returns the selected executable format.
    pub const fn executable(&self) -> LinearFormat {
        self.executable
    }

    /// Returns the selected backend lowering mechanism.
    pub const fn lowering(&self) -> WeightLoweringKind {
        self.lowering
    }

    /// Returns the complete geometry-bearing lowering request.
    pub const fn lowering_descriptor(&self) -> &WeightLoweringDescriptor {
        &self.lowering_descriptor
    }

    /// Returns the architecture-owned derivation, when this output is derived.
    pub const fn derived_recipe(&self) -> Option<&eredu_checkpoint::recipe::DerivedWeightRecipe> {
        self.derived_recipe.as_ref()
    }

    /// Returns admission-time metadata for the derived output.
    pub const fn derived_output(&self) -> Option<&eredu_checkpoint::recipe::RecipeMetadata> {
        self.derived_output.as_ref()
    }

    /// Returns exact output companion identities declared by the architecture.
    pub fn output_companions(&self) -> &[ReplicatedTextOutputCompanion] {
        &self.output_companions
    }

    /// Returns the exact source recipe selected for this task.
    ///
    /// Direct tasks are represented as a full selection of their single
    /// admitted source. Derived tasks return the architecture-owned recipe
    /// without reconstructing it from a checkpoint catalog.
    pub fn source_recipe(
        &self,
    ) -> Result<eredu_checkpoint::recipe::DerivedWeightRecipe, ReplicatedTextContractError> {
        let expects_recipe = matches!(
            self.lowering,
            WeightLoweringKind::Derived | WeightLoweringKind::DerivedTransform
        );
        match (expects_recipe, self.derived_recipe.as_ref()) {
            (true, Some(recipe)) => {
                let declared = self
                    .sources
                    .iter()
                    .map(String::as_str)
                    .collect::<BTreeSet<_>>();
                let consumed = recipe.source_keys().into_iter().collect::<BTreeSet<_>>();
                if declared != consumed {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "materialization task {:?} recipe sources differ from its exact source catalog",
                        self.name
                    )));
                }
                Ok(recipe.clone())
            }
            (false, None) => {
                let [source] = self.sources.as_slice() else {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "direct materialization task {:?} must name exactly one source",
                        self.name
                    )));
                };
                Ok(eredu_checkpoint::recipe::DerivedWeightRecipe::source(
                    source.clone(),
                    eredu_checkpoint::store::TensorSelection::Full,
                ))
            }
            (true, None) => Err(ReplicatedTextContractError::invalid(format!(
                "derived materialization task {:?} has no exact recipe",
                self.name
            ))),
            (false, Some(_)) => Err(ReplicatedTextContractError::invalid(format!(
                "direct materialization task {:?} unexpectedly carries a recipe",
                self.name
            ))),
        }
    }
}

/// Partitions exact tasks against the architecture-global execution layout.
pub fn plan_replicated_text_materialization_tasks(
    tasks: &[ReplicatedTextMaterializationTask],
    layout: &ExecutionUnitLayout,
) -> Result<ReplicatedTextMaterializationPartitionPlan, ReplicatedTextContractError> {
    let mut static_tasks = Vec::new();
    let mut unit_tasks = vec![Vec::new(); layout.len()];
    for (task_index, task) in tasks.iter().enumerate() {
        match task.owner() {
            ReplicatedTextParameterOwner::StaticRole(_) => static_tasks.push(task_index),
            ReplicatedTextParameterOwner::ExecutionUnit { group, unit } => {
                let group_index = (0..layout.group_count())
                    .find(|index| {
                        layout
                            .group_id(*index)
                            .is_some_and(|id| id.as_str() == group)
                    })
                    .ok_or_else(|| {
                        ReplicatedTextContractError::invalid(format!(
                            "exact task {:?} names unknown execution group {group:?}",
                            task.name()
                        ))
                    })?;
                let ordinal = layout.ordinal(group_index, *unit).ok_or_else(|| {
                    ReplicatedTextContractError::invalid(format!(
                        "exact task {:?} names unknown unit {unit} in group {group:?}",
                        task.name()
                    ))
                })?;
                unit_tasks[ordinal].push(task_index);
            }
        }
    }
    Ok(ReplicatedTextMaterializationPartitionPlan {
        task_count: tasks.len(),
        static_tasks,
        unit_tasks,
    })
}

/// Partitions exact tasks into one retained rank-local execution-unit order.
pub fn plan_local_replicated_text_materialization_tasks(
    tasks: &[ReplicatedTextMaterializationTask],
    global_layout: &ExecutionUnitLayout,
    addresses: &[crate::ExecutionUnitAddress],
) -> Result<ReplicatedTextMaterializationPartitionPlan, ReplicatedTextContractError> {
    if addresses.is_empty() {
        return Err(ReplicatedTextContractError::invalid(
            "local partition has no selected execution units",
        ));
    }
    let mut seen = BTreeSet::new();
    for address in addresses {
        if global_layout.address(
            global_layout
                .ordinal(address.group(), address.index())
                .unwrap_or(usize::MAX),
        ) != Some(*address)
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "local partition names unknown global unit {}.{}",
                address.group(),
                address.index()
            )));
        }
        if !seen.insert((address.group(), address.index())) {
            return Err(ReplicatedTextContractError::invalid(format!(
                "local partition repeats global unit {}.{}",
                address.group(),
                address.index()
            )));
        }
    }

    let mut static_tasks = Vec::new();
    let mut unit_tasks = vec![Vec::new(); addresses.len()];
    for (task_index, task) in tasks.iter().enumerate() {
        match task.owner() {
            ReplicatedTextParameterOwner::StaticRole(_) => static_tasks.push(task_index),
            ReplicatedTextParameterOwner::ExecutionUnit { group, unit } => {
                let local = addresses
                    .iter()
                    .position(|address| {
                        global_layout
                            .group_id(address.group())
                            .is_some_and(|id| id.as_str() == group)
                            && address.index() == *unit
                    })
                    .ok_or_else(|| {
                        ReplicatedTextContractError::invalid(format!(
                            "local task {:?} has no owned global unit {group}.{unit}",
                            task.name()
                        ))
                    })?;
                unit_tasks[local].push(task_index);
            }
        }
    }
    Ok(ReplicatedTextMaterializationPartitionPlan {
        task_count: tasks.len(),
        static_tasks,
        unit_tasks,
    })
}

/// Returns every primary and companion produced by local transformation.
pub fn locally_materialized_replicated_text_outputs(
    tasks: &[ReplicatedTextMaterializationTask],
) -> BTreeSet<String> {
    tasks
        .iter()
        .filter(|task| {
            matches!(
                task.lowering(),
                WeightLoweringKind::Transform | WeightLoweringKind::DerivedTransform
            )
        })
        .flat_map(|task| {
            std::iter::once(task.name().to_owned()).chain(
                task.output_companions()
                    .iter()
                    .map(|companion| companion.name().to_owned()),
            )
        })
        .collect()
}

/// Groups transforming tasks by exact packed output format.
///
/// Groups and indices preserve first-observed task order. Direct tasks are not
/// included, and a transforming task without a packed format fails closed.
pub fn group_replicated_text_transform_tasks(
    tasks: &[ReplicatedTextMaterializationTask],
) -> Result<Vec<ReplicatedTextTransformGroup>, ReplicatedTextContractError> {
    let mut groups = Vec::<ReplicatedTextTransformGroup>::new();
    for (task_index, task) in tasks.iter().enumerate().filter(|(_, task)| {
        matches!(
            task.lowering(),
            WeightLoweringKind::Transform | WeightLoweringKind::DerivedTransform
        )
    }) {
        let quantization = task.executable().weight_quantization().ok_or_else(|| {
            ReplicatedTextContractError::invalid(format!(
                "selected materialization task {:?} has no packed output format",
                task.name()
            ))
        })?;
        if let Some(group) = groups
            .iter_mut()
            .find(|group| group.quantization == quantization)
        {
            group.task_indices.push(task_index);
        } else {
            groups.push(ReplicatedTextTransformGroup {
                quantization,
                task_indices: vec![task_index],
            });
        }
    }
    Ok(groups)
}

/// Computes the exact executable storage charged to one selected task.
///
/// Direct tasks retain their admitted physical or derived output bytes.
/// Transform tasks replace those bytes with the packed weight and exactly the
/// companion roles selected by the executable format.
pub fn selected_materialization_task_bytes(
    task: &ReplicatedTextMaterializationTask,
) -> Result<u64, ReplicatedTextContractError> {
    let transforms = matches!(
        task.lowering(),
        WeightLoweringKind::Transform | WeightLoweringKind::DerivedTransform
    );
    if !transforms {
        if let Some(output) = task.derived_output() {
            return Ok(output.byte_len());
        }
        return task
            .physical_sources()
            .iter()
            .try_fold(0u64, |total, source| {
                total.checked_add(source.encoded_byte_len()).ok_or_else(|| {
                    ReplicatedTextContractError::invalid(format!(
                        "materialization task {:?} physical byte total overflowed",
                        task.name()
                    ))
                })
            });
    }

    let dtype = task
        .source_encoding()
        .scalar_dtype()
        .map(eredu_checkpoint::recipe::RecipeDtype::from)
        .ok_or_else(|| {
            ReplicatedTextContractError::invalid(format!(
                "materialization task {:?} transforms a non-scalar source",
                task.name()
            ))
        })?;
    let source_bytes = task
        .derived_output()
        .map(|output| output.byte_len())
        .or_else(|| {
            task.physical_sources()
                .first()
                .map(|source| source.encoded_byte_len())
        })
        .ok_or_else(|| {
            ReplicatedTextContractError::invalid(format!(
                "materialization task {:?} has no source byte extent",
                task.name()
            ))
        })?;
    let metadata = eredu_checkpoint::recipe::RecipeMetadata {
        shape: task.logical_shape().to_vec(),
        dtype,
        byte_len: source_bytes,
    };
    crate::selected_addressable_parameter_bytes(task, &metadata)
        .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))
}

/// Projects an authoritative selection into exact materialization work.
///
/// Every selected parameter must agree with its immutable requirement. The
/// returned sequence preserves selected-parameter order and contains no
/// model-wide quantization or transform value.
pub fn replicated_text_materialization_tasks(
    selected: &SelectedReplicatedTextRealization,
) -> Result<Vec<ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
    if selected.materialization_tasks.is_empty() && !selected.parameters.is_empty() {
        return Err(ReplicatedTextContractError::invalid(
            "selected realization omitted its authoritative materialization tasks",
        ));
    }
    Ok(selected.materialization_tasks.clone())
}

fn build_replicated_text_materialization_tasks(
    selected: &SelectedReplicatedTextRealization,
) -> Result<Vec<ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
    build_materialization_tasks(
        selected.requirements(),
        selected.requirements().parameters(),
        selected.parameters(),
    )
}

fn build_materialization_tasks(
    requirements: &ReplicatedTextRequirements,
    parameter_requirements: &[ReplicatedTextParameterRequirement],
    selected_parameters: &[SelectedParameterRealization],
) -> Result<Vec<ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
    let mut tasks = selected_parameters
        .iter()
        .map(|realization| {
            let requirement = parameter_requirements
                .iter()
                .find(|requirement| requirement.name() == realization.name())
                .ok_or_else(|| {
                    ReplicatedTextContractError::invalid(format!(
                        "selected parameter {:?} has no architecture requirement",
                        realization.name()
                    ))
                })?;
            if requirement.sources() != realization.sources()
                || requirement.physical_sources() != realization.physical_sources()
                || requirement.source_encoding() != Some(realization.source_encoding())
            {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "selected parameter {:?} changed admitted source provenance",
                    realization.name()
                )));
            }
            let physical_shape = requirement.physical_shape().ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "selected parameter {:?} has no physical geometry",
                    realization.name()
                ))
            })?;
            let lowering_descriptor = requirement.lowering_descriptor(realization.executable())?;
            if lowering_descriptor.source() != realization.source_encoding() {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "selected parameter {:?} changed its lowering source encoding",
                    realization.name()
                )));
            }
            let mut derived_recipe = requirements
                .derived_recipes()
                .get(realization.name())
                .cloned();
            let derived_output = requirements
                .derived_recipe_outputs()
                .get(realization.name())
                .cloned();
            if derived_recipe.is_some() != derived_output.is_some() {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "selected parameter {:?} has incomplete derived metadata",
                    realization.name()
                )));
            }
            if derived_recipe.is_none()
                && matches!(
                    realization.lowering(),
                    WeightLoweringKind::Derived | WeightLoweringKind::DerivedTransform
                )
            {
                let [source] = realization.sources() else {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "derived selected parameter {:?} has no exact recipe and does not name one source",
                        realization.name()
                    )));
                };
                derived_recipe = Some(
                    eredu_checkpoint::recipe::DerivedWeightRecipe::source(
                        source.clone(),
                        eredu_checkpoint::store::TensorSelection::Full,
                    ),
                );
            }
            Ok(ReplicatedTextMaterializationTask {
                name: realization.name().to_owned(),
                sources: realization.sources().to_vec(),
                physical_sources: realization.physical_sources().to_vec(),
                aliases: requirement.aliases().to_vec(),
                source_encoding: realization.source_encoding().clone(),
                physical_shape: physical_shape.to_vec(),
                logical_shape: requirement.logical_shape().to_vec(),
                role: requirement.role(),
                owner: requirement.owner().clone(),
                presence: requirement.presence().clone(),
                executable: realization.executable(),
                lowering: realization.lowering(),
                lowering_descriptor,
                derived_recipe,
                derived_output,
                shared_source_keys: requirements.shared_source_keys().clone(),
                permitted_native_source_dtypes: requirement
                    .permitted_native_source_dtypes()
                    .to_vec(),
                output_companions: Vec::new(),
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    let task_by_name = tasks
        .iter()
        .map(|task| (task.name().to_owned(), task.clone()))
        .collect::<BTreeMap<_, _>>();
    let requirement_by_name = parameter_requirements
        .iter()
        .map(|requirement| (requirement.name(), requirement))
        .collect::<BTreeMap<_, _>>();
    let mut declared = BTreeMap::<String, Vec<ReplicatedTextOutputCompanion>>::new();
    let mut companion_names = BTreeSet::new();
    for requirement in parameter_requirements {
        let Some((role, primary)) = requirement.linear_companion() else {
            continue;
        };
        let owner = parameter_group_owner(requirement.owner())?;
        let mut companion = ReplicatedTextOutputCompanion::new(
            requirement.name(),
            role,
            requirement.logical_shape().to_vec(),
            owner,
        )?;
        if let Some(task) = task_by_name.get(requirement.name()) {
            companion = companion.with_materialization_task(task.clone())?;
        }
        declared
            .entry(primary.to_owned())
            .or_default()
            .push(companion);
        companion_names.insert(requirement.name().to_owned());
    }
    for task in &mut tasks {
        let transforms = matches!(
            task.lowering(),
            WeightLoweringKind::Transform | WeightLoweringKind::DerivedTransform
        );
        let outputs = if transforms {
            let requirement = requirement_by_name.get(task.name()).ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "selected task {:?} has no retained requirement",
                    task.name()
                ))
            })?;
            let (scale, affine_bias) = requirement.transform_companions().ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "transformed task {:?} has no architecture-selected companion identities",
                    task.name()
                ))
            })?;
            let quantization = task.executable().weight_quantization().ok_or_else(|| {
                ReplicatedTextContractError::invalid(format!(
                    "transformed task {:?} selected a non-quantized executable",
                    task.name()
                ))
            })?;
            let mut shape = task.logical_shape().to_vec();
            let input = shape.last_mut().ok_or_else(|| {
                ReplicatedTextContractError::invalid("transformed scalar parameter")
            })?;
            let group = usize::try_from(quantization.group_size()).map_err(|_| {
                ReplicatedTextContractError::invalid("transform group size exceeds usize")
            })?;
            if group == 0 || !input.is_multiple_of(group) {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "transformed task {:?} has incompatible companion geometry",
                    task.name()
                )));
            }
            *input /= group;
            let owner = parameter_group_owner(task.owner())?;
            let mut outputs = vec![ReplicatedTextOutputCompanion::new(
                scale,
                eredu_nn::LinearCompanionRole::Scale,
                shape.clone(),
                owner.clone(),
            )?];
            if quantization.has_biases() {
                outputs.push(ReplicatedTextOutputCompanion::new(
                    affine_bias,
                    eredu_nn::LinearCompanionRole::AffineBias,
                    shape,
                    owner,
                )?);
            }
            outputs
        } else {
            declared.remove(task.name()).unwrap_or_default()
        };
        task.set_output_companions(outputs)?;
    }
    if !declared.is_empty() {
        return Err(ReplicatedTextContractError::invalid(format!(
            "selected companion primaries have no materialization task: {:?}",
            declared.keys().collect::<Vec<_>>()
        )));
    }
    tasks.retain(|task| !companion_names.contains(task.name()));
    Ok(tasks)
}

fn parameter_group_owner(
    owner: &ReplicatedTextParameterOwner,
) -> Result<ParameterGroupOwner, ReplicatedTextContractError> {
    match owner {
        ReplicatedTextParameterOwner::StaticRole(role) => {
            Ok(ParameterGroupOwner::static_role(role.clone()))
        }
        ReplicatedTextParameterOwner::ExecutionUnit { group, unit } => {
            let group = ExecutionGroupId::new(group.clone())
                .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))?;
            Ok(ParameterGroupOwner::execution_unit(group, *unit))
        }
    }
}

/// Projects selected text materialization into one exact architecture partition.
///
/// Encoded-linear companions are reconstructed from the architecture's
/// validated physical parameter groups and remain atomic with their primary
/// task. If a partition would own only part of such a physical family, the
/// complete projection fails instead of retaining an unowned output.
pub fn partitioned_replicated_text_materialization_tasks<G, A>(
    selected: &SelectedReplicatedTextRealization,
    parameters: &ArchitectureParameterDescription,
    partition: &ArchitecturePartition<G, A>,
) -> Result<Vec<ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
    let tasks = replicated_text_materialization_tasks(selected)?;
    partition_selected_replicated_text_materialization_tasks(&tasks, parameters, partition)
}

/// Completes rank projection for physical tasks selected before backend resources exist.
///
/// This attaches architecture-declared atomic companions and removes tasks not owned by
/// the exact partition. It never reselects a source, encoding, executable format, recipe,
/// or lowering from the architecture topology.
pub fn partition_selected_replicated_text_materialization_tasks<G, A>(
    tasks: &[ReplicatedTextMaterializationTask],
    parameters: &ArchitectureParameterDescription,
    partition: &ArchitecturePartition<G, A>,
) -> Result<Vec<ReplicatedTextMaterializationTask>, ReplicatedTextContractError> {
    let mut tasks = tasks.to_vec();
    let mut companions = BTreeMap::<String, Vec<ReplicatedTextOutputCompanion>>::new();
    let mut all_targets = BTreeSet::new();
    let mut owned_targets = BTreeSet::new();
    for tagged in parameters.groups() {
        let local = partition.parameter_bindings().iter().any(|binding| {
            binding.owner() == tagged.owner()
                && parameter_groups_have_same_members(binding.group(), tagged.group())
        });
        let group_targets = tagged
            .members()
            .iter()
            .map(|member| member.target())
            .collect::<BTreeSet<_>>();
        for member in tagged.members() {
            if !all_targets.insert(member.target().to_owned()) {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "architecture parameter target {:?} appears more than once",
                    member.target()
                )));
            }
            if local {
                owned_targets.insert(member.target().to_owned());
            }
            match (member.linear_companion(), member.linear_companion_of()) {
                (None, None) => {}
                (Some(role), Some(primary)) if group_targets.contains(primary) && local => {
                    companions.entry(primary.to_owned()).or_default().push(
                        ReplicatedTextOutputCompanion::new(
                            member.target(),
                            role,
                            member.global_shape().to_vec(),
                            tagged.owner().clone(),
                        )?,
                    );
                }
                (Some(_), Some(primary)) if group_targets.contains(primary) => {}
                (Some(_), Some(primary)) => {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "physical companion {:?} names primary {primary:?} outside its atomic parameter group",
                        member.target()
                    )));
                }
                _ => {
                    return Err(ReplicatedTextContractError::invalid(format!(
                        "physical parameter {:?} has incomplete companion metadata",
                        member.target()
                    )));
                }
            }
        }
    }

    let mut topology_targets = BTreeMap::<String, String>::new();
    let mut target_claims = BTreeMap::<String, String>::new();
    for task in &tasks {
        let matches = std::iter::once(task.name())
            .chain(task.aliases().iter().map(String::as_str))
            .filter(|candidate| all_targets.contains(*candidate))
            .collect::<BTreeSet<_>>();
        if matches.len() != 1 {
            return Err(ReplicatedTextContractError::invalid(format!(
                "selected materialization output {:?} resolves to {} architecture topology targets through its canonical identity and admitted aliases: {:?}",
                task.name(),
                matches.len(),
                matches
            )));
        }
        let target = matches.first().expect("one topology target was validated");
        if let Some(previous) = target_claims.insert((*target).to_owned(), task.name().to_owned()) {
            return Err(ReplicatedTextContractError::invalid(format!(
                "selected materialization outputs {previous:?} and {:?} ambiguously resolve to architecture target {target:?}",
                task.name()
            )));
        }
        topology_targets.insert(task.name().to_owned(), (*target).to_owned());
    }
    for task in &mut tasks {
        let topology_target = topology_targets
            .get(task.name())
            .expect("every task has one validated topology target");
        if !owned_targets.contains(topology_target) {
            continue;
        }
        let mut declared = companions.remove(topology_target).unwrap_or_default();
        declared.sort_by(|left, right| {
            left.role()
                .cmp(&right.role())
                .then_with(|| left.name().cmp(right.name()))
        });
        let selected = task.output_companions();
        if declared.len() != selected.len()
            || declared.iter().zip(selected).any(|(declared, selected)| {
                declared.name() != selected.name()
                    || declared.role() != selected.role()
                    || declared.logical_shape() != selected.logical_shape()
                    || !(declared.owner() == selected.owner()
                        || matches!(
                            (declared.owner(), selected.owner()),
                            (
                                ParameterGroupOwner::StaticAnyOf(declared_roles),
                                ParameterGroupOwner::StaticRole(selected_role)
                            ) if declared_roles.iter().any(|role| role == selected_role)
                        ))
            })
        {
            return Err(ReplicatedTextContractError::invalid(format!(
                "partition parameter companions for {:?} differ from authoritative selection: constructed={:?}, selected={:?}",
                task.name(), declared, selected,
            )));
        }
    }
    if !companions.is_empty() {
        return Err(ReplicatedTextContractError::invalid(format!(
            "architecture companions name missing primary tasks: {:?}",
            companions.keys().collect::<Vec<_>>()
        )));
    }
    let mut projected = Vec::new();
    for task in tasks {
        let topology_target = topology_targets
            .get(task.name())
            .expect("every task has one validated topology target");
        let emitted = std::iter::once(topology_target.as_str())
            .chain(
                task.output_companions()
                    .iter()
                    .map(ReplicatedTextOutputCompanion::name),
            )
            .collect::<Vec<_>>();
        let local = emitted
            .iter()
            .filter(|target| owned_targets.contains(**target))
            .count();
        match local {
            0 => {}
            count if count == emitted.len() => projected.push(task),
            count => {
                return Err(ReplicatedTextContractError::invalid(format!(
                    "materialization task {:?} would emit {count} of {} outputs into this partition",
                    task.name(),
                    emitted.len()
                )));
            }
        }
    }
    Ok(projected)
}

/// Parameter visitation order is an implementation detail of a local module,
/// while an architecture parameter group is an atomic, target-keyed contract.
/// Compare that contract without making otherwise-identical local ownership
/// depend on whether a backend-neutral module visits a bias before its weight.
fn parameter_groups_have_same_members(
    left: &ParameterGroupSpec,
    right: &ParameterGroupSpec,
) -> bool {
    left.logical_name() == right.logical_name()
        && left.role() == right.role()
        && left.partition_units() == right.partition_units()
        && left.members().len() == right.members().len()
        && left.members().iter().all(|left_member| {
            right.members().iter().any(|right_member| {
                left_member.target() == right_member.target()
                    && left_member.global_shape() == right_member.global_shape()
                    && left_member.sharding() == right_member.sharding()
                    && left_member.linear_companion() == right_member.linear_companion()
                    && left_member.linear_companion_of() == right_member.linear_companion_of()
            })
        })
}

impl SelectedParameterRealization {
    /// Returns the canonical logical identity.
    pub fn name(&self) -> &str {
        &self.name
    }
    /// Returns admitted physical source identities.
    pub fn sources(&self) -> &[String] {
        &self.sources
    }
    /// Returns the exact selected shard and multi-output provenance.
    pub fn physical_sources(&self) -> &[ReplicatedTextPhysicalSource] {
        &self.physical_sources
    }
    /// Returns the admitted source encoding.
    pub const fn source_encoding(&self) -> &SourceTensorEncoding {
        &self.source_encoding
    }
    /// Returns the selected executable format.
    pub const fn executable(&self) -> LinearFormat {
        self.executable
    }
    /// Returns the selected backend lowering kind.
    pub const fn lowering(&self) -> WeightLoweringKind {
        self.lowering
    }
}

/// Selected physical realization of one exact semantic state component.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SelectedStateComponentRealization {
    storage_dtype: StateStorageDtype,
    layer: usize,
    component: StateComponentPolicy,
    placement: StateComponentPlacement,
}

impl SelectedStateComponentRealization {
    /// Exact native scalar representation admitted for this component.
    pub const fn storage_dtype(&self) -> StateStorageDtype {
        self.storage_dtype
    }

    /// Returns the architecture-global state layer.
    pub const fn layer(&self) -> usize {
        self.layer
    }

    /// Returns the exact architecture-declared component contract.
    pub const fn component(&self) -> &StateComponentPolicy {
        &self.component
    }

    /// Returns the selected physical placement.
    pub const fn placement(&self) -> StateComponentPlacement {
        self.placement
    }
}

/// Authoritative mutable-state realization selected before allocation.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SelectedStateRealization {
    floating_dtype: Option<StateStorageDtype>,
    layout: StateLayout,
    access: ReplicatedTextStateAccess,
    policy: CacheResidencyPolicy,
    components: Vec<SelectedStateComponentRealization>,
    checkpoint: bool,
    rollback: bool,
    reset: bool,
    prompt_cache: bool,
    observation_retention: bool,
}

impl SelectedStateRealization {
    /// Native representation selected from the architecture's floating-state source.
    pub const fn floating_dtype(&self) -> Option<StateStorageDtype> {
        self.floating_dtype
    }

    /// Returns the exact architecture-owned state layout.
    pub const fn layout(&self) -> &StateLayout {
        &self.layout
    }

    /// Selects the exact rank-local state interval while preserving global ownership proof.
    ///
    /// Component ordinals are rebased to the local layout consumed by a rank-local runtime;
    /// prompt-cache identity retains the global offset separately through [`crate::PartitionState`].
    pub fn for_partition(
        &self,
        partition: &crate::PartitionState,
    ) -> Result<Self, ReplicatedTextContractError> {
        let range = partition.global_layers();
        let expected = self
            .layout
            .slice(range.clone())
            .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))?;
        if &expected != partition.layout() {
            return Err(ReplicatedTextContractError::invalid(
                "partition state layout differs from the selected global interval",
            ));
        }
        let components = self
            .components
            .iter()
            .filter(|component| range.contains(&component.layer))
            .cloned()
            .map(|mut component| {
                component.layer -= range.start;
                component
            })
            .collect::<Vec<_>>();
        let expected_components = (0..partition.layout().len())
            .map(|layer| {
                partition
                    .layout()
                    .components(layer)
                    .expect("validated local state layout contains every layer")
                    .len()
            })
            .sum::<usize>();
        if components.len() != expected_components {
            return Err(ReplicatedTextContractError::invalid(
                "partition state components differ from the selected global interval",
            ));
        }
        Ok(Self {
            floating_dtype: self.floating_dtype,
            layout: partition.layout().clone(),
            access: self.access,
            policy: self.policy.clone(),
            components,
            checkpoint: self.checkpoint,
            rollback: self.rollback,
            reset: self.reset,
            prompt_cache: self.prompt_cache,
            observation_retention: self.observation_retention,
        })
    }

    /// Selects a rank-local interval whose tensor-parallel component shapes were authored by the
    /// validated architecture partition.
    ///
    /// Pipeline ownership must still name the same global layer interval. Tensor-parallel
    /// geometry may narrow fixed dimensions, but it cannot change component roles, dtype,
    /// residency, presence, ordering, or selected physical placement.
    pub fn for_partitioned_geometry(
        &self,
        partition: &crate::PartitionState,
    ) -> Result<Self, ReplicatedTextContractError> {
        let range = partition.global_layers();
        let global = self
            .layout
            .slice(range.clone())
            .map_err(|error| ReplicatedTextContractError::invalid(error.to_string()))?;
        if global.len() != partition.layout().len() {
            return Err(ReplicatedTextContractError::invalid(
                "partition state layer count differs from the selected global interval",
            ));
        }
        let mut components = Vec::new();
        for local_layer in 0..partition.layout().len() {
            let global_components = global
                .components(local_layer)
                .expect("validated selected state contains every local layer");
            let local_components = partition
                .layout()
                .components(local_layer)
                .expect("validated partition state contains every local layer");
            if global_components.len() != local_components.len() {
                return Err(ReplicatedTextContractError::invalid(
                    "partition state component count differs from selected state",
                ));
            }
            let global_layer = range.start + local_layer;
            let selected_components = self
                .components
                .iter()
                .filter(|component| component.layer == global_layer)
                .collect::<Vec<_>>();
            if selected_components.len() != local_components.len() {
                return Err(ReplicatedTextContractError::invalid(
                    "partition state components differ from the selected global interval",
                ));
            }
            for ((global_policy, local_policy), selected) in global_components
                .iter()
                .zip(local_components)
                .zip(selected_components)
            {
                if global_policy.role() != local_policy.role()
                    || global_policy.dtype() != local_policy.dtype()
                    || global_policy.residency() != local_policy.residency()
                    || global_policy.presence() != local_policy.presence()
                    || selected.component != *global_policy
                {
                    return Err(ReplicatedTextContractError::invalid(
                        "partition state component semantics differ from selected state",
                    ));
                }
                components.push(SelectedStateComponentRealization {
                    layer: local_layer,
                    component: local_policy.clone(),
                    storage_dtype: selected.storage_dtype,
                    placement: selected.placement,
                });
            }
        }
        Ok(Self {
            floating_dtype: self.floating_dtype,
            layout: partition.layout().clone(),
            access: self.access,
            policy: self.policy.clone(),
            components,
            checkpoint: self.checkpoint,
            rollback: self.rollback,
            reset: self.reset,
            prompt_cache: self.prompt_cache,
            observation_retention: self.observation_retention,
        })
    }

    /// Returns the state-access semantics selected for typed traversal.
    pub const fn access(&self) -> ReplicatedTextStateAccess {
        self.access
    }

    /// Returns the selected residency policy.
    pub const fn policy(&self) -> &CacheResidencyPolicy {
        &self.policy
    }

    /// Returns exact selected component realizations in layer/component order.
    pub fn components(&self) -> &[SelectedStateComponentRealization] {
        &self.components
    }

    /// Returns whether state checkpoints are selected.
    pub const fn checkpoint(&self) -> bool {
        self.checkpoint
    }

    /// Returns whether checkpoint rollback is selected.
    pub const fn rollback(&self) -> bool {
        self.rollback
    }

    /// Returns whether complete reset is selected.
    pub const fn reset(&self) -> bool {
        self.reset
    }

    /// Returns whether prompt-cache persistence is selected.
    pub const fn prompt_cache(&self) -> bool {
        self.prompt_cache
    }

    /// Returns whether observation retains every live component.
    pub const fn observation_retention(&self) -> bool {
        self.observation_retention
    }
}

/// Authoritative realization selected before architecture or payload construction.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SelectedReplicatedTextRealization {
    max_cached_shards: usize,
    requirements: ReplicatedTextRequirements,
    /// Exact selected execution topology.
    topology: ParallelTopology,
    /// Selected ordinary parameter residency.
    residency: LayerWeightResidency,
    /// Selected exact mutable-state implementation.
    state: SelectedStateRealization,
    /// Exact per-parameter source, executable format, and lowering.
    parameters: Vec<SelectedParameterRealization>,
    /// Exact task/companion topology selected before stores or native modules exist.
    materialization_tasks: Vec<ReplicatedTextMaterializationTask>,
    /// Exact additive auxiliary parameter selections.
    auxiliary_parameters: Vec<SelectedParameterRealization>,
    /// Exact additive auxiliary task/companion topology.
    auxiliary_materialization_tasks: Vec<ReplicatedTextMaterializationTask>,
    /// Required observation facilities admitted by the backend.
    session: SessionCapabilities,
    /// Prompt-cache persistence is selected for this lifecycle.
    prompt_cache: bool,
    /// Exact completion ownership selected for this lifecycle.
    exact_completion: bool,
    grouped_operations: Vec<GroupedOperationRequirement>,
}

impl SelectedReplicatedTextRealization {
    /// Returns the source reader-cache limit retained through selection.
    pub const fn max_cached_shards(&self) -> usize {
        self.max_cached_shards
    }
    /// Returns the exact architecture/artifact requirements selected together.
    pub const fn requirements(&self) -> &ReplicatedTextRequirements {
        &self.requirements
    }
    /// Returns the exact selected topology.
    pub const fn topology(&self) -> ParallelTopology {
        self.topology
    }
    /// Returns selected weight residency.
    pub const fn residency(&self) -> LayerWeightResidency {
        self.residency
    }
    /// Returns the authoritative selected mutable-state realization.
    pub const fn state(&self) -> &SelectedStateRealization {
        &self.state
    }
    /// Returns exact per-parameter realizations.
    pub fn parameters(&self) -> &[SelectedParameterRealization] {
        &self.parameters
    }
    /// Returns the authoritative exact materialization task sequence.
    pub fn materialization_tasks(&self) -> &[ReplicatedTextMaterializationTask] {
        &self.materialization_tasks
    }
    /// Returns exact additive auxiliary parameter selections.
    pub fn auxiliary_parameters(&self) -> &[SelectedParameterRealization] {
        &self.auxiliary_parameters
    }
    /// Returns exact additive auxiliary task/companion topology.
    pub fn auxiliary_materialization_tasks(&self) -> &[ReplicatedTextMaterializationTask] {
        &self.auxiliary_materialization_tasks
    }
    /// Returns selected session facilities.
    pub const fn session(&self) -> SessionCapabilities {
        self.session
    }
    /// Returns whether prompt-cache persistence was selected.
    pub const fn prompt_cache(&self) -> bool {
        self.prompt_cache
    }
    /// Returns whether exact completion ownership was selected.
    pub const fn exact_completion(&self) -> bool {
        self.exact_completion
    }
    /// Returns selected grouped operation mechanisms.
    pub fn grouped_operations(&self) -> &[GroupedOperationRequirement] {
        &self.grouped_operations
    }
}

/// Complete fail-closed selection diagnostic.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[error("replicated text realization is unsupported: {issues}", issues = .issues.join("; "))]
pub struct ReplicatedTextSelectionError {
    issues: Vec<String>,
}

impl ReplicatedTextSelectionError {
    /// Every missing semantic or mechanism requirement in stable order.
    pub fn issues(&self) -> &[String] {
        &self.issues
    }
}

/// Deterministically selects one realization without constructing backend payloads.
pub fn select_replicated_text_realization(
    requirements: &ReplicatedTextRequirements,
    request: &ReplicatedTextSelectionRequest,
    capabilities: &BackendMechanismCapabilities,
) -> Result<SelectedReplicatedTextRealization, ReplicatedTextSelectionError> {
    let mut issues = Vec::new();
    if request
        .topology
        .is_some_and(|topology| !topology.is_replicated())
    {
        issues.push("replicated execution topology".into());
    }
    if !capabilities.operators.contains(requirements.operators) {
        issues.extend(
            capabilities
                .operators
                .missing_capability_names(requirements.operators)
                .into_iter()
                .map(|name| format!("neural operation {name}")),
        );
    }
    for operation in &requirements.grouped_operations {
        if !capabilities.grouped_operations.contains(operation) {
            issues.push(format!("grouped operation {operation:?}"));
        }
    }
    let residency_mechanism = match request.residency {
        LayerWeightResidency::FullyResident => WeightResidencyMechanism::Resident,
        LayerWeightResidency::LayerwiseHost(_) => WeightResidencyMechanism::Windowed,
        LayerWeightResidency::DenseDiskStream(_) => WeightResidencyMechanism::DiskStreamed,
    };
    if !capabilities
        .weight_residencies
        .contains(&residency_mechanism)
    {
        issues.push(format!("weight residency {residency_mechanism:?}"));
    }
    let floating_dtype = match capabilities.state.floating_state_dtype() {
        Some((source, dtype))
            if Some(source) == requirements.floating_state_source() && dtype.is_floating() =>
        {
            Some(dtype)
        }
        Some(_) => {
            issues.push("floating-state dtype support differs from the selected source".into());
            None
        }
        None => None,
    };
    let mut state_components = Vec::new();
    for layer in 0..requirements.state_layout.len() {
        for component in requirements
            .state_layout
            .components(layer)
            .expect("state layout exposes every validated layer")
        {
            let Some(storage_dtype) = StateStorageDtype::resolve(component.dtype(), floating_dtype)
            else {
                issues.push(format!(
                    "state component {} at layer {layer} has no selected floating storage dtype",
                    component.role().stable_name()
                ));
                continue;
            };
            let matches = capabilities
                .state
                .components
                .iter()
                .filter(|mechanism| mechanism.layer == layer && mechanism.component == *component)
                .collect::<Vec<_>>();
            let role = component.role().stable_name();
            match matches.as_slice() {
                [mechanism] => match mechanism.placement(&request.state) {
                    Some(placement) if placement_is_compatible(component, &request.state, placement) => {
                        state_components.push(SelectedStateComponentRealization {
                            layer,
                            component: component.clone(),
                            storage_dtype,
                            placement,
                        });
                    }
                    Some(placement) => issues.push(format!(
                        "state component {role} at layer {layer} has incompatible {placement:?} placement for {:?} and {:?} residency",
                        request.state,
                        component.residency()
                    )),
                    None => issues.push(format!(
                        "state component {role} at layer {layer} for {:?}",
                        request.state
                    )),
                },
                [] => issues.push(format!(
                    "state component {role} at layer {layer} with shape {:?} and dtype {:?}",
                    component.shape(),
                    component.dtype()
                )),
                _ => issues.push(format!(
                    "unique state component mechanism {role} at layer {layer}"
                )),
            }
        }
    }
    for (supported, name) in [
        (capabilities.state.checkpoint, "state checkpoint"),
        (capabilities.state.rollback, "state rollback"),
        (capabilities.state.reset, "state reset"),
    ] {
        if !supported {
            issues.push(name.into());
        }
    }
    if request.prompt_cache && !capabilities.state.prompt_cache {
        issues.push("state prompt-cache persistence".into());
    }
    if (request.session.output_observation() || request.session.activation_inspection())
        && !capabilities.state.observation_retention
    {
        issues.push("state observation retention".into());
    }
    for (required, supported, name) in [
        (
            request.session.persistent_cache(),
            capabilities.session.persistent_cache(),
            "persistent_cache",
        ),
        (
            request.session.output_observation(),
            capabilities.session.output_observation(),
            "output_observation",
        ),
        (
            request.session.activation_inspection(),
            capabilities.session.activation_inspection(),
            "activation_inspection",
        ),
    ] {
        if required && !supported {
            issues.push(format!("session capability {name}"));
        }
    }
    if request.prompt_cache && !capabilities.prompt_cache {
        issues.push("prompt-cache persistence".into());
    }
    if request.exact_completion && !capabilities.exact_completion {
        issues.push("exact completion ownership".into());
    }

    let mut parameters = Vec::with_capacity(requirements.parameters.len());
    let mut auxiliary_parameters = Vec::with_capacity(requirements.auxiliary_parameters.len());
    let mut names = BTreeSet::new();
    for (parameter, auxiliary) in requirements
        .parameters
        .iter()
        .map(|parameter| (parameter, false))
        .chain(
            requirements
                .auxiliary_parameters
                .iter()
                .map(|parameter| (parameter, true)),
        )
    {
        if parameter.name.trim().is_empty() || !names.insert(parameter.name.as_str()) {
            issues.push(format!(
                "unique nonempty logical parameter identity {:?}",
                parameter.name
            ));
            continue;
        }
        if !parameter.has_lowering_source() {
            continue;
        }
        let native_candidate = || {
            parameter
                .lowering_descriptor(parameter.native_executable)
                .map(|descriptor| (parameter.native_executable, descriptor))
        };
        let candidate = match request.quantization {
            Some(request) => parameter
                .transform_target(request)
                .and_then(|target| match target {
                    Some(target) => Ok((target.executable(), target.descriptor().clone())),
                    None => native_candidate(),
                }),
            None => native_candidate(),
        };
        let (executable, descriptor) = match candidate {
            Ok(candidate) => candidate,
            Err(error) => {
                issues.push(error.to_string());
                issues.push(format!(
                    "architecture transform {:?} for {:?}",
                    request.quantization, parameter.name
                ));
                continue;
            }
        };
        let Some(lowering) = capabilities
            .weight_lowerings
            .iter()
            .find(|lowering| lowering.descriptor == descriptor)
        else {
            issues.push(format!(
                "weight lowering {:?} -> {:?} for {:?} with descriptor {:?}",
                parameter.source_encoding, executable, parameter.name, descriptor
            ));
            continue;
        };
        let selected_parameter = SelectedParameterRealization {
            name: parameter.name.clone(),
            sources: parameter.sources.clone(),
            physical_sources: parameter.physical_sources.clone(),
            source_encoding: parameter
                .source_encoding
                .clone()
                .expect("physical parameter has a source encoding"),
            executable,
            lowering: match (&parameter.presence, lowering.kind) {
                (
                    ReplicatedTextParameterPresence::Derived { .. },
                    WeightLoweringKind::Transform | WeightLoweringKind::DerivedTransform,
                ) => WeightLoweringKind::DerivedTransform,
                (ReplicatedTextParameterPresence::Derived { .. }, _) => WeightLoweringKind::Derived,
                (_, kind) => kind,
            },
        };
        if auxiliary {
            auxiliary_parameters.push(selected_parameter);
        } else {
            parameters.push(selected_parameter);
        }
    }
    if !issues.is_empty() {
        return Err(ReplicatedTextSelectionError { issues });
    }
    let mut selected = SelectedReplicatedTextRealization {
        max_cached_shards: request.max_cached_shards,
        requirements: requirements.clone(),
        topology: request
            .topology
            .unwrap_or_else(|| ParallelTopology::new(1, 1, 1, 1).expect("replicated topology")),
        residency: request.residency,
        state: SelectedStateRealization {
            floating_dtype,
            layout: requirements.state_layout.clone(),
            access: requirements.state_access,
            policy: request.state.clone(),
            components: state_components,
            checkpoint: true,
            rollback: true,
            reset: true,
            prompt_cache: request.prompt_cache,
            observation_retention: request.session.output_observation()
                || request.session.activation_inspection(),
        },
        parameters,
        materialization_tasks: Vec::new(),
        auxiliary_parameters,
        auxiliary_materialization_tasks: Vec::new(),
        session: request.session,
        prompt_cache: request.prompt_cache,
        exact_completion: request.exact_completion,
        grouped_operations: requirements.grouped_operations.clone(),
    };
    selected.materialization_tasks = build_replicated_text_materialization_tasks(&selected)
        .map_err(|error| ReplicatedTextSelectionError {
            issues: vec![error.to_string()],
        })?;
    selected.auxiliary_materialization_tasks = build_materialization_tasks(
        selected.requirements(),
        selected.requirements().auxiliary_parameters(),
        &selected.auxiliary_parameters,
    )
    .map_err(|error| ReplicatedTextSelectionError {
        issues: vec![error.to_string()],
    })?;
    Ok(selected)
}

pub(crate) fn placement_is_compatible(
    component: &StateComponentPolicy,
    policy: &CacheResidencyPolicy,
    placement: StateComponentPlacement,
) -> bool {
    use eredu_core::cache::StateResidencyClass;

    let expected = match (policy, component.residency()) {
        (CacheResidencyPolicy::Device, _) => StateComponentPlacement::Device,
        (CacheResidencyPolicy::Paged(_), StateResidencyClass::SealablePaged) => {
            StateComponentPlacement::Paged
        }
        (
            CacheResidencyPolicy::Paged(_),
            StateResidencyClass::AlwaysDeviceMutable | StateResidencyClass::LayerScopedOffloadable,
        ) => StateComponentPlacement::Device,
    };
    placement == expected
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ArchitectureGroupKind, ArchitectureGroupPlacement, ArchitectureGroupTransport,
        ArchitectureMergeDestination, ArchitectureParameterDescription, ArchitecturePartition,
        ArchitectureStatePartitionPlan, ArchitectureStatePartitionRule, DenseDiskStreamLoadOptions,
        ExecutionGroupSpec, ExecutionUnitLayout, LayerwiseLoadOptions, MemberSharding,
        NoAuxiliaryBoundarySchema, OwnedParameterGroupSpec, ParameterGroupSpec,
        ParameterMemberSpec, ParameterRole, PartitionOwnership, StateLayout,
    };
    use eredu_checkpoint::{AffineQuantization, StoredDtype};
    use eredu_core::{
        cache::{
            LayerCachePolicy, MutableStateResidency, StateTensorDimension, StateTensorDtype,
            StateTensorPolicy, StateTensorRole,
        },
        AttentionPolicy, LayerSchedule,
    };

    fn paged_state() -> CacheResidencyPolicy {
        CacheResidencyPolicy::Paged(
            crate::PagedCacheOptions::new(4, 1 << 20, 1 << 20, 1)
                .unwrap()
                .with_full_attention(true),
        )
    }

    fn physical_source(name: &str) -> ReplicatedTextPhysicalSource {
        ReplicatedTextPhysicalSource::new(
            name,
            name,
            "/checkpoint/model.safetensors",
            name,
            SourceTensorEncoding::Safetensors(StoredDtype::F16),
            2,
        )
        .unwrap()
    }

    fn requirements() -> ReplicatedTextRequirements {
        let graph =
            ExecutionGraph::new(vec![ExecutionGroupSpec::root("decoder")], "decoder").unwrap();
        let execution_units = ExecutionUnitLayout::new(&graph, [1]).unwrap();
        ReplicatedTextRequirements::new(
            "test.replicated-text",
            NeuralOperatorCapabilities::EXP,
            graph,
            execution_units,
            vec![ArchitectureGroupTransport {
                placement: ArchitectureGroupPlacement::Pipeline,
                kind: ArchitectureGroupKind::Decoder,
                first_owner_static_roles: vec!["embedding".into()],
                last_owner_static_roles: vec!["output".into()],
                merge_destination: ArchitectureMergeDestination::LastOwner,
                parallel_subgroup: None,
                request_optional: false,
            }],
            StateLayout::new(
                LayerSchedule::new(
                    1,
                    vec![LayerCachePolicy::key_value(AttentionPolicy::Full, 1, 8).unwrap()],
                )
                .unwrap(),
            )
            .unwrap(),
            ReplicatedTextStateAccess::KeyValue,
            vec![
                ReplicatedTextParameterRequirement::new(
                    "model.layers.0.mlp.weight",
                    vec!["blk.0.ffn.weight".into()],
                    vec![physical_source("blk.0.ffn.weight")],
                    Vec::new(),
                    Some(SourceTensorEncoding::Safetensors(StoredDtype::F16)),
                    Some(vec![64, 64]),
                    vec![64, 64],
                    LinearFormat::Dense,
                    ReplicatedTextParameterRole::LinearWeight,
                    ReplicatedTextParameterOwner::ExecutionUnit {
                        group: "decoder".into(),
                        unit: 0,
                    },
                    ReplicatedTextParameterPresence::Required,
                    ParameterTransformConstraint::Linear { packed_axis: 1 },
                )
                .and_then(|requirement| {
                    requirement.with_transform_companions(
                        "model.layers.0.mlp.scales",
                        "model.layers.0.mlp.biases",
                    )
                })
                .unwrap(),
                ReplicatedTextParameterRequirement::new(
                    "model.layers.0.mlp.bias",
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    None,
                    None,
                    vec![64],
                    LinearFormat::Dense,
                    ReplicatedTextParameterRole::LinearBias,
                    ReplicatedTextParameterOwner::ExecutionUnit {
                        group: "decoder".into(),
                        unit: 0,
                    },
                    ReplicatedTextParameterPresence::OptionalAbsent,
                    ParameterTransformConstraint::None,
                )
                .unwrap(),
                ReplicatedTextParameterRequirement::new(
                    "model.layers.0.norm.weight",
                    vec!["blk.0.norm.weight".into()],
                    vec![physical_source("blk.0.norm.weight")],
                    Vec::new(),
                    Some(SourceTensorEncoding::Safetensors(StoredDtype::F16)),
                    Some(vec![64]),
                    vec![64],
                    LinearFormat::Dense,
                    ReplicatedTextParameterRole::Normalization,
                    ReplicatedTextParameterOwner::ExecutionUnit {
                        group: "decoder".into(),
                        unit: 0,
                    },
                    ReplicatedTextParameterPresence::Required,
                    ParameterTransformConstraint::None,
                )
                .unwrap(),
            ],
        )
        .unwrap()
        .with_floating_state_source(TensorDtype::F16)
    }

    #[test]
    fn requirements_reject_unit_layout_from_an_equally_sized_different_graph() {
        let baseline = requirements();
        let other_graph =
            ExecutionGraph::new(vec![ExecutionGroupSpec::root("mutated")], "mutated").unwrap();
        let other_layout = ExecutionUnitLayout::new(&other_graph, [1]).unwrap();
        let error = ReplicatedTextRequirements::new(
            baseline.architecture_identity.clone(),
            baseline.operators,
            baseline.execution_graph.clone(),
            other_layout,
            baseline.group_transports.clone(),
            baseline.state_layout.clone(),
            baseline.state_access,
            baseline.parameters.clone(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("layout group identities differ"));
    }

    #[test]
    fn parameter_requirement_preserves_every_admitted_alias() {
        let requirement = ReplicatedTextParameterRequirement::new(
            "model.layers.0.mlp.weight",
            vec!["released.layers.0.mlp.weight".into()],
            vec![physical_source("released.layers.0.mlp.weight")],
            vec![
                "legacy.layers.0.mlp.weight".into(),
                "vendor.layers.0.mlp.weight".into(),
            ],
            Some(SourceTensorEncoding::Safetensors(StoredDtype::F16)),
            Some(vec![64, 64]),
            vec![64, 64],
            LinearFormat::Dense,
            ReplicatedTextParameterRole::LinearWeight,
            ReplicatedTextParameterOwner::ExecutionUnit {
                group: "decoder".into(),
                unit: 0,
            },
            ReplicatedTextParameterPresence::Required,
            ParameterTransformConstraint::Linear { packed_axis: 1 },
        )
        .unwrap();

        assert_eq!(
            requirement.aliases(),
            ["legacy.layers.0.mlp.weight", "vendor.layers.0.mlp.weight"]
        );
        assert_eq!(requirement.sources(), ["released.layers.0.mlp.weight"]);

        let absent_bias = ReplicatedTextParameterRequirement::new(
            "model.layers.0.mlp.bias",
            Vec::new(),
            Vec::new(),
            vec!["released.layers.0.mlp.bias".into()],
            None,
            None,
            vec![64],
            LinearFormat::Dense,
            ReplicatedTextParameterRole::LinearBias,
            ReplicatedTextParameterOwner::ExecutionUnit {
                group: "decoder".into(),
                unit: 0,
            },
            ReplicatedTextParameterPresence::OptionalAbsent,
            ParameterTransformConstraint::None,
        )
        .unwrap();
        assert_eq!(
            absent_bias.presence(),
            &ReplicatedTextParameterPresence::OptionalAbsent
        );
        assert!(absent_bias.sources().is_empty());
        assert_eq!(
            absent_bias.transform_constraint(),
            ParameterTransformConstraint::None
        );
    }

    #[test]
    fn scalar_parameter_requirement_preserves_rank_zero_geometry() {
        let requirement = ReplicatedTextParameterRequirement::new(
            "model.audio_tower.input_max",
            vec!["model.audio_tower.input_max".into()],
            vec![physical_source("model.audio_tower.input_max")],
            Vec::new(),
            Some(SourceTensorEncoding::Safetensors(StoredDtype::F32)),
            Some(Vec::new()),
            Vec::new(),
            LinearFormat::Dense,
            ReplicatedTextParameterRole::Other,
            ReplicatedTextParameterOwner::StaticRole("audio".into()),
            ReplicatedTextParameterPresence::Required,
            ParameterTransformConstraint::None,
        )
        .unwrap();

        let descriptor = requirement
            .lowering_descriptor(LinearFormat::Dense)
            .unwrap();
        assert!(descriptor.physical_shape().is_empty());
        assert!(descriptor.logical_shape().is_empty());
        assert_eq!(descriptor.packed_axis(), None);
    }

    #[test]
    fn physical_provenance_distinguishes_outputs_from_one_sharded_tensor() {
        let shard = "/checkpoint/model-00002-of-00003.gguf";
        let weight = ReplicatedTextPhysicalSource::new(
            "model.layers.0.gate_proj.weight",
            "blk.0.ffn_gate.weight",
            shard,
            "blk.0.ffn_gate.weight",
            SourceTensorEncoding::Safetensors(StoredDtype::F16),
            2,
        )
        .unwrap();
        let scales = ReplicatedTextPhysicalSource::new(
            "model.layers.0.gate_proj.scales",
            "blk.0.ffn_gate.weight",
            shard,
            "blk.0.ffn_gate.scales",
            SourceTensorEncoding::Safetensors(StoredDtype::F16),
            2,
        )
        .unwrap();
        assert_eq!(weight.tensor(), scales.tensor());
        assert_eq!(weight.shard(), scales.shard());
        assert_ne!(weight.output(), scales.output());
    }

    fn capabilities() -> BackendMechanismCapabilities {
        let source = SourceTensorEncoding::Safetensors(StoredDtype::F16);
        let requirements = requirements();
        let state = StateMechanismCapabilities::new(
            (0..requirements.state_layout().len()).flat_map(|layer| {
                requirements
                    .state_layout()
                    .components(layer)
                    .unwrap()
                    .iter()
                    .cloned()
                    .map(move |component| {
                        let paged = match component.role() {
                            eredu_core::cache::StateComponentRole::AttentionKeys
                            | eredu_core::cache::StateComponentRole::AttentionValues
                            | eredu_core::cache::StateComponentRole::CompressedLatent
                            | eredu_core::cache::StateComponentRole::RotaryKeys => {
                                StateComponentPlacement::Paged
                            }
                            eredu_core::cache::StateComponentRole::Fixed(_) => {
                                StateComponentPlacement::Device
                            }
                        };
                        StateComponentMechanism::new(
                            layer,
                            component,
                            Some(StateComponentPlacement::Device),
                            Some(paged),
                        )
                    })
            }),
        )
        .with_floating_state_dtype(TensorDtype::F16, StateStorageDtype::F16)
        .with_transactions(true, true)
        .with_reset(true)
        .with_prompt_cache(true)
        .with_observation_retention(true);
        BackendMechanismCapabilities::new(
            NeuralOperatorCapabilities::EXP,
            vec![
                WeightLoweringCapability::new(
                    WeightLoweringDescriptor::new(
                        source.clone(),
                        LinearFormat::Dense,
                        vec![64, 64],
                        vec![64, 64],
                        Some(1),
                    )
                    .unwrap(),
                    WeightLoweringKind::Direct,
                ),
                WeightLoweringCapability::new(
                    WeightLoweringDescriptor::new(
                        source,
                        LinearFormat::Affine(AffineQuantization::new(64, 4).unwrap()),
                        vec![64, 64],
                        vec![64, 64],
                        Some(1),
                    )
                    .unwrap(),
                    WeightLoweringKind::Transform,
                ),
                WeightLoweringCapability::new(
                    WeightLoweringDescriptor::new(
                        SourceTensorEncoding::Safetensors(StoredDtype::F16),
                        LinearFormat::Dense,
                        vec![64],
                        vec![64],
                        None,
                    )
                    .unwrap(),
                    WeightLoweringKind::Direct,
                ),
            ],
            vec![
                WeightResidencyMechanism::Resident,
                WeightResidencyMechanism::Windowed,
                WeightResidencyMechanism::DiskStreamed,
            ],
            state,
        )
        .with_session(SessionCapabilities::new(true, true, true))
        .with_prompt_cache(true)
        .with_exact_completion(true)
    }

    fn request(residency: LayerWeightResidency) -> ReplicatedTextSelectionRequest {
        ReplicatedTextSelectionRequest::new(residency, paged_state())
            .with_session(SessionCapabilities::new(true, true, true))
            .with_prompt_cache(true)
            .with_exact_completion(true)
    }

    #[test]
    fn complete_requirements_are_invariant_across_all_caller_policy_dimensions() {
        let baseline = requirements();
        let disk = DenseDiskStreamLoadOptions::new(4096, 8192, 2, 1).unwrap();
        let requests = [
            ReplicatedTextSelectionRequest::new(
                LayerWeightResidency::FullyResident,
                CacheResidencyPolicy::Device,
            ),
            ReplicatedTextSelectionRequest::new(
                LayerWeightResidency::LayerwiseHost(LayerwiseLoadOptions::default()),
                paged_state(),
            )
            .with_topology(ParallelTopology::new(2, 1, 1, 1).unwrap())
            .with_quantization(QuantizationRequest::Affine {
                group_size: 64,
                bits: 4,
            })
            .with_session(SessionCapabilities::new(true, true, true))
            .with_prompt_cache(true)
            .with_exact_completion(true),
            ReplicatedTextSelectionRequest::new(
                LayerWeightResidency::DenseDiskStream(disk),
                CacheResidencyPolicy::Device,
            )
            .with_quantization(QuantizationRequest::MxFp4),
        ];

        for _request in &requests {
            assert_eq!(requirements(), baseline);
        }
        assert_eq!(requests[0].state(), &CacheResidencyPolicy::Device);
        assert!(matches!(
            requests[1].residency(),
            LayerWeightResidency::LayerwiseHost(_)
        ));
        assert_eq!(requests[1].topology().unwrap().tensor(), 2);
        assert_eq!(
            requests[1].quantization(),
            Some(QuantizationRequest::Affine {
                group_size: 64,
                bits: 4,
            })
        );
        assert!(requests[1].prompt_cache());
        assert!(requests[1].exact_completion());
        assert!(requests[1].session().activation_inspection());
        assert_eq!(
            requests[2].residency(),
            LayerWeightResidency::DenseDiskStream(disk)
        );
        assert_eq!(requests[2].quantization(), Some(QuantizationRequest::MxFp4));
    }

    #[test]
    fn partitioned_tasks_keep_encoded_companions_atomic_and_reject_split_groups() {
        let request = request(LayerWeightResidency::FullyResident).with_quantization(
            QuantizationRequest::Affine {
                group_size: 64,
                bits: 4,
            },
        );
        let selected =
            select_replicated_text_realization(&requirements(), &request, &capabilities()).unwrap();
        let graph = selected.requirements().execution_graph().clone();
        let layout = selected.requirements().execution_units().clone();
        let format = eredu_nn::LinearFormatSpec::affine(
            LinearFormat::Affine(AffineQuantization::new(64, 4).unwrap()),
            eredu_nn::ParameterSpec::trainable("model.layers.0.mlp.scales").unwrap(),
            eredu_nn::ParameterSpec::trainable("model.layers.0.mlp.biases").unwrap(),
        )
        .unwrap();
        let [physical] = crate::expand_linear_format_parameter_groups(
            vec![ParameterGroupSpec::new(
                "mlp",
                ParameterRole::FeedForwardIntermediate,
                [ParameterMemberSpec::new(
                    "model.layers.0.mlp.weight",
                    vec![64, 64],
                    MemberSharding::Replicated,
                )],
            )
            .unwrap()],
            |_| Ok(Some(format.clone())),
        )
        .unwrap()
        .try_into()
        .unwrap();
        let norm = ParameterGroupSpec::new(
            "norm",
            ParameterRole::Replicated,
            [ParameterMemberSpec::new(
                "model.layers.0.norm.weight",
                vec![64],
                MemberSharding::Replicated,
            )],
        )
        .unwrap();
        let owner = ParameterGroupOwner::execution_unit(layout.group_id(0).unwrap().clone(), 0);
        let description = ArchitectureParameterDescription::new(
            &graph,
            &layout,
            [physical.clone(), norm.clone()],
            [
                OwnedParameterGroupSpec::new(owner.clone(), physical.clone()),
                OwnedParameterGroupSpec::new(owner.clone(), norm.clone()),
            ],
        )
        .unwrap();
        let ownership =
            PartitionOwnership::new(false, false, std::iter::empty::<String>()).unwrap();
        let state = selected.requirements().state_layout();
        let state_plan =
            ArchitectureStatePartitionPlan::new([ArchitectureStatePartitionRule::group_units(
                0,
                0..state.len(),
            )]);
        let partition = ArchitecturePartition::from_description(
            &description,
            [(layout.group_id(0).unwrap().as_str(), 0..1)],
            ownership.clone(),
            state,
            &state_plan,
            (),
            NoAuxiliaryBoundarySchema::new(64),
        )
        .unwrap();
        let tasks =
            partitioned_replicated_text_materialization_tasks(&selected, &description, &partition)
                .unwrap();
        let task = tasks
            .iter()
            .find(|task| task.name() == "model.layers.0.mlp.weight")
            .unwrap();
        assert_eq!(task.output_companions().len(), 2);

        let members = physical.members();
        let primary = ParameterGroupSpec::new(
            "primary",
            ParameterRole::FeedForwardIntermediate,
            [members[0].clone()],
        )
        .unwrap();
        let companions = ParameterGroupSpec::new(
            "companions",
            ParameterRole::FeedForwardIntermediate,
            members[1..].to_vec(),
        )
        .unwrap();
        let malformed = ArchitectureParameterDescription::new(
            &graph,
            &layout,
            [primary.clone(), companions.clone(), norm.clone()],
            [
                OwnedParameterGroupSpec::new(owner.clone(), primary),
                OwnedParameterGroupSpec::new(owner.clone(), companions),
                OwnedParameterGroupSpec::new(owner, norm),
            ],
        )
        .unwrap();
        let malformed_partition = ArchitecturePartition::from_description(
            &malformed,
            [(layout.group_id(0).unwrap().as_str(), 0..1)],
            ownership,
            state,
            &state_plan,
            (),
            NoAuxiliaryBoundarySchema::new(64),
        )
        .unwrap();
        let error = partitioned_replicated_text_materialization_tasks(
            &selected,
            &malformed,
            &malformed_partition,
        )
        .unwrap_err();
        assert!(error
            .to_string()
            .contains("outside its atomic parameter group"));
    }

    #[test]
    fn partitioned_tasks_require_one_canonical_or_admitted_alias_topology_target() {
        let mut requirements = requirements();
        requirements.parameters[0].aliases = vec!["architecture.mlp.weight".into()];
        let selected = select_replicated_text_realization(
            &requirements,
            &request(LayerWeightResidency::FullyResident),
            &capabilities(),
        )
        .unwrap();
        let graph = selected.requirements().execution_graph().clone();
        let layout = selected.requirements().execution_units().clone();
        let owner = ParameterGroupOwner::execution_unit(layout.group_id(0).unwrap().clone(), 0);
        let ownership =
            PartitionOwnership::new(false, false, std::iter::empty::<String>()).unwrap();
        let state = selected.requirements().state_layout();
        let state_plan =
            ArchitectureStatePartitionPlan::new([ArchitectureStatePartitionRule::group_units(
                0,
                0..state.len(),
            )]);

        let project = |primary_targets: &[&str]| {
            let mut groups = primary_targets
                .iter()
                .enumerate()
                .map(|(index, target)| {
                    ParameterGroupSpec::new(
                        format!("mlp-{index}"),
                        ParameterRole::FeedForwardIntermediate,
                        [ParameterMemberSpec::new(
                            *target,
                            vec![64, 64],
                            MemberSharding::Replicated,
                        )],
                    )
                    .unwrap()
                })
                .collect::<Vec<_>>();
            groups.push(
                ParameterGroupSpec::new(
                    "norm",
                    ParameterRole::Replicated,
                    [ParameterMemberSpec::new(
                        "model.layers.0.norm.weight",
                        vec![64],
                        MemberSharding::Replicated,
                    )],
                )
                .unwrap(),
            );
            let description = ArchitectureParameterDescription::new(
                &graph,
                &layout,
                groups.clone(),
                groups
                    .into_iter()
                    .map(|group| OwnedParameterGroupSpec::new(owner.clone(), group)),
            )
            .unwrap();
            let partition = ArchitecturePartition::from_description(
                &description,
                [(layout.group_id(0).unwrap().as_str(), 0..1)],
                ownership.clone(),
                state,
                &state_plan,
                (),
                NoAuxiliaryBoundarySchema::new(64),
            )
            .unwrap();
            partitioned_replicated_text_materialization_tasks(&selected, &description, &partition)
        };

        let canonical = project(&["model.layers.0.mlp.weight"]).unwrap();
        assert!(canonical
            .iter()
            .any(|task| task.name() == "model.layers.0.mlp.weight"));

        let aliased = project(&["architecture.mlp.weight"]).unwrap();
        let task = aliased
            .iter()
            .find(|task| task.name() == "model.layers.0.mlp.weight")
            .unwrap();
        assert_eq!(task.aliases(), ["architecture.mlp.weight"]);

        let error = project(&["model.layers.0.mlp.weight", "architecture.mlp.weight"]).unwrap_err();
        assert!(error
            .to_string()
            .contains("resolves to 2 architecture topology targets"));
    }

    #[test]
    fn selection_is_deterministic_and_keeps_source_format_distinct() {
        let disk = DenseDiskStreamLoadOptions::new(1234, 5678, 3, 2).unwrap();
        let request = request(LayerWeightResidency::DenseDiskStream(disk)).with_quantization(
            QuantizationRequest::Affine {
                group_size: 64,
                bits: 4,
            },
        );
        let left =
            select_replicated_text_realization(&requirements(), &request, &capabilities()).unwrap();
        let right =
            select_replicated_text_realization(&requirements(), &request, &capabilities()).unwrap();
        assert_eq!(left, right);
        assert_eq!(
            left.residency(),
            LayerWeightResidency::DenseDiskStream(disk)
        );
        assert_eq!(left.state().policy(), &paged_state());
        assert_eq!(left.state().layout(), requirements().state_layout());
        assert_eq!(left.parameters().len(), 2);
        assert_eq!(requirements().parameters().len(), 3);
        assert!(matches!(
            requirements().parameters()[1].presence(),
            ReplicatedTextParameterPresence::OptionalAbsent
        ));
        assert!(matches!(
            requirements().parameters()[2].role(),
            ReplicatedTextParameterRole::Normalization
        ));
        assert_eq!(requirements().parameters()[2].logical_shape(), [64]);
        assert_eq!(
            requirements().parameters()[2].transform_constraint(),
            ParameterTransformConstraint::None
        );
        assert_eq!(
            left.parameters()[0].lowering(),
            WeightLoweringKind::Transform
        );
        assert_ne!(
            format!("{:?}", left.parameters()[0].source_encoding()),
            format!("{:?}", left.parameters()[0].executable())
        );
    }

    #[test]
    fn exact_tasks_are_the_authority_for_direct_derived_and_transform_sources() {
        use eredu_checkpoint::recipe::{DerivedWeightRecipe, RecipeDtype, RecipeMetadata};

        let direct = select_replicated_text_realization(
            &requirements(),
            &request(LayerWeightResidency::FullyResident),
            &capabilities(),
        )
        .unwrap();
        let direct_tasks = replicated_text_materialization_tasks(&direct).unwrap();
        assert_eq!(
            direct_tasks[0].source_recipe().unwrap(),
            DerivedWeightRecipe::source(
                "blk.0.ffn.weight",
                eredu_checkpoint::store::TensorSelection::Full,
            )
        );

        let recipe = DerivedWeightRecipe::source(
            "blk.0.ffn.weight",
            eredu_checkpoint::store::TensorSelection::Full,
        );
        let outputs = BTreeMap::from([(
            "model.layers.0.mlp.weight".into(),
            RecipeMetadata {
                shape: vec![64, 64],
                dtype: RecipeDtype::F16,
                byte_len: 64 * 64 * 2,
            },
        )]);
        let derived_requirements = requirements()
            .with_derived_recipes(
                BTreeMap::from([("model.layers.0.mlp.weight".into(), recipe.clone())]),
                outputs,
            )
            .unwrap();
        let derived = select_replicated_text_realization(
            &derived_requirements,
            &request(LayerWeightResidency::FullyResident),
            &capabilities(),
        )
        .unwrap();
        let derived_tasks = replicated_text_materialization_tasks(&derived).unwrap();
        assert_eq!(derived_tasks[0].lowering(), WeightLoweringKind::Derived);
        assert_eq!(derived_tasks[0].source_recipe().unwrap(), recipe);

        let transformed = select_replicated_text_realization(
            &derived_requirements,
            &request(LayerWeightResidency::FullyResident).with_quantization(
                QuantizationRequest::Affine {
                    group_size: 64,
                    bits: 4,
                },
            ),
            &capabilities(),
        )
        .unwrap();
        let transformed_tasks = replicated_text_materialization_tasks(&transformed).unwrap();
        assert_eq!(
            transformed_tasks[0].lowering(),
            WeightLoweringKind::DerivedTransform
        );
        assert_eq!(transformed_tasks[0].source_recipe().unwrap(), recipe);

        // These corruptions fail while projecting the cold exact plan; no
        // backend mechanism or checkpoint payload is available to perform work.
        let mut corrupt_direct = direct_tasks[0].clone();
        corrupt_direct.sources.push("unselected.weight".into());
        assert!(corrupt_direct.source_recipe().is_err());
        let mut corrupt_kind = derived_tasks[0].clone();
        corrupt_kind.lowering = WeightLoweringKind::Direct;
        assert!(corrupt_kind.source_recipe().is_err());
        let mut corrupt_recipe = derived_tasks[0].clone();
        corrupt_recipe.derived_recipe = Some(DerivedWeightRecipe::source(
            "unselected.weight",
            eredu_checkpoint::store::TensorSelection::Full,
        ));
        assert!(corrupt_recipe.source_recipe().is_err());

        let member_output = RecipeMetadata {
            shape: vec![64, 64],
            dtype: RecipeDtype::F16,
            byte_len: 64 * 64 * 2,
        };
        let member_recipe = direct_tasks[0].source_recipe().unwrap();
        let project = |task, selected_bytes| {
            crate::AddressableBankParameter::new(
                "weight",
                task,
                member_recipe.clone(),
                member_output.clone(),
                selected_bytes,
                None,
            )
        };
        assert!(project(direct_tasks[0].clone(), member_output.byte_len()).is_ok());
        assert!(matches!(
            project(direct_tasks[0].clone(), member_output.byte_len() - 1),
            Err(crate::AddressableBankMemberError::SelectedByteMismatch { .. })
        ));

        let mut corrupt_source = direct_tasks[0].clone();
        corrupt_source.source_encoding = SourceTensorEncoding::Safetensors(StoredDtype::F32);
        assert!(project(corrupt_source, member_output.byte_len()).is_err());
        let mut corrupt_executable = direct_tasks[0].clone();
        corrupt_executable.executable = LinearFormat::MxFp4;
        assert!(project(corrupt_executable, member_output.byte_len()).is_err());
        let mut corrupt_lowering = direct_tasks[0].clone();
        corrupt_lowering.lowering = WeightLoweringKind::Derived;
        assert!(project(corrupt_lowering, member_output.byte_len()).is_err());

        let mut exact_transform = transformed_tasks[0].clone();
        let companion_owner = crate::ParameterGroupOwner::ExecutionUnit {
            group: crate::ExecutionGroupId::new("decoder").unwrap(),
            global_unit: 0,
        };
        exact_transform
            .set_output_companions(vec![
                ReplicatedTextOutputCompanion::new(
                    "model.layers.0.mlp.weight_scales",
                    eredu_nn::LinearCompanionRole::Scale,
                    vec![64, 1],
                    companion_owner.clone(),
                )
                .unwrap(),
                ReplicatedTextOutputCompanion::new(
                    "model.layers.0.mlp.weight_biases",
                    eredu_nn::LinearCompanionRole::AffineBias,
                    vec![64, 1],
                    companion_owner,
                )
                .unwrap(),
            ])
            .unwrap();
        let transformed_bytes =
            crate::selected_addressable_parameter_bytes(&exact_transform, &member_output).unwrap();
        assert!(crate::AddressableBankParameter::new(
            "weight",
            exact_transform.clone(),
            recipe.clone(),
            member_output.clone(),
            transformed_bytes,
            Some(
                crate::QuantizationCompanionBindings::new(
                    "weight_scales",
                    Some("weight_biases".into()),
                )
                .unwrap(),
            ),
        )
        .is_ok());
        assert!(crate::AddressableBankParameter::new(
            "weight",
            exact_transform,
            recipe.clone(),
            member_output.clone(),
            transformed_bytes,
            Some(
                crate::QuantizationCompanionBindings::new(
                    "drifted_scales",
                    Some("weight_biases".into()),
                )
                .unwrap(),
            ),
        )
        .is_err());

        let mut scale_only = transformed_tasks[0].clone();
        scale_only.executable = LinearFormat::MxFp4;
        scale_only.lowering_descriptor = WeightLoweringDescriptor::new(
            scale_only.source_encoding.clone(),
            LinearFormat::MxFp4,
            scale_only.physical_shape.clone(),
            scale_only.logical_shape.clone(),
            scale_only.logical_shape.len().checked_sub(1),
        )
        .unwrap();
        scale_only
            .set_output_companions(vec![ReplicatedTextOutputCompanion::new(
                "model.layers.0.mlp.weight_scales",
                eredu_nn::LinearCompanionRole::Scale,
                vec![64, 2],
                crate::ParameterGroupOwner::ExecutionUnit {
                    group: crate::ExecutionGroupId::new("decoder").unwrap(),
                    global_unit: 0,
                },
            )
            .unwrap()])
            .unwrap();
        let scale_only_bytes =
            crate::selected_addressable_parameter_bytes(&scale_only, &member_output).unwrap();
        let scale_companions =
            crate::QuantizationCompanionBindings::new("weight_scales", None).unwrap();
        assert!(crate::AddressableBankParameter::new(
            "weight",
            scale_only.clone(),
            recipe.clone(),
            member_output.clone(),
            scale_only_bytes,
            Some(scale_companions),
        )
        .is_ok());
        let invented_bias = crate::QuantizationCompanionBindings::new(
            "weight_scales",
            Some("invented_bias".into()),
        )
        .unwrap();
        assert!(crate::AddressableBankParameter::new(
            "weight",
            scale_only,
            recipe,
            member_output,
            scale_only_bytes,
            Some(invented_bias),
        )
        .is_err());
    }

    #[test]
    fn selection_reports_all_missing_mechanisms_together() {
        let capabilities = BackendMechanismCapabilities::new(
            NeuralOperatorCapabilities::NONE,
            Vec::new(),
            Vec::new(),
            StateMechanismCapabilities::new(Vec::new()),
        );
        let error = select_replicated_text_realization(
            &requirements(),
            &request(LayerWeightResidency::LayerwiseHost(
                LayerwiseLoadOptions::default(),
            )),
            &capabilities,
        )
        .unwrap_err();
        assert!(error.issues().len() >= 7, "{:?}", error.issues());
        assert!(error.issues().iter().any(|issue| issue.contains("exp")));
        assert!(error
            .issues()
            .iter()
            .any(|issue| issue.contains("weight lowering")));
    }

    #[test]
    fn selection_rejects_paged_fixed_component_placement_even_when_reported() {
        let fixed = StateTensorPolicy::new(
            StateTensorRole::Recurrent,
            vec![
                StateTensorDimension::Batch,
                StateTensorDimension::fixed(8).unwrap(),
            ],
            StateTensorDtype::Float32,
            MutableStateResidency::LayerScopedOffloadable,
        )
        .unwrap();
        let mut requirements = requirements();
        requirements.state_layout = StateLayout::new(
            LayerSchedule::new(
                1,
                vec![LayerCachePolicy::key_value_with_fixed_state(
                    AttentionPolicy::Full,
                    1,
                    8,
                    vec![fixed],
                )
                .unwrap()],
            )
            .unwrap(),
        )
        .unwrap();
        requirements.state_access = ReplicatedTextStateAccess::AttentionWithFixed;
        let mut capabilities = capabilities();
        capabilities.state.components = (0..requirements.state_layout.len())
            .flat_map(|layer| {
                requirements
                    .state_layout
                    .components(layer)
                    .unwrap()
                    .iter()
                    .cloned()
                    .map(move |component| {
                        StateComponentMechanism::new(
                            layer,
                            component,
                            Some(StateComponentPlacement::Device),
                            Some(StateComponentPlacement::Paged),
                        )
                    })
            })
            .collect();

        let error = select_replicated_text_realization(
            &requirements,
            &request(LayerWeightResidency::FullyResident),
            &capabilities,
        )
        .unwrap_err();
        assert!(error
            .issues()
            .iter()
            .any(|issue| issue.contains("incompatible Paged placement")));
    }

    #[test]
    fn requirements_reject_state_layout_and_access_profile_mismatch() {
        let fixed = StateTensorPolicy::new(
            StateTensorRole::Recurrent,
            vec![
                StateTensorDimension::Batch,
                StateTensorDimension::fixed(8).unwrap(),
            ],
            StateTensorDtype::Float32,
            MutableStateResidency::LayerScopedOffloadable,
        )
        .unwrap();
        let layout = StateLayout::new(
            LayerSchedule::new(
                1,
                vec![LayerCachePolicy::key_value_with_fixed_state(
                    AttentionPolicy::Full,
                    1,
                    8,
                    vec![fixed],
                )
                .unwrap()],
            )
            .unwrap(),
        )
        .unwrap();
        let base = requirements();
        let error = ReplicatedTextRequirements::new(
            base.architecture_identity,
            base.operators,
            base.execution_graph,
            base.execution_units,
            base.group_transports,
            layout,
            ReplicatedTextStateAccess::KeyValue,
            base.parameters,
        )
        .unwrap_err();
        assert!(error.message().contains("does not match component roles"));
    }

    #[test]
    fn transform_selection_rejects_incompatible_exact_geometry() {
        for quantization in [
            QuantizationRequest::Affine {
                group_size: 96,
                bits: 4,
            },
            QuantizationRequest::Affine {
                group_size: 256,
                bits: 4,
            },
            QuantizationRequest::Affine {
                group_size: 0,
                bits: 4,
            },
            QuantizationRequest::Affine {
                group_size: u32::MAX,
                bits: 4,
            },
            QuantizationRequest::Affine {
                group_size: 32,
                bits: 0,
            },
            QuantizationRequest::Affine {
                group_size: 32,
                bits: 7,
            },
        ] {
            let error = select_replicated_text_realization(
                &requirements(),
                &request(LayerWeightResidency::FullyResident).with_quantization(quantization),
                &capabilities(),
            )
            .unwrap_err();
            assert!(error
                .issues()
                .iter()
                .any(|issue| issue.contains("invalid replicated text contract")));
        }

        let mut indivisible = requirements();
        indivisible.parameters[0].logical_shape = vec![64, 48];
        let error = select_replicated_text_realization(
            &indivisible,
            &request(LayerWeightResidency::FullyResident)
                .with_quantization(QuantizationRequest::MxFp4),
            &capabilities(),
        )
        .unwrap_err();
        assert!(error
            .issues()
            .iter()
            .any(|issue| issue.contains("MXFP4 packed extent 48")));
    }

    #[test]
    fn exact_source_and_physical_geometry_fail_before_construction_or_payload() {
        for mutate in [
            |requirement: &mut ReplicatedTextParameterRequirement| {
                requirement.source_encoding =
                    Some(SourceTensorEncoding::Safetensors(StoredDtype::U8));
            },
            |requirement: &mut ReplicatedTextParameterRequirement| {
                requirement.physical_shape = Some(vec![64, 32]);
            },
        ] {
            let mut requirements = requirements();
            mutate(&mut requirements.parameters[0]);
            let selected = select_replicated_text_realization(
                &requirements,
                &request(LayerWeightResidency::FullyResident),
                &capabilities(),
            );
            let error = selected.unwrap_err();
            assert!(error
                .issues()
                .iter()
                .any(|issue| issue.contains("weight lowering")));
        }
    }

    #[test]
    fn missing_tensor_parallel_grouped_partial_fails_before_construction_or_forward() {
        let requirements = requirements().with_grouped_operations([
            GroupedOperationRequirement::GatedProduct,
            GroupedOperationRequirement::GatedProductTensorParallelPartial,
        ]);
        let capabilities =
            capabilities().with_grouped_operations([GroupedOperationRequirement::GatedProduct]);
        let selected = select_replicated_text_realization(
            &requirements,
            &request(LayerWeightResidency::FullyResident),
            &capabilities,
        );
        let error = selected.unwrap_err();
        assert!(error
            .issues()
            .iter()
            .any(|issue| { issue.contains("GatedProductTensorParallelPartial") }));
    }
}