KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
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
//! Narrow public fixed-`P,T` phase-equilibrium workflow.
//!
//! This facade owns orchestration only: it joins validated resolved data,
//! physical inventory, numerical settings, bridge construction, and immutable
//! result publication. It does not duplicate residual construction or expose
//! the historical mutable solver as an alternative public engine.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use crate::Thermodynamics::ChemEquilibrium::equilibrium_candidate_selection::{
    ElementInventoryCandidateSelection, EquilibriumCandidatePhasePlan,
    EquilibriumCandidateSelectionReport,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_constant_validation::EquilibriumConstantValidationMode;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_diagnostics::{
    EquilibriumDiagnosticEvent, EquilibriumDiagnosticsCollector, EquilibriumDiagnosticsMode,
    EquilibriumDiagnosticsOptions,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventory;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_execution::{
    EquilibriumExecutionControl, EquilibriumProgressEvent, EquilibriumProgressStage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_extensive_normalization::ExtensiveNormalization;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::EquilibriumInstrumentationMode;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::{
    EquilibriumSolverSettings, Solvers,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::{
    MultiphaseEquilibriumLayout, MultiphaseInitialComposition,
};
#[cfg(test)]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
    BackendFailureKind, SolveError,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
    ReactionExtentError, ReactionExtentErrorKind,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
    EquilibriumConditions, LogMolesInitialGuess, TraceSpeciesSeedPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
    SolverBackend, SolverCascadeBudget, SolverPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_temperature_range::{
    TemperatureGrid, TemperatureRangeBestEffortOutcome, TemperatureRangeRequest,
    TemperatureRangeSolution,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::{
    EquilibriumTimingMode, EquilibriumTimingReport, EquilibriumTimingStage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{
    InitialPhaseSet, PhaseManager, PhaseSet,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::{
    PhaseEquilibriumBuildRequest, PhaseEquilibriumProblemBundle, SupportedPhaseModelPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_solution::MultiphaseEquilibriumSolution;
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_solution::{
    ExtensiveNormalizationRecoveryEvidence, ExtensiveNormalizationTrigger,
};
use crate::Thermodynamics::User_PhaseOrSolution::{
    ResolvedPhaseSystem, ResolvedPhaseSystemReport, SubstanceSystemFactory,
    SubstanceSystemFactoryError, SubstanceSystemSpec,
};
use crate::Thermodynamics::phase_layout::PhaseComponentId;
use crate::Thermodynamics::thermo_lib_api::ThermoRepository;

/// Current solve mode exposed by the typed public facade.
///
/// Fixed declared phases and bounded phase control share the same resolved
/// data bridge and immutable result model. The mutable solver is only the
/// retained compatibility implementation; bounded mode uses the prepared
/// immutable runner and callers do not receive an alternative mutable
/// production API.
#[derive(Debug, Clone)]
pub enum PhaseEquilibriumSolveMode {
    /// Solve all declared phases as one immutable fixed active set.
    FixedDeclaredPhases,
    /// Run the bounded active-set phase-control algorithm with an explicit
    /// hysteresis and initial-phase policy.
    BoundedPhaseControl(PhaseControlPolicy),
}

impl Default for PhaseEquilibriumSolveMode {
    fn default() -> Self {
        Self::FixedDeclaredPhases
    }
}

impl PhaseEquilibriumSolveMode {
    /// Explicit safe default for the canonical production path.
    pub fn fixed_declared_phases() -> Self {
        Self::FixedDeclaredPhases
    }

    /// Explicit constructor for bounded phase-control mode.
    pub fn bounded_phase_control(policy: PhaseControlPolicy) -> Self {
        Self::BoundedPhaseControl(policy)
    }
}

/// Policy for recovering a numerically ill-conditioned extensive inventory.
///
/// Recovery never changes the published physical problem. It first solves one
/// exactly normalized equivalent and then prefers a physical-coordinate retry.
/// If that retry remains ill-conditioned, the accepted normalized snapshot is
/// passed through the audited physical publication boundary; provenance says
/// explicitly which route produced the public result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExtensiveNormalizationPolicy {
    /// Do not attempt extensive-coordinate recovery.
    Disabled,
    /// Retry only after a classified numerical failure of the physical solve.
    OnNumericalFailure,
    /// Also precondition P,H requests whose physical inventory scale is below
    /// one mole before attempting the physical-coordinate route.
    OnNumericalFailureAndSmallScalePhPreconditioning,
}

impl ExtensiveNormalizationPolicy {
    pub const fn allows_numerical_failure_recovery(self) -> bool {
        matches!(
            self,
            Self::OnNumericalFailure | Self::OnNumericalFailureAndSmallScalePhPreconditioning
        )
    }

    pub const fn allows_small_scale_ph_preconditioning(self) -> bool {
        matches!(self, Self::OnNumericalFailureAndSmallScalePhPreconditioning)
    }
}

impl Default for ExtensiveNormalizationPolicy {
    fn default() -> Self {
        Self::OnNumericalFailureAndSmallScalePhPreconditioning
    }
}

/// Narrow validated wrapper for solver policy knobs exposed at the facade boundary.
///
/// The inner `EquilibriumSolverSettings` still exists as the canonical backend
/// structure, but production callers should interact with this wrapper so the
/// public workflow can evolve without exposing every internal field.
#[derive(Clone)]
pub struct EquilibriumSolveOptions {
    settings: EquilibriumSolverSettings,
    timing_mode: EquilibriumTimingMode,
    instrumentation_mode: EquilibriumInstrumentationMode,
    diagnostics: EquilibriumDiagnosticsOptions,
    execution_control: Option<EquilibriumExecutionControl>,
    extensive_normalization: ExtensiveNormalizationPolicy,
}

/// Serializable, read-only record of effective numerical controls.
///
/// This deliberately records the resolved backend order rather than only the
/// caller's optional `SolverPolicy`: an absent explicit policy still expands
/// to the production cascade at solve time. It excludes the live execution
/// handle because cancellation/progress callbacks are process-local, not part
/// of a reproducible numerical contract.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EquilibriumSolveOptionsSnapshot {
    pub preferred_native_backend: String,
    #[serde(default)]
    pub rst_symbolic_frontend: String,
    pub effective_backend_order: Vec<String>,
    pub max_iterations: usize,
    pub tolerance: f64,
    pub scaling_enabled: bool,
    pub trace_seed_policy: String,
    pub continuation_seed_policy: String,
    pub equilibrium_constant_validation_mode: String,
    pub timing_mode: String,
    pub instrumentation_mode: String,
    pub diagnostics_mode: String,
    pub diagnostics_max_events: usize,
    pub diagnostics_range_policy: String,
    pub solver_budget: Option<EquilibriumSolverBudgetSnapshot>,
    pub execution_control_attached: bool,
    pub extensive_normalization_policy: String,
}

/// Serializable resource limits attached to a solver-cascade snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct EquilibriumSolverBudgetSnapshot {
    pub max_attempts: usize,
    pub max_iterations_per_attempt: usize,
    pub max_total_iterations: usize,
}

impl fmt::Debug for EquilibriumSolveOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EquilibriumSolveOptions")
            .finish_non_exhaustive()
    }
}

impl Default for EquilibriumSolveOptions {
    fn default() -> Self {
        Self {
            settings: EquilibriumSolverSettings::default(),
            timing_mode: EquilibriumTimingMode::default(),
            instrumentation_mode: EquilibriumInstrumentationMode::default(),
            diagnostics: EquilibriumDiagnosticsOptions::default(),
            execution_control: None,
            extensive_normalization: ExtensiveNormalizationPolicy::default(),
        }
    }
}

impl EquilibriumSolveOptions {
    /// Creates one wrapper around validated backend solver settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Wraps an existing backend settings value after validating it.
    #[cfg(test)]
    pub(crate) fn from_settings(
        settings: EquilibriumSolverSettings,
    ) -> Result<Self, ReactionExtentError> {
        settings.validate()?;
        Ok(Self {
            settings,
            timing_mode: EquilibriumTimingMode::default(),
            instrumentation_mode: EquilibriumInstrumentationMode::default(),
            diagnostics: EquilibriumDiagnosticsOptions::default(),
            execution_control: None,
            extensive_normalization: ExtensiveNormalizationPolicy::default(),
        })
    }

    /// Consumes the wrapper for the crate-internal immutable runner.
    pub(crate) fn into_settings(self) -> EquilibriumSolverSettings {
        let mut settings = self.settings;
        settings.execution_control = self.execution_control;
        settings
    }

    /// Installs cooperative cancellation and progress reporting for this
    /// transaction. The handle is shared with the worker-facing caller.
    pub fn with_execution_control(mut self, control: EquilibriumExecutionControl) -> Self {
        self.execution_control = Some(control);
        self
    }

    /// Selects whether a classified extensive-conditioning failure may use
    /// normalized basin discovery and the audited physical publication path.
    pub fn with_extensive_normalization_policy(
        mut self,
        policy: ExtensiveNormalizationPolicy,
    ) -> Self {
        self.extensive_normalization = policy;
        self
    }

    /// Returns the extensive-conditioning recovery policy.
    pub fn extensive_normalization_policy(&self) -> ExtensiveNormalizationPolicy {
        self.extensive_normalization
    }

    /// Returns the execution handle, if this request is externally controlled.
    pub fn execution_control(&self) -> Option<&EquilibriumExecutionControl> {
        self.execution_control.as_ref()
    }

    /// Uses the standard RST-first production cascade with the configured
    /// native backend family retained as a fallback.
    pub fn with_production_cascade(mut self) -> Self {
        self.settings.solver_policy = Some(SolverPolicy::production_default(self.settings.solver));
        self
    }

    /// Changes the nonlinear iteration budget without exposing raw settings.
    pub fn with_max_iterations(mut self, max_iter: usize) -> Result<Self, ReactionExtentError> {
        self.settings.solver_params.max_iter = max_iter;
        self.settings.validate()?;
        Ok(self)
    }

    /// Installs explicit resource limits for the ordered backend cascade.
    ///
    /// The GUI and other typed frontends use this boundary instead of reaching
    /// into the historical mutable settings object. Leaving it unset keeps the
    /// policy-derived production budget intact.
    pub fn with_solver_budget(
        mut self,
        budget: SolverCascadeBudget,
    ) -> Result<Self, ReactionExtentError> {
        self.settings.solver_budget = Some(budget);
        self.settings.validate()?;
        Ok(self)
    }

    /// Changes the common residual tolerance without exposing raw settings.
    pub fn with_tolerance(mut self, tolerance: f64) -> Result<Self, ReactionExtentError> {
        self.settings.solver_params.tol = tolerance;
        self.settings.validate()?;
        Ok(self)
    }

    /// Enables or disables the canonical residual/Jacobian scaling contract.
    pub fn with_scaling(mut self, enabled: bool) -> Self {
        self.settings.scaling_flag = enabled;
        self
    }

    /// Replaces the preferred backend ordering used by the solver cascade.
    pub fn with_solver_backend(mut self, solver: Solvers) -> Self {
        self.settings.solver = solver;
        // `solver_policy` is an explicit ordered cascade and therefore wins
        // over the legacy preferred-solver field. Clear it here so this
        // convenience method cannot silently become a no-op.
        self.settings.solver_policy = None;
        self
    }

    /// Selects the symbolic frontend used when an RST backend is prepared.
    /// ExprLegacy remains the default; AtomView is an explicit opt-in.
    pub fn with_rst_symbolic_frontend(
        mut self,
        frontend: crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstSymbolicFrontend,
    ) -> Self {
        self.settings.rst_symbolic_frontend = frontend;
        self
    }

    /// Returns the RST symbolic frontend selected for this solve.
    pub fn rst_symbolic_frontend(
        &self,
    ) -> crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstSymbolicFrontend {
        self.settings.rst_symbolic_frontend
    }

    /// Installs an explicit ordered backend policy after validating it.
    pub fn with_solver_policy(mut self, policy: SolverPolicy) -> Result<Self, ReactionExtentError> {
        self.settings.solver_policy = Some(policy);
        self.settings.validate()?;
        Ok(self)
    }

    /// Replaces the policy used to seed positive log-mole coordinates.
    pub fn with_trace_seed_policy(mut self, policy: TraceSpeciesSeedPolicy) -> Self {
        self.settings.trace_seed_policy = policy;
        self
    }

    /// Returns the single trace-seed policy carried by this options bundle.
    pub fn trace_seed_policy(&self) -> TraceSpeciesSeedPolicy {
        self.settings.trace_seed_policy
    }

    /// Requests independent equilibrium-constant validation when the resolved
    /// system belongs to the validator's supported domain.
    ///
    /// This leaves the numerical solve unchanged. It only controls whether the
    /// accepted candidate carries a secondary `K_eq` comparison report, or is
    /// rejected when validation was explicitly required but unavailable.
    pub fn with_keq_validation_mode(mut self, mode: EquilibriumConstantValidationMode) -> Self {
        self.settings.keq_validation_mode = mode;
        self
    }

    /// Enables or disables stage timing in the immutable result report.
    ///
    /// Timing is off by default so ordinary production solves do not pay for
    /// repeated clock reads. Enable it for characterization and bottleneck
    /// investigations.
    pub fn with_timing_mode(mut self, mode: EquilibriumTimingMode) -> Self {
        self.timing_mode = mode;
        self
    }

    /// Enables fine-grained evaluation counters for the enclosing facade
    /// operation. The default keeps all counter hooks inactive.
    pub fn with_instrumentation_mode(mut self, mode: EquilibriumInstrumentationMode) -> Self {
        self.instrumentation_mode = mode;
        self
    }

    /// Returns the fine-grained instrumentation policy for this request.
    pub fn instrumentation_mode(&self) -> EquilibriumInstrumentationMode {
        self.instrumentation_mode
    }

    /// Enables bounded typed diagnostics for this solve transaction.
    ///
    /// Diagnostics remain observational: they never change the numerical
    /// formulation, phase-control policy, or acceptance contract.
    pub fn with_diagnostics(mut self, diagnostics: EquilibriumDiagnosticsOptions) -> Self {
        self.diagnostics = diagnostics;
        self
    }

    /// Returns the explicit diagnostics policy for this request.
    pub fn diagnostics_options(&self) -> &EquilibriumDiagnosticsOptions {
        &self.diagnostics
    }

    /// Returns the timing policy carried by this solve request.
    pub fn timing_mode(&self) -> EquilibriumTimingMode {
        self.timing_mode
    }

    /// Captures the effective immutable numerical contract for reports or
    /// reproducibility records. Calling this never changes the options or the
    /// attached execution handle.
    pub fn reproducibility_snapshot(&self) -> EquilibriumSolveOptionsSnapshot {
        let policy = self
            .settings
            .solver_policy
            .clone()
            .unwrap_or_else(|| SolverPolicy::production_default(self.settings.solver));
        EquilibriumSolveOptionsSnapshot {
            preferred_native_backend: format!("{:?}", self.settings.solver),
            rst_symbolic_frontend: format!("{:?}", self.settings.rst_symbolic_frontend),
            effective_backend_order: policy
                .ordered_backends()
                .into_iter()
                .map(|backend| format!("{backend:?}"))
                .collect(),
            max_iterations: self.settings.solver_params.max_iter,
            tolerance: self.settings.solver_params.tol,
            scaling_enabled: self.settings.scaling_flag,
            trace_seed_policy: format!("{:?}", self.settings.trace_seed_policy),
            continuation_seed_policy: format!("{:?}", self.settings.continuation_seed_policy),
            equilibrium_constant_validation_mode: format!(
                "{:?}",
                self.settings.keq_validation_mode
            ),
            timing_mode: format!("{:?}", self.timing_mode),
            instrumentation_mode: format!("{:?}", self.instrumentation_mode),
            diagnostics_mode: format!("{:?}", self.diagnostics.mode()),
            diagnostics_max_events: self.diagnostics.max_events(),
            diagnostics_range_policy: format!("{:?}", self.diagnostics.range_policy()),
            solver_budget: self.settings.solver_budget.map(|budget| {
                EquilibriumSolverBudgetSnapshot {
                    max_attempts: budget.max_attempts,
                    max_iterations_per_attempt: budget.max_iterations_per_attempt,
                    max_total_iterations: budget.max_total_iterations,
                }
            }),
            execution_control_attached: self.execution_control.is_some(),
            extensive_normalization_policy: format!("{:?}", self.extensive_normalization),
        }
    }

    /// Returns whether this policy can execute an RST symbolic backend.
    ///
    /// Resolved thermochemical problems have symbolic expressions by
    /// construction, so the implicit production policy is RST-first. The
    /// range facade uses this bit to decide whether symbolic preparation can
    /// be retained and parameter-updated across points.
    pub(crate) fn prepares_rst_backend(&self) -> bool {
        self.settings
            .solver_policy
            .as_ref()
            .map(|policy| {
                policy
                    .ordered_backends()
                    .iter()
                    .any(|backend| matches!(backend, SolverBackend::RustedSciThe(_)))
            })
            .unwrap_or(true)
    }
}

/// Narrow validated wrapper for phase-control policy exposed at the facade boundary.
///
/// The inner `PhaseManager` remains the canonical backend controller, but the
/// public workflow should traffic in this policy type so callers do not need to
/// know about mutable solver internals or historical phase-control helpers.
#[derive(Clone)]
pub struct PhaseControlPolicy {
    phase_manager: PhaseManager,
}

impl fmt::Debug for PhaseControlPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PhaseControlPolicy").finish_non_exhaustive()
    }
}

impl Default for PhaseControlPolicy {
    fn default() -> Self {
        Self {
            phase_manager: PhaseManager::default(),
        }
    }
}

impl PhaseControlPolicy {
    /// Creates one policy wrapper from the backend controller.
    pub(crate) fn new(phase_manager: PhaseManager) -> Result<Self, ReactionExtentError> {
        phase_manager.validate()?;
        Ok(Self { phase_manager })
    }

    /// Convenience constructor for explicit phase hysteresis thresholds.
    pub fn with_explicit_hysteresis(
        phase_eps: f64,
        dg_create: f64,
        dg_keep: f64,
    ) -> Result<Self, ReactionExtentError> {
        let phase_manager = PhaseManager::new(phase_eps, dg_create, dg_keep);
        Self::new(phase_manager)
    }

    /// Convenience constructor for temperature-scaled hysteresis thresholds.
    pub fn with_temperature_scaled_hysteresis(
        phase_eps: f64,
        create_rt_factor: f64,
        keep_rt_factor: f64,
    ) -> Result<Self, ReactionExtentError> {
        let phase_manager = PhaseManager::with_temperature_scaled_hysteresis(
            phase_eps,
            create_rt_factor,
            keep_rt_factor,
        );
        Self::new(phase_manager)
    }

    /// Consumes the wrapper for the crate-internal immutable phase runner.
    pub(crate) fn into_phase_manager(self) -> PhaseManager {
        self.phase_manager
    }

    /// Changes the phase destruction threshold through the typed policy.
    pub fn with_phase_epsilon(mut self, phase_eps: f64) -> Result<Self, ReactionExtentError> {
        self.phase_manager.phase_eps = phase_eps;
        self.phase_manager.validate()?;
        Ok(self)
    }

    /// Converts only the absolute phase-mole threshold for normalized space.
    ///
    /// The returned policy keeps its active-set budget, initial phase set, and
    /// intensive TPD hysteresis. Pair it with a request whose composition and
    /// other extensive inputs were normalized by the same
    /// [`ExtensiveNormalization`]. This is an explicit representation mapping,
    /// not an automatic retry or default solver route.
    pub fn normalized_for_extensive_representation(
        mut self,
        normalization: ExtensiveNormalization,
    ) -> Result<Self, ReactionExtentError> {
        self.phase_manager.phase_eps =
            normalization.normalize_physical_mole_threshold(self.phase_manager.phase_eps)?;
        self.phase_manager.validate()?;
        Ok(self)
    }

    /// Changes the bounded outer-loop budget through the typed policy.
    pub fn with_max_phase_iterations(
        mut self,
        iterations: usize,
    ) -> Result<Self, ReactionExtentError> {
        self.phase_manager.max_phase_iterations = iterations;
        self.phase_manager.validate()?;
        Ok(self)
    }

    /// Chooses the initial active-phase policy through the typed boundary.
    pub fn with_initial_phase_set(
        mut self,
        initial_phase_set: InitialPhaseSet,
    ) -> Result<Self, ReactionExtentError> {
        self.phase_manager.initial_phase_set = initial_phase_set;
        self.phase_manager.validate()?;
        Ok(self)
    }
}

/// High-level production pipeline error.
#[derive(Debug)]
pub enum PhaseEquilibriumPipelineError {
    /// The phase/specification layer rejected the requested system.
    Resolve(SubstanceSystemFactoryError),
    /// The bridge or solver rejected the resolved problem.
    Solve(ReactionExtentError),
}

impl fmt::Display for PhaseEquilibriumPipelineError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Resolve(error) => write!(f, "phase-system resolution failed: {error}"),
            Self::Solve(error) => write!(f, "phase-equilibrium solve failed: {error}"),
        }
    }
}

impl std::error::Error for PhaseEquilibriumPipelineError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Resolve(error) => Some(error),
            Self::Solve(error) => Some(error),
        }
    }
}

impl From<SubstanceSystemFactoryError> for PhaseEquilibriumPipelineError {
    fn from(value: SubstanceSystemFactoryError) -> Self {
        Self::Resolve(value)
    }
}

impl From<ReactionExtentError> for PhaseEquilibriumPipelineError {
    fn from(value: ReactionExtentError) -> Self {
        Self::Solve(value)
    }
}

#[derive(Debug, Clone)]
enum PipelineInitialComposition {
    Dense(Vec<f64>),
    Sparse(Vec<(PhaseComponentId, f64)>),
    ElementInventory(ElementInventory),
}

/// High-level one-shot request that resolves phase specs and then solves them.
///
/// The caller supplies phase declarations, lookup policy, the initial
/// composition in canonical layout order, and fixed-`P,T` solve controls. The
/// builder performs resolve -> build -> solve as one transactional pipeline.
#[derive(Clone)]
pub struct PhaseEquilibriumPipelineRequest {
    spec: SubstanceSystemSpec,
    initial_composition: PipelineInitialComposition,
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
    conditions: EquilibriumConditions,
    model_policy: SupportedPhaseModelPolicy,
    solve_options: EquilibriumSolveOptions,
    solve_mode: PhaseEquilibriumSolveMode,
    multi_start_seeds: Vec<LogMolesInitialGuess>,
    repository: Option<Arc<ThermoRepository>>,
}

impl PhaseEquilibriumPipelineRequest {
    /// Creates one pipeline request with default numerical and model policies.
    pub fn new(
        spec: SubstanceSystemSpec,
        initial_moles: Vec<f64>,
        conditions: EquilibriumConditions,
    ) -> Self {
        Self {
            spec,
            initial_composition: PipelineInitialComposition::Dense(initial_moles),
            candidate_selection: None,
            conditions,
            model_policy: SupportedPhaseModelPolicy::default(),
            solve_options: EquilibriumSolveOptions::default(),
            solve_mode: PhaseEquilibriumSolveMode::fixed_declared_phases(),
            multi_start_seeds: Vec::new(),
            repository: None,
        }
    }

    /// Creates a P,T pipeline from a closed elemental inventory and an
    /// explicit real phase/species universe.
    ///
    /// The inventory is not expanded into an artificial species. After lookup
    /// it enters the canonical bridge as `b`, while a seed is built from the
    /// resolved real components only.
    pub fn from_element_inventory(
        spec: SubstanceSystemSpec,
        element_inventory: ElementInventory,
        conditions: EquilibriumConditions,
    ) -> Self {
        Self {
            spec,
            initial_composition: PipelineInitialComposition::ElementInventory(element_inventory),
            candidate_selection: None,
            conditions,
            model_policy: SupportedPhaseModelPolicy::default(),
            solve_options: EquilibriumSolveOptions::default(),
            solve_mode: PhaseEquilibriumSolveMode::fixed_declared_phases(),
            multi_start_seeds: Vec::new(),
            repository: None,
        }
    }

    /// Creates a production pipeline from an element-search report and an
    /// explicit physical phase plan.
    ///
    /// The selection report supplies exact record keys and library
    /// provenance; the phase plan supplies the activity model.  Keeping both
    /// inputs mandatory prevents the top-level API from silently turning an
    /// arbitrary element search into an ideal-gas or condensed calculation.
    pub fn from_candidate_selection(
        repository: Arc<ThermoRepository>,
        selection: &EquilibriumCandidateSelectionReport,
        phase_plan: &EquilibriumCandidatePhasePlan,
        initial_moles: Vec<f64>,
        conditions: EquilibriumConditions,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        let spec = phase_plan.build_spec(selection)?;
        Ok(Self::new(spec, initial_moles, conditions)
            .with_repository(repository)
            .with_candidate_selection(selection.clone()))
    }

    /// Creates an element-defined pipeline from a deterministic catalog
    /// selection and explicit physical phase plan.
    pub fn from_candidate_selection_with_element_inventory(
        repository: Arc<ThermoRepository>,
        selection: &EquilibriumCandidateSelectionReport,
        phase_plan: &EquilibriumCandidatePhasePlan,
        element_inventory: ElementInventory,
        conditions: EquilibriumConditions,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        let spec = phase_plan.build_spec(selection)?;
        Ok(
            Self::from_element_inventory(spec, element_inventory, conditions)
                .with_repository(repository)
                .with_candidate_selection(selection.clone()),
        )
    }

    /// Creates a reproducible element-defined pipeline directly from typed
    /// selection evidence. The inventory remains the physical conservation
    /// vector; the nested report explains the selected real record universe.
    pub fn from_element_inventory_candidate_selection(
        repository: Arc<ThermoRepository>,
        selection: &ElementInventoryCandidateSelection,
        phase_plan: &EquilibriumCandidatePhasePlan,
        conditions: EquilibriumConditions,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        Self::from_candidate_selection_with_element_inventory(
            repository,
            selection.report(),
            phase_plan,
            selection.inventory().clone(),
            conditions,
        )
    }

    /// Creates a pipeline request with phase-qualified initial inventory.
    ///
    /// Unlike the dense constructor, this form does not make callers predict
    /// the post-resolution vector order. Missing declared components receive
    /// zero physical moles; duplicate or unknown component identities are
    /// rejected transactionally when the resolved layout is built.
    pub fn new_with_sparse_initial_composition(
        spec: SubstanceSystemSpec,
        entries: Vec<(PhaseComponentId, f64)>,
        conditions: EquilibriumConditions,
    ) -> Self {
        Self {
            spec,
            initial_composition: PipelineInitialComposition::Sparse(entries),
            candidate_selection: None,
            conditions,
            model_policy: SupportedPhaseModelPolicy::default(),
            solve_options: EquilibriumSolveOptions::default(),
            solve_mode: PhaseEquilibriumSolveMode::fixed_declared_phases(),
            multi_start_seeds: Vec::new(),
            repository: None,
        }
    }

    /// Uses an explicit immutable repository instead of the default search path.
    pub fn with_repository(mut self, repository: Arc<ThermoRepository>) -> Self {
        self.repository = Some(repository);
        self
    }

    /// Retains the immutable catalog-selection transaction in the eventual
    /// bridge build report.
    pub fn with_candidate_selection(
        mut self,
        selection: EquilibriumCandidateSelectionReport,
    ) -> Self {
        self.candidate_selection = Some(selection);
        self
    }

    /// Replaces only the numerical trace-coordinate policy.
    pub fn with_trace_seed_policy(mut self, policy: TraceSpeciesSeedPolicy) -> Self {
        self.solve_options = self.solve_options.with_trace_seed_policy(policy);
        self
    }

    /// Replaces only the supported physical-model policy.
    pub fn with_model_policy(mut self, policy: SupportedPhaseModelPolicy) -> Self {
        self.model_policy = policy;
        self
    }

    /// Replaces only the phase-control policy used by bounded outer loops.
    pub fn with_phase_control_policy(mut self, policy: PhaseControlPolicy) -> Self {
        self.solve_mode = PhaseEquilibriumSolveMode::BoundedPhaseControl(policy);
        self
    }

    /// Explicitly returns the request to the safe fixed-declared-phases path.
    pub fn with_fixed_declared_phases(mut self) -> Self {
        self.solve_mode = PhaseEquilibriumSolveMode::fixed_declared_phases();
        self
    }

    /// Replaces only numerical backend and acceptance settings.
    pub fn with_solve_options(mut self, options: EquilibriumSolveOptions) -> Self {
        self.solve_options = options;
        self
    }

    /// Borrows the typed numerical options so an execution handle can be
    /// attached by a frontend without exposing the request fields.
    pub fn solve_options(&self) -> &EquilibriumSolveOptions {
        &self.solve_options
    }

    /// Requests an explicit deterministic multi-start solve for fixed declared
    /// phases.
    ///
    /// Every seed must use the canonical component order of this request and
    /// contain log-moles, not ordinary mole numbers. The solver reuses the
    /// prepared formulation and publishes the per-seed comparison report. This
    /// recovery policy is intentionally unavailable for bounded phase control:
    /// retrying an entire active-set lifecycle needs its own transition policy.
    pub fn with_multi_start_seeds(mut self, seeds: Vec<LogMolesInitialGuess>) -> Self {
        self.multi_start_seeds = seeds;
        self
    }

    /// Legacy compatibility shim for callers that still select the whole mode enum directly.
    #[deprecated(note = "use with_fixed_declared_phases() or with_phase_control_policy() instead")]
    pub fn with_solve_mode(mut self, mode: PhaseEquilibriumSolveMode) -> Self {
        self.solve_mode = mode;
        self
    }

    /// Resolves phase specifications into immutable lookup data.
    pub fn resolve(self) -> Result<ResolvedPhaseSystem, PhaseEquilibriumPipelineError> {
        let Self {
            spec, repository, ..
        } = self;
        let resolved = match repository {
            Some(repository) => {
                SubstanceSystemFactory::resolve_phase_system_with_repository(spec, repository)?
            }
            None => SubstanceSystemFactory::resolve_phase_system(spec)?,
        };
        Ok(resolved)
    }

    /// Resolves and solves the complete pipeline in one transactional pass.
    pub fn solve(self) -> Result<ResolvedPhaseEquilibriumOutcome, PhaseEquilibriumPipelineError> {
        let started = std::time::Instant::now();
        let Self {
            spec,
            initial_composition,
            candidate_selection,
            conditions,
            model_policy,
            solve_options,
            solve_mode,
            multi_start_seeds,
            repository,
        } = self;
        let execution_control = solve_options.execution_control().cloned();
        if let Some(control) = &execution_control {
            control.check_cancelled()?;
        }

        let lookup_started = std::time::Instant::now();
        let resolved = match repository {
            Some(repository) => {
                SubstanceSystemFactory::resolve_phase_system_with_repository(spec, repository)?
            }
            None => SubstanceSystemFactory::resolve_phase_system(spec)?,
        };
        let layout = crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::MultiphaseEquilibriumLayout::new(
            resolved.phase_specs().to_vec(),
        )?;
        if let Some(control) = &execution_control {
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::RepositoryLookup,
                None,
                None,
                Some(conditions.temperature()),
            ));
            control.check_cancelled()?;
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::FormulationPreparation,
                None,
                None,
                Some(conditions.temperature()),
            ));
        }
        let initial_composition = match initial_composition {
            PipelineInitialComposition::Dense(initial_moles) => {
                MultiphaseInitialComposition::from_dense(&layout, initial_moles)?
            }
            PipelineInitialComposition::Sparse(entries) => {
                MultiphaseInitialComposition::from_sparse(&layout, entries)?
            }
            PipelineInitialComposition::ElementInventory(element_inventory) => {
                if !multi_start_seeds.is_empty() {
                    return Err(PhaseEquilibriumPipelineError::Solve(
                        ReactionExtentError::InvalidProblem {
                            field: "multi_start_element_inventory",
                            message: "explicit multi-start is not yet available for element-defined P,T pipelines".to_string(),
                        },
                    ));
                }
                let phase_control = match solve_mode {
                    PhaseEquilibriumSolveMode::FixedDeclaredPhases => None,
                    PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => Some(policy),
                };
                let solution = solve_resolved_pt_from_element_inventory_with_selection(
                    &resolved,
                    conditions,
                    element_inventory,
                    None,
                    candidate_selection,
                    solve_options,
                    phase_control,
                )?
                .with_timing_stage(
                    EquilibriumTimingStage::RepositoryLookup,
                    lookup_started.elapsed(),
                )
                .with_timing_total(started.elapsed());
                return Ok(ResolvedPhaseEquilibriumOutcome { resolved, solution });
            }
        };
        let lookup_elapsed = lookup_started.elapsed();
        let request =
            ResolvedPhaseEquilibriumRequest::new(&resolved, conditions, initial_composition)
                .with_model_policy(model_policy)
                .with_solve_options(solve_options)
                .with_multi_start_seeds(multi_start_seeds)
                .with_fixed_declared_phases()
                .with_candidate_selection(candidate_selection);
        let request = match solve_mode {
            PhaseEquilibriumSolveMode::FixedDeclaredPhases => request,
            PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => {
                request.with_phase_control_policy(policy)
            }
        };
        let solution = solve_resolved_pt(request)?
            .with_timing_stage(EquilibriumTimingStage::RepositoryLookup, lookup_elapsed)
            .with_timing_total(started.elapsed());

        Ok(ResolvedPhaseEquilibriumOutcome { resolved, solution })
    }

    /// Resolves once and runs a typed temperature range.
    ///
    /// Fixed mode reuses one active formulation. Bounded mode additionally
    /// carries the accepted phase set between points and records any active-set
    /// transition that requires a new projection. In both modes the resolved
    /// layout and conserved elemental inventory remain immutable.
    pub fn solve_temperature_range(
        self,
        temperatures: TemperatureGrid,
    ) -> Result<TemperatureRangeSolution, PhaseEquilibriumPipelineError> {
        self.run_temperature_range(temperatures, false)
            .map(TemperatureRangeBestEffortOutcome::into_solution)
    }

    /// Solves a temperature range while retaining successful points around
    /// point-local failures. Range-wide preparation errors and cancellation
    /// still abort the request.
    pub fn solve_temperature_range_best_effort(
        self,
        temperatures: TemperatureGrid,
    ) -> Result<TemperatureRangeBestEffortOutcome, PhaseEquilibriumPipelineError> {
        self.run_temperature_range(temperatures, true)
    }

    fn run_temperature_range(
        self,
        temperatures: TemperatureGrid,
        best_effort: bool,
    ) -> Result<TemperatureRangeBestEffortOutcome, PhaseEquilibriumPipelineError> {
        let Self {
            spec,
            initial_composition,
            candidate_selection,
            conditions,
            model_policy,
            solve_options,
            solve_mode,
            multi_start_seeds,
            repository,
        } = self;
        if let Some(control) = solve_options.execution_control() {
            control.check_cancelled()?;
        }
        if !multi_start_seeds.is_empty() {
            return Err(PhaseEquilibriumPipelineError::Solve(
                ReactionExtentError::InvalidProblem {
                    field: "multi_start_temperature_range",
                    message: "explicit multi-start is supported only for one fixed-P,T solve"
                        .to_string(),
                },
            ));
        }
        let phase_control_policy = match solve_mode {
            PhaseEquilibriumSolveMode::FixedDeclaredPhases => None,
            PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => Some(policy),
        };

        let resolved = match repository {
            Some(repository) => {
                SubstanceSystemFactory::resolve_phase_system_with_repository(spec, repository)?
            }
            None => SubstanceSystemFactory::resolve_phase_system(spec)?,
        };
        let range_request = match initial_composition {
            PipelineInitialComposition::Dense(initial_moles) => {
                let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec())?;
                let initial_composition =
                    MultiphaseInitialComposition::from_dense(&layout, initial_moles)?;
                TemperatureRangeRequest::new(
                    &resolved,
                    initial_composition,
                    conditions.pressure(),
                    conditions.reference_pressure(),
                    temperatures,
                )?
            }
            PipelineInitialComposition::Sparse(entries) => {
                let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec())?;
                let initial_composition =
                    MultiphaseInitialComposition::from_sparse(&layout, entries)?;
                TemperatureRangeRequest::new(
                    &resolved,
                    initial_composition,
                    conditions.pressure(),
                    conditions.reference_pressure(),
                    temperatures,
                )?
            }
            PipelineInitialComposition::ElementInventory(element_inventory) => {
                TemperatureRangeRequest::from_element_inventory(
                    &resolved,
                    element_inventory,
                    conditions.pressure(),
                    conditions.reference_pressure(),
                    temperatures,
                )?
            }
        };
        let request = range_request
            .with_model_policy(model_policy)
            .with_solve_options(solve_options);
        let request = match candidate_selection {
            Some(selection) => request.with_candidate_selection(selection),
            None => request,
        };
        let request = match phase_control_policy {
            Some(policy) => request.with_phase_control_policy(policy),
            None => request,
        };

        let outcome = if best_effort {
            request.solve_best_effort()
        } else {
            request
                .solve()
                .map(TemperatureRangeBestEffortOutcome::from_solution)
        };
        outcome.map_err(PhaseEquilibriumPipelineError::from)
    }
}

/// Fully typed high-level pipeline outcome.
#[derive(Debug, Clone)]
pub struct ResolvedPhaseEquilibriumOutcome {
    resolved: ResolvedPhaseSystem,
    solution: MultiphaseEquilibriumSolution,
}

impl ResolvedPhaseEquilibriumOutcome {
    /// Rebuilds the transport wrapper after an integration layer has consumed
    /// a calculator-facade point. No numerical payload is cloned.
    pub fn from_parts(
        resolved: ResolvedPhaseSystem,
        solution: MultiphaseEquilibriumSolution,
    ) -> Self {
        Self { resolved, solution }
    }

    /// Immutable resolved phase system and its provenance.
    pub fn resolved(&self) -> &ResolvedPhaseSystem {
        &self.resolved
    }

    /// Immutable lookup provenance forwarded from the resolved phase system.
    pub fn lookup_report(&self) -> &ResolvedPhaseSystemReport {
        self.resolved.report()
    }

    /// Immutable accepted phase-equilibrium result.
    pub fn solution(&self) -> &MultiphaseEquilibriumSolution {
        &self.solution
    }

    /// Immutable stage timing evidence for this pipeline solve.
    pub fn timing_report(&self) -> &EquilibriumTimingReport {
        self.solution.timing_report()
    }

    /// Consumes the outcome and keeps only the accepted solution.
    pub fn into_solution(self) -> MultiphaseEquilibriumSolution {
        self.solution
    }
}

/// Complete public input for one resolved fixed-pressure, fixed-temperature
/// equilibrium solve.
#[derive(Clone)]
pub struct ResolvedPhaseEquilibriumRequest<'a> {
    resolved: &'a ResolvedPhaseSystem,
    conditions: EquilibriumConditions,
    initial_composition: MultiphaseInitialComposition,
    physical_input: ResolvedPhaseEquilibriumPhysicalInput,
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
    model_policy: SupportedPhaseModelPolicy,
    solve_options: EquilibriumSolveOptions,
    solve_mode: PhaseEquilibriumSolveMode,
    multi_start_seeds: Vec<LogMolesInitialGuess>,
    /// Internal numerical seed used by extensive-conditioning recovery. It is
    /// never interpreted as accepted phase-set continuation.
    recovery_basin_seed: Option<LogMolesInitialGuess>,
    /// Accepted active set carried only by a prepared continuation owner.
    /// Keeping this crate-internal prevents arbitrary callers from claiming
    /// unvalidated phase history.
    continuation_phase_set: Option<PhaseSet>,
}

#[derive(Clone)]
enum ResolvedPhaseEquilibriumPhysicalInput {
    Composition,
    ElementInventory(ElementInventory),
}

impl<'a> ResolvedPhaseEquilibriumRequest<'a> {
    /// Creates one explicit solver request. The resolved system remains
    /// borrowed and immutable for the full build/solve transaction.
    pub fn new(
        resolved: &'a ResolvedPhaseSystem,
        conditions: EquilibriumConditions,
        initial_composition: MultiphaseInitialComposition,
    ) -> Self {
        Self {
            resolved,
            conditions,
            initial_composition,
            physical_input: ResolvedPhaseEquilibriumPhysicalInput::Composition,
            candidate_selection: None,
            model_policy: SupportedPhaseModelPolicy::default(),
            solve_options: EquilibriumSolveOptions::default(),
            solve_mode: PhaseEquilibriumSolveMode::fixed_declared_phases(),
            multi_start_seeds: Vec::new(),
            recovery_basin_seed: None,
            continuation_phase_set: None,
        }
    }

    /// Replaces only the numerical trace-coordinate policy.
    pub fn with_trace_seed_policy(mut self, policy: TraceSpeciesSeedPolicy) -> Self {
        self.solve_options = self.solve_options.with_trace_seed_policy(policy);
        self
    }

    /// Replaces only the supported physical-model policy.
    pub fn with_model_policy(mut self, policy: SupportedPhaseModelPolicy) -> Self {
        self.model_policy = policy;
        self
    }

    /// Replaces only the phase-control policy used by bounded outer loops.
    pub fn with_phase_control_policy(mut self, policy: PhaseControlPolicy) -> Self {
        self.solve_mode = PhaseEquilibriumSolveMode::BoundedPhaseControl(policy);
        self
    }

    /// Explicitly returns the request to the safe fixed-declared-phases path.
    pub fn with_fixed_declared_phases(mut self) -> Self {
        self.solve_mode = PhaseEquilibriumSolveMode::fixed_declared_phases();
        self
    }

    /// Replaces only numerical backend and acceptance settings.
    pub fn with_solve_options(mut self, options: EquilibriumSolveOptions) -> Self {
        self.solve_options = options;
        self
    }

    /// Requests an explicit deterministic multi-start solve for fixed declared
    /// phases. Seeds use the canonical component order and log-mole units.
    /// Bounded phase control rejects this option because retrying a complete
    /// active-set lifecycle needs a separate transition policy.
    pub fn with_multi_start_seeds(mut self, seeds: Vec<LogMolesInitialGuess>) -> Self {
        self.multi_start_seeds = seeds;
        self
    }

    /// Carries a previously accepted numerical state into an internal range
    /// recovery without exposing mutable phase-control state publicly.
    pub(crate) fn with_continuation_state(
        mut self,
        seed: LogMolesInitialGuess,
        phase_set: Option<PhaseSet>,
    ) -> Self {
        self.recovery_basin_seed = Some(seed);
        self.continuation_phase_set = phase_set;
        self
    }

    /// Legacy compatibility shim for callers that still select the whole mode enum directly.
    #[deprecated(note = "use with_fixed_declared_phases() or with_phase_control_policy() instead")]
    pub fn with_solve_mode(mut self, mode: PhaseEquilibriumSolveMode) -> Self {
        self.solve_mode = mode;
        self
    }

    /// Borrow the immutable resolved system.
    pub fn resolved(&self) -> &'a ResolvedPhaseSystem {
        self.resolved
    }

    /// Fixed thermodynamic conditions.
    pub fn conditions(&self) -> EquilibriumConditions {
        self.conditions
    }

    /// Physical initial inventory in canonical layout order.
    pub fn initial_composition(&self) -> &MultiphaseInitialComposition {
        &self.initial_composition
    }

    /// Replaces only the physical conservation source with a validated
    /// elemental inventory. The composition remains a numerical seed and is
    /// checked against this inventory during bridge construction.
    pub fn with_element_inventory(mut self, inventory: ElementInventory) -> Self {
        self.physical_input = ResolvedPhaseEquilibriumPhysicalInput::ElementInventory(inventory);
        self
    }

    /// Carries immutable candidate-selection provenance into the build report.
    pub fn with_candidate_selection(
        mut self,
        selection: Option<EquilibriumCandidateSelectionReport>,
    ) -> Self {
        self.candidate_selection = selection;
        self
    }

    /// Numerical policy to be applied after the physical inventory is validated.
    pub fn solve_options(&self) -> &EquilibriumSolveOptions {
        &self.solve_options
    }
}

/// Builds and solves one resolved phase system through the canonical bridge.
///
/// All preparation stays transactional: a failed lookup, validation, or
/// backend attempt returns an error without modifying the supplied resolved
/// phase system or publishing a partial result.
pub fn solve_resolved_pt(
    request: ResolvedPhaseEquilibriumRequest<'_>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    let started = std::time::Instant::now();
    let execution_control = request.solve_options.execution_control().cloned();
    if let Some(control) = &execution_control {
        control.check_cancelled()?;
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PointStarted,
            Some(0),
            Some(1),
            Some(request.conditions.temperature()),
        ));
    }
    let solved = solve_resolved_pt_transaction(request)?.with_timing_total(started.elapsed());
    if let Some(control) = &execution_control {
        control.check_cancelled()?;
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PointAccepted,
            Some(0),
            Some(1),
            Some(solved.conditions().temperature()),
        ));
    }
    Ok(solved)
}

/// Solves one P,T point from a closed elemental inventory over an already
/// resolved real phase/species universe.
///
/// This is a typed sibling of [`solve_resolved_pt`] rather than a second
/// solver request hierarchy. The inventory is consumed by the bridge to
/// produce `A`, `b`, and a real-component numerical seed; all backend,
/// acceptance, and optional phase-control behavior remains identical.
pub fn solve_resolved_pt_from_element_inventory(
    resolved: &ResolvedPhaseSystem,
    conditions: EquilibriumConditions,
    element_inventory: ElementInventory,
    solve_options: EquilibriumSolveOptions,
    phase_control: Option<PhaseControlPolicy>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    solve_resolved_pt_from_element_inventory_with_numerical_seed(
        resolved,
        conditions,
        element_inventory,
        None,
        solve_options,
        phase_control,
    )
}

/// Internal continuation-capable form of
/// [`solve_resolved_pt_from_element_inventory`].
///
/// `numerical_seed` affects only log-coordinate initialization. The bridge
/// still derives conserved totals exclusively from `element_inventory`.
pub(crate) fn solve_resolved_pt_from_element_inventory_with_numerical_seed(
    resolved: &ResolvedPhaseSystem,
    conditions: EquilibriumConditions,
    element_inventory: ElementInventory,
    numerical_seed: Option<MultiphaseInitialComposition>,
    solve_options: EquilibriumSolveOptions,
    phase_control: Option<PhaseControlPolicy>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    solve_resolved_pt_from_element_inventory_with_selection(
        resolved,
        conditions,
        element_inventory,
        numerical_seed,
        None,
        solve_options,
        phase_control,
    )
}

fn solve_resolved_pt_from_element_inventory_with_selection(
    resolved: &ResolvedPhaseSystem,
    conditions: EquilibriumConditions,
    element_inventory: ElementInventory,
    numerical_seed: Option<MultiphaseInitialComposition>,
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
    solve_options: EquilibriumSolveOptions,
    phase_control: Option<PhaseControlPolicy>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    let trace_seed_policy = solve_options.trace_seed_policy();
    let build_request = PhaseEquilibriumBuildRequest::from_element_inventory(
        resolved,
        conditions,
        element_inventory,
        trace_seed_policy,
        SupportedPhaseModelPolicy::default(),
    )?;
    let build_request = match candidate_selection {
        Some(selection) => build_request.with_candidate_selection(selection),
        None => build_request,
    };
    let build_request = match numerical_seed {
        Some(seed) => build_request.with_numerical_seed(seed)?,
        None => build_request,
    };
    match phase_control {
        Some(policy) => crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
            build_phase_equilibrium_problem(build_request)?
            .solve_with_bounded_phase_control_with_diagnostics(
            |settings| *settings = solve_options.clone().into_settings(),
            |manager| *manager = policy.into_phase_manager(),
            solve_options.diagnostics_options().clone(),
        ),
        None => crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
            build_phase_equilibrium_problem(build_request)?
            .solve_with(|settings| *settings = solve_options.into_settings())?
            .into_multiphase_solution(),
    }
}

/// Runs one complete point transaction without emitting range-level progress.
///
/// Prepared continuation drivers use this only after their cached fast path
/// fails. Progress publication stays with the outer owner, so a recovered
/// range point cannot masquerade as a nested one-point request.
pub(crate) fn solve_resolved_pt_transaction(
    request: ResolvedPhaseEquilibriumRequest<'_>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    solve_resolved_pt_transaction_with_optional_bundle(request, None)
}

/// Runs a point transaction whose first physical attempt already owns a
/// canonical bridge prepared by the caller.
///
/// The elemental P,T calculator needs the bridge once to derive its numerical
/// seed. Passing that same bundle into the transaction avoids rebuilding the
/// identical thermochemical and numerical problem immediately afterward.
/// Recovery deliberately remains request-based: a normalized retry must build
/// its own transformed problem and retains the existing recovery contract.
pub(crate) fn solve_resolved_pt_transaction_with_bundle(
    request: ResolvedPhaseEquilibriumRequest<'_>,
    bundle: PhaseEquilibriumProblemBundle,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    solve_resolved_pt_transaction_with_optional_bundle(request, Some(bundle))
}

fn solve_resolved_pt_transaction_with_optional_bundle(
    request: ResolvedPhaseEquilibriumRequest<'_>,
    bundle: Option<PhaseEquilibriumProblemBundle>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    let transaction_started = std::time::Instant::now();
    match solve_resolved_pt_once_with_bundle(request.clone(), bundle) {
        Ok(solution) => Ok(solution),
        Err(physical_error) => {
            if request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled {
                recover_resolved_pt_after_numerical_failure(request, physical_error).map(
                    |solution| {
                        // Recovery timing owns the whole fallback transaction,
                        // including the rejected physical-coordinate attempt.
                        // Otherwise that failed attempt leaks into the facade
                        // wall time and appears as an unexplained outer gap.
                        let elapsed = transaction_started.elapsed();
                        solution
                            .with_timing_stage(EquilibriumTimingStage::Recovery, elapsed)
                            .with_timing_total(elapsed)
                    },
                )
            } else {
                recover_resolved_pt_after_numerical_failure(request, physical_error)
            }
        }
    }
}

/// Applies canonical extensive recovery to an already observed point error.
///
/// This avoids repeating the same failed physical attempt when a prepared
/// range formulation has already produced complete typed failure evidence.
pub(crate) fn recover_resolved_pt_after_numerical_failure<'a>(
    request: ResolvedPhaseEquilibriumRequest<'a>,
    physical_error: ReactionExtentError,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    if request
        .solve_options
        .extensive_normalization_policy()
        .allows_numerical_failure_recovery()
        && is_extensive_normalization_recovery_candidate(&physical_error)
    {
        recover_resolved_pt_by_extensive_normalization(request, physical_error)
    } else {
        Err(physical_error)
    }
}

fn build_phase_equilibrium_request<'a>(
    request: &ResolvedPhaseEquilibriumRequest<'a>,
    numerical_seed: MultiphaseInitialComposition,
) -> Result<PhaseEquilibriumBuildRequest<'a>, ReactionExtentError> {
    let trace_seed_policy = request.solve_options.trace_seed_policy();
    let build_request = match &request.physical_input {
        ResolvedPhaseEquilibriumPhysicalInput::Composition => PhaseEquilibriumBuildRequest::new(
            request.resolved,
            request.conditions,
            numerical_seed,
            trace_seed_policy,
            request.model_policy,
        ),
        ResolvedPhaseEquilibriumPhysicalInput::ElementInventory(inventory) => {
            PhaseEquilibriumBuildRequest::from_element_inventory(
                request.resolved,
                request.conditions,
                inventory.clone(),
                trace_seed_policy,
                request.model_policy,
            )?
            .with_numerical_seed(numerical_seed)
        }
    }?;
    Ok(match &request.candidate_selection {
        Some(selection) => build_request.with_candidate_selection(selection.clone()),
        None => build_request,
    })
}

/// Executes exactly one physical or explicitly normalized request.
///
/// Keeping retry policy outside this function prevents recursive recovery and
/// makes every individual attempt retain the ordinary solver contract.
fn solve_resolved_pt_once(
    request: ResolvedPhaseEquilibriumRequest<'_>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    solve_resolved_pt_once_with_bundle(request, None)
}

fn solve_resolved_pt_once_with_bundle(
    request: ResolvedPhaseEquilibriumRequest<'_>,
    initial_bundle: Option<PhaseEquilibriumProblemBundle>,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    let timing_mode = request.solve_options.timing_mode();
    let diagnostics = request.solve_options.diagnostics_options().clone();
    let started = std::time::Instant::now();
    match request.solve_mode.clone() {
        PhaseEquilibriumSolveMode::FixedDeclaredPhases => {
            let bundle = match initial_bundle {
                Some(bundle) => bundle,
                None => crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
                    build_phase_equilibrium_problem_with_timing(
                        build_phase_equilibrium_request(
                            &request,
                            request.initial_composition.clone(),
                        )?,
                        timing_mode,
                    )?,
            };
            let settings = request.solve_options.into_settings();
            let solved = if request.multi_start_seeds.is_empty() {
                bundle.solve_with(|configured| *configured = settings)
            } else {
                bundle.solve_with_initial_guesses(request.multi_start_seeds, |configured| {
                    *configured = settings
                })
            };
            solved
                .and_then(|bundle| bundle.into_multiphase_solution())
                .map(|solution| solution.with_timing_total(started.elapsed()))
        }
        PhaseEquilibriumSolveMode::BoundedPhaseControl(phase_control_policy) => {
            if !request.multi_start_seeds.is_empty() {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "multi_start_phase_control",
                    message: "explicit multi-start is supported only for fixed declared phases"
                        .to_string(),
                });
            }
            let bundle = match initial_bundle {
                Some(bundle) => bundle,
                None => crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
                    build_phase_equilibrium_problem_with_timing(
                        build_phase_equilibrium_request(
                            &request,
                            request.initial_composition.clone(),
                        )?,
                        timing_mode,
                    )?,
            };
            let settings = request.solve_options.into_settings();
            bundle
                .solve_with_bounded_phase_control_with_diagnostics_and_seed(
                    |configured| *configured = settings,
                    |configured| *configured = phase_control_policy.into_phase_manager(),
                    diagnostics,
                    request.recovery_basin_seed,
                    request.continuation_phase_set,
                )
                .map(|solution| solution.with_timing_total(started.elapsed()))
        }
    }
}

/// The recovery route is reserved for genuinely extensive conditioning.
///
/// A factor in `[0.1, 10]` is deliberately treated as near-unit: applying a
/// second formulation there would turn an ordinary numerical failure into an
/// implicit multi-start policy and would make the failure provenance harder to
/// interpret. The bound is expressed in the physical scale domain so the
/// exact boundary is testable without constructing a complete solve request.
const EXTENSIVE_RECOVERY_MIN_SCALE_FACTOR: f64 = 10.0;

// The normalized recovery state is used as a cross-representation witness.
// A tighter floor prevents a scale-dependent phase-control amount from being
// published when the ordinary production tolerance is sufficient for solve
// acceptance but not for strict extensive equivalence.
const EXTENSIVE_RECOVERY_MAX_SOLVER_TOLERANCE: f64 = 1.0e-12;
const EXTENSIVE_RECOVERY_RELATIVE_TRACE_FRACTION: f64 = 1.0e-12;

pub(crate) fn normalized_recovery_trace_policy(
    normalization: ExtensiveNormalization,
    physical_policy: TraceSpeciesSeedPolicy,
) -> Result<TraceSpeciesSeedPolicy, ReactionExtentError> {
    let normalized_policy = normalization.normalize_trace_seed_policy(physical_policy)?;
    match normalized_policy {
        TraceSpeciesSeedPolicy::Absolute { floor } => {
            // A physical absolute floor can become far below the useful
            // numerical basin after extensive normalization. The floor is a
            // seed-only device, so use a scale-free normalized fraction while
            // retaining the transformed physical floor as the lower bound.
            Ok(TraceSpeciesSeedPolicy::RelativeToLargestInitialMole {
                fraction: EXTENSIVE_RECOVERY_RELATIVE_TRACE_FRACTION,
                minimum_floor: floor,
            })
        }
        relative => Ok(relative),
    }
}

fn is_materially_extensive_scaled(scale: f64) -> bool {
    scale.is_finite() && scale > 0.0 && scale.ln().abs() > EXTENSIVE_RECOVERY_MIN_SCALE_FACTOR.ln()
}

fn is_extensive_normalization_recovery_candidate(error: &ReactionExtentError) -> bool {
    matches!(
        error.kind(),
        ReactionExtentErrorKind::AllBackendsFailed
            | ReactionExtentErrorKind::NonConvergence
            | ReactionExtentErrorKind::BackendFailure
    )
}

/// Finds a basin in an exactly normalized equivalent, then proves that basin
/// against the original physical extensive formulation before publication.
fn recover_resolved_pt_by_extensive_normalization<'a>(
    request: ResolvedPhaseEquilibriumRequest<'a>,
    physical_error: ReactionExtentError,
) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
    let normalization_started = std::time::Instant::now();
    let normalization = match &request.physical_input {
        ResolvedPhaseEquilibriumPhysicalInput::Composition => {
            ExtensiveNormalization::from_physical_moles(request.initial_composition.moles())?
        }
        ResolvedPhaseEquilibriumPhysicalInput::ElementInventory(inventory) => {
            ExtensiveNormalization::from_element_inventory(inventory)?
        }
    };
    // A near-unit inventory is not an extensive-conditioning problem. Avoid
    // turning this route into an implicit general-purpose multi-start policy.
    if !is_materially_extensive_scaled(normalization.physical_inventory_scale()) {
        return Err(physical_error);
    }

    let trigger = ExtensiveNormalizationTrigger::NumericalFailure {
        error_kind: physical_error.kind(),
        message: physical_error.to_string(),
    };
    let layout = MultiphaseEquilibriumLayout::new(request.resolved.phase_specs().to_vec())?;
    let normalized_composition =
        normalization.normalize_initial_composition(&layout, &request.initial_composition)?;
    let normalized_seeds = request
        .multi_start_seeds
        .iter()
        .map(|seed| normalization.normalize_log_mole_guess(seed))
        .collect::<Result<Vec<_>, _>>()?;
    let normalized_basin_seed = request
        .recovery_basin_seed
        .as_ref()
        .map(|seed| normalization.normalize_log_mole_guess(seed))
        .transpose()?;
    let normalized_physical_input = match &request.physical_input {
        ResolvedPhaseEquilibriumPhysicalInput::Composition => {
            ResolvedPhaseEquilibriumPhysicalInput::Composition
        }
        ResolvedPhaseEquilibriumPhysicalInput::ElementInventory(inventory) => {
            ResolvedPhaseEquilibriumPhysicalInput::ElementInventory(
                normalization.normalize_element_inventory(inventory)?,
            )
        }
    };
    let normalized_mode = match request.solve_mode.clone() {
        PhaseEquilibriumSolveMode::FixedDeclaredPhases => {
            PhaseEquilibriumSolveMode::FixedDeclaredPhases
        }
        PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => {
            PhaseEquilibriumSolveMode::BoundedPhaseControl(
                policy.normalized_for_extensive_representation(normalization)?,
            )
        }
    };
    let normalized_options = request
        .solve_options
        .clone()
        .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::Disabled)
        // Discovery is an internal numerical operation. Streaming its events
        // would expose normalized mole units through a physical API. A
        // successful physical retry retains ordinary diagnostics; an explicit
        // reconstruction retains typed recovery provenance instead.
        .with_diagnostics(EquilibriumDiagnosticsOptions::disabled())
        .with_trace_seed_policy(normalized_recovery_trace_policy(
            normalization,
            request.solve_options.trace_seed_policy(),
        )?);
    let recovery_tolerance = normalized_options
        .reproducibility_snapshot()
        .tolerance
        .min(EXTENSIVE_RECOVERY_MAX_SOLVER_TOLERANCE);
    let normalized_options = normalized_options.with_tolerance(recovery_tolerance)?;
    let normalized_request = ResolvedPhaseEquilibriumRequest {
        resolved: request.resolved,
        conditions: request.conditions,
        initial_composition: normalized_composition,
        physical_input: normalized_physical_input,
        candidate_selection: request.candidate_selection.clone(),
        model_policy: request.model_policy,
        solve_options: normalized_options,
        solve_mode: normalized_mode,
        multi_start_seeds: normalized_seeds,
        recovery_basin_seed: normalized_basin_seed,
        continuation_phase_set: request.continuation_phase_set.clone(),
    };
    let normalization_duration = normalization_started.elapsed();
    let physical_failure_attempts = physical_error.backend_attempt_reports();
    let normalized_solution = match solve_resolved_pt_once(normalized_request) {
        Ok(solution) => solution,
        Err(recovery) => {
            return Err(ReactionExtentError::ExtensiveNormalizationRecoveryFailed {
                stage: "normalized basin discovery",
                physical: Box::new(physical_error),
                recovery: Box::new(recovery),
            });
        }
    };
    let discovery_backend = normalized_solution.solve_report().accepted_backend.clone();
    let normalized_discovery_attempts = normalized_solution.solve_report().attempts.clone();

    let mut physical_retry = request.clone();
    physical_retry.solve_options = physical_retry
        .solve_options
        .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::Disabled);
    match &physical_retry.solve_mode {
        PhaseEquilibriumSolveMode::FixedDeclaredPhases => {
            let recovered_seed = normalization
                .denormalize_log_moles(normalized_solution.accepted_solution().log_moles())?;
            physical_retry.multi_start_seeds.insert(0, recovered_seed);
        }
        PhaseEquilibriumSolveMode::BoundedPhaseControl(_) => {
            // For an activation lifecycle, `restart_seed` retains the accepted
            // pre-activation coordinates for every previously active species
            // and only adds the incipient phase seed. The original physical
            // active set therefore sees the basin it needs while still
            // reproducing the activation transition itself.
            let normalized_seed = normalized_solution
                .phase_control_report()
                .and_then(|report| report.transitions.first())
                .filter(|transition| {
                    !transition.activated.is_empty() && transition.deactivated.is_empty()
                })
                .map(|transition| transition.restart_seed.as_slice())
                .unwrap_or_else(|| normalized_solution.accepted_solution().log_moles());
            physical_retry.recovery_basin_seed =
                Some(normalization.denormalize_log_moles(normalized_seed)?);
        }
    }

    match solve_resolved_pt_once(physical_retry) {
        Ok(physical_solution) => {
            let physical_retry_backend = physical_solution.solve_report().accepted_backend.clone();
            let physical_retry_attempts = physical_solution.solve_report().attempts.clone();
            Ok(attach_extensive_normalization_recovery(
                physical_solution.with_timing_stage(
                    EquilibriumTimingStage::Normalization,
                    normalization_duration,
                ),
                ExtensiveNormalizationRecoveryEvidence {
                    physical_inventory_scale: normalization.physical_inventory_scale(),
                    trigger: trigger.clone(),
                    discovery_backend,
                    physical_retry_backend: Some(physical_retry_backend),
                    physical_retry_failure: None,
                    physical_failure_attempts: physical_failure_attempts.clone(),
                    normalized_discovery_attempts: normalized_discovery_attempts.clone(),
                    physical_retry_attempts,
                    physical_failure_duration: Duration::ZERO,
                    normalization_duration,
                    normalized_discovery_duration: Duration::ZERO,
                    physical_retry_duration: Duration::ZERO,
                    reconstruction_duration: Duration::ZERO,
                    reconstructed_physical_boundary: false,
                },
                request.solve_options.diagnostics_options(),
            ))
        }
        Err(physical_retry_error) => {
            let retry_message = physical_retry_error.to_string();
            let physical_publication = (|| {
                let physical_build_report = crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
                    build_phase_equilibrium_problem_with_timing(
                        build_phase_equilibrium_request(
                            &request,
                            request.initial_composition.clone(),
                        )?,
                        request.solve_options.timing_mode(),
                    )?
                    .report()
                    .clone();
                normalized_solution
                    .reconstruct_physical_extensive_boundary(normalization, physical_build_report)
            })();
            match physical_publication {
                Ok(physical_solution) => Ok(attach_extensive_normalization_recovery(
                    physical_solution.with_timing_stage(
                        EquilibriumTimingStage::Normalization,
                        normalization_duration,
                    ),
                    ExtensiveNormalizationRecoveryEvidence {
                        physical_inventory_scale: normalization.physical_inventory_scale(),
                        trigger: trigger.clone(),
                        discovery_backend,
                        physical_retry_backend: None,
                        physical_retry_failure: Some(retry_message),
                        physical_failure_attempts,
                        normalized_discovery_attempts,
                        physical_retry_attempts: physical_retry_error.backend_attempt_reports(),
                        physical_failure_duration: Duration::ZERO,
                        normalization_duration,
                        normalized_discovery_duration: Duration::ZERO,
                        physical_retry_duration: Duration::ZERO,
                        reconstruction_duration: Duration::ZERO,
                        reconstructed_physical_boundary: true,
                    },
                    request.solve_options.diagnostics_options(),
                )),
                Err(recovery) => Err(ReactionExtentError::ExtensiveNormalizationRecoveryFailed {
                    stage: "physical publication reconstruction",
                    physical: Box::new(physical_error),
                    recovery: Box::new(recovery),
                }),
            }
        }
    }
}

/// Publishes one recovery fact through the same opt-in retained/sink
/// diagnostics contract as the rest of the canonical workflow.
fn attach_extensive_normalization_recovery(
    solution: MultiphaseEquilibriumSolution,
    evidence: ExtensiveNormalizationRecoveryEvidence,
    diagnostics: &EquilibriumDiagnosticsOptions,
) -> MultiphaseEquilibriumSolution {
    let event = EquilibriumDiagnosticEvent::ExtensiveNormalizationRecoveryAccepted {
        physical_inventory_scale: evidence.physical_inventory_scale,
        trigger_kind: evidence.trigger.error_kind(),
        trigger_reason: evidence.trigger.description(),
        discovery_backend: format!("{:?}", evidence.discovery_backend),
        physical_retry_backend: evidence
            .physical_retry_backend
            .as_ref()
            .map(|backend| format!("{backend:?}")),
        reconstructed_physical_boundary: evidence.reconstructed_physical_boundary,
    };
    let mut collector = solution.diagnostics_report().map_or_else(
        || EquilibriumDiagnosticsCollector::new(diagnostics.clone()),
        |report| EquilibriumDiagnosticsCollector::from_report(diagnostics.clone(), report),
    );
    collector.record(EquilibriumDiagnosticsMode::Summary, event);
    solution
        .with_diagnostics(collector.finish())
        .with_extensive_normalization_recovery(evidence)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_candidate_selection::{
        EquilibriumCandidatePhaseAssignment, EquilibriumCandidatePolicy,
        EquilibriumCandidateSelector,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_diagnostics::{
        EquilibriumDiagnosticEvent, EquilibriumDiagnosticsMode, EquilibriumDiagnosticsOptions,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_temperature_range::{
        TemperatureGrid, TemperatureRangePointPreparation,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::PhaseStatus;
    #[allow(deprecated)]
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::gas_solver_for_T_range;
    use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::{
        PhaseEquilibriumInputKind, PhaseEquilibriumSeedSource,
    };
    use crate::Thermodynamics::ChemEquilibrium::prelude::{
        LogMolesInitialGuess, NativeEquilibriumSolver, RustedSciTheSolver, SolverBackend,
        SolverPolicy,
    };
    use crate::Thermodynamics::User_PhaseOrSolution::{
        PhaseModel, PhaseSpec, SubstanceSystemFactory, SubstanceSystemSpec,
        SubstanceSystemSpecBuilder, SubstancesContainer,
    };
    use crate::Thermodynamics::phase_layout::{PhaseComponentId, PhaseId};
    use crate::Thermodynamics::physical_state::PhysicalState;
    use crate::Thermodynamics::thermo_lib_api::{ThermoData, ThermoRepository};
    use std::collections::HashMap;

    fn real_h_o_multiphase_repository() -> Arc<ThermoRepository> {
        let source = ThermoData::try_default_repository()
            .expect("bundled repository must load for the real multiphase fixture");
        let records = [
            ("NASA_gas", "O2"),
            ("NASA_gas", "H2O"),
            ("NASA_cond", "H2O(L)"),
        ];
        let mut payloads = HashMap::new();
        for (library, record_key) in records {
            payloads
                .entry(library.to_string())
                .or_insert_with(HashMap::new)
                .insert(
                    record_key.to_string(),
                    source
                        .LibThermoData
                        .get(library)
                        .and_then(|records| records.get(record_key))
                        .cloned()
                        .expect("fixture record must exist in bundled JSON"),
                );
        }

        let mut elements = HashMap::new();
        for element in ["H", "O"] {
            let rows = source
                .ElementsData
                .get(element)
                .into_iter()
                .flatten()
                .filter(|row| {
                    row.len() >= 2
                        && records.iter().any(|(library, record_key)| {
                            row[0] == *record_key && row[1] == *library
                        })
                })
                .cloned()
                .collect();
            elements.insert(element.to_string(), rows);
        }

        Arc::new(ThermoRepository::from_parts(
            records
                .iter()
                .map(|(library, record_key)| (library.to_string(), record_key.to_string()))
                .collect(),
            payloads,
            elements,
            vec!["NASA_gas".to_string(), "NASA_cond".to_string()],
            HashMap::new(),
            HashMap::from([
                ("NASA_gas".to_string(), "NASA".to_string()),
                ("NASA_cond".to_string(), "NASA".to_string()),
            ]),
            vec!["NASA_gas".to_string(), "NASA_cond".to_string()],
            Vec::new(),
        ))
    }

    #[test]
    fn solve_options_round_trip_explicit_cascade_budget() {
        let budget = SolverCascadeBudget::new(2, 10, 1);
        let options = EquilibriumSolveOptions::new()
            .with_solver_budget(budget)
            .expect("positive cascade budget must validate");
        assert_eq!(options.into_settings().solver_budget, Some(budget));

        let error = EquilibriumSolveOptions::new()
            .with_solver_budget(SolverCascadeBudget::new(0, 10, 10))
            .expect_err("zero attempt budget must be rejected");
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "solver_budget",
                ..
            }
        ));
    }

    #[test]
    fn cancelled_pipeline_stops_before_repository_resolution_for_point_and_range() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let conditions = EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap();
        let control =
            crate::Thermodynamics::ChemEquilibrium::prelude::EquilibriumExecutionControl::new();
        control.request_cancel();
        let options = EquilibriumSolveOptions::new().with_execution_control(control);

        let point_error = PhaseEquilibriumPipelineRequest::new(spec.clone(), vec![1.0], conditions)
            .with_solve_options(options.clone())
            .solve()
            .expect_err("cancelled point must not enter repository lookup");
        assert!(matches!(
            point_error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::Cancelled)
        ));

        let range_error = PhaseEquilibriumPipelineRequest::new(spec, vec![1.0], conditions)
            .with_solve_options(options)
            .solve_temperature_range(TemperatureGrid::new(vec![500.0, 600.0]).unwrap())
            .expect_err("cancelled range must not enter repository lookup");
        assert!(matches!(
            range_error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::Cancelled)
        ));
    }

    #[test]
    fn production_prelude_exposes_complete_backend_policy_contract() {
        let rst = SolverPolicy::Single(SolverBackend::RustedSciThe(
            RustedSciTheSolver::MinpackLevenbergMarquardt,
        ));
        let legacy = SolverPolicy::Single(SolverBackend::Native(NativeEquilibriumSolver::NR));

        EquilibriumSolveOptions::new()
            .with_solver_policy(rst)
            .expect("RST policy exported by the production prelude must validate");
        EquilibriumSolveOptions::new()
            .with_solver_policy(legacy)
            .expect("legacy fallback policy exported by the production prelude must validate");
    }

    #[test]
    fn typed_ideal_solution_spec_resolves_through_the_repository_boundary() {
        // This intentionally bypasses the compatibility `MultiPhase` builder:
        // its historical phase-nature enum cannot express a mixing model.
        // Production callers and the GUI use `from_phases`, which must retain
        // the explicit semantic model through ordinary local lookup.
        let phase = PhaseSpec::ideal_solution(
            PhaseId::new(Some("oxide_solution".to_string())),
            vec!["AL(cr)".to_string(), "AL2O3(a)".to_string()],
            PhysicalState::Solid,
        )
        .expect("the typed ideal-solution declaration must be valid");
        let spec = SubstanceSystemSpec::from_phases(vec![phase])
            .expect("typed phase specification must validate")
            .with_lookup_policy(vec!["NASA_cond".to_string()], Vec::new(), None, false);
        let resolved = SubstanceSystemFactory::resolve_phase_system_with_repository(
            spec,
            ThermoData::try_default_repository().expect("bundled repository must load"),
        )
        .expect("bundled condensed records must resolve through the typed specification");

        assert_eq!(resolved.phase_specs().len(), 1);
        assert_eq!(resolved.phase_specs()[0].model(), PhaseModel::IdealSolution);
        assert_eq!(
            resolved.phase_specs()[0].components(),
            ["AL(cr)", "AL2O3(a)"]
        );
        let data = resolved
            .phase_data()
            .get(&Some("oxide_solution".to_string()))
            .expect("resolved phase payload must retain its declared identity");
        assert_eq!(data.substances, vec!["AL(cr)", "AL2O3(a)"]);
        assert_eq!(
            resolved.report().nist_fallback_enabled(),
            false,
            "the contract fixture must remain fully local and deterministic"
        );
    }

    #[test]
    fn enabled_timing_is_published_on_pipeline_solution() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let options =
            EquilibriumSolveOptions::new().with_timing_mode(EquilibriumTimingMode::Enabled);
        let outcome = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_solve_options(options)
        .solve()
        .unwrap();

        let timing = outcome.timing_report();
        assert!(timing.enabled());
        assert!(timing.total() > std::time::Duration::ZERO);
        assert!(timing.thermochemistry_preparation() > std::time::Duration::ZERO);
        assert!(timing.numeric_closure_construction() > std::time::Duration::ZERO);
        assert!(timing.symbolic_construction() > std::time::Duration::ZERO);
        assert!(timing.equation_construction() > std::time::Duration::ZERO);
        assert!(timing.nonlinear_solve() > std::time::Duration::ZERO);
        assert!(timing.validation() >= std::time::Duration::ZERO);
        assert!(timing.postprocessing() > std::time::Duration::ZERO);
    }

    #[test]
    fn bounded_phase_control_publishes_opt_in_lifecycle_diagnostics() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let options = EquilibriumSolveOptions::new()
            .with_timing_mode(EquilibriumTimingMode::Enabled)
            .with_diagnostics(EquilibriumDiagnosticsOptions::enabled(
                EquilibriumDiagnosticsMode::PhaseLifecycle,
            ));
        let solution = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_solve_options(options)
        .with_phase_control_policy(PhaseControlPolicy::default())
        .solve()
        .unwrap()
        .into_solution();

        let diagnostics = solution
            .diagnostics_report()
            .expect("enabled diagnostics must be attached to the accepted solution");
        assert!(matches!(
            diagnostics.events().first(),
            Some(EquilibriumDiagnosticEvent::SolveStarted { .. })
        ));
        assert!(
            diagnostics.events().iter().any(|event| matches!(
                event,
                EquilibriumDiagnosticEvent::StabilityEvaluated { .. }
            ))
        );
        assert!(matches!(
            diagnostics.events().last(),
            Some(EquilibriumDiagnosticEvent::SolveAccepted { .. })
        ));
        let rendered = crate::Thermodynamics::ChemEquilibrium::
            equilibrium_diagnostics_display::format_solution_diagnostics(&solution)
            .expect("enabled diagnostics must render through the presentation adapter");
        assert!(rendered.contains("solve started"));
        assert!(rendered.contains("stability iteration"));
        assert!(rendered.contains("solve accepted"));
        assert!(rendered.contains("timing ms: total="));
    }

    #[test]
    fn diagnostics_remain_absent_when_the_default_options_are_used() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let solution = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_phase_control_policy(PhaseControlPolicy::default())
        .solve()
        .unwrap()
        .into_solution();

        assert!(solution.diagnostics_report().is_none());
        let summary = crate::Thermodynamics::ChemEquilibrium::
            equilibrium_diagnostics_display::format_solution_execution_summary(&solution);
        assert!(summary.contains("equilibrium execution:"));
        assert!(summary.contains("phase control:"));
        assert!(summary.contains("verbose diagnostics: disabled"));
    }

    #[test]
    fn resolve_and_solve_pipeline_round_trips_one_gas_phase_with_two_species() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(true)
        .build()
        .unwrap();
        let request = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        );

        let outcome = request.solve().unwrap();

        assert_eq!(outcome.resolved().phase_specs().len(), 1);
        assert_eq!(outcome.solution().component_moles().len(), 2);
        assert_eq!(outcome.solution().build_report().components().len(), 2);
    }

    #[test]
    fn element_inventory_pipeline_solves_without_dense_component_moles() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "H2".to_string(),
            "O2".to_string(),
            "H2O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let outcome = PhaseEquilibriumPipelineRequest::from_element_inventory(
            spec,
            ElementInventory::from_amounts([("H", 4.0), ("O", 2.0)]).unwrap(),
            EquilibriumConditions::new(1_200.0, 101_325.0, 101_325.0).unwrap(),
        )
        .solve()
        .expect("element-defined pipeline must resolve and solve locally");

        assert_eq!(outcome.resolved().phase_specs()[0].components().len(), 3);
        assert!(
            outcome
                .solution()
                .component_moles()
                .iter()
                .all(|moles| moles.is_finite() && *moles >= 0.0)
        );
    }

    #[test]
    fn element_inventory_pipeline_solves_temperature_range_with_accepted_continuation() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "H2".to_string(),
            "O2".to_string(),
            "H2O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .expect("element-defined range spec must validate");
        let inventory = ElementInventory::from_amounts([("H", 4.0), ("O", 2.0)])
            .expect("element inventory must validate");
        let range = PhaseEquilibriumPipelineRequest::from_element_inventory(
            spec,
            inventory,
            EquilibriumConditions::new(1_100.0, 101_325.0, 101_325.0)
                .expect("range conditions must validate"),
        )
        .solve_temperature_range(
            TemperatureGrid::new(vec![1_100.0, 1_200.0]).expect("temperature grid must validate"),
        )
        .expect("element-defined temperature range must solve");

        assert_eq!(range.report().point_count(), 2);
        assert!(!range.report().phase_control_enabled());
        assert!(!range.points()[0].report().used_continuation_seed());
        assert!(range.points()[1].report().used_continuation_seed());
        for point in range.points() {
            let solution = point.solution();
            let report = solution.build_report();
            assert_eq!(
                report.input_kind(),
                PhaseEquilibriumInputKind::ElementInventory
            );
            assert_eq!(report.element_labels(), ["H", "O"]);
            assert_eq!(report.element_totals(), [4.0, 2.0]);
            assert!(
                solution
                    .accepted_solution()
                    .validation()
                    .max_abs_element_balance_error
                    < 1e-8,
                "element inventory must remain conserved at every accepted range point"
            );
        }
    }

    #[test]
    fn explicit_species_universe_changes_the_problem_without_catalog_supplementation() {
        let inventory = ElementInventory::from_amounts([("H", 4.0), ("O", 2.0)])
            .expect("element inventory must validate");
        let conditions = EquilibriumConditions::new(1_200.0, 101_325.0, 101_325.0)
            .expect("conditions must validate");
        let full_spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "H2".to_string(),
            "O2".to_string(),
            "H2O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .expect("full explicit universe must validate");
        let restricted_spec =
            SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
                "H2".to_string(),
                "O2".to_string(),
            ]))
            .with_library_priorities(vec!["NASA_gas".to_string()])
            .with_search_in_nist(false)
            .build()
            .expect("restricted explicit universe must validate");

        let full = PhaseEquilibriumPipelineRequest::from_element_inventory(
            full_spec,
            inventory.clone(),
            conditions,
        )
        .solve()
        .expect("full explicit universe must solve");
        let restricted = PhaseEquilibriumPipelineRequest::from_element_inventory(
            restricted_spec,
            inventory,
            conditions,
        )
        .solve()
        .expect("restricted explicit universe must solve");

        assert_eq!(
            full.resolved().phase_specs()[0].components(),
            ["H2", "O2", "H2O"]
        );
        assert_eq!(
            restricted.resolved().phase_specs()[0].components(),
            ["H2", "O2"]
        );
        assert_eq!(restricted.solution().component_moles().len(), 2);
        assert!(
            restricted
                .solution()
                .build_report()
                .components()
                .iter()
                .all(|component| component.component().label() != "H2O")
        );
        assert!(full.solution().component_moles()[2] > 1.0e-12);
        assert!(
            restricted
                .solution()
                .accepted_solution()
                .validation()
                .max_abs_element_balance_error
                < 1.0e-8
        );
    }

    #[test]
    fn truncated_catalog_selection_cannot_bypass_inventory_representability() {
        let repository = ThermoData::try_default_repository()
            .expect("bundled repository must load for truncation validation");
        let inventory = ElementInventory::from_amounts([("H", 4.0), ("O", 2.0)])
            .expect("element inventory must validate");
        let policy = EquilibriumCandidatePolicy::default()
            .with_allowed_libraries(vec!["NASA_gas".to_string()])
            .with_temperature_range(1_200.0, 1_200.0)
            .expect("candidate temperature range must validate")
            .with_max_candidates(1)
            .expect("candidate limit must validate");
        let selection = EquilibriumCandidateSelector::new(Arc::clone(&repository))
            .select_inventory(&inventory, policy)
            .expect("truncated H/O selection must still produce evidence");
        assert!(selection.is_truncated());
        assert_eq!(selection.selected().len(), 1);

        let phase_plan = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::ideal_gas(
                PhaseId::new(Some("gas".to_string())),
                selection
                    .selected()
                    .iter()
                    .map(|candidate| candidate.record_key().to_string())
                    .collect(),
            ),
        ]);
        let error =
            PhaseEquilibriumPipelineRequest::from_candidate_selection_with_element_inventory(
                repository,
                &selection,
                &phase_plan,
                inventory,
                EquilibriumConditions::new(1_200.0, 101_325.0, 101_325.0).unwrap(),
            )
            .expect("truncated selection must still produce a typed phase plan")
            .solve()
            .expect_err("a truncated universe that cannot represent b must be rejected");

        assert!(matches!(
            error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::Preparation(_))
        ));
    }

    #[test]
    fn candidate_selection_provenance_survives_bridge_and_reproducibility() {
        let repository = ThermoData::try_default_repository()
            .expect("bundled repository must load for selection provenance");
        let inventory = ElementInventory::from_amounts([("H", 4.0), ("O", 2.0)])
            .expect("element inventory must validate");
        let policy = EquilibriumCandidatePolicy::default()
            .with_allowed_libraries(vec!["NASA_gas".to_string()])
            .with_temperature_range(1_200.0, 1_200.0)
            .expect("temperature selection range must validate")
            .with_max_candidates(3)
            .expect("candidate cap must validate");
        let selection = EquilibriumCandidateSelector::new(Arc::clone(&repository))
            .select_inventory(&inventory, policy)
            .expect("local H/O selection must succeed");
        assert_eq!(selection.selected().len(), 3);
        let phase_plan = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::ideal_gas(
                PhaseId::new(Some("gas".to_string())),
                selection
                    .selected()
                    .iter()
                    .map(|candidate| candidate.record_key().to_string())
                    .collect(),
            ),
        ]);
        let outcome =
            PhaseEquilibriumPipelineRequest::from_candidate_selection_with_element_inventory(
                repository,
                &selection,
                &phase_plan,
                inventory,
                EquilibriumConditions::new(1_200.0, 101_325.0, 101_325.0).unwrap(),
            )
            .expect("candidate phase plan must build")
            .with_solve_options(
                EquilibriumSolveOptions::new()
                    .with_solver_policy(SolverPolicy::Single(SolverBackend::Native(Solvers::NR)))
                    .expect("single local backend policy must validate"),
            )
            .solve()
            .expect("selected local H/O universe must solve");

        assert_eq!(
            outcome.solution().build_report().candidate_selection(),
            Some(&selection)
        );
        let capsule = crate::Thermodynamics::ChemEquilibrium::equilibrium_reproducibility::
            EquilibriumReproducibilityCapsule::from_outcome(
                &outcome,
                &EquilibriumSolveOptions::new(),
            );
        assert!(capsule.candidate_selection.is_some());
        assert_eq!(
            capsule
                .candidate_selection
                .as_ref()
                .unwrap()
                .selected_records
                .len(),
            selection.selected().len()
        );
        assert_eq!(
            capsule
                .candidate_selection
                .as_ref()
                .unwrap()
                .rejected_records
                .len(),
            selection.rejected().len()
        );
        assert!(capsule.candidate_selection.as_ref().unwrap().truncated);
    }

    #[test]
    fn real_offline_multiphase_fixture_tracks_phase_lifecycle_inventory_and_universe_provenance() {
        let source = ThermoData::try_default_repository()
            .expect("bundled repository must load for the real multiphase fixture");
        let source_payloads = source.LibThermoData.as_ref().clone();
        let source_elements = source.ElementsData.as_ref().clone();
        let repository = real_h_o_multiphase_repository();
        let inventory = ElementInventory::from_amounts([("H", 1.0), ("O", 1.0)])
            .expect("closed H/O inventory must validate");
        let policy = EquilibriumCandidatePolicy::default()
            .with_allowed_libraries(vec!["NASA_gas".to_string(), "NASA_cond".to_string()])
            .with_temperature_range(300.0, 600.0)
            .expect("real fixture range must validate")
            .with_max_candidates(4)
            .expect("real fixture candidate cap must validate");
        let selection = EquilibriumCandidateSelector::new(Arc::clone(&repository))
            .select_inventory(&inventory, policy)
            .expect("real H/O fixture selection must succeed");

        assert_eq!(
            selection
                .selected()
                .iter()
                .map(|candidate| candidate.record_key())
                .collect::<Vec<_>>(),
            vec!["H2O", "O2", "H2O(L)"]
        );
        assert_eq!(
            selection.selected()[2].physical_state(),
            Some(PhysicalState::Liquid)
        );

        let phase_plan = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::ideal_gas(
                PhaseId::new(Some("gas".to_string())),
                vec!["H2O".to_string(), "O2".to_string()],
            ),
            EquilibriumCandidatePhaseAssignment::pure_condensed(
                PhaseId::new(Some("liquid".to_string())),
                PhysicalState::Liquid,
                vec!["H2O(L)".to_string()],
            ),
        ]);

        let resolved = SubstanceSystemFactory::resolve_phase_system_with_repository(
            phase_plan
                .build_spec(&selection)
                .expect("real phase plan must build a typed specification"),
            Arc::clone(&repository),
        )
        .expect("real offline phase universe must resolve");
        let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec())
            .expect("real offline phase layout must validate");
        let solve_automatic = |temperature, initial_moles| {
            let initial_composition =
                MultiphaseInitialComposition::from_dense(&layout, initial_moles)
                    .expect("element-conserving numerical seed must match the layout");
            solve_resolved_pt(
                ResolvedPhaseEquilibriumRequest::new(
                    &resolved,
                    EquilibriumConditions::new(temperature, 101_325.0, 101_325.0).unwrap(),
                    initial_composition,
                )
                .with_element_inventory(inventory.clone())
                .with_candidate_selection(Some(selection.clone()))
                .with_solve_options(
                    EquilibriumSolveOptions::new().with_timing_mode(EquilibriumTimingMode::Enabled),
                )
                .with_phase_control_policy(PhaseControlPolicy::default()),
            )
            .expect("real offline multiphase fixture must solve")
        };
        let low_temperature = solve_automatic(350.0, vec![0.5, 0.25, 0.0]);
        let high_temperature = solve_automatic(550.0, vec![0.25, 0.25, 0.25]);

        for outcome in [&low_temperature, &high_temperature] {
            let report = outcome.build_report();
            assert_eq!(
                report.input_kind(),
                PhaseEquilibriumInputKind::ElementInventory
            );
            assert_eq!(
                report.seed_evidence().source(),
                PhaseEquilibriumSeedSource::SuppliedNumericalSeed
            );
            assert_eq!(report.candidate_selection(), Some(&selection));
            let totals = report
                .element_labels()
                .iter()
                .zip(report.element_totals().iter().copied())
                .map(|(label, total)| (label.as_str(), total))
                .collect::<HashMap<_, _>>();
            assert_eq!(totals.get("H"), Some(&1.0));
            assert_eq!(totals.get("O"), Some(&1.0));
            assert!(
                outcome
                    .acceptance_report()
                    .expect("bounded solve must publish acceptance evidence")
                    .final_validation
                    .max_abs_element_balance_error
                    < 1e-6
            );
        }

        let low_liquid_status = low_temperature
            .phase_status(&PhaseId::new(Some("liquid".to_string())))
            .expect("liquid status must be published");
        assert!(matches!(
            low_liquid_status,
            PhaseStatus::Appeared | PhaseStatus::Active
        ));
        assert!(
            low_temperature
                .phase_control_report()
                .expect("low-temperature phase control report must be published")
                .transitions
                .iter()
                .any(|transition| transition.activated.iter().any(|phase| phase.index() == 1))
        );

        let high_liquid_status = high_temperature
            .phase_status(&PhaseId::new(Some("liquid".to_string())))
            .expect("liquid status must be published");
        assert!(matches!(
            high_liquid_status,
            PhaseStatus::Inactive | PhaseStatus::Disappeared
        ));
        assert!(
            high_temperature
                .phase_control_report()
                .expect("high-temperature phase control report must be published")
                .transitions
                .iter()
                .any(|transition| transition
                    .deactivated
                    .iter()
                    .any(|phase| phase.index() == 1))
        );

        let explicit_initial =
            MultiphaseInitialComposition::from_dense(&layout, vec![0.5, 0.25, 0.0])
                .expect("explicit numerical seed must match the resolved layout");
        let explicit = solve_resolved_pt(
            ResolvedPhaseEquilibriumRequest::new(
                &resolved,
                EquilibriumConditions::new(350.0, 101_325.0, 101_325.0).unwrap(),
                explicit_initial,
            )
            .with_element_inventory(inventory)
            .with_solve_options(
                EquilibriumSolveOptions::new().with_timing_mode(EquilibriumTimingMode::Enabled),
            )
            .with_phase_control_policy(PhaseControlPolicy::default()),
        )
        .expect("explicit real phase universe must solve");
        assert!(explicit.build_report().candidate_selection().is_none());
        assert_eq!(
            explicit.build_report().input_kind(),
            PhaseEquilibriumInputKind::ElementInventory
        );
        assert_eq!(
            explicit.phases(),
            low_temperature.phases(),
            "automatic selection and explicit species declaration must resolve the same phases"
        );
        for (automatic, explicit) in low_temperature
            .component_moles()
            .iter()
            .zip(explicit.component_moles())
        {
            assert!((automatic - explicit).abs() <= 1e-8);
        }

        let build_report = low_temperature.build_report();
        let acceptance = low_temperature
            .acceptance_report()
            .expect("release story must retain acceptance evidence");
        println!(
            "offline automatic multiphase release story\n  b={:?}\n  selected={:?}\n  rejected={:?}\n  matrix={}x{} rank={} reaction_dimension={}\n  seed={:?} backend={:?} iterations={} residual={:.3e} balance={:.3e}\n  transitions={} provenance={:?}\n  timing={:?}\n  explicit_backend={:?} explicit_iterations={}",
            build_report.element_totals(),
            selection
                .selected()
                .iter()
                .map(|candidate| format!("{}:{}", candidate.library(), candidate.record_key()))
                .collect::<Vec<_>>(),
            selection
                .rejected()
                .iter()
                .map(|rejection| format!("{}:{}", rejection.library(), rejection.substance()))
                .collect::<Vec<_>>(),
            build_report.components().len(),
            build_report.element_labels().len(),
            build_report.solver_element_labels().len(),
            build_report
                .components()
                .len()
                .saturating_sub(build_report.solver_element_labels().len()),
            build_report.seed_evidence().source(),
            low_temperature.solve_report().accepted_backend,
            low_temperature.nonlinear_iterations(),
            acceptance.final_validation.residual_l2_norm,
            acceptance.final_validation.max_abs_element_balance_error,
            low_temperature.phase_control_transitions(),
            build_report
                .components()
                .iter()
                .map(|component| {
                    format!(
                        "{}<-{}:{}",
                        component.component().label(),
                        component.thermo_source().library(),
                        component.thermo_source().record_key()
                    )
                })
                .collect::<Vec<_>>(),
            low_temperature.timing_report(),
            explicit.solve_report().accepted_backend,
            explicit.nonlinear_iterations(),
        );

        assert_eq!(source.LibThermoData.as_ref(), &source_payloads);
        assert_eq!(source.ElementsData.as_ref(), &source_elements);
    }

    #[test]
    fn pipeline_and_resolved_pt_facades_publish_the_same_fixed_solution() {
        // The pipeline is intentionally exercised against the already
        // resolved facade with one explicit backend. This isolates the
        // resolve/build orchestration difference from backend cascade policy
        // and makes parity a durable API contract rather than a coincidence
        // of two independent defaults.
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let conditions = EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap();
        let options = EquilibriumSolveOptions::new()
            .with_solver_policy(SolverPolicy::Single(SolverBackend::Native(Solvers::NR)))
            .expect("single native backend policy must validate");
        let pipeline = PhaseEquilibriumPipelineRequest::new(spec, vec![0.79, 0.21], conditions)
            .with_solve_options(options.clone());
        let resolved = pipeline
            .clone()
            .resolve()
            .expect("pipeline resolution must succeed");
        let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec()).unwrap();
        let composition = MultiphaseInitialComposition::from_dense(&layout, vec![0.79, 0.21])
            .expect("direct facade composition must match the resolved layout");

        let pipeline_solution = pipeline
            .solve()
            .expect("pipeline facade must solve")
            .into_solution();
        let direct_solution = solve_resolved_pt(
            ResolvedPhaseEquilibriumRequest::new(&resolved, conditions, composition)
                .with_solve_options(options),
        )
        .expect("resolved facade must solve");

        assert_eq!(
            pipeline_solution.component_moles().len(),
            direct_solution.component_moles().len()
        );
        for (pipeline_moles, direct_moles) in pipeline_solution
            .component_moles()
            .iter()
            .zip(direct_solution.component_moles())
        {
            assert!((pipeline_moles - direct_moles).abs() <= 1e-8);
        }
        assert!(
            (pipeline_solution
                .accepted_solution()
                .validation()
                .residual_l2_norm
                - direct_solution
                    .accepted_solution()
                    .validation()
                    .residual_l2_norm)
                .abs()
                <= 1e-12
        );
        assert_eq!(
            pipeline_solution.build_report().layout_fingerprint(),
            direct_solution.build_report().layout_fingerprint()
        );
    }

    #[test]
    #[allow(deprecated)]
    fn mutable_and_typed_serial_temperature_ranges_match_on_o2_o_fixture() {
        let temperatures = vec![1_000.0, 1_200.0, 1_400.0];
        let pressure = 101_325.0;
        let initial_moles = vec![1.0, 1.0e-5];
        let policy = SolverPolicy::native_default(Solvers::LM);

        let legacy = gas_solver_for_T_range(
            vec!["O2".to_string(), "O".to_string()],
            initial_moles.clone(),
            pressure,
            temperatures[0],
            1_500.0,
            200.0,
            Solvers::LM,
            None,
            false,
        )
        .expect("mutable compatibility sweep should solve the O2/O fixture");

        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "O2".to_string(),
            "O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .expect("local O2/O system specification must validate");
        let options = EquilibriumSolveOptions::new()
            .with_scaling(false)
            .with_solver_policy(policy)
            .expect("matched native solver policy must validate");
        let typed = PhaseEquilibriumPipelineRequest::new(
            spec,
            initial_moles,
            EquilibriumConditions::new(temperatures[0], pressure, pressure).unwrap(),
        )
        .with_solve_options(options)
        .solve_temperature_range(TemperatureGrid::new(temperatures.clone()).unwrap())
        .expect("typed transactional sweep should solve the O2/O fixture");

        assert!(legacy.temperature_failures.is_empty());
        assert!(legacy.list_of_failed_T.is_empty());
        assert_eq!(legacy.moles_for_T_range.len(), temperatures.len());
        assert_eq!(typed.points().len(), temperatures.len());
        assert_eq!(
            typed.points()[0].report().preparation(),
            TemperatureRangePointPreparation::InitialFormulation
        );
        assert!(typed.points()[1..].iter().all(|point| {
            point.report().preparation() == TemperatureRangePointPreparation::ReusedFormulation
        }));

        for ((legacy_temperature, legacy_moles), typed_point) in
            legacy.moles_for_T_range.iter().zip(typed.points())
        {
            assert_eq!(*legacy_temperature, typed_point.report().temperature());
            let typed_moles = typed_point.solution().component_moles();
            assert_eq!(legacy_moles.len(), typed_moles.len());
            let mut max_abs_mole_delta: f64 = 0.0;
            let mut max_relative_mole_delta: f64 = 0.0;
            for (legacy_moles, typed_moles) in legacy_moles.iter().zip(typed_moles) {
                let scale = legacy_moles.abs().max(typed_moles.abs()).max(1.0e-12);
                let delta = (legacy_moles - typed_moles).abs();
                max_abs_mole_delta = max_abs_mole_delta.max(delta);
                max_relative_mole_delta = max_relative_mole_delta.max(delta / scale);
                assert!(
                    delta <= 1.0e-4 * scale + 1.0e-14,
                    "range parity mismatch at T={legacy_temperature}: mutable={legacy_moles:.16e}, typed={typed_moles:.16e}"
                );
            }
            let typed_balance = typed_point
                .solution()
                .accepted_solution()
                .validation()
                .max_abs_element_balance_error;
            let legacy_balance = legacy
                .temperature_solutions
                .iter()
                .find(|snapshot| snapshot.temperature == *legacy_temperature)
                .expect("legacy sweep must retain one snapshot per accepted point")
                .validation
                .max_abs_element_balance_error;
            eprintln!(
                "O2/O range parity T={legacy_temperature:.0} K max_abs_mole_delta={max_abs_mole_delta:.3e} max_relative_mole_delta={max_relative_mole_delta:.3e} mutable_balance={legacy_balance:.3e} typed_balance={typed_balance:.3e}"
            );
            assert!(typed_balance < 1.0e-8);
            assert!(legacy_balance < 1.0e-8);
        }
    }

    #[test]
    #[allow(deprecated)]
    fn mutable_and_typed_temperature_ranges_characterize_large_inventory_recovery() {
        let temperatures = vec![1_000.0, 1_200.0, 1_400.0];
        let pressure = 101_325.0;
        let scale = 1.0e8;
        let initial_moles = vec![scale, scale * 1.0e-5];
        let policy = SolverPolicy::native_default(Solvers::LM);

        let legacy = gas_solver_for_T_range(
            vec!["O2".to_string(), "O".to_string()],
            initial_moles.clone(),
            pressure,
            temperatures[0],
            1_500.0,
            200.0,
            Solvers::LM,
            None,
            false,
        )
        .expect("mutable compatibility sweep should prepare the scaled O2/O case");

        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "O2".to_string(),
            "O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .expect("local O2/O system specification must validate");
        let options = EquilibriumSolveOptions::new()
            .with_scaling(false)
            .with_solver_policy(policy)
            .expect("matched native solver policy must validate")
            .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::OnNumericalFailure);
        let typed_result = PhaseEquilibriumPipelineRequest::new(
            spec,
            initial_moles,
            EquilibriumConditions::new(temperatures[0], pressure, pressure).unwrap(),
        )
        .with_solve_options(options)
        .solve_temperature_range(TemperatureGrid::new(temperatures.clone()).unwrap());

        assert_eq!(
            legacy.moles_for_T_range.len() + legacy.temperature_failures.len(),
            temperatures.len(),
            "mutable range must account for each requested point as accepted or failed"
        );
        assert_eq!(
            legacy.list_of_failed_T,
            legacy
                .temperature_failures
                .iter()
                .map(|failure| failure.temperature)
                .collect::<Vec<_>>()
        );

        let legacy_accepted = legacy
            .moles_for_T_range
            .iter()
            .map(|(temperature, _)| *temperature)
            .collect::<Vec<_>>();
        let legacy_failed = legacy
            .temperature_failures
            .iter()
            .map(|failure| failure.temperature)
            .collect::<Vec<_>>();
        assert!(legacy_accepted.is_empty());
        assert_eq!(legacy_failed, temperatures);
        eprintln!(
            "O2/O scale={scale:.1e}: mutable rejected all points; first failure: {}",
            legacy.temperature_failures[0].message
        );

        let typed = typed_result.expect("typed range should recover the scaled O2/O case");
        assert_eq!(typed.points().len(), temperatures.len());
        assert_eq!(
            typed.points()[0].report().preparation(),
            TemperatureRangePointPreparation::RecoveryFormulation
        );
        assert!(typed.points()[1..].iter().all(|point| {
            point.report().preparation() == TemperatureRangePointPreparation::ReusedFormulation
        }));
        let recovery = typed.points()[0]
            .solution()
            .extensive_normalization_recovery()
            .expect("first point must retain normalization recovery provenance");
        assert!(
            (recovery.physical_inventory_scale - scale * (1.0 + 1.0e-5)).abs()
                <= 1.0e-12 * recovery.physical_inventory_scale
        );
        let reference_spec =
            SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
                "O2".to_string(),
                "O".to_string(),
            ]))
            .with_library_priorities(vec!["NASA_gas".to_string()])
            .with_search_in_nist(false)
            .build()
            .expect("unit-scale O2/O system specification must validate");
        let reference = PhaseEquilibriumPipelineRequest::new(
            reference_spec,
            vec![1.0, 1.0e-5],
            EquilibriumConditions::new(temperatures[0], pressure, pressure).unwrap(),
        )
        .with_solve_options(
            EquilibriumSolveOptions::new()
                .with_scaling(false)
                .with_solver_policy(SolverPolicy::native_default(Solvers::LM))
                .expect("reference native solver policy must validate"),
        )
        .solve_temperature_range(TemperatureGrid::new(temperatures.clone()).unwrap())
        .expect("unit-scale O2/O reference range should solve");

        for (point, reference_point) in typed.points().iter().zip(reference.points()) {
            let solution = point.solution();
            let totals = solution.build_report().element_totals();
            let relative_balance = solution
                .accepted_solution()
                .validation()
                .max_abs_element_balance_error
                / totals
                    .iter()
                    .map(|total| total.abs())
                    .fold(1.0e-30, f64::max);
            let relative_mole_error = solution
                .component_moles()
                .iter()
                .zip(reference_point.solution().component_moles())
                .map(|(scaled, unit)| (scaled / scale - unit).abs() / unit.abs().max(1.0e-20))
                .fold(0.0, f64::max);
            eprintln!(
                "O2/O scale={scale:.1e} T={:.0} K preparation={:?} recovery={} relative_mole_error={relative_mole_error:.3e} relative_balance={relative_balance:.3e}",
                point.report().temperature(),
                point.report().preparation(),
                solution.extensive_normalization_recovery().is_some()
            );
            assert!(relative_mole_error < 1.0e-4);
            assert!(relative_balance < 1.0e-12);
        }
    }

    #[test]
    #[allow(deprecated)]
    fn mutable_and_typed_temperature_ranges_characterize_solver_budget_failures() {
        let temperatures = vec![400.0, 1_900.0, 3_400.0, 4_900.0];
        let pressure = 101_325.0;
        let mut found_mutable_partial_sweep = false;
        let mut found_mutable_continuation_after_failure = false;
        let mut no_worse_failures = Vec::new();

        for max_iterations in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 20, 30] {
            let mut mutable = gas_solver_for_T_range(
                vec!["O2".to_string(), "O".to_string()],
                vec![1.0, 1.0e-5],
                pressure,
                temperatures[0],
                5_000.0,
                1_500.0,
                Solvers::LM,
                None,
                false,
            )
            .expect("mutable O2/O range should prepare");
            let mutable_initial_seed = mutable
                .initial_guess
                .clone()
                .expect("mutable setup should retain its generated first-point seed");
            mutable.solver_settings.solver_params.max_iter = max_iterations;
            let mutable_result = mutable
                .solve_for_T_range(temperatures[0], 5_000.0, 1_500.0)
                .expect("mutable sweep should record per-point solver failures");
            assert_eq!(
                mutable_result.len() + mutable.temperature_failures.len(),
                temperatures.len()
            );

            let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
                "O2".to_string(),
                "O".to_string(),
            ]))
            .with_library_priorities(vec!["NASA_gas".to_string()])
            .with_search_in_nist(false)
            .build()
            .expect("local O2/O system specification must validate");
            let options = EquilibriumSolveOptions::new()
                .with_scaling(false)
                .with_solver_policy(SolverPolicy::native_default(Solvers::LM))
                .expect("native solver policy must validate")
                .with_max_iterations(max_iterations)
                .expect("iteration budget must validate")
                .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::Disabled);
            let old_params = &mutable.solver_settings.solver_params;
            let typed_params = &options.settings.solver_params;
            assert_eq!(mutable.solver_settings.solver, options.settings.solver);
            assert_eq!(
                mutable.solver_settings.solver_policy,
                options.settings.solver_policy
            );
            assert_eq!(
                mutable.solver_settings.solver_budget,
                options.settings.solver_budget
            );
            assert_eq!(old_params.max_iter, typed_params.max_iter);
            assert_eq!(old_params.tol, typed_params.tol);
            assert_eq!(old_params.lambda, typed_params.lambda);
            assert_eq!(old_params.alpha_min, typed_params.alpha_min);
            assert_eq!(old_params.delta_init, typed_params.delta_init);
            assert_eq!(old_params.delta_max, typed_params.delta_max);
            assert_eq!(old_params.eta, typed_params.eta);
            assert_eq!(
                mutable.solver_settings.scaling_flag,
                options.settings.scaling_flag
            );
            let resolved = SubstanceSystemFactory::resolve_phase_system(spec)
                .expect("O2/O records should resolve once for the prepared range");
            let seed_composition = MultiphaseInitialComposition::from_dense(
                &MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec()).unwrap(),
                mutable_initial_seed
                    .iter()
                    .map(|value| value.exp())
                    .collect(),
            )
            .expect("generated mutable seed should map into the resolved species layout");
            let typed_result = TemperatureRangeRequest::from_element_inventory(
                &resolved,
                ElementInventory::from_amounts([("O", 2.0 + 1.0e-5)])
                    .expect("physical oxygen inventory should validate"),
                pressure,
                pressure,
                TemperatureGrid::new(temperatures.clone()).unwrap(),
            )
            .expect("element-defined typed range should prepare")
            .with_initial_composition(seed_composition)
            .expect("mutable generated seed should validate as a numerical seed")
            .with_solve_options(options)
            .solve_best_effort()
            .expect("best-effort typed range should return point-level outcomes");

            let mutable_failed = mutable
                .temperature_failures
                .iter()
                .map(|failure| failure.temperature)
                .collect::<Vec<_>>();
            let mutable_accepted = mutable
                .moles_for_T_range
                .iter()
                .map(|(temperature, _)| *temperature)
                .collect::<Vec<_>>();
            if !mutable_failed.is_empty() && !mutable_accepted.is_empty() {
                found_mutable_partial_sweep = true;
                found_mutable_continuation_after_failure |= mutable_accepted
                    .iter()
                    .any(|accepted| *accepted > mutable_failed[0]);
            }
            let typed_accepted = typed_result
                .solution()
                .points()
                .iter()
                .map(|point| point.report().temperature())
                .collect::<Vec<_>>();
            let typed_failed = typed_result
                .failures()
                .iter()
                .map(|failure| failure.temperature())
                .collect::<Vec<_>>();
            eprintln!(
                "range budget={max_iterations}: mutable accepted={mutable_accepted:?} failed={mutable_failed:?}; typed accepted={typed_accepted:?} failed={typed_failed:?}"
            );
            assert_eq!(
                typed_accepted.len() + typed_failed.len(),
                temperatures.len()
            );
            for temperature in &mutable_accepted {
                if !typed_accepted.contains(temperature) {
                    no_worse_failures.push((max_iterations, *temperature));
                }
            }
            for (temperature, mutable_moles) in &mutable.moles_for_T_range {
                let Some(typed_point) = typed_result
                    .solution()
                    .points()
                    .iter()
                    .find(|point| point.report().temperature() == *temperature)
                else {
                    continue;
                };
                for (typed_mole, mutable_mole) in typed_point
                    .solution()
                    .component_moles()
                    .iter()
                    .zip(mutable_moles)
                {
                    let scale = typed_mole.abs().max(mutable_mole.abs()).max(1.0e-12);
                    assert!(
                        (typed_mole - mutable_mole).abs() <= 1.0e-4 * scale + 1.0e-14,
                        "typed/mutable mole mismatch at {temperature} K with budget {max_iterations}: typed={typed_mole}, mutable={mutable_mole}"
                    );
                }
            }
        }

        assert!(
            found_mutable_partial_sweep,
            "budget scan did not find a mutable sweep with both accepted and failed points"
        );
        assert!(
            found_mutable_continuation_after_failure,
            "mutable range did not resume after an isolated failed point"
        );
        assert_eq!(
            no_worse_failures,
            Vec::<(usize, f64)>::new(),
            "typed prepared ranges must not lose any point accepted by the mutable route"
        );
    }

    #[test]
    #[allow(deprecated)]
    fn mutable_and_typed_high_temperature_problem_contract_diagnostic() {
        let temperature = 4_900.0;
        let pressure = 101_325.0;
        let mutable = gas_solver_for_T_range(
            vec!["O2".to_string(), "O".to_string()],
            vec![1.0, 1.0e-5],
            pressure,
            temperature,
            5_000.0,
            1_500.0,
            Solvers::LM,
            None,
            false,
        )
        .expect("mutable high-temperature problem should prepare");
        let seed = LogMolesInitialGuess::new(
            mutable
                .initial_guess
                .clone()
                .expect("mutable setup should retain its generated seed"),
        )
        .unwrap();
        let old_delta_n = crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::
            reaction_phase_stoichiometry(&mutable.stoich_matrix, &mutable.phases);
        let old_residual_fn = crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::
            equilibrium_logmole_residual(
                mutable.stoich_matrix.clone(),
                mutable.elem_composition.clone(),
                mutable.elements_vector.clone(),
                mutable.gibbs.clone(),
                mutable.phases.clone(),
                temperature,
                mutable.P,
                mutable.p0,
                mutable.species_phase.clone(),
                mutable.species_eps,
                mutable.substate_eps,
            )
            .expect("mutable residual contract should build");
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "O2".to_string(),
            "O".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let resolved = SubstanceSystemFactory::resolve_phase_system(spec).unwrap();
        let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec()).unwrap();
        let composition = MultiphaseInitialComposition::from_dense(
            &layout,
            seed.as_slice().iter().map(|value| value.exp()).collect(),
        )
        .expect("mutable generated seed should map into the typed species layout");
        let build_request = PhaseEquilibriumBuildRequest::from_element_inventory(
            &resolved,
            EquilibriumConditions::new(temperature, pressure, pressure).unwrap(),
            ElementInventory::from_amounts([("O", 2.0 + 1.0e-5)])
                .expect("physical oxygen inventory should validate"),
            TraceSpeciesSeedPolicy::Absolute {
                floor: crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::
                    DEFAULT_TRACE_MOLE_FLOOR,
            },
            SupportedPhaseModelPolicy::default(),
        )
        .unwrap()
        .with_numerical_seed(composition)
        .unwrap();
        let bundle = crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
            build_phase_equilibrium_problem_with_timing(
                build_request,
                EquilibriumTimingMode::Disabled,
            )
            .unwrap();
        let typed_initial_seed = bundle.problem().initial_log_moles().as_slice().to_vec();
        assert_eq!(typed_initial_seed, seed.as_slice());
        assert_eq!(mutable.initial_guess.as_deref(), Some(seed.as_slice()));
        let typed_prepared = crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::
            PreparedEquilibriumProblem::new(bundle.into_problem())
            .unwrap();
        assert_eq!(mutable.elements_vector, typed_prepared.element_totals());

        for perturbation in [[0.0, 0.0], [0.2, -0.1], [-1.0, 0.5], [1.0, -0.7]] {
            let probe = seed
                .as_slice()
                .iter()
                .zip(perturbation)
                .map(|(value, delta)| value + delta)
                .collect::<Vec<_>>();
            let old_residual = old_residual_fn(&probe).unwrap();
            let typed_residual = typed_prepared.residual(&probe).unwrap();
            let old_jacobian = crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::
                evaluate_equilibrium_logmole_jacobian(
                    &probe,
                    &mutable.stoich_matrix,
                    &mutable.elem_composition,
                    &mutable.species_phase,
                    &old_delta_n,
                    mutable.phases.len(),
                )
                .unwrap();
            let typed_jacobian = typed_prepared.jacobian(&probe).unwrap();
            let residual_max_abs_delta = old_residual
                .iter()
                .zip(&typed_residual)
                .map(|(old, typed)| (old - typed).abs())
                .fold(0.0, f64::max);
            let jacobian_max_abs_delta = old_jacobian
                .iter()
                .zip(typed_jacobian.iter())
                .map(|(old, typed)| (old - typed).abs())
                .fold(0.0, f64::max);
            assert_eq!(old_residual.len(), typed_residual.len());
            assert_eq!(old_jacobian.shape(), typed_jacobian.shape());
            assert!(
                residual_max_abs_delta <= 1.0e-12,
                "same-state residual drift at perturbation {perturbation:?}: old={old_residual:?}, typed={typed_residual:?}"
            );
            assert!(
                jacobian_max_abs_delta <= 1.0e-12,
                "same-state Jacobian drift at perturbation {perturbation:?}: max_abs_delta={jacobian_max_abs_delta:e}"
            );
            eprintln!(
                "4900 K perturbation={perturbation:?} max_residual_delta={residual_max_abs_delta:.3e} max_jacobian_delta={jacobian_max_abs_delta:.3e} old={old_residual:?}"
            );
        }
    }

    #[test]
    #[allow(deprecated)]
    fn typed_best_effort_range_matches_mutable_partial_sweep_after_middle_failure() {
        let temperatures = vec![1_000.0, 1_200.0, 1_400.0];
        let pressure = 101_325.0;
        let typed_request = || {
            let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
                "O2".to_string(),
                "O".to_string(),
            ]))
            .with_library_priorities(vec!["NASA_gas".to_string()])
            .with_search_in_nist(false)
            .build()
            .expect("local O2/O system specification must validate");
            PhaseEquilibriumPipelineRequest::new(
                spec,
                vec![1.0, 1.0e-5],
                EquilibriumConditions::new(temperatures[0], pressure, pressure).unwrap(),
            )
            .with_solve_options(
                EquilibriumSolveOptions::new()
                    .with_scaling(false)
                    .with_solver_policy(SolverPolicy::native_default(Solvers::LM))
                    .expect("native solver policy must validate"),
            )
        };
        let reference = typed_request()
            .solve_temperature_range(TemperatureGrid::new(temperatures.clone()).unwrap())
            .expect("clean typed reference range must solve");

        crate::Thermodynamics::ChemEquilibrium::equilibrium_temperature_range::
            arm_test_range_failure(1);
        let typed_error = typed_request()
            .solve_temperature_range(TemperatureGrid::new(temperatures.clone()).unwrap())
            .expect_err("typed range must abort atomically at the injected point");
        match typed_error {
            PhaseEquilibriumPipelineError::Solve(
                ReactionExtentError::TemperatureRangePointFailed {
                    point_index,
                    temperature,
                    cause,
                },
            ) => {
                assert_eq!(point_index, 1);
                assert_eq!(temperature, temperatures[1]);
                assert!(matches!(
                    *cause,
                    ReactionExtentError::InvalidProblem {
                        field: "test_temperature_range_failure",
                        ref message,
                    } if message == "test-only injected point failure"
                ));
            }
            other => panic!("expected indexed typed range failure, got {other:?}"),
        }

        crate::Thermodynamics::ChemEquilibrium::equilibrium_temperature_range::
            arm_test_range_failure(1);
        let typed_partial = typed_request()
            .solve_temperature_range_best_effort(
                TemperatureGrid::new(temperatures.clone()).unwrap(),
            )
            .expect("best-effort typed range should retain points around an isolated failure");
        assert_eq!(typed_partial.failures().len(), 1);
        assert_eq!(typed_partial.failures()[0].point_index(), 1);
        assert_eq!(typed_partial.failures()[0].temperature(), temperatures[1]);
        assert_eq!(
            typed_partial
                .solution()
                .points()
                .iter()
                .map(|point| point.report().temperature())
                .collect::<Vec<_>>(),
            vec![temperatures[0], temperatures[2]]
        );

        crate::Thermodynamics::ChemEquilibrium::equilibrium_temperature_range::
            arm_test_range_failure(1);
        let mutable = gas_solver_for_T_range(
            vec!["O2".to_string(), "O".to_string()],
            vec![1.0, 1.0e-5],
            pressure,
            temperatures[0],
            1_500.0,
            200.0,
            Solvers::LM,
            None,
            false,
        )
        .expect("mutable O2/O compatibility range should prepare");
        let rows = &mutable.moles_for_T_range;

        assert_eq!(
            rows.iter()
                .map(|(temperature, _)| *temperature)
                .collect::<Vec<_>>(),
            vec![temperatures[0], temperatures[2]]
        );
        assert_eq!(mutable.list_of_failed_T, vec![temperatures[1]]);
        assert_eq!(mutable.temperature_failures.len(), 1);
        assert!(
            mutable.temperature_failures[0]
                .message
                .contains("test-only injected point failure")
        );
        for ((temperature, moles), reference_point) in rows
            .iter()
            .zip([&reference.points()[0], &reference.points()[2]])
        {
            assert_eq!(*temperature, reference_point.report().temperature());
            for (actual, expected) in moles
                .iter()
                .zip(reference_point.solution().component_moles())
            {
                let scale = actual.abs().max(expected.abs()).max(1.0e-12);
                assert!((actual - expected).abs() <= 1.0e-4 * scale + 1.0e-14);
            }
        }
        for (typed_point, mutable_row) in typed_partial.solution().points().iter().zip(rows.iter())
        {
            assert_eq!(typed_point.report().temperature(), mutable_row.0);
            for (typed_mole, mutable_mole) in typed_point
                .solution()
                .component_moles()
                .iter()
                .zip(&mutable_row.1)
            {
                let scale = typed_mole.abs().max(mutable_mole.abs()).max(1.0e-12);
                assert!((typed_mole - mutable_mole).abs() <= 1.0e-4 * scale + 1.0e-14);
            }
        }
    }

    #[test]
    fn fixed_pipeline_publishes_explicit_multi_start_evidence() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let conditions = EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap();
        let seed = LogMolesInitialGuess::from_initial_moles(&[0.79, 0.21]).unwrap();

        let outcome = PhaseEquilibriumPipelineRequest::new(spec, vec![0.79, 0.21], conditions)
            .with_multi_start_seeds(vec![seed.clone(), seed])
            .solve()
            .unwrap();

        let report = outcome
            .solution()
            .multi_start_report()
            .expect("fixed multi-start must publish its comparison report");
        assert_eq!(report.attempts.len(), 2);
        assert!(report.attempts.iter().all(|attempt| attempt.accepted));
        assert!(report.selected_start < report.attempts.len());
    }

    #[test]
    fn multi_start_is_rejected_for_bounded_phase_control() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let seed = LogMolesInitialGuess::from_initial_moles(&[0.79, 0.21]).unwrap();

        let error = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_phase_control_policy(PhaseControlPolicy::default())
        .with_multi_start_seeds(vec![seed])
        .solve()
        .unwrap_err();

        assert!(matches!(
            error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::InvalidProblem {
                field: "multi_start_phase_control",
                ..
            })
        ));
    }

    #[test]
    fn multi_start_rejects_a_seed_with_the_wrong_component_dimension() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(false)
        .build()
        .unwrap();
        let bad_seed = LogMolesInitialGuess::from_initial_moles(&[1.0]).unwrap();

        let error = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_multi_start_seeds(vec![bad_seed])
        .solve()
        .unwrap_err();

        assert!(matches!(
            error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::InvalidProblem {
                field: "multi_start_seed_dimension",
                ..
            })
        ));
    }

    #[test]
    fn sparse_pipeline_inventory_matches_dense_ordered_inventory() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(true)
        .build()
        .unwrap();
        let conditions = EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap();
        let dense =
            PhaseEquilibriumPipelineRequest::new(spec.clone(), vec![0.79, 0.21], conditions)
                .solve()
                .unwrap();
        let sparse = PhaseEquilibriumPipelineRequest::new_with_sparse_initial_composition(
            spec,
            vec![
                (PhaseComponentId::new(PhaseId::new(None), "N2"), 0.79),
                (PhaseComponentId::new(PhaseId::new(None), "O2"), 0.21),
            ],
            conditions,
        )
        .solve()
        .unwrap();

        assert_eq!(
            dense.solution().component_moles(),
            sparse.solution().component_moles()
        );
        assert_eq!(
            dense.solution().layout_fingerprint(),
            sparse.solution().layout_fingerprint()
        );
    }

    #[test]
    fn sparse_pipeline_inventory_rejects_duplicate_phase_components() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(true)
        .build()
        .unwrap();
        let duplicate = PhaseComponentId::new(PhaseId::new(None), "N2");
        let error = PhaseEquilibriumPipelineRequest::new_with_sparse_initial_composition(
            spec,
            vec![(duplicate.clone(), 0.79), (duplicate, 0.21)],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .solve()
        .unwrap_err();

        assert!(matches!(
            error,
            PhaseEquilibriumPipelineError::Solve(ReactionExtentError::InvalidProblem {
                field: "initial_composition",
                ..
            })
        ));
    }

    #[test]
    fn phase_control_policy_rejects_an_invalid_hysteresis_order() {
        assert!(PhaseControlPolicy::with_explicit_hysteresis(1e-6, 1.0, 0.5).is_err());
    }

    #[test]
    fn phase_control_policy_rejects_invalid_scalar_limits_at_construction() {
        let mut manager = PhaseManager::default();
        manager.phase_eps = 0.0;
        assert!(PhaseControlPolicy::new(manager).is_err());

        let mut manager = PhaseManager::default();
        manager.max_phase_iterations = 0;
        assert!(PhaseControlPolicy::new(manager).is_err());
    }

    #[test]
    fn typed_policy_builders_reject_invalid_limits_before_solving() {
        assert!(
            EquilibriumSolveOptions::default()
                .with_max_iterations(0)
                .is_err()
        );
        assert!(
            EquilibriumSolveOptions::default()
                .with_tolerance(0.0)
                .is_err()
        );
        assert!(
            PhaseControlPolicy::default()
                .with_phase_epsilon(0.0)
                .is_err()
        );
        assert!(
            PhaseControlPolicy::default()
                .with_max_phase_iterations(0)
                .is_err()
        );
    }

    #[test]
    fn normalized_phase_policy_scales_only_the_absolute_phase_epsilon() {
        let policy = PhaseControlPolicy::with_explicit_hysteresis(1.0e-12, -2.0, -1.0)
            .unwrap()
            .normalized_for_extensive_representation(
                ExtensiveNormalization::from_physical_inventory_scale(1.0e6).unwrap(),
            )
            .unwrap();
        let manager = policy.into_phase_manager();
        assert!((manager.phase_eps - 1.0e-18).abs() <= 1.0e-30);
        assert_eq!(
            manager.phase_hysteresis,
            crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::
                PhaseHysteresisPolicy::Explicit {
                dg_create: -2.0,
                dg_keep: -1.0,
            }
        );
    }

    #[test]
    fn extensive_normalization_policy_is_explicit_and_reproducible() {
        let defaults = EquilibriumSolveOptions::default();
        assert_eq!(
            defaults.extensive_normalization_policy(),
            ExtensiveNormalizationPolicy::OnNumericalFailureAndSmallScalePhPreconditioning
        );
        assert_eq!(
            defaults
                .reproducibility_snapshot()
                .extensive_normalization_policy,
            "OnNumericalFailureAndSmallScalePhPreconditioning"
        );
        assert!(
            defaults
                .extensive_normalization_policy()
                .allows_small_scale_ph_preconditioning()
        );
        let failure_only = defaults
            .clone()
            .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::OnNumericalFailure);
        assert!(
            failure_only
                .extensive_normalization_policy()
                .allows_numerical_failure_recovery()
        );
        assert!(
            !failure_only
                .extensive_normalization_policy()
                .allows_small_scale_ph_preconditioning()
        );

        let disabled =
            defaults.with_extensive_normalization_policy(ExtensiveNormalizationPolicy::Disabled);
        assert_eq!(
            disabled.extensive_normalization_policy(),
            ExtensiveNormalizationPolicy::Disabled
        );
        assert_eq!(
            disabled
                .reproducibility_snapshot()
                .extensive_normalization_policy,
            "Disabled"
        );
    }

    #[test]
    fn extensive_recovery_guard_is_symmetric_and_has_an_explicit_boundary() {
        assert!(!is_materially_extensive_scaled(0.1));
        assert!(!is_materially_extensive_scaled(1.0));
        assert!(!is_materially_extensive_scaled(10.0));
        assert!(is_materially_extensive_scaled(0.099));
        assert!(is_materially_extensive_scaled(10.001));
        assert!(!is_materially_extensive_scaled(0.0));
        assert!(!is_materially_extensive_scaled(f64::NAN));
        assert!(!is_materially_extensive_scaled(f64::INFINITY));
    }

    #[test]
    fn normalized_recovery_uses_a_relative_seed_after_absolute_floor_scaling() {
        let normalization = ExtensiveNormalization::from_physical_moles(&[4.0e4, 2.0e4])
            .expect("positive physical inventory must normalize");
        let policy = normalized_recovery_trace_policy(
            normalization,
            TraceSpeciesSeedPolicy::Absolute { floor: 1.0e-30 },
        )
        .expect("absolute trace policy must normalize");

        assert!(matches!(
            policy,
            TraceSpeciesSeedPolicy::RelativeToLargestInitialMole {
                fraction,
                minimum_floor,
            } if fraction == EXTENSIVE_RECOVERY_RELATIVE_TRACE_FRACTION
                && (minimum_floor - 1.0e-30 / 6.0e4).abs() <= 1.0e-48
        ));
    }

    #[test]
    fn extensive_recovery_authorizes_only_retryable_numerical_failures() {
        let retryable = [
            ReactionExtentError::AllBackendsFailed { attempts: vec![] },
            ReactionExtentError::SolveError(SolveError::MaxIterations),
            ReactionExtentError::SolveError(SolveError::SingularMatrix),
            ReactionExtentError::BackendFailure {
                backend: "test".to_string(),
                kind: BackendFailureKind::NumericalBreakdown,
                message: "test numerical breakdown".to_string(),
            },
        ];
        assert!(
            retryable
                .iter()
                .all(is_extensive_normalization_recovery_candidate)
        );

        let non_retryable = [
            ReactionExtentError::Cancelled,
            ReactionExtentError::InvalidProblem {
                field: "test",
                message: "invalid".to_string(),
            },
            ReactionExtentError::InvalidConditions {
                parameter: "temperature",
                value: 0.0,
            },
            ReactionExtentError::InvalidCandidate {
                field: "residual",
                message: "rejected".to_string(),
            },
            ReactionExtentError::ResidualEvaluation("test residual".to_string()),
            ReactionExtentError::JacobianEvaluation("test jacobian".to_string()),
            ReactionExtentError::UnsupportedBackendCapability {
                backend: "test".to_string(),
                capability: "test",
                alternatives: "none".to_string(),
            },
            ReactionExtentError::CascadeAborted {
                attempts: vec![],
                cause: Box::new(ReactionExtentError::InvalidProblem {
                    field: "test",
                    message: "abort".to_string(),
                }),
            },
        ];
        assert!(
            non_retryable
                .iter()
                .all(|error| !is_extensive_normalization_recovery_candidate(error))
        );
    }

    #[test]
    fn options_snapshot_round_trips_the_extensive_recovery_policy() {
        for policy in [
            ExtensiveNormalizationPolicy::Disabled,
            ExtensiveNormalizationPolicy::OnNumericalFailure,
        ] {
            let snapshot = EquilibriumSolveOptions::new()
                .with_extensive_normalization_policy(policy)
                .reproducibility_snapshot();
            let json = serde_json::to_string(&snapshot).unwrap();
            let decoded: EquilibriumSolveOptionsSnapshot = serde_json::from_str(&json).unwrap();
            assert_eq!(decoded, snapshot);
            assert_eq!(
                decoded.extensive_normalization_policy,
                format!("{policy:?}")
            );
        }
    }

    #[test]
    fn trace_seed_policy_has_one_typed_source_of_truth() {
        let policy = TraceSpeciesSeedPolicy::RelativeToLargestInitialMole {
            fraction: 1e-8,
            minimum_floor: 1e-16,
        };
        let options = EquilibriumSolveOptions::default().with_trace_seed_policy(policy);
        assert_eq!(options.trace_seed_policy(), policy);
    }

    #[test]
    fn phase_control_policy_rejects_indices_after_resolved_phase_count_is_known() {
        let manager = PhaseManager {
            initial_phase_set: crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::
                InitialPhaseSet::Explicit {
                active: vec![crate::Thermodynamics::ChemEquilibrium::equilibrium_ids::PhaseIndex::new(2, 3).unwrap()],
                excluded: Vec::new(),
            },
            ..PhaseManager::default()
        };

        PhaseControlPolicy::new(manager)
            .unwrap()
            .into_phase_manager()
            .validate_for_phase_count(2)
            .expect_err("resolved phase bounds must be checked before active-set construction");
    }

    #[test]
    fn selecting_a_preferred_backend_clears_an_explicit_policy() {
        let settings = EquilibriumSolverSettings {
            solver_policy: Some(SolverPolicy::Single(SolverBackend::Native(Solvers::NR))),
            ..EquilibriumSolverSettings::default()
        };
        let options = EquilibriumSolveOptions::from_settings(settings)
            .unwrap()
            .with_solver_backend(Solvers::TR);
        let settings = options.into_settings();

        assert_eq!(settings.solver, Solvers::TR);
        assert!(settings.solver_policy.is_none());
    }

    #[test]
    fn rst_symbolic_frontend_is_publicly_selectable_and_defaults_to_expr_legacy() {
        use crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstSymbolicFrontend;

        let defaults = EquilibriumSolveOptions::new();
        assert_eq!(
            defaults.rst_symbolic_frontend(),
            RstSymbolicFrontend::ExprLegacy
        );
        assert_eq!(
            defaults.reproducibility_snapshot().rst_symbolic_frontend,
            "ExprLegacy"
        );

        let atom = defaults.with_rst_symbolic_frontend(RstSymbolicFrontend::AtomView);
        assert_eq!(atom.rst_symbolic_frontend(), RstSymbolicFrontend::AtomView);
        assert_eq!(
            atom.reproducibility_snapshot().rst_symbolic_frontend,
            "AtomView"
        );
    }

    #[test]
    fn pipeline_outcome_exposes_the_original_lookup_provenance() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(true)
        .build()
        .unwrap();
        let request = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        );

        let outcome = request.solve().unwrap();

        assert_eq!(outcome.lookup_report(), outcome.resolved().report());
        assert_eq!(
            outcome.solution().build_report().lookup_report(),
            outcome.lookup_report()
        );
        let report_table = outcome.lookup_report().render_table();
        assert!(report_table.contains("NIST fallback=enabled"));
        assert!(report_table.contains("N2"));
        assert!(report_table.contains("NASA_gas"));
    }

    #[test]
    fn solve_mode_defaults_to_the_explicit_fixed_declared_phase_path() {
        assert!(matches!(
            PhaseEquilibriumSolveMode::default(),
            PhaseEquilibriumSolveMode::FixedDeclaredPhases
        ));
        assert!(matches!(
            PhaseEquilibriumSolveMode::fixed_declared_phases(),
            PhaseEquilibriumSolveMode::FixedDeclaredPhases
        ));
    }

    #[test]
    fn request_can_explicitly_reset_to_the_fixed_declared_phase_path() {
        let spec = SubstanceSystemSpecBuilder::new(SubstancesContainer::SinglePhase(vec![
            "N2".to_string(),
            "O2".to_string(),
        ]))
        .with_library_priorities(vec!["NASA_gas".to_string()])
        .with_search_in_nist(true)
        .build()
        .unwrap();
        let request = PhaseEquilibriumPipelineRequest::new(
            spec,
            vec![0.79, 0.21],
            EquilibriumConditions::new(500.0, 101_325.0, 101_325.0).unwrap(),
        )
        .with_phase_control_policy(PhaseControlPolicy::default())
        .with_fixed_declared_phases();

        let outcome = request.solve().unwrap();

        assert_eq!(outcome.resolved().phase_specs().len(), 1);
        assert_eq!(outcome.solution().component_moles().len(), 2);
    }
}