KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, 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
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
//! Fixed-pressure, fixed-total-enthalpy workflow.
//!
//! The canonical resolved-data implementation is the coupled monolithic
//! solve. The outer safeguarded scalar solve around
//! [`super::phase_equilibrium_workflow::solve_resolved_pt`] remains an
//! independent reference and recovery path behind an explicit solve-mode
//! boundary.
//!
//! # Supported physical contract
//!
//! This workflow currently supports closed, fixed-pressure systems made from
//! the ideal-gas and pure-condensed phase models accepted by the canonical
//! `P,T` engine. Total enthalpy is the additive standard-state quantity
//! `H = sum_i n_i h_i(T)` in joules. Consequently, a request is physically
//! meaningful only when every selected component record uses a compatible
//! thermochemical reference convention and the supplied `H_target` was built
//! from that same convention.
//!
//! In this scope, a `P,H` request represents an adiabatic isobaric equilibrium
//! calculation only when heat transfer, shaft/electrical work, and kinetic or
//! potential-energy terms are either absent or already included in the target.
//! Non-ideal solution excess enthalpy, pressure-dependent real-fluid
//! enthalpy, and unimplemented phase-model contributions are intentionally not
//! inferred from this additive model.
//!
//! The workflow is **thermochemical-format agnostic**. It never branches on
//! NASA, NIST, or a library name: phase resolution selects records first, then
//! [`ResolvedThermochemistry`] asks each selected `ThermoCalculator` for the
//! same `g0(T)`, `h(T)`, optional `Cp(T)`, and valid-temperature capabilities.
//! Provenance remains in the result precisely so format/library differences
//! stay observable without leaking into numerical residual construction.
//!
//! # Validation scope
//!
//! Optional equilibrium-constant validation remains attached to an inner
//! fixed-`P,T` chemical candidate. It is evidence about that candidate only;
//! outer `P,H` acceptance is independently determined from the typed enthalpy
//! residual, scalar bracket, conservation, and normal `P,T` acceptance gate.

use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::Thermodynamics::ChemEquilibrium::equilibrium_candidate_selection::EquilibriumCandidateSelectionReport;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::{
    EnthalpyScale, EquilibriumConstraint, TemperatureBounds, additive_total_enthalpy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_diagnostics::{
    EquilibriumDiagnosticEvent, EquilibriumDiagnosticsCollector, EquilibriumDiagnosticsMode,
    EquilibriumDiagnosticsOptions, PhDiagnosticRoute,
};
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_log_moles::GibbsFn;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::{
    MultiphaseEquilibriumLayout, MultiphaseInitialComposition,
    initial_composition_from_element_inventory,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
    ReactionExtentError, ReactionExtentErrorKind,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_formulation::PreparedPhFormulation;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_monolithic::{
    PreparedMonolithicPhRunner, solve_monolithic_active_set_candidate_with_seed_report,
};
#[cfg(test)]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_nested::safeguarded_interpolation_step;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_nested::{
    NestedBracketOptions, solve_bracketed_temperature as solve_nested_bracketed_temperature,
};
pub use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_nested::{
    PhTemperatureStepKind, PhTemperatureTrial, PhTrialInnerEvidence, PhTrialPhaseState,
    PhTrialPreparation, PhTrialTimingReport,
};
pub use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_options::{
    PhAcceptanceOptions, PhMonolithicOptions, PhMonolithicSeedAttemptReport,
    PhMonolithicSeedPolicy, PhMonolithicSeedRecoveryReport, PhMonotonicityPolicy, PhNestedOptions,
};
pub use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_thermochemistry::{
    MolarEnthalpyFunction, MolarThermoFunction, ResolvedThermochemistry, ThermochemistryProvenance,
    ThermochemistryStandardStatePressure,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::LogMolesInitialGuess;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::{
    RstPreparedProblem, prepare_rst_symbolic_ph_problem_with_timing,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
    EquilibriumSolveReport, MultiStartSolveReport,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::{
    EquilibriumTimingCollector, EquilibriumTimingMode, EquilibriumTimingReport,
    EquilibriumTimingStage, RstPreparationTimingReport,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{
    MultiphaseAcceptanceReport, PhaseControlledSolveReport,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::{
    PhaseEquilibriumBuildRequest, PreparedPhaseEquilibriumTemplate, SupportedPhaseModelPolicy,
    build_phase_equilibrium_problem_with_timing,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_solution::MultiphaseEquilibriumSolution;
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_solution::{
    ExtensiveNormalizationRecoveryEvidence, ExtensiveNormalizationTrigger,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_workflow::{
    EquilibriumSolveOptions, ExtensiveNormalizationPolicy, PhaseControlPolicy,
    PhaseEquilibriumSolveMode, ResolvedPhaseEquilibriumRequest, normalized_recovery_trace_policy,
    solve_resolved_pt,
};
use crate::Thermodynamics::User_PhaseOrSolution::ResolvedPhaseSystem;

impl ResolvedThermochemistry {
    /// Converts the mandatory enthalpy column to the compatibility model used
    /// by the independent nested P,H route. The capability bundle remains the
    /// source of truth; this is only an adapter for that older input shape.
    pub fn enthalpy_model(&self) -> EnthalpyModel<'static> {
        EnthalpyModel {
            functions: self.enthalpy_functions(),
            heat_capacity: self.heat_capacity_functions(),
        }
    }
}

/// Component-aligned molar enthalpy capabilities for the additive model.
///
/// The component order must be the same as the resolved `SystemLayout` and
/// the initial composition. The resolved-data bridge is
/// `ResolvedThermochemistry`; this smaller type remains useful for analytic
/// and adapter-level callers.
#[derive(Clone)]
pub struct EnthalpyModel<'a> {
    functions: Vec<MolarEnthalpyFunction<'a>>,
    heat_capacity: Vec<Option<MolarEnthalpyFunction<'a>>>,
}

/// Pure additive enthalpy evidence at one temperature.
///
/// `partial_temperature_derivative` deliberately means `dH/dT` at fixed
/// composition. It is not the full outer derivative of
/// `H(solution_of_P_T(T), T)`, which also contains the implicit composition
/// term `sum(h_i * d n_i / dT)`.
#[derive(Debug, Clone, PartialEq)]
pub struct EnthalpyEvaluation {
    molar_enthalpies: Vec<f64>,
    heat_capacities: Vec<f64>,
    total_enthalpy: f64,
    partial_temperature_derivative: f64,
}

/// Numerical formulation selected for one fixed-pressure, fixed-enthalpy solve.
///
/// The production default is `Auto`: it runs the coupled monolithic path with
/// its bounded seed recovery first, then uses the independently formulated
/// safeguarded nested route only after a classified numerical failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhSolveMode {
    /// Solve composition and bounded temperature in one nonlinear system.
    Monolithic,
    /// Safeguarded scalar temperature solve around accepted fixed-P,T solves.
    NestedTemperature,
    /// Monolithic first, then a nested fallback only for classified numerical
    /// failures.
    Auto,
}

impl Default for PhSolveMode {
    fn default() -> Self {
        Self::Auto
    }
}

/// Numerical route that produced an accepted `P,H` result.
///
/// This is result evidence, not a caller preference. An `Auto` request may
/// legitimately publish a nested recovery result after a classified
/// monolithic failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhSolvePath {
    /// One coupled nonlinear solve over log-moles and bounded temperature for
    /// a fixed declared active phase set.
    MonolithicFixedActiveSet,
    /// Coupled log-mole/temperature candidates executed by the shared
    /// transactional bounded phase-control lifecycle.
    MonolithicPhaseControl,
    /// Safeguarded scalar temperature search containing accepted P,T solves.
    NestedTemperature,
}

/// Why an automatic P,H request left the monolithic formulation.
///
/// The reason is retained in the immutable result rather than being emitted
/// only to logs. This makes `Auto` auditable and prevents a numerical recovery
/// from looking like an ordinary nested solve.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhFallbackReason {
    error_kind: ReactionExtentErrorKind,
    message: String,
}

impl PhFallbackReason {
    /// Classifies a [`ReactionExtentError`] into a typed fallback reason.
    ///
    /// Captures the high-level error kind and the full display message so the
    /// monolithic-to-nested recovery path can report *why* the coupled solve
    /// failed without retaining the original error's dynamic type or backtrace.
    /// The classification is deliberately lossy: only the kind and message
    /// survive, which is sufficient for diagnostics and summary rows.
    pub(crate) fn from_error(error: &ReactionExtentError) -> Self {
        Self {
            error_kind: error.kind(),
            message: error.to_string(),
        }
    }

    /// High-level classification of the rejected monolithic attempt.
    pub fn error_kind(&self) -> ReactionExtentErrorKind {
        self.error_kind
    }

    /// Human-readable typed error rendered at the fallback boundary.
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Immutable decision made by the outer P,H route selector.
///
/// This is intentionally separate from scalar temperature trials and coupled
/// solver attempts. It answers one architectural question: which high-level
/// formulation was selected, or abandoned, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PhRouteDecision {
    /// `Auto` rejected the monolithic formulation and accepted the independent
    /// nested-temperature route instead.
    AutoFallback {
        from_route: PhDiagnosticRoute,
        to_route: PhDiagnosticRoute,
        reason: PhFallbackReason,
    },
}

impl PhRouteDecision {
    /// Route that was abandoned before the accepted result was published.
    pub fn from_route(&self) -> PhDiagnosticRoute {
        match self {
            Self::AutoFallback { from_route, .. } => *from_route,
        }
    }

    /// Route that produced the accepted result.
    pub fn to_route(&self) -> PhDiagnosticRoute {
        match self {
            Self::AutoFallback { to_route, .. } => *to_route,
        }
    }

    /// Classified numerical reason for the route decision.
    pub fn reason(&self) -> &PhFallbackReason {
        match self {
            Self::AutoFallback { reason, .. } => reason,
        }
    }
}

impl EnthalpyEvaluation {
    /// Component-aligned molar enthalpies in J/mol.
    pub fn molar_enthalpies(&self) -> &[f64] {
        &self.molar_enthalpies
    }

    /// Component-aligned heat capacities in J/(mol K).
    pub fn heat_capacities(&self) -> &[f64] {
        &self.heat_capacities
    }

    /// Additive total enthalpy in J.
    pub fn total_enthalpy(&self) -> f64 {
        self.total_enthalpy
    }

    /// `dH/dT` while holding the supplied component moles fixed.
    pub fn partial_temperature_derivative(&self) -> f64 {
        self.partial_temperature_derivative
    }
}

impl<'a> EnthalpyModel<'a> {
    /// Creates a model from functions returning J/mol at temperature in K.
    pub fn from_functions(
        functions: Vec<MolarEnthalpyFunction<'a>>,
    ) -> Result<Self, ReactionExtentError> {
        if functions.is_empty() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "enthalpy_functions",
                message: "at least one molar enthalpy function is required".to_string(),
            });
        }
        Ok(Self {
            heat_capacity: vec![None; functions.len()],
            functions,
        })
    }

    /// Creates an enthalpy model with component-aligned heat-capacity
    /// capabilities for derivative-ready callers.
    ///
    /// A `None` entry is retained intentionally: it means the source record
    /// has no usable `Cp(T)` capability. The ordinary P,H bracketed workflow
    /// may still use such a model, while derivative evaluation rejects it at
    /// the point where the missing capability matters.
    pub fn from_functions_with_heat_capacity(
        functions: Vec<MolarEnthalpyFunction<'a>>,
        heat_capacity: Vec<Option<MolarEnthalpyFunction<'a>>>,
    ) -> Result<Self, ReactionExtentError> {
        let model = Self::from_functions(functions)?;
        if model.functions.len() != heat_capacity.len() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "enthalpy model has {} functions but {} heat-capacity functions",
                model.functions.len(),
                heat_capacity.len()
            )));
        }
        Ok(Self {
            heat_capacity,
            ..model
        })
    }

    /// Builds component-aligned `dH(T)` capabilities from resolved phase data.
    ///
    /// This compatibility constructor delegates to the complete bundle so it
    /// cannot accidentally trust a stale zero-valued closure cache. The
    /// returned model retains the bundle's temperature-aware calculator path.
    pub fn from_resolved_system(
        resolved: &'a ResolvedPhaseSystem,
    ) -> Result<Self, ReactionExtentError> {
        Ok(ResolvedThermochemistry::from_resolved_system(resolved)?.enthalpy_model())
    }

    /// Number of component-aligned capabilities.
    pub fn len(&self) -> usize {
        self.functions.len()
    }

    /// Whether this model contains no capabilities.
    pub fn is_empty(&self) -> bool {
        self.functions.is_empty()
    }

    /// Evaluates all molar enthalpies at one temperature in K.
    pub fn evaluate_molar(&self, temperature: f64) -> Result<Vec<f64>, ReactionExtentError> {
        if !temperature.is_finite() || temperature <= 0.0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "temperature",
                message: "enthalpy temperature must be finite and positive".to_string(),
            });
        }

        self.functions
            .iter()
            .enumerate()
            .map(|(index, function)| {
                let value = function(temperature)?;
                if !value.is_finite() {
                    return Err(ReactionExtentError::InvalidProblem {
                        field: "molar_enthalpy",
                        message: format!("enthalpy function {index} returned a non-finite value"),
                    });
                }
                Ok(value)
            })
            .collect()
    }

    /// Evaluates the additive total enthalpy in J for a physical composition.
    pub fn evaluate_total(
        &self,
        moles: &[f64],
        temperature: f64,
    ) -> Result<f64, ReactionExtentError> {
        let molar = self.evaluate_molar(temperature)?;
        additive_total_enthalpy(moles, &molar)
    }

    /// Evaluates additive enthalpy and its explicit temperature derivative.
    ///
    /// This method does not solve the chemical equilibrium sensitivity
    /// problem. It is therefore safe to use as a building block for a future
    /// implicit derivative, where the missing term is obtained from the
    /// inner residual Jacobian and its temperature column.
    pub fn evaluate_total_with_partial_temperature_derivative(
        &self,
        moles: &[f64],
        temperature: f64,
    ) -> Result<EnthalpyEvaluation, ReactionExtentError> {
        let molar_enthalpies = self.evaluate_molar(temperature)?;
        let total_enthalpy = additive_total_enthalpy(moles, &molar_enthalpies)?;
        let mut heat_capacities = Vec::with_capacity(self.heat_capacity.len());
        for (index, function) in self.heat_capacity.iter().enumerate() {
            let Some(function) = function else {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "heat_capacity",
                    message: format!("heat capacity capability {index} is unavailable"),
                });
            };
            let value = function(temperature)?;
            if !value.is_finite() {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "heat_capacity",
                    message: format!(
                        "heat capacity capability {index} returned a non-finite value"
                    ),
                });
            }
            heat_capacities.push(value);
        }
        let partial_temperature_derivative = moles
            .iter()
            .zip(&heat_capacities)
            .map(|(&moles_i, &cp_i)| moles_i * cp_i)
            .sum::<f64>();
        if !partial_temperature_derivative.is_finite() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "enthalpy_temperature_derivative",
                message: "partial enthalpy temperature derivative is not finite".to_string(),
            });
        }
        Ok(EnthalpyEvaluation {
            molar_enthalpies,
            heat_capacities,
            total_enthalpy,
            partial_temperature_derivative,
        })
    }
}

/// Scalar solver controls for the outer `P,H` temperature problem.
#[derive(Debug, Clone)]
pub struct PhTemperatureSolveOptions {
    /// Dimensionless enthalpy residual tolerance after scaling.
    pub scaled_enthalpy_tolerance: f64,
    /// Absolute enthalpy tolerance in joules. The effective acceptance limit
    /// is the larger of this floor and the scale-aware relative tolerance.
    pub absolute_enthalpy_tolerance_joules: f64,
    /// Initial-temperature recovery policy for the coupled monolithic route.
    pub monolithic_seed_policy: PhMonolithicSeedPolicy,
    /// Temperature interval tolerance in K.
    pub temperature_tolerance: f64,
    /// Maximum number of interior temperature trials.
    pub max_iterations: usize,
    /// Global maximum number of scalar temperature evaluations, including
    /// both bracket endpoints. This is not multiplied by inner backend work.
    pub max_temperature_evaluations: usize,
    /// Policy for sampled reversals of the outer `H_eq(P,T)` branch.
    pub monotonicity_policy: PhMonotonicityPolicy,
    /// Optional global budget for started inner nonlinear backend attempts.
    ///
    /// This is deliberately separate from the scalar-evaluation budget: one
    /// temperature trial may use several fallback backends, so a bounded
    /// outer solve must be able to cap that nested work explicitly.
    pub max_inner_backend_attempts: Option<usize>,
    /// Optional global budget for nonlinear iterations across all inner P,T
    /// solves and all continuation seeds.
    pub max_inner_nonlinear_iterations: Option<usize>,
    /// Optional global budget for accepted phase transitions across all inner
    /// bounded phase-control solves.
    pub max_phase_control_transitions: Option<usize>,
    /// Optional wall-clock budget for the complete outer transaction.
    pub max_wall_time: Option<Duration>,
    /// Optional cancellation/progress control shared with every inner P,T
    /// solve in this outer transaction.
    execution_control: Option<EquilibriumExecutionControl>,
}

impl Default for PhTemperatureSolveOptions {
    fn default() -> Self {
        Self {
            scaled_enthalpy_tolerance: 1.0e-8,
            absolute_enthalpy_tolerance_joules: 1.0e-6,
            monolithic_seed_policy: PhMonolithicSeedPolicy::default(),
            temperature_tolerance: 1.0e-8,
            max_iterations: 80,
            max_temperature_evaluations: 82,
            monotonicity_policy: PhMonotonicityPolicy::default(),
            max_inner_backend_attempts: None,
            max_inner_nonlinear_iterations: None,
            max_phase_control_transitions: None,
            max_wall_time: None,
            execution_control: None,
        }
    }
}

impl PhTemperatureSolveOptions {
    /// Selects how the monolithic route recovers from a retryable failure at
    /// the caller-provided temperature seed.
    pub fn with_monolithic_seed_policy(mut self, policy: PhMonolithicSeedPolicy) -> Self {
        self.monolithic_seed_policy = policy;
        self
    }

    /// Limits the total number of started inner backend attempts across all
    /// scalar temperature trials.
    ///
    /// The limit is checked after each completed inner solve. A failed inner
    /// solve is still accounted for by its own backend policy and remains
    /// visible as the original typed error.
    pub fn with_max_inner_backend_attempts(
        mut self,
        limit: usize,
    ) -> Result<Self, ReactionExtentError> {
        if limit == 0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_inner_backend_attempts",
                message: "inner backend-attempt budget must be positive".to_string(),
            });
        }
        self.max_inner_backend_attempts = Some(limit);
        Ok(self)
    }

    /// Removes the optional global inner backend-attempt limit.
    pub fn without_inner_backend_attempt_limit(mut self) -> Self {
        self.max_inner_backend_attempts = None;
        self
    }

    /// Limits total nonlinear iterations across the complete outer solve.
    pub fn with_max_inner_nonlinear_iterations(
        mut self,
        limit: usize,
    ) -> Result<Self, ReactionExtentError> {
        if limit == 0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_inner_nonlinear_iterations",
                message: "inner nonlinear-iteration budget must be positive".to_string(),
            });
        }
        self.max_inner_nonlinear_iterations = Some(limit);
        Ok(self)
    }

    /// Removes the optional global nonlinear-iteration limit.
    pub fn without_inner_nonlinear_iteration_limit(mut self) -> Self {
        self.max_inner_nonlinear_iterations = None;
        self
    }

    /// Limits accepted phase transitions across the complete outer solve.
    pub fn with_max_phase_control_transitions(
        mut self,
        limit: usize,
    ) -> Result<Self, ReactionExtentError> {
        if limit == 0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_phase_control_transitions",
                message: "phase-transition budget must be positive".to_string(),
            });
        }
        self.max_phase_control_transitions = Some(limit);
        Ok(self)
    }

    /// Removes the optional global phase-transition limit.
    pub fn without_phase_control_transition_limit(mut self) -> Self {
        self.max_phase_control_transitions = None;
        self
    }

    /// Sets the explicit policy for sampled outer-branch reversals.
    pub fn with_monotonicity_policy(mut self, policy: PhMonotonicityPolicy) -> Self {
        self.monotonicity_policy = policy;
        self
    }

    /// Validates scalar solver controls before any inner equilibrium solve.
    pub fn validate(&self) -> Result<(), ReactionExtentError> {
        if !self.scaled_enthalpy_tolerance.is_finite() || self.scaled_enthalpy_tolerance <= 0.0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "scaled_enthalpy_tolerance",
                message: "tolerance must be finite and positive".to_string(),
            });
        }
        if !self.absolute_enthalpy_tolerance_joules.is_finite()
            || self.absolute_enthalpy_tolerance_joules <= 0.0
        {
            return Err(ReactionExtentError::InvalidProblem {
                field: "absolute_enthalpy_tolerance_joules",
                message: "tolerance must be finite and positive".to_string(),
            });
        }
        if !self.temperature_tolerance.is_finite() || self.temperature_tolerance <= 0.0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "temperature_tolerance",
                message: "tolerance must be finite and positive".to_string(),
            });
        }
        if self.max_iterations == 0 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_iterations",
                message: "maximum iterations must be greater than zero".to_string(),
            });
        }
        if self.max_temperature_evaluations < 2 {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_temperature_evaluations",
                message: "at least two evaluations are required to test a bracket".to_string(),
            });
        }
        if matches!(self.max_inner_backend_attempts, Some(limit) if limit == 0) {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_inner_backend_attempts",
                message: "inner backend-attempt budget must be positive when provided".to_string(),
            });
        }
        if matches!(self.max_inner_nonlinear_iterations, Some(limit) if limit == 0) {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_inner_nonlinear_iterations",
                message: "inner nonlinear-iteration budget must be positive when provided"
                    .to_string(),
            });
        }
        if matches!(self.max_phase_control_transitions, Some(limit) if limit == 0) {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_phase_control_transitions",
                message: "phase-transition budget must be positive when provided".to_string(),
            });
        }
        if matches!(self.max_wall_time, Some(limit) if limit.is_zero()) {
            return Err(ReactionExtentError::InvalidProblem {
                field: "max_wall_time",
                message: "wall-time budget must be positive when provided".to_string(),
            });
        }
        Ok(())
    }

    /// Returns the absolute joule limit corresponding to a validated scale.
    ///
    /// Using the maximum makes the contract meaningful both for ordinary
    /// extensive enthalpies and for targets close to zero. A relative-only
    /// test would otherwise demand an unrealistically tiny absolute residual
    /// whenever the reference scale is small.
    pub fn accepted_enthalpy_error_limit_joules(&self, scale: EnthalpyScale) -> f64 {
        self.absolute_enthalpy_tolerance_joules
            .max(self.scaled_enthalpy_tolerance * scale.joules())
    }

    /// Tests the complete absolute-plus-relative enthalpy acceptance contract.
    pub fn accepts_enthalpy_error(&self, error_joules: f64, scale: EnthalpyScale) -> bool {
        error_joules.is_finite()
            && error_joules.abs() <= self.accepted_enthalpy_error_limit_joules(scale)
    }

    /// Installs cooperative cancellation and progress reporting for the
    /// complete outer transaction. The same handle is forwarded to inner P,T
    /// attempts, so cancellation cannot leave an inner solve running after
    /// the outer caller has requested shutdown.
    pub fn with_execution_control(mut self, control: EquilibriumExecutionControl) -> Self {
        self.execution_control = Some(control);
        self
    }

    /// Returns the shared execution control, if configured.
    pub fn execution_control(&self) -> Option<&EquilibriumExecutionControl> {
        self.execution_control.as_ref()
    }

    /// Returns the common enthalpy acceptance contract shared by both routes.
    ///
    /// The fields remain public for the existing builder surface, so this
    /// method validates them again before exposing the typed value object.
    pub fn acceptance_options(&self) -> Result<PhAcceptanceOptions, ReactionExtentError> {
        PhAcceptanceOptions::new(
            self.scaled_enthalpy_tolerance,
            self.absolute_enthalpy_tolerance_joules,
        )
    }

    /// Returns controls consumed only by the coupled monolithic runner.
    pub fn monolithic_options(&self) -> Result<PhMonolithicOptions, ReactionExtentError> {
        Ok(PhMonolithicOptions::new(
            self.acceptance_options()?,
            self.monolithic_seed_policy,
        ))
    }

    /// Returns controls consumed only by the nested scalar/bracket runner.
    pub fn nested_options(&self) -> Result<PhNestedOptions, ReactionExtentError> {
        PhNestedOptions::new(
            self.acceptance_options()?,
            self.temperature_tolerance,
            self.max_iterations,
            self.max_temperature_evaluations,
            self.monotonicity_policy,
            self.max_wall_time,
        )
    }
}

/// Applies the route-independent work contract before a monolithic candidate
/// can cross the publication boundary.
fn enforce_monolithic_work_limits(
    options: &PhTemperatureSolveOptions,
    started: Instant,
    backend_attempts: usize,
    nonlinear_iterations: usize,
    phase_control_transitions: usize,
) -> Result<(), ReactionExtentError> {
    if let Some(limit) = options.max_inner_backend_attempts {
        if backend_attempts > limit {
            return Err(ReactionExtentError::InvalidProblem {
                field: "inner_backend_budget",
                message: format!(
                    "monolithic P,H solve started {backend_attempts} backend attempt(s), exceeding the configured limit of {limit}"
                ),
            });
        }
    }
    if let Some(limit) = options.max_inner_nonlinear_iterations {
        if nonlinear_iterations > limit {
            return Err(ReactionExtentError::InvalidProblem {
                field: "inner_nonlinear_iteration_budget",
                message: format!(
                    "monolithic P,H solve used {nonlinear_iterations} nonlinear iteration(s), exceeding the configured limit of {limit}"
                ),
            });
        }
    }
    if let Some(limit) = options.max_phase_control_transitions {
        if phase_control_transitions > limit {
            return Err(ReactionExtentError::InvalidProblem {
                field: "phase_control_transition_budget",
                message: format!(
                    "monolithic P,H solve accepted {phase_control_transitions} phase transition(s), exceeding the configured limit of {limit}"
                ),
            });
        }
    }
    if let Some(limit) = options.max_wall_time {
        if started.elapsed() > limit {
            return Err(ReactionExtentError::InvalidProblem {
                field: "wall_time_budget",
                message: format!("monolithic P,H solve exceeded its wall-time budget of {limit:?}"),
            });
        }
    }
    if let Some(control) = options.execution_control() {
        control.check_cancelled()?;
    }
    Ok(())
}

/// Evidence from the outer scalar temperature solve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PhTemperatureTimingReport {
    enabled: bool,
    total: Duration,
    scalar_orchestration: Duration,
    enthalpy_evaluation: Duration,
    trial_total: Duration,
    trial_inner_execution: Duration,
    trial_preparation: Duration,
    trial_template_preparation: Duration,
    trial_postprocessing: Duration,
    bracket_orchestration: Duration,
    monolithic_preparation: Duration,
    request_validation: Duration,
    initial_enthalpy: Duration,
    initial_enthalpy_reused: bool,
    prepared_problem_retarget: Duration,
    gibbs_snapshot: Duration,
    gibbs_snapshot_reused: bool,
    monolithic_rst_preparation: Duration,
    monolithic_backend_execution: Duration,
    monolithic_execution: Duration,
    monolithic_publication: Duration,
    recovery_request_clone: Duration,
    rst_preparation_timing: RstPreparationTimingReport,
}

impl PhTemperatureTimingReport {
    /// Whether this report contains measured outer-stage timings.
    pub fn enabled(&self) -> bool {
        self.enabled
    }

    /// Wall-clock duration of the complete outer P,H transaction.
    pub fn total(&self) -> Duration {
        self.total
    }

    /// Time spent in bracket orchestration, including nested P,T work.
    pub fn scalar_orchestration(&self) -> Duration {
        self.scalar_orchestration
    }

    /// Aggregate time spent evaluating additive total enthalpy at trials.
    pub fn enthalpy_evaluation(&self) -> Duration {
        self.enthalpy_evaluation
    }

    /// Aggregate wall-clock duration of all accepted scalar trials.
    pub fn trial_total(&self) -> Duration {
        self.trial_total
    }

    /// Aggregate wall-clock duration spent executing inner P,T requests.
    pub fn trial_inner_execution(&self) -> Duration {
        self.trial_inner_execution
    }

    /// Trial time outside the inner P,T request and additive enthalpy
    /// evaluation. This includes per-trial request/formulation preparation.
    pub fn trial_preparation(&self) -> Duration {
        self.trial_preparation
    }

    /// Time spent building the reusable fixed-phase P,T template for nested
    /// trials. This is normally paid once per nested request.
    pub fn trial_template_preparation(&self) -> Duration {
        self.trial_template_preparation
    }

    /// Time spent publishing trial evidence after the inner solve and
    /// enthalpy evaluation have returned.
    pub fn trial_postprocessing(&self) -> Duration {
        self.trial_postprocessing
    }

    /// Scalar bracket bookkeeping outside all trial callbacks.
    pub fn bracket_orchestration(&self) -> Duration {
        self.bracket_orchestration
    }

    /// Time spent preparing a monolithic P,H formulation before its coupled
    /// nonlinear runner starts.
    pub fn monolithic_preparation(&self) -> Duration {
        self.monolithic_preparation
    }

    /// Time spent validating the prepared point request before its nonlinear
    /// runner starts.
    pub fn request_validation(&self) -> Duration {
        self.request_validation
    }

    /// Time spent obtaining the molar enthalpy vector used for initial P,H
    /// normalization, including a cache clone when one is available.
    pub fn initial_enthalpy(&self) -> Duration {
        self.initial_enthalpy
    }

    /// Whether the initial molar enthalpy vector came from the previous
    /// continuation point at the same seed temperature.
    pub fn initial_enthalpy_reused(&self) -> bool {
        self.initial_enthalpy_reused
    }

    /// Time spent retargeting the reusable prepared P,T problem for one
    /// prepared P,H point, including its structural clone and validation.
    pub fn prepared_problem_retarget(&self) -> Duration {
        self.prepared_problem_retarget
    }

    /// Time spent preparing or cloning the constant Gibbs snapshot used by
    /// the prepared P,H retarget path.
    pub fn gibbs_snapshot(&self) -> Duration {
        self.gibbs_snapshot
    }

    /// Whether the Gibbs snapshot came from the previous accepted point.
    pub fn gibbs_snapshot_reused(&self) -> bool {
        self.gibbs_snapshot_reused
    }

    /// Time spent materializing the RST symbolic payload for the accepted
    /// monolithic seed.
    pub fn monolithic_rst_preparation(&self) -> Duration {
        self.monolithic_rst_preparation
    }

    /// Wall-clock time spent in the selected monolithic backend cascade after
    /// RST payload preparation.
    pub fn monolithic_backend_execution(&self) -> Duration {
        self.monolithic_backend_execution
    }

    /// Wall-clock duration of the coupled monolithic runner.
    pub fn monolithic_execution(&self) -> Duration {
        self.monolithic_execution
    }

    /// Time spent publishing a monolithic candidate after the runner returns.
    pub fn monolithic_publication(&self) -> Duration {
        self.monolithic_publication
    }

    /// Time spent cloning the physical request kept for classified recovery.
    ///
    /// This is measured separately because a successful physical solve does
    /// not use the retained request at all. It therefore must not be hidden in
    /// generic P,H orchestration time when evaluating copy-on-failure work.
    pub fn recovery_request_clone(&self) -> Duration {
        self.recovery_request_clone
    }

    /// Fine-grained stages inside monolithic RST symbolic/problem preparation.
    pub fn rst_preparation_timing(&self) -> RstPreparationTimingReport {
        self.rst_preparation_timing
    }
}

/// Backend and active-set evidence for a coupled monolithic P,H solve.
///
/// This is deliberately separate from [`PhTemperatureTrial`]. A monolithic
/// solve has no outer scalar temperature trials: its Newton/LM/TR iterations
/// operate on one coupled `[log-moles, temperature]` system. Nested scalar
/// diagnostics therefore must not be used as a container for this evidence.
#[derive(Debug, Clone, PartialEq)]
pub struct PhMonolithicEvidence {
    solve_report: EquilibriumSolveReport,
    multi_start_report: Option<MultiStartSolveReport>,
    temperature_seed_report: Option<PhMonolithicSeedRecoveryReport>,
    phase_control_report: Option<PhaseControlledSolveReport>,
    acceptance_report: Option<MultiphaseAcceptanceReport>,
    inner_timing: EquilibriumTimingReport,
    validation_duration: Duration,
}

impl PhMonolithicEvidence {
    /// Ordered backend attempts for the coupled monolithic candidate.
    pub fn solve_report(&self) -> &EquilibriumSolveReport {
        &self.solve_report
    }

    /// Seed comparison evidence, when the inner policy used multi-start.
    pub fn multi_start_report(&self) -> Option<&MultiStartSolveReport> {
        self.multi_start_report.as_ref()
    }

    /// Ordered physical-temperature starts used by the coupled formulation.
    pub fn temperature_seed_report(&self) -> Option<&PhMonolithicSeedRecoveryReport> {
        self.temperature_seed_report.as_ref()
    }

    /// Transactional phase-control evidence for bounded monolithic mode.
    pub fn phase_control_report(&self) -> Option<&PhaseControlledSolveReport> {
        self.phase_control_report.as_ref()
    }

    /// Final fixed-P,T acceptance evidence carried by the monolithic solve.
    pub fn acceptance_report(&self) -> Option<&MultiphaseAcceptanceReport> {
        self.acceptance_report.as_ref()
    }

    /// Timing report for the coupled inner equilibrium solve.
    pub fn inner_timing(&self) -> EquilibriumTimingReport {
        self.inner_timing
    }

    /// Time spent validating candidate snapshots in the monolithic cascade.
    pub fn validation_duration(&self) -> Duration {
        self.validation_duration
    }

    /// Residual evaluations reported by the coupled backend cascade.
    pub fn residual_evaluations(&self) -> usize {
        self.solve_report
            .attempts
            .iter()
            .filter_map(|attempt| attempt.metrics.as_ref())
            .map(|metrics| metrics.residual_evaluations)
            .sum()
    }

    /// Jacobian evaluations reported by the coupled backend cascade.
    pub fn jacobian_evaluations(&self) -> usize {
        self.solve_report
            .attempts
            .iter()
            .filter_map(|attempt| attempt.metrics.as_ref())
            .map(|metrics| metrics.jacobian_evaluations)
            .sum()
    }
}

/// Evidence from the outer scalar temperature solve.
#[derive(Debug, Clone, PartialEq)]
pub struct PhTemperatureSolveReport {
    solve_path: PhSolvePath,
    fallback_reason: Option<PhFallbackReason>,
    route_decisions: Vec<PhRouteDecision>,
    target_enthalpy: f64,
    enthalpy_scale_joules: f64,
    absolute_enthalpy_tolerance_joules: f64,
    scaled_enthalpy_tolerance: f64,
    max_temperature_evaluations: usize,
    initial_temperature_seed: f64,
    monotonicity_policy: PhMonotonicityPolicy,
    max_inner_backend_attempts: Option<usize>,
    max_inner_nonlinear_iterations: Option<usize>,
    max_phase_control_transitions: Option<usize>,
    max_wall_time: Option<Duration>,
    inner_backend_attempts: usize,
    inner_nonlinear_iterations: usize,
    phase_control_transitions: usize,
    fixed_formulation_builds: usize,
    fixed_formulation_reuses: usize,
    inner_timing: EquilibriumTimingReport,
    timing: PhTemperatureTimingReport,
    iterations: usize,
    trials: Vec<PhTemperatureTrial>,
    monolithic_evidence: Option<PhMonolithicEvidence>,
}

impl PhTemperatureSolveReport {
    /// Numerical route that accepted this immutable result.
    pub fn solve_path(&self) -> PhSolvePath {
        self.solve_path
    }

    /// Numerical reason that caused `Auto` to recover through the nested
    /// formulation, if recovery occurred.
    pub fn fallback_reason(&self) -> Option<&PhFallbackReason> {
        self.fallback_reason.as_ref()
    }

    /// High-level P,H route decisions retained with the accepted result.
    ///
    /// An explicit `Monolithic` or `NestedTemperature` request normally has
    /// no decisions. An `Auto` fallback retains exactly one decision rather
    /// than manufacturing a scalar temperature trial for the failed route.
    pub fn route_decisions(&self) -> &[PhRouteDecision] {
        &self.route_decisions
    }

    /// Target total enthalpy in J.
    pub fn target_enthalpy(&self) -> f64 {
        self.target_enthalpy
    }

    /// Scale used to make the energy residual dimensionless, in J.
    pub fn enthalpy_scale_joules(&self) -> f64 {
        self.enthalpy_scale_joules
    }

    /// Absolute tolerance floor used by the accepted result contract.
    pub fn absolute_enthalpy_tolerance_joules(&self) -> f64 {
        self.absolute_enthalpy_tolerance_joules
    }

    /// Scale-aware relative tolerance used by the accepted result contract.
    pub fn scaled_enthalpy_tolerance(&self) -> f64 {
        self.scaled_enthalpy_tolerance
    }

    /// Global scalar evaluation budget configured for this solve.
    pub fn max_temperature_evaluations(&self) -> usize {
        self.max_temperature_evaluations
    }

    /// User-supplied P,H temperature seed evaluated inside the explicit
    /// thermochemistry bounds. It is evidence only and never widens bounds.
    pub fn initial_temperature_seed(&self) -> f64 {
        self.initial_temperature_seed
    }

    /// Outer-branch policy used while sampling the temperature bracket.
    pub fn monotonicity_policy(&self) -> PhMonotonicityPolicy {
        self.monotonicity_policy
    }

    /// Optional global budget for started inner backend attempts.
    pub fn max_inner_backend_attempts(&self) -> Option<usize> {
        self.max_inner_backend_attempts
    }

    /// Optional global nonlinear-iteration budget configured for this solve.
    pub fn max_inner_nonlinear_iterations(&self) -> Option<usize> {
        self.max_inner_nonlinear_iterations
    }

    /// Optional global phase-transition budget configured for this solve.
    pub fn max_phase_control_transitions(&self) -> Option<usize> {
        self.max_phase_control_transitions
    }

    /// Optional global wall-time budget configured for this solve.
    pub fn max_wall_time(&self) -> Option<Duration> {
        self.max_wall_time
    }

    /// Total inner backend attempts across all successful temperature trials.
    pub fn inner_backend_attempts(&self) -> usize {
        self.inner_backend_attempts
    }

    /// Total nonlinear iterations across all successful temperature trials.
    pub fn inner_nonlinear_iterations(&self) -> usize {
        self.inner_nonlinear_iterations
    }

    /// Total accepted phase-control transitions across all successful trials.
    pub fn phase_control_transitions(&self) -> usize {
        self.phase_control_transitions
    }

    /// Number of fixed-phase structural formulations built by this outer
    /// transaction. Bounded phase control reports zero because its active set
    /// has a separate lifecycle and is never reused across arbitrary bracket
    /// trial ordering.
    pub fn fixed_formulation_builds(&self) -> usize {
        self.fixed_formulation_builds
    }

    /// Number of accepted P,H trials that reused the fixed declared-phase
    /// formulation after its first local construction.
    pub fn fixed_formulation_reuses(&self) -> usize {
        self.fixed_formulation_reuses
    }

    /// Aggregate inner P,T timing across all successful temperature trials.
    pub fn inner_timing(&self) -> EquilibriumTimingReport {
        self.inner_timing
    }

    /// Outer scalar and enthalpy timing, when explicitly enabled.
    pub fn timing(&self) -> PhTemperatureTimingReport {
        self.timing
    }

    /// Effective absolute acceptance limit in joules.
    pub fn accepted_enthalpy_error_limit_joules(&self) -> f64 {
        self.absolute_enthalpy_tolerance_joules
            .max(self.scaled_enthalpy_tolerance * self.enthalpy_scale_joules)
    }

    /// Number of interior bisection trials.
    pub fn iterations(&self) -> usize {
        self.iterations
    }

    /// All endpoint and interior scalar trial records in evaluation order.
    ///
    /// This is empty for monolithic mode because a coupled Newton/LM/TR solve
    /// does not perform an outer scalar temperature search. Use
    /// [`Self::monolithic_evidence`] for that route's backend diagnostics.
    pub fn trials(&self) -> &[PhTemperatureTrial] {
        &self.trials
    }

    /// Coupled backend and phase-control evidence for monolithic mode.
    pub fn monolithic_evidence(&self) -> Option<&PhMonolithicEvidence> {
        self.monolithic_evidence.as_ref()
    }
}

/// Immutable result of one accepted `P,H` solve.
#[derive(Debug, Clone, PartialEq)]
pub struct FixedPressureEnthalpySolution {
    solution: MultiphaseEquilibriumSolution,
    calculated_enthalpy: f64,
    target_enthalpy: f64,
    report: PhTemperatureSolveReport,
    thermochemistry: Option<ResolvedThermochemistry>,
}

impl FixedPressureEnthalpySolution {
    /// Accepted fixed-`P,T` inner solution.
    pub fn equilibrium(&self) -> &MultiphaseEquilibriumSolution {
        &self.solution
    }

    /// Removes inner phase-lifecycle diagnostics when a containing P,H range
    /// elects not to publish a quiet point under `TransitionsOnly` sampling.
    pub(crate) fn without_equilibrium_diagnostics(mut self) -> Self {
        self.solution = self.solution.without_diagnostics();
        self
    }

    /// Marks a nested result as the accepted recovery of one rejected
    /// monolithic `Auto` attempt without fabricating scalar trial records.
    pub(crate) fn with_auto_fallback(mut self, reason: PhFallbackReason) -> Self {
        self.report.fallback_reason = Some(reason.clone());
        self.report
            .route_decisions
            .push(PhRouteDecision::AutoFallback {
                from_route: PhDiagnosticRoute::Monolithic,
                to_route: PhDiagnosticRoute::NestedTemperature,
                reason,
            });
        self
    }

    /// Adds timing for an enclosing P,H route decision and keeps the copied
    /// report in sync with the accepted inner solution timing.
    pub(crate) fn with_route_selection_timing(self, duration: std::time::Duration) -> Self {
        self.with_inner_timing_stage(EquilibriumTimingStage::RouteSelection, duration)
    }

    pub(crate) fn with_inner_timing_stage(
        mut self,
        stage: EquilibriumTimingStage,
        duration: std::time::Duration,
    ) -> Self {
        self.solution = self.solution.with_timing_stage(stage, duration);
        self.report.inner_timing = *self.solution.timing_report();
        self
    }

    pub(crate) fn with_recovery_request_clone_timing(
        mut self,
        duration: std::time::Duration,
    ) -> Self {
        self.report.timing.recovery_request_clone = duration;
        self
    }

    /// Solved equilibrium temperature in K.
    pub fn temperature(&self) -> f64 {
        self.solution.conditions().temperature()
    }

    /// Accepted pressure in Pa.
    pub fn pressure(&self) -> f64 {
        self.solution.conditions().pressure()
    }

    /// Calculated total enthalpy in J.
    pub fn calculated_enthalpy(&self) -> f64 {
        self.calculated_enthalpy
    }

    /// Requested total enthalpy in J.
    pub fn target_enthalpy(&self) -> f64 {
        self.target_enthalpy
    }

    /// Raw energy error in J.
    pub fn enthalpy_error(&self) -> f64 {
        self.calculated_enthalpy - self.target_enthalpy
    }

    /// Scale-aware energy error used by the outer acceptance contract.
    pub fn scaled_enthalpy_error(&self) -> f64 {
        self.enthalpy_error() / self.report.enthalpy_scale_joules()
    }

    /// Effective absolute energy tolerance used to accept this result.
    pub fn enthalpy_error_limit_joules(&self) -> f64 {
        self.report.accepted_enthalpy_error_limit_joules()
    }

    /// Outer scalar-solver diagnostics.
    pub fn report(&self) -> &PhTemperatureSolveReport {
        &self.report
    }

    /// Thermochemistry bundle used for the accepted energy evaluation, when
    /// the request was built from resolved thermochemical records.
    pub fn thermochemistry(&self) -> Option<&ResolvedThermochemistry> {
        self.thermochemistry.as_ref()
    }

    /// Maps an accepted normalized P,H result back to physical extensive
    /// units. The caller must supply a build report made from the original
    /// physical request at the accepted temperature; this prevents normalized
    /// element totals from leaking into the public provenance report.
    pub(crate) fn reconstruct_physical_extensive_boundary(
        mut self,
        normalization: ExtensiveNormalization,
        physical_build_report: crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::PhaseEquilibriumBuildReport,
    ) -> Result<Self, ReactionExtentError> {
        self.solution = self
            .solution
            .reconstruct_physical_extensive_boundary(normalization, physical_build_report)?;
        self.calculated_enthalpy = normalization
            .denormalize_total_enthalpy(
                crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
                    self.calculated_enthalpy,
                )?,
            )?
            .joules();
        self.target_enthalpy = normalization
            .denormalize_total_enthalpy(
                crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
                    self.target_enthalpy,
                )?,
            )?
            .joules();
        self.report.target_enthalpy = normalization
            .denormalize_total_enthalpy(
                crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
                    self.report.target_enthalpy,
                )?,
            )?
            .joules();
        self.report.enthalpy_scale_joules =
            normalization.denormalize_extensive_error(self.report.enthalpy_scale_joules)?;
        self.report.absolute_enthalpy_tolerance_joules = normalization
            .denormalize_extensive_error(self.report.absolute_enthalpy_tolerance_joules)?;
        Ok(self)
    }
}

/// Complete request for one typed `P,H` workflow.
#[derive(Clone)]
pub struct ResolvedPhaseEnthalpyRequest<'a> {
    /// Immutable snapshot captured when the request is built. The solve does
    /// not borrow the caller's mutable lifecycle or depend on its storage.
    resolved: Arc<ResolvedPhaseSystem>,
    /// Physical conservation input.  A dense composition is both the legacy
    /// physical input and its first numerical seed; an elemental inventory
    /// remains `b` while `initial_composition` is only a numerical seed.
    physical_input: PhPhysicalInput,
    initial_composition: MultiphaseInitialComposition,
    constraint: EquilibriumConstraint,
    temperature_bounds: TemperatureBounds,
    enthalpy: EnthalpyModel<'a>,
    solve_options: EquilibriumSolveOptions,
    solve_mode: PhaseEquilibriumSolveMode,
    ph_solve_mode: PhSolveMode,
    temperature_options: PhTemperatureSolveOptions,
    thermochemistry: Option<ResolvedThermochemistry>,
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
}

/// Physical P,H input kept distinct from a numerical starting composition.
#[derive(Clone)]
enum PhPhysicalInput {
    Composition,
    ElementInventory(ElementInventory),
}

impl<'a> ResolvedPhaseEnthalpyRequest<'a> {
    /// Creates the legacy/reference request from arbitrary enthalpy closures.
    ///
    /// This constructor intentionally selects [`PhSolveMode::NestedTemperature`]
    /// and cannot construct the coupled monolithic formulation because it has
    /// no resolved Gibbs/Cp bundle. New production callers must use
    /// [`Self::from_resolved_thermochemistry`] instead. The constructor is
    /// retained only for compatibility and for the independent nested
    /// reference route.
    #[deprecated(
        note = "use ResolvedPhaseEnthalpyRequest::from_resolved_thermochemistry for the canonical production API"
    )]
    pub fn new<'resolved>(
        resolved: &'resolved ResolvedPhaseSystem,
        initial_composition: MultiphaseInitialComposition,
        constraint: EquilibriumConstraint,
        temperature_bounds: TemperatureBounds,
        enthalpy: EnthalpyModel<'a>,
    ) -> Result<Self, ReactionExtentError> {
        Self::from_legacy_parts(
            resolved,
            initial_composition,
            constraint,
            temperature_bounds,
            enthalpy,
        )
    }

    /// Shared construction helper used by both the deprecated [`new`] and the
    /// canonical [`from_resolved_thermochemistry`] constructors.
    ///
    /// Validates the component count against the resolved layout, checks that
    /// the enthalpy model dimension matches, and stores the immutable request
    /// fields without touching the repository or evaluating thermochemistry.
    /// The caller is responsible for attaching the optional
    /// [`ResolvedThermochemistry`] bundle when the thermochemistry-aware path
    /// is used.
    fn from_legacy_parts<'resolved>(
        resolved: &'resolved ResolvedPhaseSystem,
        initial_composition: MultiphaseInitialComposition,
        constraint: EquilibriumConstraint,
        temperature_bounds: TemperatureBounds,
        enthalpy: EnthalpyModel<'a>,
    ) -> Result<Self, ReactionExtentError> {
        let request = Self {
            resolved: Arc::new(resolved.clone()),
            physical_input: PhPhysicalInput::Composition,
            initial_composition,
            constraint,
            temperature_bounds,
            enthalpy,
            solve_options: EquilibriumSolveOptions::default(),
            solve_mode: PhaseEquilibriumSolveMode::fixed_declared_phases(),
            // This constructor accepts arbitrary enthalpy closures and does
            // not have the Gibbs/Cp bundle required by the coupled system.
            // Keep it on the independent reference route; resolved-data
            // callers are promoted to the monolithic default below.
            ph_solve_mode: PhSolveMode::NestedTemperature,
            temperature_options: PhTemperatureSolveOptions::default(),
            thermochemistry: None,
            candidate_selection: None,
        };
        request.validate()?;
        Ok(request)
    }

    /// Creates a P,H request from the resolved thermochemistry bundle.
    ///
    /// The user may narrow the bundle interval, but cannot extend it. This
    /// keeps scalar trials inside the domain supported by every selected
    /// thermochemical record.
    pub fn from_resolved_thermochemistry<'resolved>(
        resolved: &'resolved ResolvedPhaseSystem,
        initial_composition: MultiphaseInitialComposition,
        constraint: EquilibriumConstraint,
        temperature_bounds: TemperatureBounds,
        thermochemistry: ResolvedThermochemistry,
    ) -> Result<Self, ReactionExtentError> {
        let bundle_bounds = thermochemistry.temperature_bounds();
        if temperature_bounds.lower() < bundle_bounds.lower()
            || temperature_bounds.upper() > bundle_bounds.upper()
        {
            return Err(ReactionExtentError::InvalidProblem {
                field: "temperature_bounds",
                message: "P,H bounds extend beyond the selected thermochemistry domain".to_string(),
            });
        }
        let enthalpy = thermochemistry.enthalpy_model();
        let mut request = Self::from_legacy_parts(
            resolved,
            initial_composition,
            constraint,
            temperature_bounds,
            enthalpy,
        )?;
        request.thermochemistry = Some(thermochemistry);
        request.ph_solve_mode = PhSolveMode::default();
        Ok(request)
    }

    /// Creates a canonical P,H request from a closed elemental inventory.
    ///
    /// The bridge derives the first numerical seed from real resolved
    /// components, but every subsequent P,T trial still receives the original
    /// inventory as its conserved vector.  In particular, the generated seed
    /// is never reinterpreted as a user-specified molecular feed.
    pub fn from_element_inventory<'resolved>(
        resolved: &'resolved ResolvedPhaseSystem,
        element_inventory: ElementInventory,
        constraint: EquilibriumConstraint,
        temperature_bounds: TemperatureBounds,
        thermochemistry: ResolvedThermochemistry,
    ) -> Result<Self, ReactionExtentError> {
        validated_ph_parameters(constraint)?;
        let numerical_seed =
            initial_composition_from_element_inventory(resolved, &element_inventory)?;
        let mut request = Self::from_resolved_thermochemistry(
            resolved,
            numerical_seed,
            constraint,
            temperature_bounds,
            thermochemistry,
        )?;
        request.physical_input = PhPhysicalInput::ElementInventory(element_inventory);
        Ok(request)
    }

    /// Creates the canonical bridge request without allowing a numerical seed
    /// to replace the physical conserved inventory.
    fn build_pt_request(
        &self,
        conditions: crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::EquilibriumConditions,
    ) -> Result<PhaseEquilibriumBuildRequest<'_>, ReactionExtentError> {
        let request = match &self.physical_input {
            PhPhysicalInput::Composition => PhaseEquilibriumBuildRequest::new(
                &self.resolved,
                conditions,
                self.initial_composition.clone(),
                self.solve_options.trace_seed_policy(),
                SupportedPhaseModelPolicy::default(),
            ),
            PhPhysicalInput::ElementInventory(inventory) => {
                PhaseEquilibriumBuildRequest::from_element_inventory(
                    &self.resolved,
                    conditions,
                    inventory.clone(),
                    self.solve_options.trace_seed_policy(),
                    SupportedPhaseModelPolicy::default(),
                )?
                .with_numerical_seed(self.initial_composition.clone())
            }
        }?;
        Ok(match &self.candidate_selection {
            Some(selection) => request.with_candidate_selection(selection.clone()),
            None => request,
        })
    }

    /// Retains the immutable catalog-selection transaction in every inner
    /// fixed-`P,T` bridge report.
    pub fn with_candidate_selection(
        mut self,
        selection: EquilibriumCandidateSelectionReport,
    ) -> Self {
        self.candidate_selection = Some(selection);
        self
    }

    /// Validates the complete `P,H` request before any inner equilibrium solve.
    ///
    /// Checks that the constraint is a valid `P,H` specification (not `P,T`),
    /// that the initial temperature seed lies inside the declared thermochemistry
    /// bounds, and that the initial composition dimension matches the resolved
    /// layout. Returns a typed error with the offending field name on the first
    /// violation so callers receive a diagnostic message rather than a silent
    /// assertion failure during the scalar search.
    fn validate(&self) -> Result<(), ReactionExtentError> {
        let (_, initial_temperature) = self.validate_structure()?;
        let initial_molar = self.enthalpy.evaluate_molar(initial_temperature)?;
        self.validate_with_initial_molar_enthalpies(&initial_molar)
    }

    /// Validates fields that do not require evaluating thermochemistry.
    fn validate_structure(&self) -> Result<(f64, f64), ReactionExtentError> {
        let parameters = validated_ph_parameters(self.constraint)?;
        let (_, initial_temperature) = parameters;
        self.constraint
            .validate_temperature(initial_temperature, self.temperature_bounds)?;
        if self.initial_composition.moles().len() != self.resolved.layout().component_count() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "initial composition has {} entries but resolved layout has {} components",
                self.initial_composition.moles().len(),
                self.resolved.layout().component_count()
            )));
        }
        if self.enthalpy.len() != self.initial_composition.moles().len() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "enthalpy model has {} functions but resolved layout has {} components",
                self.enthalpy.len(),
                self.initial_composition.moles().len()
            )));
        }
        self.temperature_options.validate()?;
        Ok(parameters)
    }

    /// Completes request validation from an already evaluated molar enthalpy
    /// vector, avoiding a second thermochemistry traversal on prepared points.
    fn validate_with_initial_molar_enthalpies(
        &self,
        initial_molar: &[f64],
    ) -> Result<(), ReactionExtentError> {
        let (target_enthalpy, _) = self.validate_structure()?;
        if initial_molar.len() != self.enthalpy.len() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "molar enthalpy vector has {} entries but enthalpy model has {} functions",
                initial_molar.len(),
                self.enthalpy.len()
            )));
        }
        EnthalpyScale::from_magnitudes(
            target_enthalpy,
            self.initial_composition.moles(),
            initial_molar,
        )?;
        Ok(())
    }

    /// Replaces inner fixed-`P,T` solver controls.
    pub fn with_solve_options(mut self, options: EquilibriumSolveOptions) -> Self {
        self.solve_options = options;
        self
    }

    /// Uses bounded active-set phase control for each temperature trial.
    pub fn with_phase_control_policy(mut self, policy: PhaseControlPolicy) -> Self {
        self.solve_mode = PhaseEquilibriumSolveMode::bounded_phase_control(policy);
        self
    }

    /// Selects the P,H numerical formulation explicitly.
    ///
    /// `Monolithic` requires a complete [`ResolvedThermochemistry`] bundle.
    /// With bounded phase control, the coupled candidate is still executed by
    /// the shared transactional active-set lifecycle. `Auto` tries this
    /// monolithic route first and falls back only for retryable numerical
    /// failures; its report retains the classified reason.
    pub fn with_ph_solve_mode(mut self, mode: PhSolveMode) -> Self {
        self.ph_solve_mode = mode;
        self
    }

    /// Replaces outer scalar solver controls after validation.
    pub fn with_temperature_options(
        mut self,
        options: PhTemperatureSolveOptions,
    ) -> Result<Self, ReactionExtentError> {
        options.validate()?;
        self.temperature_options = options;
        Ok(self)
    }

    /// Replaces the physical composition used to seed the next `P,H` solve.
    ///
    /// This is the continuation boundary for a target-enthalpy sweep. The
    /// composition is validated against the immutable resolved layout before
    /// the request is returned, so a point from another system cannot be
    /// accidentally used as a seed.
    pub fn with_initial_composition(
        mut self,
        composition: MultiphaseInitialComposition,
    ) -> Result<Self, ReactionExtentError> {
        let layout = MultiphaseEquilibriumLayout::new(self.resolved.phase_specs().to_vec())?;
        composition.validate_for(&layout)?;
        self.initial_composition = composition;
        self.validate()?;
        Ok(self)
    }

    /// Replaces the target enthalpy and continuation temperature seed.
    ///
    /// The temperature is only an initial estimate; the accepted solution
    /// still has to satisfy the full `P,H` solve and its bounds. Keeping this
    /// operation on the typed request prevents a batch layer from mutating
    /// solver state between points.
    pub fn with_target_enthalpy_and_seed(
        mut self,
        target_enthalpy: crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::
            TotalEnthalpyJoules,
        initial_temperature: f64,
    ) -> Result<Self, ReactionExtentError> {
        self.constraint = EquilibriumConstraint::ph_joules(
            self.constraint.pressure(),
            self.constraint.reference_pressure(),
            target_enthalpy,
            initial_temperature,
        )?;
        self.validate()?;
        Ok(self)
    }

    /// Retargets an owned prepared-session request without cloning its large
    /// resolved and thermochemistry payloads. The caller owns the session's
    /// transactional seed and invokes this only at the next point boundary.
    pub(crate) fn retarget_for_prepared_session(
        &mut self,
        target_enthalpy: crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::
            TotalEnthalpyJoules,
        initial_temperature: f64,
        initial_composition: MultiphaseInitialComposition,
    ) -> Result<(), ReactionExtentError> {
        let constraint = EquilibriumConstraint::ph_joules(
            self.constraint.pressure(),
            self.constraint.reference_pressure(),
            target_enthalpy,
            initial_temperature,
        )?;
        let layout = MultiphaseEquilibriumLayout::new(self.resolved.phase_specs().to_vec())?;
        initial_composition.validate_for(&layout)?;
        let previous_constraint = self.constraint;
        let previous_composition = self.initial_composition.clone();
        self.constraint = constraint;
        self.initial_composition = initial_composition;
        if let Err(error) = self.validate_structure() {
            self.constraint = previous_constraint;
            self.initial_composition = previous_composition;
            return Err(error);
        }
        Ok(())
    }

    /// Returns the immutable resolved system borrowed by this request.
    pub fn resolved(&self) -> &ResolvedPhaseSystem {
        self.resolved.as_ref()
    }

    /// Returns the physical composition used to initialize this request.
    ///
    /// Batch continuation uses this value only as the first-point seed; all
    /// later seeds come from the preceding accepted solution.
    pub fn initial_composition(&self) -> &MultiphaseInitialComposition {
        &self.initial_composition
    }

    /// Returns the closed elemental inventory when this request is
    /// element-defined. `None` means the legacy explicit-composition mode.
    pub fn element_inventory(&self) -> Option<&ElementInventory> {
        match &self.physical_input {
            PhPhysicalInput::Composition => None,
            PhPhysicalInput::ElementInventory(inventory) => Some(inventory),
        }
    }

    pub(crate) fn needs_small_scale_ph_preconditioning(&self) -> Result<bool, ReactionExtentError> {
        if !self
            .solve_options
            .extensive_normalization_policy()
            .allows_small_scale_ph_preconditioning()
        {
            return Ok(false);
        }
        let normalization = match &self.physical_input {
            PhPhysicalInput::Composition => {
                ExtensiveNormalization::from_physical_moles(self.initial_composition.moles())?
            }
            PhPhysicalInput::ElementInventory(inventory) => {
                ExtensiveNormalization::from_element_inventory(inventory)?
            }
        };
        Ok(normalization.physical_inventory_scale() < 1.0)
    }

    /// Returns the `P,H` constraint.
    pub fn constraint(&self) -> EquilibriumConstraint {
        self.constraint
    }

    /// Selected P,H numerical formulation.
    pub fn ph_solve_mode(&self) -> PhSolveMode {
        self.ph_solve_mode
    }

    /// Creates a shallow clone of this request with a different `P,H` solve mode.
    ///
    /// The resolved system, initial composition, constraint, temperature bounds,
    /// enthalpy model, and solve options are shared via cloning the `Arc`-wrapped
    /// resolved system and copying the remaining value-type fields. Only the
    /// [`PhSolveMode`] is replaced, which lets the monolithic-to-nested fallback
    /// path retry with a different numerical route without rebuilding the request.
    pub(crate) fn cloned_with_ph_solve_mode(&self, mode: PhSolveMode) -> Self {
        Self {
            resolved: Arc::clone(&self.resolved),
            physical_input: self.physical_input.clone(),
            initial_composition: self.initial_composition.clone(),
            constraint: self.constraint,
            temperature_bounds: self.temperature_bounds,
            enthalpy: self.enthalpy.clone(),
            solve_options: self.solve_options.clone(),
            solve_mode: self.solve_mode.clone(),
            ph_solve_mode: mode,
            temperature_options: self.temperature_options.clone(),
            thermochemistry: self.thermochemistry.clone(),
            candidate_selection: self.candidate_selection.clone(),
        }
    }

    /// Borrows the inner fixed-`P,T` solver options so a frontend can attach
    /// cancellation, progress, or diagnostic policy without opening the
    /// request's mutable internals.
    pub fn solve_options(&self) -> &EquilibriumSolveOptions {
        &self.solve_options
    }

    /// Whether this request owns a fixed declared phase layout rather than a
    /// phase-control lifecycle. Prepared P,H range state is valid only for
    /// this topology-stable route.
    pub(crate) fn uses_fixed_declared_phases(&self) -> bool {
        matches!(
            self.solve_mode,
            PhaseEquilibriumSolveMode::FixedDeclaredPhases
        )
    }
}

/// Prepared fixed-active P,H state shared by a target-enthalpy range.
///
/// The structural problem and symbolic residual are immutable across points;
/// only the accepted composition/temperature seed and the two scalar energy
/// parameters are retargeted. This state is crate-private so the public range
/// facade remains the sole orchestration boundary.
pub(crate) struct PreparedPhContinuationState {
    prepared: crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::
        PreparedFixedActiveProblem,
    formulation: PreparedPhFormulation,
    thermochemistry: ResolvedThermochemistry,
    rst_problem: Option<RstPreparedProblem>,
    preparation_timing: EquilibriumTimingReport,
    cached_target_enthalpy: f64,
    cached_enthalpy_scale: f64,
    cached_initial_enthalpies: Option<(f64, Vec<f64>)>,
    cached_gibbs: Option<(f64, Vec<GibbsFn>)>,
}

/// Shared fixed-`P,T` template for a nested `P,H` target range.
///
/// The nested route still owns an independent scalar bracket for every
/// target. Only the topology-stable inner formulation is shared here. In
/// particular, this type never carries a bracket, a rejected trial, or a
/// bounded phase-control active set from one target into the next.
pub(crate) struct PreparedNestedPhContinuationState {
    fixed_template: Option<PreparedPhaseEquilibriumTemplate>,
}

impl PreparedNestedPhContinuationState {
    /// Creates an empty shared template for a fixed-declared nested range.
    pub(crate) fn new(
        request: &ResolvedPhaseEnthalpyRequest<'_>,
    ) -> Result<Self, ReactionExtentError> {
        request.validate()?;
        if !matches!(
            request.ph_solve_mode,
            PhSolveMode::NestedTemperature | PhSolveMode::Auto
        ) || !request.uses_fixed_declared_phases()
        {
            return Err(ReactionExtentError::InvalidProblem {
                field: "ph_range_nested_template",
                message: "nested P,H template requires fixed declared phases".into(),
            });
        }
        Ok(Self {
            fixed_template: None,
        })
    }

    /// Solves one scalar target while sharing only the prepared inner
    /// fixed-`P,T` formulation with earlier targets.
    pub(crate) fn solve(
        &mut self,
        request: ResolvedPhaseEnthalpyRequest<'_>,
    ) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
        solve_resolved_ph_nested_with_template(request, &mut self.fixed_template)
    }
}

impl PreparedPhContinuationState {
    /// Returns the immutable timing captured while preparing the fixed state.
    pub(crate) fn preparation_timing(&self) -> EquilibriumTimingReport {
        self.preparation_timing
    }

    /// Whether preparation materialized a reusable RST P,H graph.
    pub(crate) fn rst_graph_prepared(&self) -> bool {
        self.rst_problem.is_some()
    }

    /// Builds structural P,H state from the first range point.
    pub(crate) fn new(
        request: &ResolvedPhaseEnthalpyRequest<'_>,
    ) -> Result<Self, ReactionExtentError> {
        let started = Instant::now();
        let mut timing = EquilibriumTimingCollector::new(request.solve_options.timing_mode());
        timing.measure(EquilibriumTimingStage::RequestPreparation, || {
            request.validate_structure().map(|_| ())
        })?;
        if !matches!(
            request.ph_solve_mode,
            PhSolveMode::Monolithic | PhSolveMode::Auto
        ) || !matches!(
            request.solve_mode,
            PhaseEquilibriumSolveMode::FixedDeclaredPhases
        ) {
            return Err(ReactionExtentError::InvalidProblem {
                field: "ph_range_prepared_state",
                message: "prepared monolithic P,H state requires fixed declared phases".into(),
            });
        }
        let thermochemistry =
            request
                .thermochemistry
                .clone()
                .ok_or_else(|| ReactionExtentError::InvalidProblem {
                    field: "ph_monolithic_thermochemistry",
                    message: "prepared monolithic P,H state requires resolved thermochemistry"
                        .into(),
                })?;
        let (target, initial_temperature) = timing
            .measure(EquilibriumTimingStage::RequestPreparation, || {
                validated_ph_parameters(request.constraint)
            })?;
        let initial_molar_enthalpies = timing
            .measure(EquilibriumTimingStage::ThermochemistryPreparation, || {
                thermochemistry.evaluate_enthalpy(initial_temperature)
            })?;
        let scale = timing.measure(EquilibriumTimingStage::Normalization, || {
            EnthalpyScale::from_magnitudes(
                target,
                request.initial_composition.moles(),
                &initial_molar_enthalpies,
            )
        })?;
        let conditions = timing.measure(EquilibriumTimingStage::RequestPreparation, || {
            request.constraint.conditions_at(initial_temperature)
        })?;
        let bundle = build_phase_equilibrium_problem_with_timing(
            request.build_pt_request(conditions)?,
            request.solve_options.timing_mode(),
        )?;
        let prepared = bundle.into_prepared_fixed_active_problem()?;
        timing.accumulate(prepared.timing);
        let formulation =
            timing.measure(EquilibriumTimingStage::PhFormulationPreparation, || {
                PreparedPhFormulation::new(
                    prepared.prepared.clone(),
                    thermochemistry.clone(),
                    request.temperature_bounds,
                    target,
                    scale,
                )
            })?;
        let rst_problem = if request.solve_options.prepares_rst_backend() {
            let (problem, rst_timing) = prepare_rst_symbolic_ph_problem_with_timing(
                &formulation,
                request.solve_options.timing_mode(),
                request.solve_options.rst_symbolic_frontend(),
            )?;
            timing.accumulate(rst_timing);
            Some(problem)
        } else {
            None
        };
        timing.set_total(started.elapsed());
        Ok(Self {
            prepared,
            formulation,
            thermochemistry,
            rst_problem,
            preparation_timing: timing.finish(),
            cached_target_enthalpy: target,
            cached_enthalpy_scale: scale.joules(),
            cached_initial_enthalpies: Some((initial_temperature, initial_molar_enthalpies)),
            cached_gibbs: None,
        })
    }

    /// Solves one accepted target using the shared prepared state.
    pub(crate) fn solve(
        &mut self,
        request: &ResolvedPhaseEnthalpyRequest<'_>,
        formulation_reused: bool,
    ) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
        let started = Instant::now();
        let timing_enabled = request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled;
        let (target, initial_temperature) = validated_ph_parameters(request.constraint)?;
        let enthalpy_started = timing_enabled.then(Instant::now);
        let (initial_molar_enthalpies, initial_enthalpy_reused) = match self
            .cached_initial_enthalpies
            .as_ref()
            .filter(|(temperature, _)| *temperature == initial_temperature)
        {
            Some((_, enthalpies)) => (enthalpies.clone(), true),
            None => (
                self.thermochemistry
                    .evaluate_enthalpy(initial_temperature)?,
                false,
            ),
        };
        let initial_enthalpy = enthalpy_started.map_or(Duration::ZERO, |started| started.elapsed());
        let request_validation_started = timing_enabled.then(Instant::now);
        request.validate_with_initial_molar_enthalpies(&initial_molar_enthalpies)?;
        let request_validation =
            request_validation_started.map_or(Duration::ZERO, |started| started.elapsed());
        let scale = EnthalpyScale::from_magnitudes(
            target,
            request.initial_composition.moles(),
            &initial_molar_enthalpies,
        )?;
        let conditions = request.constraint.conditions_at(initial_temperature)?;
        let log_seed =
            LogMolesInitialGuess::from_initial_moles(request.initial_composition.moles())?;
        let gibbs_started = timing_enabled.then(Instant::now);
        let (gibbs, gibbs_snapshot_reused) = match self
            .cached_gibbs
            .as_ref()
            .filter(|(temperature, _)| *temperature == initial_temperature)
        {
            Some((_, gibbs)) => (gibbs.clone(), true),
            None => {
                let gibbs = self
                    .thermochemistry
                    .gibbs_snapshot_for_legacy_boundary(initial_temperature)?;
                (gibbs, false)
            }
        };
        let gibbs_snapshot = gibbs_started.map_or(Duration::ZERO, |started| started.elapsed());
        let retarget_started = timing_enabled.then(Instant::now);
        let prepared =
            self.prepared
                .prepared
                .retarget_with_gibbs(conditions, log_seed.clone(), gibbs)?;
        let prepared_problem_retarget =
            retarget_started.map_or(Duration::ZERO, |started| started.elapsed());
        // Retarget local copies. The prepared cache is committed only after
        // the candidate has passed the ordinary publication boundary; a
        // failed point must not become the seed/formulation of the next one.
        let formulation = self.formulation.retarget(prepared.clone(), target, scale)?;
        let options = request.temperature_options.clone();
        let monolithic_options = options.monolithic_options()?;
        let runner = PreparedMonolithicPhRunner::new(
            formulation.clone(),
            request.solve_options.clone().into_settings(),
            monolithic_options,
        )?
        .with_timing_enabled(request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled);
        if let Some(control) = options.execution_control() {
            control.check_cancelled()?;
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::FormulationPreparation,
                Some(0),
                Some(1),
                Some(initial_temperature),
            ));
        }
        // Delay the only mutable backend-cache write until all fallible
        // preparation and cancellation checks have completed. The error path
        // below then has one explicit restoration point.
        if let Some(rst_problem) = self.rst_problem.as_mut() {
            rst_problem.set_ph_parameters(target, scale.joules())?;
        }
        let outcome = match runner.solve_from_log_moles_and_temperature_seed(
            &log_seed,
            initial_temperature,
            self.rst_problem.as_ref(),
        ) {
            Ok(outcome) => outcome,
            Err(error) => {
                // RST owns a mutable parameter buffer, so restore its last
                // committed values before returning a failed transaction.
                if let Some(rst_problem) = self.rst_problem.as_mut() {
                    rst_problem.set_ph_parameters(
                        self.cached_target_enthalpy,
                        self.cached_enthalpy_scale,
                    )?;
                }
                enforce_monolithic_work_limits(
                    &options,
                    started,
                    error.started_backend_attempts(),
                    error.nonlinear_iterations(),
                    0,
                )?;
                return Err(error);
            }
        };
        enforce_monolithic_work_limits(
            &options,
            started,
            outcome.temperature_seed_report.started_backend_attempts(),
            outcome.temperature_seed_report.nonlinear_iterations(),
            0,
        )?;
        let accepted_conditions = request
            .constraint
            .conditions_at(outcome.snapshot.temperature)?;
        let accepted_solution = prepared.accepted_solution_at_conditions(
            outcome.snapshot.log_moles.clone(),
            outcome.pt_validation.clone(),
            accepted_conditions,
        )?;
        let accepted_gibbs = self
            .thermochemistry
            .evaluate_gibbs(outcome.snapshot.temperature)?
            .into_iter()
            .map(|value| Rc::new(move |_| value) as GibbsFn)
            .collect::<Vec<_>>();
        let next_cached_initial_enthalpies =
            (initial_temperature, initial_molar_enthalpies.clone());
        let next_cached_gibbs = (outcome.snapshot.temperature, accepted_gibbs.clone());
        let accepted_report = self
            .prepared
            .report
            .at_conditions(accepted_conditions, &accepted_gibbs)?;
        let solution = MultiphaseEquilibriumSolution::from_fixed_active_parts(
            self.prepared.metadata.clone(),
            accepted_report,
            accepted_solution,
            outcome.solve_report.clone(),
            self.prepared.timing,
        )?;
        let report = PhTemperatureSolveReport {
            solve_path: PhSolvePath::MonolithicFixedActiveSet,
            fallback_reason: None,
            route_decisions: Vec::new(),
            target_enthalpy: target,
            enthalpy_scale_joules: scale.joules(),
            absolute_enthalpy_tolerance_joules: options.absolute_enthalpy_tolerance_joules,
            scaled_enthalpy_tolerance: options.scaled_enthalpy_tolerance,
            max_temperature_evaluations: options.max_temperature_evaluations,
            initial_temperature_seed: initial_temperature,
            monotonicity_policy: options.monotonicity_policy,
            max_inner_backend_attempts: options.max_inner_backend_attempts,
            max_inner_nonlinear_iterations: options.max_inner_nonlinear_iterations,
            max_phase_control_transitions: options.max_phase_control_transitions,
            max_wall_time: options.max_wall_time,
            inner_backend_attempts: outcome.temperature_seed_report.started_backend_attempts(),
            inner_nonlinear_iterations: outcome.temperature_seed_report.nonlinear_iterations(),
            phase_control_transitions: 0,
            fixed_formulation_builds: usize::from(!formulation_reused),
            fixed_formulation_reuses: usize::from(formulation_reused),
            inner_timing: *solution.timing_report(),
            timing: PhTemperatureTimingReport {
                enabled: timing_enabled,
                total: if timing_enabled {
                    started.elapsed()
                } else {
                    Duration::ZERO
                },
                scalar_orchestration: Duration::ZERO,
                enthalpy_evaluation: Duration::ZERO,
                trial_total: Duration::ZERO,
                trial_inner_execution: Duration::ZERO,
                trial_preparation: Duration::ZERO,
                trial_template_preparation: Duration::ZERO,
                trial_postprocessing: Duration::ZERO,
                bracket_orchestration: Duration::ZERO,
                monolithic_preparation: Duration::ZERO,
                request_validation,
                initial_enthalpy,
                initial_enthalpy_reused,
                prepared_problem_retarget,
                gibbs_snapshot,
                gibbs_snapshot_reused,
                monolithic_rst_preparation: outcome.rst_preparation,
                monolithic_backend_execution: outcome.backend_execution,
                monolithic_execution: Duration::ZERO,
                monolithic_publication: Duration::ZERO,
                recovery_request_clone: Duration::ZERO,
                rst_preparation_timing: outcome.rst_preparation_timing,
            },
            iterations: 0,
            trials: Vec::new(),
            monolithic_evidence: Some(PhMonolithicEvidence {
                solve_report: solution.solve_report().clone(),
                multi_start_report: solution.multi_start_report().cloned(),
                temperature_seed_report: Some(outcome.temperature_seed_report.clone()),
                phase_control_report: None,
                acceptance_report: solution.acceptance_report().cloned(),
                inner_timing: *solution.timing_report(),
                validation_duration: outcome.validation_duration,
            }),
        };
        let result = FixedPressureEnthalpySolution {
            solution,
            calculated_enthalpy: outcome.snapshot.total_enthalpy,
            target_enthalpy: target,
            report,
            thermochemistry: Some(self.thermochemistry.clone()),
        };
        // Commit the retargeted structural state only after construction of a
        // complete accepted result succeeded.
        self.prepared.prepared = prepared;
        self.formulation = formulation;
        self.cached_target_enthalpy = target;
        self.cached_enthalpy_scale = scale.joules();
        self.cached_initial_enthalpies = Some(next_cached_initial_enthalpies);
        self.cached_gibbs = Some(next_cached_gibbs);
        Ok(result)
    }
}

/// Solves one resolved system at fixed pressure and total enthalpy.
///
/// The selected [`PhSolveMode`] determines the numerical formulation. The
/// canonical resolved-data request defaults to the auditable `Auto` path.
/// The nested path keeps every scalar trial local until its bracket accepts
/// one temperature; no failed trial is published. `Auto` attempts monolithic
/// solving first and falls back only for classified numerical failures.
pub fn solve_resolved_ph(
    request: ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    if request
        .solve_options
        .extensive_normalization_policy()
        .allows_small_scale_ph_preconditioning()
    {
        if let Some(solution) = solve_small_scale_ph_normalized_first(&request)? {
            return Ok(solution);
        }
    }
    let diagnostics = request.solve_options.diagnostics_options().clone();
    match request.ph_solve_mode {
        PhSolveMode::NestedTemperature => solve_resolved_ph_nested(request),
        PhSolveMode::Monolithic => match request.solve_mode {
            PhaseEquilibriumSolveMode::FixedDeclaredPhases => solve_resolved_ph_monolithic(request),
            PhaseEquilibriumSolveMode::BoundedPhaseControl(_) => {
                solve_resolved_ph_monolithic_phase_control(request)
            }
        },
        PhSolveMode::Auto => {
            let monolithic_request = request.cloned_with_ph_solve_mode(PhSolveMode::Monolithic);
            match solve_resolved_ph(monolithic_request) {
                Ok(solution) => Ok(solution),
                Err(error) if error.is_retryable_formulation_failure() => {
                    let fallback_reason = PhFallbackReason::from_error(&error);
                    diagnostics.emit(
                        EquilibriumDiagnosticsMode::Summary,
                        EquilibriumDiagnosticEvent::PhRouteFallback {
                            from_route: PhDiagnosticRoute::Monolithic,
                            to_route: PhDiagnosticRoute::NestedTemperature,
                            error_kind: error.kind(),
                            message: error.to_string(),
                        },
                    );
                    let route_selection_started = Instant::now();
                    let nested_request =
                        request.cloned_with_ph_solve_mode(PhSolveMode::NestedTemperature);
                    let route_selection_duration = route_selection_started.elapsed();
                    match solve_resolved_ph(nested_request) {
                        Ok(mut nested) => {
                            nested.report.fallback_reason = Some(fallback_reason.clone());
                            nested
                                .report
                                .route_decisions
                                .push(PhRouteDecision::AutoFallback {
                                    from_route: PhDiagnosticRoute::Monolithic,
                                    to_route: PhDiagnosticRoute::NestedTemperature,
                                    reason: fallback_reason,
                                });
                            Ok(nested.with_route_selection_timing(route_selection_duration))
                        }
                        Err(nested) => {
                            diagnostics.emit(
                                EquilibriumDiagnosticsMode::Summary,
                                EquilibriumDiagnosticEvent::PhRouteFailed {
                                    route: PhDiagnosticRoute::NestedTemperature,
                                    error_kind: nested.kind(),
                                    message: nested.to_string(),
                                },
                            );
                            Err(ReactionExtentError::PhAutoFallbackFailed {
                                monolithic: Box::new(error),
                                nested: Box::new(nested),
                            })
                        }
                    }
                }
                Err(error) => {
                    diagnostics.emit(
                        EquilibriumDiagnosticsMode::Summary,
                        EquilibriumDiagnosticEvent::PhRouteFailed {
                            route: PhDiagnosticRoute::Monolithic,
                            error_kind: error.kind(),
                            message: error.to_string(),
                        },
                    );
                    Err(error)
                }
            }
        }
    }
}

/// Runs one complete `P,H` point transaction, including typed extensive
/// recovery after a classified physical-coordinate failure.
///
/// This is the single-point counterpart to the range driver's recovery
/// boundary. Prepared range states keep invoking
/// [`recover_resolved_ph_after_numerical_failure`] themselves because they
/// already own the failed fast-path evidence and continuation state.
pub(crate) fn solve_resolved_ph_transaction(
    request: ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    let transaction_started = Instant::now();
    let timing_enabled = request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled;
    let (working_request, recovery_request_clone) = if timing_enabled {
        let clone_started = Instant::now();
        let working_request = request.clone();
        (working_request, clone_started.elapsed())
    } else {
        (request.clone(), Duration::ZERO)
    };
    let physical_attempt_started = Instant::now();
    match solve_resolved_ph(working_request) {
        Ok(solution) => Ok(solution.with_recovery_request_clone_timing(recovery_request_clone)),
        Err(physical_error) => {
            let physical_failure_duration = physical_attempt_started.elapsed();
            if request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled {
                recover_resolved_ph_after_numerical_failure(
                    request,
                    physical_error,
                    physical_failure_duration,
                )
                .map(|mut solution| {
                    // Preserve the rejected physical attempt in the
                    // accepted recovery transaction's timing evidence.
                    let elapsed = transaction_started.elapsed();
                    solution.solution = solution
                        .solution
                        .with_timing_stage(EquilibriumTimingStage::Recovery, elapsed)
                        .with_timing_total(elapsed);
                    solution.report.inner_timing = *solution.solution.timing_report();
                    // The accepted normalized result carries the inner
                    // recovery evidence, but its outer P,H report was
                    // created by the normalized solve. Restore the wall
                    // clock of the complete physical transaction here.
                    if timing_enabled {
                        solution.report.timing.total = elapsed;
                    }
                    solution = solution.with_recovery_request_clone_timing(recovery_request_clone);
                    solution
                })
            } else {
                recover_resolved_ph_after_numerical_failure(
                    request,
                    physical_error,
                    physical_failure_duration,
                )
            }
        }
    }
}

fn solve_small_scale_ph_normalized_first(
    request: &ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<Option<FixedPressureEnthalpySolution>, ReactionExtentError> {
    let normalization = match &request.physical_input {
        PhPhysicalInput::Composition => {
            ExtensiveNormalization::from_physical_moles(request.initial_composition.moles())?
        }
        PhPhysicalInput::ElementInventory(inventory) => {
            ExtensiveNormalization::from_element_inventory(inventory)?
        }
    };
    if normalization.physical_inventory_scale() >= 1.0 {
        return Ok(None);
    }

    let transaction_started = Instant::now();
    let normalization_started = Instant::now();
    let normalized_request = build_normalized_ph_request(request, normalization)?;
    let normalization_duration = normalization_started.elapsed();
    let discovery_started = Instant::now();
    let normalized_solution = solve_resolved_ph(normalized_request)?;
    let discovery_duration = discovery_started.elapsed();
    let discovery_backend = normalized_solution
        .equilibrium()
        .solve_report()
        .accepted_backend
        .clone();
    let normalized_discovery_attempts = normalized_solution
        .equilibrium()
        .solve_report()
        .attempts
        .clone();

    let reconstruction_started = Instant::now();
    let physical_build_report = build_phase_equilibrium_problem_with_timing(
        request.build_pt_request(normalized_solution.equilibrium().conditions())?,
        request.solve_options.timing_mode(),
    )?
    .report()
    .clone();
    let mut recovered = normalized_solution
        .reconstruct_physical_extensive_boundary(normalization, physical_build_report)?;
    let reconstruction_duration = reconstruction_started.elapsed();
    let trigger = ExtensiveNormalizationTrigger::SmallScalePreconditioning {
        physical_inventory_scale: normalization.physical_inventory_scale(),
    };
    let evidence = ExtensiveNormalizationRecoveryEvidence {
        physical_inventory_scale: normalization.physical_inventory_scale(),
        trigger: trigger.clone(),
        discovery_backend,
        physical_retry_backend: None,
        physical_retry_failure: None,
        physical_failure_attempts: Vec::new(),
        normalized_discovery_attempts,
        physical_retry_attempts: Vec::new(),
        physical_failure_duration: Duration::ZERO,
        normalization_duration,
        normalized_discovery_duration: discovery_duration,
        physical_retry_duration: Duration::ZERO,
        reconstruction_duration,
        reconstructed_physical_boundary: true,
    };
    let event = EquilibriumDiagnosticEvent::ExtensiveNormalizationRecoveryAccepted {
        physical_inventory_scale: evidence.physical_inventory_scale,
        trigger_kind: trigger.error_kind(),
        trigger_reason: trigger.description(),
        discovery_backend: format!("{:?}", evidence.discovery_backend),
        physical_retry_backend: None,
        reconstructed_physical_boundary: true,
    };
    let mut diagnostics = recovered.equilibrium().diagnostics_report().map_or_else(
        || {
            EquilibriumDiagnosticsCollector::new(
                request.solve_options.diagnostics_options().clone(),
            )
        },
        |report| {
            EquilibriumDiagnosticsCollector::from_report(
                request.solve_options.diagnostics_options().clone(),
                report,
            )
        },
    );
    diagnostics.record(EquilibriumDiagnosticsMode::Summary, event);
    recovered.solution = recovered
        .solution
        .clone()
        .with_diagnostics(diagnostics.finish())
        .with_extensive_normalization_recovery(evidence);
    let total = transaction_started.elapsed();
    recovered.solution = recovered
        .solution
        .with_timing_stage(
            EquilibriumTimingStage::Normalization,
            normalization_duration,
        )
        .with_timing_total(total);
    recovered.report.inner_timing = *recovered.solution.timing_report();
    if request.solve_options.timing_mode() == EquilibriumTimingMode::Enabled {
        recovered.report.timing.total = total;
    }
    Ok(Some(recovered))
}

fn build_normalized_ph_request<'a>(
    request: &ResolvedPhaseEnthalpyRequest<'a>,
    normalization: ExtensiveNormalization,
) -> Result<ResolvedPhaseEnthalpyRequest<'a>, ReactionExtentError> {
    let layout = MultiphaseEquilibriumLayout::new(request.resolved.phase_specs().to_vec())?;
    let normalized_composition =
        normalization.normalize_initial_composition(&layout, &request.initial_composition)?;
    let normalized_physical_input = match &request.physical_input {
        PhPhysicalInput::Composition => PhPhysicalInput::Composition,
        PhPhysicalInput::ElementInventory(inventory) => {
            PhPhysicalInput::ElementInventory(normalization.normalize_element_inventory(inventory)?)
        }
    };
    let (target, seed) = validated_ph_parameters(request.constraint)?;
    let normalized_target = normalization.normalize_total_enthalpy(
        crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
            target,
        )?,
    )?;
    let normalized_constraint = EquilibriumConstraint::ph_joules(
        request.constraint.pressure(),
        request.constraint.reference_pressure(),
        normalized_target,
        seed,
    )?;
    let mut normalized_temperature_options = request.temperature_options.clone();
    normalized_temperature_options.absolute_enthalpy_tolerance_joules = normalization
        .normalize_physical_energy_tolerance(
            normalized_temperature_options.absolute_enthalpy_tolerance_joules,
        )?;
    let normalized_options = request
        .solve_options
        .clone()
        .with_extensive_normalization_policy(ExtensiveNormalizationPolicy::Disabled)
        .with_diagnostics(EquilibriumDiagnosticsOptions::disabled())
        .with_trace_seed_policy(normalized_recovery_trace_policy(
            normalization,
            request.solve_options.trace_seed_policy(),
        )?);
    let normalized_request = ResolvedPhaseEnthalpyRequest {
        resolved: request.resolved.clone(),
        physical_input: normalized_physical_input,
        initial_composition: normalized_composition,
        constraint: normalized_constraint,
        temperature_bounds: request.temperature_bounds,
        enthalpy: request.enthalpy.clone(),
        solve_options: normalized_options,
        solve_mode: request.solve_mode.clone(),
        ph_solve_mode: request.ph_solve_mode,
        temperature_options: normalized_temperature_options,
        thermochemistry: request.thermochemistry.clone(),
        candidate_selection: request.candidate_selection.clone(),
    };
    Ok(normalized_request)
}

/// Recovers one rejected P,H point in an exactly equivalent normalized
/// extensive representation.
///
/// This entry point is intentionally separate from [`solve_resolved_ph`]: a
/// range driver calls it only after its prepared fast path has failed. The
/// normalized transaction is fresh, its accepted result is reconstructed into
/// physical units, and only then may the range driver update continuation.
pub(crate) fn recover_resolved_ph_after_numerical_failure<'a>(
    request: ResolvedPhaseEnthalpyRequest<'a>,
    physical_error: ReactionExtentError,
    physical_failure_duration: Duration,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    if !request
        .solve_options
        .extensive_normalization_policy()
        .allows_numerical_failure_recovery()
        || !matches!(
            physical_error.kind(),
            ReactionExtentErrorKind::AllBackendsFailed
                | ReactionExtentErrorKind::NonConvergence
                | ReactionExtentErrorKind::BackendFailure
        )
    {
        return Err(physical_error);
    }

    let normalization_started = Instant::now();
    let normalization = match &request.physical_input {
        PhPhysicalInput::Composition => {
            ExtensiveNormalization::from_physical_moles(request.initial_composition.moles())?
        }
        PhPhysicalInput::ElementInventory(inventory) => {
            ExtensiveNormalization::from_element_inventory(inventory)?
        }
    };
    if !normalization.physical_inventory_scale().is_finite()
        || normalization.physical_inventory_scale() <= 0.0
        || normalization.physical_inventory_scale().ln().abs() <= 10.0_f64.ln()
    {
        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_physical_input = match &request.physical_input {
        PhPhysicalInput::Composition => PhPhysicalInput::Composition,
        PhPhysicalInput::ElementInventory(inventory) => {
            PhPhysicalInput::ElementInventory(normalization.normalize_element_inventory(inventory)?)
        }
    };
    let (target, seed) = validated_ph_parameters(request.constraint)?;
    let normalized_target = normalization.normalize_total_enthalpy(
        crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
            target,
        )?,
    )?;
    let normalized_constraint = EquilibriumConstraint::ph_joules(
        request.constraint.pressure(),
        request.constraint.reference_pressure(),
        normalized_target,
        seed,
    )?;
    let mut normalized_temperature_options = request.temperature_options.clone();
    normalized_temperature_options.absolute_enthalpy_tolerance_joules = normalization
        .normalize_physical_energy_tolerance(
            normalized_temperature_options.absolute_enthalpy_tolerance_joules,
        )?;
    let normalized_options = request
        .solve_options
        .clone()
        .with_extensive_normalization_policy(
            crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_workflow::
                ExtensiveNormalizationPolicy::Disabled,
        )
        .with_diagnostics(EquilibriumDiagnosticsOptions::disabled())
        .with_trace_seed_policy(
            normalized_recovery_trace_policy(
                normalization,
                request.solve_options.trace_seed_policy(),
            )?,
        );
    let normalized_request = ResolvedPhaseEnthalpyRequest {
        resolved: request.resolved.clone(),
        physical_input: normalized_physical_input,
        initial_composition: normalized_composition,
        constraint: normalized_constraint,
        temperature_bounds: request.temperature_bounds,
        enthalpy: request.enthalpy.clone(),
        solve_options: normalized_options,
        solve_mode: request.solve_mode.clone(),
        ph_solve_mode: request.ph_solve_mode,
        temperature_options: normalized_temperature_options,
        thermochemistry: request.thermochemistry.clone(),
        candidate_selection: request.candidate_selection.clone(),
    };
    let normalization_duration = normalization_started.elapsed();
    let physical_failure_attempts = physical_error.backend_attempt_reports();
    let normalized_discovery_started = Instant::now();
    let normalized_solution = solve_resolved_ph(normalized_request).map_err(|recovery| {
        ReactionExtentError::ExtensiveNormalizationRecoveryFailed {
            stage: "P,H normalized basin discovery",
            physical: Box::new(physical_error),
            recovery: Box::new(recovery),
        }
    })?;
    let normalized_discovery_duration = normalized_discovery_started.elapsed();
    let discovery_backend = normalized_solution
        .equilibrium()
        .solve_report()
        .accepted_backend
        .clone();
    let normalized_discovery_attempts = normalized_solution
        .equilibrium()
        .solve_report()
        .attempts
        .clone();
    let accepted_conditions = normalized_solution.equilibrium().conditions();
    let recovered_moles = normalization.denormalize_moles(
        normalized_solution
            .equilibrium()
            .accepted_solution()
            .moles(),
    )?;
    let recovered_composition = MultiphaseInitialComposition::from_dense(&layout, recovered_moles)?;
    let physical_retry_constraint = EquilibriumConstraint::ph_joules(
        request.constraint.pressure(),
        request.constraint.reference_pressure(),
        crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::TotalEnthalpyJoules::new(
            target,
        )?,
        accepted_conditions.temperature(),
    )?;
    let mut physical_retry = request.clone();
    physical_retry.initial_composition = recovered_composition;
    physical_retry.constraint = physical_retry_constraint;
    physical_retry.solve_options = physical_retry
        .solve_options
        .clone()
        .with_extensive_normalization_policy(
            crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_workflow::
                ExtensiveNormalizationPolicy::Disabled,
        );
    let physical_retry_started = Instant::now();
    let physical_retry_result = solve_resolved_ph(physical_retry);
    let physical_retry_duration = physical_retry_started.elapsed();
    let physical_retry_attempts = match physical_retry_result {
        Ok(physical_solution) => {
            let physical_retry_backend = physical_solution
                .equilibrium()
                .solve_report()
                .accepted_backend
                .clone();
            let mut physical_solution = physical_solution.with_inner_timing_stage(
                EquilibriumTimingStage::Normalization,
                normalization_duration,
            );
            let physical_retry_attempts = physical_solution
                .equilibrium()
                .solve_report()
                .attempts
                .clone();
            physical_solution.solution = physical_solution
                .solution
                .with_extensive_normalization_recovery(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_retry_attempts.clone(),
                    physical_failure_duration,
                    normalization_duration,
                    normalized_discovery_duration,
                    physical_retry_duration,
                    reconstruction_duration: Duration::ZERO,
                    reconstructed_physical_boundary: false,
                });
            return Ok(physical_solution);
        }
        Err(error) => Some((error.to_string(), error.backend_attempt_reports())),
    };
    let reconstruction_started = Instant::now();
    let physical_build_report = build_phase_equilibrium_problem_with_timing(
        request.build_pt_request(accepted_conditions)?,
        request.solve_options.timing_mode(),
    )?
    .report()
    .clone();
    let mut recovered = normalized_solution
        .reconstruct_physical_extensive_boundary(normalization, physical_build_report)?;
    let reconstruction_duration = reconstruction_started.elapsed();
    recovered = recovered.with_inner_timing_stage(
        EquilibriumTimingStage::Normalization,
        normalization_duration,
    );
    recovered.solution = recovered.solution.with_extensive_normalization_recovery(
        ExtensiveNormalizationRecoveryEvidence {
            physical_inventory_scale: normalization.physical_inventory_scale(),
            trigger: trigger.clone(),
            discovery_backend,
            physical_retry_backend: None,
            physical_retry_failure: physical_retry_attempts
                .as_ref()
                .map(|(message, _)| message.clone()),
            physical_failure_attempts,
            normalized_discovery_attempts,
            physical_retry_attempts: physical_retry_attempts
                .map(|(_, attempts)| attempts)
                .unwrap_or_default(),
            physical_failure_duration,
            normalization_duration,
            normalized_discovery_duration,
            physical_retry_duration,
            reconstruction_duration,
            reconstructed_physical_boundary: true,
        },
    );
    Ok(recovered)
}

/// Runs monolithic P,H candidates through the canonical transactional phase
/// lifecycle.
///
/// The nonlinear formulation is rebuilt only for the active mask selected by
/// the phase controller. Activation, destruction, hysteresis, cycle checks,
/// and final publication remain owned by `PreparedPhaseControlRunner`; this
/// function only adapts one fixed active mask to the coupled P,H equations.
fn solve_resolved_ph_monolithic_phase_control(
    request: ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    let started = Instant::now();
    request.validate()?;
    let thermochemistry = request.thermochemistry.clone().ok_or_else(|| {
        ReactionExtentError::InvalidProblem {
            field: "ph_monolithic_thermochemistry",
            message: "monolithic P,H requires a ResolvedThermochemistry bundle with Gibbs, enthalpy, and Cp capabilities".to_string(),
        }
    })?;
    let (target, initial_temperature) = validated_ph_parameters(request.constraint)?;
    let initial_molar_enthalpies = thermochemistry.evaluate_enthalpy(initial_temperature)?;
    let scale = EnthalpyScale::from_magnitudes(
        target,
        request.initial_composition.moles(),
        &initial_molar_enthalpies,
    )?;
    let initial_conditions = request.constraint.conditions_at(initial_temperature)?;
    let timing_mode = request.solve_options.timing_mode();
    let bundle = build_phase_equilibrium_problem_with_timing(
        request.build_pt_request(initial_conditions)?,
        timing_mode,
    )?;
    let policy = match request.solve_mode {
        PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => policy,
        PhaseEquilibriumSolveMode::FixedDeclaredPhases => {
            return Err(ReactionExtentError::InvalidProblem {
                field: "ph_monolithic_phase_control",
                message: "the bounded monolithic adapter requires a phase-control policy"
                    .to_string(),
            });
        }
    };
    let template = bundle.into_phase_control_template_with_diagnostics(
        |manager| *manager = policy.into_phase_manager(),
        request.solve_options.diagnostics_options().clone(),
    )?;
    let settings = request.solve_options.clone().into_settings();
    let temperature_options = request.temperature_options.clone();
    let monolithic_options = temperature_options.monolithic_options()?;
    let temperature_bounds = request.temperature_bounds;
    let mut temperature_seed = initial_temperature;
    let mut temperature_seed_report = None;
    let mut inner_backend_attempts = 0usize;
    let mut inner_nonlinear_iterations = 0usize;
    let solution = template.solve_with_fixed_active_solver(
        settings,
        |runner, active, seed, species_phase, full_element_totals| {
            let attempt = solve_monolithic_active_set_candidate_with_seed_report(
                runner,
                active,
                seed,
                species_phase,
                full_element_totals,
                &thermochemistry,
                temperature_bounds,
                target,
                scale,
                &mut temperature_seed,
                &monolithic_options,
            );
            let (candidate, report) = match attempt {
                Ok(outcome) => outcome,
                Err(error) => {
                    inner_backend_attempts =
                        inner_backend_attempts.saturating_add(error.started_backend_attempts());
                    inner_nonlinear_iterations =
                        inner_nonlinear_iterations.saturating_add(error.nonlinear_iterations());
                    enforce_monolithic_work_limits(
                        &temperature_options,
                        started,
                        inner_backend_attempts,
                        inner_nonlinear_iterations,
                        0,
                    )?;
                    return Err(error);
                }
            };
            inner_backend_attempts =
                inner_backend_attempts.saturating_add(report.started_backend_attempts());
            inner_nonlinear_iterations =
                inner_nonlinear_iterations.saturating_add(report.nonlinear_iterations());
            enforce_monolithic_work_limits(
                &temperature_options,
                started,
                inner_backend_attempts,
                inner_nonlinear_iterations,
                0,
            )?;
            temperature_seed_report = Some(report);
            Ok(candidate)
        },
    )?;
    let phase_control_report = solution.phase_control_report().cloned().ok_or_else(|| {
        ReactionExtentError::InvalidCandidate {
            field: "ph_monolithic_phase_control_report",
            message: "bounded monolithic solve published no phase-control report".to_string(),
        }
    })?;
    let calculated_enthalpy = thermochemistry.enthalpy_model().evaluate_total(
        solution.component_moles(),
        solution.conditions().temperature(),
    )?;
    enforce_monolithic_work_limits(
        &temperature_options,
        started,
        inner_backend_attempts,
        inner_nonlinear_iterations,
        phase_control_report.transitions.len(),
    )?;
    let timing_enabled = timing_mode == EquilibriumTimingMode::Enabled;
    let total = started.elapsed();
    let report = PhTemperatureSolveReport {
        solve_path: PhSolvePath::MonolithicPhaseControl,
        fallback_reason: None,
        route_decisions: Vec::new(),
        target_enthalpy: target,
        enthalpy_scale_joules: scale.joules(),
        absolute_enthalpy_tolerance_joules: temperature_options.absolute_enthalpy_tolerance_joules,
        scaled_enthalpy_tolerance: temperature_options.scaled_enthalpy_tolerance,
        max_temperature_evaluations: temperature_options.max_temperature_evaluations,
        initial_temperature_seed: initial_temperature,
        monotonicity_policy: temperature_options.monotonicity_policy,
        max_inner_backend_attempts: temperature_options.max_inner_backend_attempts,
        max_inner_nonlinear_iterations: temperature_options.max_inner_nonlinear_iterations,
        max_phase_control_transitions: temperature_options.max_phase_control_transitions,
        max_wall_time: temperature_options.max_wall_time,
        inner_backend_attempts,
        inner_nonlinear_iterations,
        phase_control_transitions: phase_control_report.transitions.len(),
        // These counters describe reusable scalar P,H formulations, not the
        // per-active-set candidates owned by phase control. Their lifecycle
        // evidence is retained in `PhaseControlledSolveReport` instead.
        fixed_formulation_builds: 0,
        fixed_formulation_reuses: 0,
        inner_timing: *solution.timing_report(),
        timing: PhTemperatureTimingReport {
            enabled: timing_enabled,
            total: timing_enabled.then_some(total).unwrap_or(Duration::ZERO),
            scalar_orchestration: Duration::ZERO,
            enthalpy_evaluation: Duration::ZERO,
            trial_total: Duration::ZERO,
            trial_inner_execution: Duration::ZERO,
            trial_preparation: Duration::ZERO,
            trial_template_preparation: Duration::ZERO,
            trial_postprocessing: Duration::ZERO,
            bracket_orchestration: Duration::ZERO,
            monolithic_preparation: Duration::ZERO,
            request_validation: Duration::ZERO,
            initial_enthalpy: Duration::ZERO,
            initial_enthalpy_reused: false,
            prepared_problem_retarget: Duration::ZERO,
            gibbs_snapshot: Duration::ZERO,
            gibbs_snapshot_reused: false,
            monolithic_rst_preparation: Duration::ZERO,
            monolithic_backend_execution: Duration::ZERO,
            monolithic_execution: Duration::ZERO,
            monolithic_publication: Duration::ZERO,
            recovery_request_clone: Duration::ZERO,
            rst_preparation_timing: RstPreparationTimingReport::default(),
        },
        iterations: phase_control_report.iterations,
        trials: Vec::new(),
        monolithic_evidence: Some(PhMonolithicEvidence {
            solve_report: solution.solve_report().clone(),
            multi_start_report: solution.multi_start_report().cloned(),
            temperature_seed_report,
            phase_control_report: Some(phase_control_report),
            acceptance_report: solution.acceptance_report().cloned(),
            inner_timing: *solution.timing_report(),
            validation_duration: solution.timing_report().validation(),
        }),
    };
    let result = FixedPressureEnthalpySolution {
        solution,
        calculated_enthalpy,
        target_enthalpy: target,
        report,
        thermochemistry: Some(thermochemistry),
    };
    if let Some(control) = temperature_options.execution_control() {
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PublicationCompleted,
            Some(1),
            Some(1),
            Some(result.temperature()),
        ));
        control.check_cancelled()?;
    }
    Ok(result)
}

/// Runs the coupled P,H equations for one declared, fixed active phase set.
///
/// This private helper is the fixed-phase branch of the public monolithic
/// facade. Bounded phase control uses the sibling adapter above and never
/// treats a changing active set as one smooth residual system.
fn solve_resolved_ph_monolithic(
    request: ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    let started = Instant::now();
    let timing_mode = request.solve_options.timing_mode();
    let timing_enabled = timing_mode == EquilibriumTimingMode::Enabled;
    let preparation_started = timing_enabled.then(Instant::now);
    request.validate()?;
    let thermochemistry = request.thermochemistry.clone().ok_or_else(|| {
        ReactionExtentError::InvalidProblem {
            field: "ph_monolithic_thermochemistry",
            message: "monolithic P,H requires a ResolvedThermochemistry bundle with Gibbs, enthalpy, and Cp capabilities".to_string(),
        }
    })?;
    let (target, initial_temperature) = validated_ph_parameters(request.constraint)?;
    let initial_molar_enthalpies = thermochemistry.evaluate_enthalpy(initial_temperature)?;
    let scale = EnthalpyScale::from_magnitudes(
        target,
        request.initial_composition.moles(),
        &initial_molar_enthalpies,
    )?;
    let initial_conditions = request.constraint.conditions_at(initial_temperature)?;
    let bundle = build_phase_equilibrium_problem_with_timing(
        request.build_pt_request(initial_conditions)?,
        timing_mode,
    )?;
    let mut prepared = bundle.into_prepared_fixed_active_problem()?;
    let mut formulation_timing = EquilibriumTimingCollector::from_report(prepared.timing);
    let formulation =
        formulation_timing.measure(EquilibriumTimingStage::PhFormulationPreparation, || {
            PreparedPhFormulation::new(
                prepared.prepared.clone(),
                thermochemistry.clone(),
                request.temperature_bounds,
                target,
                scale,
            )
        })?;
    let options = request.temperature_options.clone();
    let runner =
        formulation_timing.measure(EquilibriumTimingStage::PhFormulationPreparation, || {
            let monolithic_options = options.monolithic_options()?;
            PreparedMonolithicPhRunner::new(
                formulation,
                request.solve_options.clone().into_settings(),
                monolithic_options,
            )
            .map(|runner| runner.with_timing_enabled(timing_enabled))
        })?;
    prepared.timing = formulation_timing.finish();
    if let Some(control) = options.execution_control() {
        control.check_cancelled()?;
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::FormulationPreparation,
            Some(0),
            Some(1),
            Some(initial_temperature),
        ));
    }
    let monolithic_preparation =
        preparation_started.map_or(Duration::ZERO, |started| started.elapsed());
    let execution_started = timing_enabled.then(Instant::now);
    let outcome = match runner.solve_from_temperature_seed(initial_temperature) {
        Ok(outcome) => outcome,
        Err(error) => {
            enforce_monolithic_work_limits(
                &options,
                started,
                error.started_backend_attempts(),
                error.nonlinear_iterations(),
                0,
            )?;
            return Err(error);
        }
    };
    enforce_monolithic_work_limits(
        &options,
        started,
        outcome.temperature_seed_report.started_backend_attempts(),
        outcome.temperature_seed_report.nonlinear_iterations(),
        0,
    )?;
    let monolithic_execution =
        execution_started.map_or(Duration::ZERO, |started| started.elapsed());
    let publication_started = timing_enabled.then(Instant::now);
    let conditions = request
        .constraint
        .conditions_at(outcome.snapshot.temperature)?;
    let accepted_solution = prepared.prepared.accepted_solution_at_conditions(
        outcome.snapshot.log_moles.clone(),
        outcome.pt_validation.clone(),
        conditions,
    )?;
    // The structural bridge was prepared at the temperature seed, while the
    // coupled solve owns the accepted temperature. Rebuild only the immutable
    // report view at that accepted condition before publication; otherwise the
    // result gate would correctly reject a solution/report temperature
    // mismatch even though the numerical candidate itself is valid.
    let accepted_gibbs = thermochemistry
        .evaluate_gibbs(outcome.snapshot.temperature)?
        .into_iter()
        .map(|value| Rc::new(move |_| value) as GibbsFn)
        .collect::<Vec<_>>();
    let accepted_report = prepared.report.at_conditions(conditions, &accepted_gibbs)?;
    let solution = MultiphaseEquilibriumSolution::from_fixed_active_parts(
        prepared.metadata,
        accepted_report,
        accepted_solution,
        outcome.solve_report.clone(),
        prepared.timing,
    )?;
    let monolithic_publication =
        publication_started.map_or(Duration::ZERO, |started| started.elapsed());
    let total = started.elapsed();
    let report = PhTemperatureSolveReport {
        solve_path: PhSolvePath::MonolithicFixedActiveSet,
        fallback_reason: None,
        route_decisions: Vec::new(),
        target_enthalpy: target,
        enthalpy_scale_joules: scale.joules(),
        absolute_enthalpy_tolerance_joules: options.absolute_enthalpy_tolerance_joules,
        scaled_enthalpy_tolerance: options.scaled_enthalpy_tolerance,
        max_temperature_evaluations: options.max_temperature_evaluations,
        initial_temperature_seed: initial_temperature,
        monotonicity_policy: options.monotonicity_policy,
        max_inner_backend_attempts: options.max_inner_backend_attempts,
        max_inner_nonlinear_iterations: options.max_inner_nonlinear_iterations,
        max_phase_control_transitions: options.max_phase_control_transitions,
        max_wall_time: options.max_wall_time,
        inner_backend_attempts: outcome.temperature_seed_report.started_backend_attempts(),
        inner_nonlinear_iterations: outcome.temperature_seed_report.nonlinear_iterations(),
        phase_control_transitions: 0,
        fixed_formulation_builds: 1,
        fixed_formulation_reuses: 0,
        inner_timing: *solution.timing_report(),
        timing: PhTemperatureTimingReport {
            enabled: timing_enabled,
            total: timing_enabled.then_some(total).unwrap_or(Duration::ZERO),
            scalar_orchestration: Duration::ZERO,
            enthalpy_evaluation: Duration::ZERO,
            trial_total: Duration::ZERO,
            trial_inner_execution: Duration::ZERO,
            trial_preparation: Duration::ZERO,
            trial_template_preparation: Duration::ZERO,
            trial_postprocessing: Duration::ZERO,
            bracket_orchestration: Duration::ZERO,
            monolithic_preparation,
            request_validation: Duration::ZERO,
            initial_enthalpy: Duration::ZERO,
            initial_enthalpy_reused: false,
            prepared_problem_retarget: Duration::ZERO,
            gibbs_snapshot: Duration::ZERO,
            gibbs_snapshot_reused: false,
            monolithic_rst_preparation: outcome.rst_preparation,
            monolithic_backend_execution: outcome.backend_execution,
            monolithic_execution,
            monolithic_publication,
            recovery_request_clone: Duration::ZERO,
            rst_preparation_timing: outcome.rst_preparation_timing,
        },
        iterations: 0,
        trials: Vec::new(),
        monolithic_evidence: Some(PhMonolithicEvidence {
            solve_report: solution.solve_report().clone(),
            multi_start_report: solution.multi_start_report().cloned(),
            temperature_seed_report: Some(outcome.temperature_seed_report.clone()),
            phase_control_report: None,
            acceptance_report: solution.acceptance_report().cloned(),
            inner_timing: *solution.timing_report(),
            validation_duration: outcome.validation_duration,
        }),
    };
    let result = FixedPressureEnthalpySolution {
        solution,
        calculated_enthalpy: outcome.snapshot.total_enthalpy,
        target_enthalpy: target,
        report,
        thermochemistry: Some(thermochemistry),
    };
    if let Some(control) = options.execution_control() {
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PublicationCompleted,
            Some(1),
            Some(1),
            Some(result.temperature()),
        ));
        control.check_cancelled()?;
    }
    Ok(result)
}

/// Retained safeguarded reference implementation.
fn solve_resolved_ph_nested(
    request: ResolvedPhaseEnthalpyRequest<'_>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    let mut fixed_template = None;
    solve_resolved_ph_nested_with_template(request, &mut fixed_template)
}

fn solve_resolved_ph_nested_with_template(
    request: ResolvedPhaseEnthalpyRequest<'_>,
    fixed_template: &mut Option<PreparedPhaseEquilibriumTemplate>,
) -> Result<FixedPressureEnthalpySolution, ReactionExtentError> {
    let outer_started = Instant::now();
    request.validate()?;
    let constraint = request.constraint;
    let (target, initial_temperature) = validated_ph_parameters(constraint)?;
    let initial_molar = request.enthalpy.evaluate_molar(initial_temperature)?;
    let scale = EnthalpyScale::from_magnitudes(
        target,
        request.initial_composition.moles(),
        &initial_molar,
    )?;

    let bounds = request.temperature_bounds;
    let options = request.temperature_options;
    let resolved = &request.resolved;
    let initial_composition = request.initial_composition.clone();
    let physical_input = request.physical_input.clone();
    let enthalpy = request.enthalpy.clone();
    let solve_options = request.solve_options.clone();
    let solve_mode = request.solve_mode.clone();
    let thermochemistry = request.thermochemistry.clone();
    let candidate_selection = request.candidate_selection.clone();
    let timing_enabled = solve_options.timing_mode() == EquilibriumTimingMode::Enabled;
    let execution_control = options.execution_control().cloned();
    // The evaluator owns one clone; the outer publication boundary keeps a
    // second handle so cancellation is still checked after the bracket has
    // returned but before the immutable result is exposed.
    let publication_execution_control = execution_control.clone();
    let evaluator_options = options.clone();
    if let Some(control) = &execution_control {
        control.check_cancelled()?;
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::FormulationPreparation,
            None,
            None,
            None,
        ));
    }
    // A fixed declared phase layout has no active-set history. Its structural
    // preparation can therefore be safely retained while the P,H bracket
    // samples temperatures in non-monotone order. Bounded phase control is
    // deliberately excluded: its active set has lifecycle semantics and must
    // not inherit state from an arbitrary rejected scalar trial.
    let template_was_initialized = fixed_template.is_some();
    // Continuation is safe for fixed declared phases. Bounded phase control
    // keeps the original inventory seed because its active set can change.
    let use_continuation = matches!(&solve_mode, PhaseEquilibriumSolveMode::FixedDeclaredPhases);
    // A bounded active set may change between two bracket samples. Secant
    // interpolation would then act as if their enthalpy values came from one
    // smooth branch, so only the topology-safe bisection step is allowed.
    let allow_interpolation = use_continuation;
    let mut continuation_seed: Option<LogMolesInitialGuess> = None;
    let mut temperature_evaluations = 0usize;
    let mut inner_backend_attempts_total = 0usize;
    let mut inner_nonlinear_iterations_total = 0usize;
    let mut phase_control_transitions_total = 0usize;
    let mut nested_evidence = Vec::<PhNestedTrialEvidence>::new();
    let mut enthalpy_timing = Duration::ZERO;
    let mut trial_total_timing = Duration::ZERO;
    let mut trial_inner_execution_timing = Duration::ZERO;
    let mut trial_preparation_timing = Duration::ZERO;
    let mut trial_template_preparation_timing = Duration::ZERO;
    let mut trial_postprocessing_timing = Duration::ZERO;
    let evaluator = |temperature: f64| {
        if temperature_evaluations >= evaluator_options.max_temperature_evaluations {
            return Err(ReactionExtentError::InvalidProblem {
                field: "temperature_budget",
                message: format!(
                    "outer P,H solve exceeded the global temperature evaluation budget of {}",
                    evaluator_options.max_temperature_evaluations
                ),
            });
        }
        if let Some(control) = &execution_control {
            control.check_cancelled()?;
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::TemperatureTrialStarted,
                Some(temperature_evaluations),
                Some(evaluator_options.max_temperature_evaluations),
                Some(temperature),
            ));
        }
        temperature_evaluations += 1;
        if let Some(control) = &execution_control {
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::InnerSolveStarted,
                Some(temperature_evaluations - 1),
                Some(evaluator_options.max_temperature_evaluations),
                Some(temperature),
            ));
            control.check_cancelled()?;
        }
        let conditions = constraint.conditions_at(temperature)?;
        let trial_preparation_started = timing_enabled.then(Instant::now);
        let mut trial_template_preparation_duration = Duration::ZERO;
        let mut template_preparation_timing = EquilibriumTimingReport::default();
        let fixed_template_was_initialized = fixed_template.is_some();
        let fixed_template_for_trial =
            if use_continuation {
                if fixed_template.is_none() {
                    let template_started = timing_enabled.then(Instant::now);
                    let build_request = PhTrialEvaluator {
                        resolved,
                        physical_input: &physical_input,
                        initial_composition: &initial_composition,
                        constraint,
                        enthalpy: &enthalpy,
                        solve_options: &solve_options,
                        solve_mode: &solve_mode,
                        fixed_template: None,
                        execution_control: execution_control.as_ref(),
                        fixed_template_was_initialized,
                        candidate_selection: candidate_selection.as_ref(),
                        timing_enabled,
                        template_preparation_timing: EquilibriumTimingReport::default(),
                    }
                    .build_pt_request(conditions)?;
                    let template = build_phase_equilibrium_problem_with_timing(
                        build_request,
                        solve_options.timing_mode(),
                    )?
                    .into_temperature_template(
                        solve_options.prepares_rst_backend(),
                        solve_options.timing_mode(),
                        solve_options.rst_symbolic_frontend(),
                    )?;
                    template_preparation_timing = template.build_timing();
                    *fixed_template = Some(template);
                    trial_template_preparation_duration =
                        template_started.map_or(Duration::ZERO, |started| started.elapsed());
                }
                Some(fixed_template.as_mut().ok_or_else(|| {
                    ReactionExtentError::InvalidProblem {
                        field: "ph_fixed_template",
                        message: "fixed P,H formulation was not initialized".to_string(),
                    }
                })?)
            } else {
                None
            };
        let trial_preparation_duration =
            trial_preparation_started.map_or(Duration::ZERO, |started| started.elapsed());
        let mut trial_evaluator = PhTrialEvaluator {
            resolved,
            physical_input: &physical_input,
            initial_composition: &initial_composition,
            constraint,
            enthalpy: &enthalpy,
            solve_options: &solve_options,
            solve_mode: &solve_mode,
            fixed_template: fixed_template_for_trial,
            execution_control: execution_control.as_ref(),
            fixed_template_was_initialized,
            candidate_selection: candidate_selection.as_ref(),
            timing_enabled,
            template_preparation_timing,
        };
        let trial_continuation_seed = use_continuation.then(|| continuation_seed.take()).flatten();
        let outcome = match trial_evaluator.evaluate(temperature, trial_continuation_seed) {
            Ok(outcome) => outcome,
            Err(error) => {
                if !matches!(&error, ReactionExtentError::Cancelled) {
                    if let Some(control) = &execution_control {
                        control.report(EquilibriumProgressEvent::new(
                            EquilibriumProgressStage::TemperatureTrialRejected,
                            Some(temperature_evaluations - 1),
                            Some(evaluator_options.max_temperature_evaluations),
                            Some(temperature),
                        ));
                    }
                }
                return Err(error);
            }
        };
        if let Some(control) = &execution_control {
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::InnerSolveCompleted,
                Some(temperature_evaluations - 1),
                Some(evaluator_options.max_temperature_evaluations),
                Some(temperature),
            ));
            for _ in 0..outcome.evidence.phase_control_transitions {
                control.report(EquilibriumProgressEvent::new(
                    EquilibriumProgressStage::PhaseTransitionAccepted,
                    Some(temperature_evaluations - 1),
                    Some(evaluator_options.max_temperature_evaluations),
                    Some(temperature),
                ));
            }
            control.check_cancelled()?;
        }
        let attempts = outcome.evidence.backend_attempts;
        inner_backend_attempts_total = inner_backend_attempts_total.saturating_add(attempts);
        if let Some(limit) = evaluator_options.max_inner_backend_attempts {
            if inner_backend_attempts_total > limit {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "inner_backend_budget",
                    message: format!(
                        "outer P,H solve exceeded the global inner backend-attempt budget of {limit}"
                    ),
                });
            }
        }
        let nonlinear_iterations = outcome.evidence.nonlinear_iterations;
        inner_nonlinear_iterations_total =
            inner_nonlinear_iterations_total.saturating_add(nonlinear_iterations);
        if let Some(limit) = evaluator_options.max_inner_nonlinear_iterations {
            if inner_nonlinear_iterations_total > limit {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "inner_nonlinear_iteration_budget",
                    message: format!(
                        "outer P,H solve exceeded the global inner nonlinear-iteration budget of {limit}"
                    ),
                });
            }
        }
        phase_control_transitions_total = phase_control_transitions_total
            .saturating_add(outcome.evidence.phase_control_transitions);
        if let Some(limit) = evaluator_options.max_phase_control_transitions {
            if phase_control_transitions_total > limit {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "phase_control_transition_budget",
                    message: format!(
                        "outer P,H solve exceeded the global phase-transition budget of {limit}"
                    ),
                });
            }
        }
        if use_continuation {
            continuation_seed = Some(LogMolesInitialGuess::from_initial_moles(
                outcome.solution.component_moles(),
            )?);
        }
        enthalpy_timing += outcome.enthalpy_evaluation;
        let inner_execution = outcome.evidence.trial_timing.inner_execution;
        let trial_reported_overhead = outcome
            .evidence
            .trial_timing
            .total
            .saturating_sub(inner_execution)
            .saturating_sub(outcome.enthalpy_evaluation);
        trial_total_timing += trial_preparation_duration + outcome.evidence.trial_timing.total;
        trial_inner_execution_timing += inner_execution;
        trial_preparation_timing += trial_preparation_duration + trial_reported_overhead;
        trial_template_preparation_timing += trial_template_preparation_duration;
        trial_postprocessing_timing += outcome.evidence.trial_timing.postprocessing;
        nested_evidence.push(outcome.evidence.clone());
        if let Some(control) = &execution_control {
            control.check_cancelled()?;
            control.report(EquilibriumProgressEvent::new(
                EquilibriumProgressStage::TemperatureTrialAccepted,
                Some(temperature_evaluations - 1),
                Some(evaluator_options.max_temperature_evaluations),
                Some(temperature),
            ));
        }
        Ok((outcome.solution, outcome.total_enthalpy))
    };

    let report_options = options.clone();
    let scalar_started = Instant::now();
    let (solution, total_enthalpy, iterations, mut trials) = solve_bracketed_temperature_from(
        bounds,
        scale,
        target,
        Some(initial_temperature),
        allow_interpolation,
        options,
        outer_started,
        evaluator,
    )?;
    let scalar_duration = if timing_enabled {
        scalar_started.elapsed()
    } else {
        Duration::ZERO
    };
    if let Some(control) = &publication_execution_control {
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PublicationStarted,
            None,
            None,
            Some(solution.conditions().temperature()),
        ));
        control.check_cancelled()?;
    }
    let timing = PhTemperatureTimingReport {
        enabled: timing_enabled,
        total: if timing_enabled {
            outer_started.elapsed()
        } else {
            Duration::ZERO
        },
        scalar_orchestration: if timing_enabled {
            scalar_duration
        } else {
            Duration::ZERO
        },
        enthalpy_evaluation: if timing_enabled {
            enthalpy_timing
        } else {
            Duration::ZERO
        },
        trial_total: if timing_enabled {
            trial_total_timing
        } else {
            Duration::ZERO
        },
        trial_inner_execution: if timing_enabled {
            trial_inner_execution_timing
        } else {
            Duration::ZERO
        },
        trial_preparation: if timing_enabled {
            trial_preparation_timing
        } else {
            Duration::ZERO
        },
        trial_template_preparation: if timing_enabled {
            trial_template_preparation_timing
        } else {
            Duration::ZERO
        },
        trial_postprocessing: if timing_enabled {
            trial_postprocessing_timing
        } else {
            Duration::ZERO
        },
        bracket_orchestration: if timing_enabled {
            scalar_duration.saturating_sub(trial_total_timing)
        } else {
            Duration::ZERO
        },
        monolithic_preparation: Duration::ZERO,
        request_validation: Duration::ZERO,
        initial_enthalpy: Duration::ZERO,
        initial_enthalpy_reused: false,
        prepared_problem_retarget: Duration::ZERO,
        gibbs_snapshot: Duration::ZERO,
        gibbs_snapshot_reused: false,
        monolithic_rst_preparation: Duration::ZERO,
        monolithic_backend_execution: Duration::ZERO,
        monolithic_execution: Duration::ZERO,
        monolithic_publication: Duration::ZERO,
        recovery_request_clone: Duration::ZERO,
        rst_preparation_timing: RstPreparationTimingReport::default(),
    };
    let (
        inner_backend_attempts,
        inner_nonlinear_iterations,
        phase_control_transitions,
        inner_timing,
    ) = attach_nested_evidence(&mut trials, &nested_evidence)?;
    let template_is_initialized = fixed_template.is_some();
    let fixed_formulation_builds =
        usize::from(!template_was_initialized && template_is_initialized);
    let fixed_formulation_reuses = if !template_is_initialized {
        0
    } else if template_was_initialized {
        trials.len()
    } else {
        trials.len().saturating_sub(1)
    };
    let report = PhTemperatureSolveReport {
        solve_path: PhSolvePath::NestedTemperature,
        fallback_reason: None,
        route_decisions: Vec::new(),
        target_enthalpy: target,
        enthalpy_scale_joules: scale.joules(),
        absolute_enthalpy_tolerance_joules: report_options.absolute_enthalpy_tolerance_joules,
        scaled_enthalpy_tolerance: report_options.scaled_enthalpy_tolerance,
        max_temperature_evaluations: report_options.max_temperature_evaluations,
        initial_temperature_seed: initial_temperature,
        monotonicity_policy: report_options.monotonicity_policy,
        max_inner_backend_attempts: report_options.max_inner_backend_attempts,
        max_inner_nonlinear_iterations: report_options.max_inner_nonlinear_iterations,
        max_phase_control_transitions: report_options.max_phase_control_transitions,
        max_wall_time: report_options.max_wall_time,
        inner_backend_attempts,
        inner_nonlinear_iterations,
        phase_control_transitions,
        fixed_formulation_builds,
        fixed_formulation_reuses,
        inner_timing,
        timing,
        iterations,
        trials,
        monolithic_evidence: None,
    };
    let result = FixedPressureEnthalpySolution {
        solution,
        calculated_enthalpy: total_enthalpy,
        target_enthalpy: target,
        report,
        thermochemistry,
    };
    if let Some(control) = &publication_execution_control {
        control.report(EquilibriumProgressEvent::new(
            EquilibriumProgressStage::PublicationCompleted,
            None,
            None,
            Some(result.temperature()),
        ));
        control.check_cancelled()?;
    }
    Ok(result)
}

#[cfg(test)]
fn solve_bracketed_temperature<T, F>(
    bounds: TemperatureBounds,
    scale: EnthalpyScale,
    target: f64,
    options: PhTemperatureSolveOptions,
    evaluate: F,
) -> Result<(T, f64, usize, Vec<PhTemperatureTrial>), ReactionExtentError>
where
    F: FnMut(f64) -> Result<(T, f64), ReactionExtentError>,
{
    solve_bracketed_temperature_from(
        bounds,
        scale,
        target,
        None,
        true,
        options,
        Instant::now(),
        evaluate,
    )
}

fn solve_bracketed_temperature_from<T, F>(
    bounds: TemperatureBounds,
    scale: EnthalpyScale,
    target: f64,
    seed_temperature: Option<f64>,
    allow_interpolation: bool,
    options: PhTemperatureSolveOptions,
    started: Instant,
    evaluate: F,
) -> Result<(T, f64, usize, Vec<PhTemperatureTrial>), ReactionExtentError>
where
    F: FnMut(f64) -> Result<(T, f64), ReactionExtentError>,
{
    options.validate()?;
    let route_options = options.nested_options()?;
    let acceptance = route_options.acceptance();
    let nested_options = NestedBracketOptions {
        scaled_enthalpy_tolerance: acceptance.scaled_enthalpy_tolerance(),
        absolute_enthalpy_tolerance_joules: acceptance.absolute_enthalpy_tolerance_joules(),
        temperature_tolerance: route_options.temperature_tolerance(),
        max_iterations: route_options.max_iterations(),
        max_temperature_evaluations: route_options.max_temperature_evaluations(),
        allow_interpolation,
        allow_bracketed_sign_search: matches!(
            route_options.monotonicity_policy(),
            PhMonotonicityPolicy::AllowBracketedSignSearch
        ),
        max_wall_time: route_options.max_wall_time(),
    };
    let result = solve_nested_bracketed_temperature(
        bounds,
        scale,
        target,
        seed_temperature,
        nested_options,
        started,
        evaluate,
    )?;
    let trials = result
        .trials
        .into_iter()
        .map(PhTemperatureTrial::from)
        .collect();
    Ok((
        result.value,
        result.total_enthalpy,
        result.iterations,
        trials,
    ))
}
/// Publishes inner execution evidence onto the corresponding outer trials.
///
/// The bracket helper and the evaluator are intentionally separate layers, so
/// their record counts are checked at this boundary. A silent `zip` would
/// make an incomplete report look valid and could hide a publication bug.
#[derive(Debug, Clone)]
struct PhNestedTrialEvidence {
    backend_attempts: usize,
    nonlinear_iterations: usize,
    phase_control_transitions: usize,
    preparation: PhTrialPreparation,
    phase_states: Vec<PhTrialPhaseState>,
    timing: EquilibriumTimingReport,
    trial_timing: PhTrialTimingReport,
    inner_evidence: Option<PhTrialInnerEvidence>,
}

/// Immutable outcome of one local `P,T -> H` trial. It is deliberately not
/// published until the outer scalar workflow accepts its temperature.
struct PhTrialOutcome {
    solution: MultiphaseEquilibriumSolution,
    total_enthalpy: f64,
    enthalpy_evaluation: Duration,
    evidence: PhNestedTrialEvidence,
}

/// Builds one P,H scalar trial from immutable request data.
///
/// This object owns no global counters, continuation state, or publication
/// state. The outer solve is therefore the sole authority for budgets,
/// progress notifications, and transactional result publication.
struct PhTrialEvaluator<'request, 'enthalpy, 'template> {
    resolved: &'request ResolvedPhaseSystem,
    physical_input: &'request PhPhysicalInput,
    initial_composition: &'request MultiphaseInitialComposition,
    constraint: EquilibriumConstraint,
    enthalpy: &'request EnthalpyModel<'enthalpy>,
    solve_options: &'request EquilibriumSolveOptions,
    solve_mode: &'request PhaseEquilibriumSolveMode,
    fixed_template: Option<&'template mut PreparedPhaseEquilibriumTemplate>,
    execution_control: Option<&'request EquilibriumExecutionControl>,
    fixed_template_was_initialized: bool,
    candidate_selection: Option<&'request EquilibriumCandidateSelectionReport>,
    timing_enabled: bool,
    template_preparation_timing: EquilibriumTimingReport,
}

impl<'request, 'enthalpy, 'template> PhTrialEvaluator<'request, 'enthalpy, 'template> {
    /// Builds a P,T request for the current trial. For an element-defined
    /// P,H problem, `initial_composition` is an accepted numerical seed; the
    /// original element inventory remains the conservation contract.
    fn build_pt_request(
        &self,
        conditions: crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::EquilibriumConditions,
    ) -> Result<PhaseEquilibriumBuildRequest<'request>, ReactionExtentError> {
        let request = match self.physical_input {
            PhPhysicalInput::Composition => PhaseEquilibriumBuildRequest::new(
                self.resolved,
                conditions,
                self.initial_composition.clone(),
                self.solve_options.trace_seed_policy(),
                SupportedPhaseModelPolicy::default(),
            ),
            PhPhysicalInput::ElementInventory(inventory) => {
                PhaseEquilibriumBuildRequest::from_element_inventory(
                    self.resolved,
                    conditions,
                    inventory.clone(),
                    self.solve_options.trace_seed_policy(),
                    SupportedPhaseModelPolicy::default(),
                )?
                .with_numerical_seed(self.initial_composition.clone())
            }
        }?;
        Ok(match self.candidate_selection {
            Some(selection) => request.with_candidate_selection(selection.clone()),
            None => request,
        })
    }

    /// Evaluates `H(solution_of_P_T(T), T)` without mutating the request or
    /// publishing a partial result.
    ///
    /// Solves the inner fixed-`P,T` equilibrium at the supplied temperature
    /// using the configured solve mode (fixed-declared-phases or bounded phase
    /// control), then evaluates the additive total enthalpy from the accepted
    /// composition. The optional continuation seed is forwarded to the inner
    /// solver when the caller wants to warm-start from a previous point.
    /// Timing is collected when the request has timing enabled.
    fn evaluate(
        &mut self,
        temperature: f64,
        continuation_seed: Option<LogMolesInitialGuess>,
    ) -> Result<PhTrialOutcome, ReactionExtentError> {
        let trial_started = self.timing_enabled.then(Instant::now);
        let conditions = self.constraint.conditions_at(temperature)?;
        let trial_solve_options = if let Some(control) = self.execution_control {
            self.solve_options
                .clone()
                .with_execution_control(control.clone())
        } else {
            self.solve_options.clone()
        };
        let inner_started = self.timing_enabled.then(Instant::now);
        let (solution, preparation) = match self.solve_mode {
            PhaseEquilibriumSolveMode::FixedDeclaredPhases => {
                let mut seeds = vec![LogMolesInitialGuess::from_initial_moles(
                    self.initial_composition.moles(),
                )?];
                if let Some(seed) = continuation_seed {
                    seeds.push(seed);
                }
                let solution = self
                    .fixed_template
                    .as_mut()
                    .ok_or_else(|| ReactionExtentError::InvalidProblem {
                        field: "ph_fixed_template",
                        message: "fixed P,H trial is missing its prepared formulation".to_string(),
                    })?
                    .solve_at_with_initial_guesses(
                        conditions,
                        seeds,
                        trial_solve_options.into_settings(),
                        self.solve_options.timing_mode(),
                    )?;
                (
                    solution,
                    if self.fixed_template_was_initialized {
                        PhTrialPreparation::FixedFormulationReused
                    } else {
                        PhTrialPreparation::FixedFormulationInitial
                    },
                )
            }
            PhaseEquilibriumSolveMode::BoundedPhaseControl(policy) => {
                let solution = match self.physical_input {
                    PhPhysicalInput::Composition => {
                        let inner = ResolvedPhaseEquilibriumRequest::new(
                            self.resolved,
                            conditions,
                            self.initial_composition.clone(),
                        )
                        .with_solve_options(trial_solve_options)
                        .with_phase_control_policy(policy.clone());
                        solve_resolved_pt(inner)?
                    }
                    PhPhysicalInput::ElementInventory(inventory) => crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_workflow::
                        solve_resolved_pt_from_element_inventory_with_numerical_seed(
                            self.resolved,
                            conditions,
                            inventory.clone(),
                            Some(self.initial_composition.clone()),
                            trial_solve_options,
                            Some(policy.clone()),
                        )?,
                };
                (solution, PhTrialPreparation::BoundedPhaseControlIsolated)
            }
        };
        let inner_execution = inner_started.map_or(Duration::ZERO, |started| started.elapsed());
        let enthalpy_started = self.timing_enabled.then(Instant::now);
        let total_enthalpy = self
            .enthalpy
            .evaluate_total(solution.component_moles(), temperature)?;
        let enthalpy_evaluation =
            enthalpy_started.map_or(Duration::ZERO, |started| started.elapsed());
        let postprocessing_started = self.timing_enabled.then(Instant::now);
        let phase_states = phase_states_from_solution(&solution)?;
        let inner_evidence = PhTrialInnerEvidence {
            solve_report: solution.solve_report().clone(),
            multi_start_report: solution.multi_start_report().cloned(),
            phase_control_report: solution.phase_control_report().cloned(),
            acceptance_report: solution.acceptance_report().cloned(),
            extensive_normalization_recovery: solution.extensive_normalization_recovery().cloned(),
        };
        let postprocessing =
            postprocessing_started.map_or(Duration::ZERO, |started| started.elapsed());
        let trial_timing = PhTrialTimingReport {
            enabled: self.timing_enabled,
            total: trial_started.map_or(Duration::ZERO, |started| started.elapsed()),
            inner_execution,
            inner_equilibrium: if self.timing_enabled {
                solution.timing_report().total()
            } else {
                Duration::ZERO
            },
            enthalpy_evaluation,
            postprocessing,
            template_preparation: self.template_preparation_timing,
        };
        let evidence = PhNestedTrialEvidence {
            backend_attempts: solution.started_backend_attempts(),
            nonlinear_iterations: solution.nonlinear_iterations(),
            phase_control_transitions: solution.phase_control_transitions(),
            preparation,
            phase_states,
            timing: *solution.timing_report(),
            trial_timing,
            inner_evidence: Some(inner_evidence),
        };
        Ok(PhTrialOutcome {
            solution,
            total_enthalpy,
            enthalpy_evaluation,
            evidence,
        })
    }
}

fn attach_nested_evidence(
    trials: &mut [PhTemperatureTrial],
    evidence: &[PhNestedTrialEvidence],
) -> Result<(usize, usize, usize, EquilibriumTimingReport), ReactionExtentError> {
    if trials.len() != evidence.len() {
        return Err(ReactionExtentError::InvalidProblem {
            field: "ph_nested_evidence",
            message: format!(
                "outer trial count {} does not match nested evidence count {}",
                trials.len(),
                evidence.len()
            ),
        });
    }

    let mut inner_backend_attempts = 0usize;
    let mut inner_nonlinear_iterations = 0usize;
    let mut phase_control_transitions = 0usize;
    let mut inner_timing = EquilibriumTimingReport::default();
    for (trial, evidence) in trials.iter_mut().zip(evidence) {
        trial.inner_backend_attempts = evidence.backend_attempts;
        trial.inner_nonlinear_iterations = evidence.nonlinear_iterations;
        trial.phase_control_transitions = evidence.phase_control_transitions;
        trial.preparation = evidence.preparation;
        trial.phase_states = evidence.phase_states.clone();
        trial.inner_timing = evidence.timing;
        trial.timing = evidence.trial_timing;
        trial.inner_evidence = evidence.inner_evidence.clone();
        inner_backend_attempts = inner_backend_attempts.saturating_add(evidence.backend_attempts);
        inner_nonlinear_iterations =
            inner_nonlinear_iterations.saturating_add(evidence.nonlinear_iterations);
        phase_control_transitions =
            phase_control_transitions.saturating_add(evidence.phase_control_transitions);
        inner_timing.accumulate(evidence.timing);
    }
    Ok((
        inner_backend_attempts,
        inner_nonlinear_iterations,
        phase_control_transitions,
        inner_timing,
    ))
}

/// Captures the phase lifecycle states that identify an accepted P,T branch.
fn phase_states_from_solution(
    solution: &MultiphaseEquilibriumSolution,
) -> Result<Vec<PhTrialPhaseState>, ReactionExtentError> {
    solution
        .phases()
        .iter()
        .map(|descriptor| {
            let phase = descriptor.id().clone();
            let status = solution.phase_status(&phase).ok_or_else(|| {
                ReactionExtentError::InvalidProblem {
                    field: "phase_status",
                    message: format!(
                        "accepted equilibrium solution omitted the status for phase '{phase:?}'"
                    ),
                }
            })?;
            Ok(PhTrialPhaseState { phase, status })
        })
        .collect()
}

/// Extracts the scalar parameters required by the P,H workflow without
/// relying on an `expect` after validation. This keeps the public solve path
/// typed-error-only even if a future request mutation violates its invariant.
fn validated_ph_parameters(
    constraint: EquilibriumConstraint,
) -> Result<(f64, f64), ReactionExtentError> {
    match constraint {
        EquilibriumConstraint::PH {
            target_enthalpy,
            initial_temperature,
            ..
        } => Ok((target_enthalpy.joules(), initial_temperature)),
        EquilibriumConstraint::PT { .. } => Err(ReactionExtentError::InvalidProblem {
            field: "constraint",
            message: "resolved phase enthalpy workflow requires a PH constraint".to_string(),
        }),
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex, mpsc};

    use crate::Thermodynamics::ChemEquilibrium::equilibrium_diagnostics::{
        EquilibriumDiagnosticEvent, EquilibriumDiagnosticsMode, EquilibriumDiagnosticsOptions,
        PhDiagnosticRoute,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::MultiphaseEquilibriumLayout;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::EquilibriumConditions;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::EquilibriumSolveReport;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::PhaseStatus;
    use crate::Thermodynamics::User_PhaseOrSolution::PhaseSpec;
    use crate::Thermodynamics::User_substances::{DataType, SubsData};
    use crate::Thermodynamics::phase_layout::{PhaseComponentId, PhaseId};

    #[path = "../stanjan15_atom_view_diagnostics.rs"]
    mod stanjan15_atom_view_diagnostics;

    fn linear_enthalpy_model() -> EnthalpyModel<'static> {
        EnthalpyModel::from_functions(vec![Arc::new(|temperature| Ok(temperature * 10.0))]).unwrap()
    }

    #[test]
    fn native_request_accepts_a_borrowed_enthalpy_callback() {
        let slope = 10.0_f64;
        let mut data = SubsData::new();
        data.set_substances(vec!["A".to_string()]);
        let phase = PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap();
        let resolved =
            ResolvedPhaseSystem::new(vec![phase.clone()], HashMap::from([(None, data)])).unwrap();
        let layout = MultiphaseEquilibriumLayout::new(vec![phase]).unwrap();
        let composition = MultiphaseInitialComposition::from_dense(&layout, vec![1.0]).unwrap();
        let enthalpy =
            EnthalpyModel::from_functions(vec![Arc::new(|temperature| Ok(temperature * slope))])
                .unwrap();

        let request = ResolvedPhaseEnthalpyRequest::new(
            &resolved,
            composition,
            EquilibriumConstraint::ph(101_325.0, 101_325.0, 0.0, 700.0).unwrap(),
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            enthalpy,
        )
        .unwrap();

        assert_eq!(request.ph_solve_mode(), PhSolveMode::NestedTemperature);
        drop(request);
        assert_eq!(slope, 10.0);
    }

    fn synthetic_inner_evidence() -> PhTrialInnerEvidence {
        use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::Solvers;
        use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
            SolverAttemptOutcome, SolverAttemptReport, SolverBackend, SolverPolicy,
        };

        let backend = SolverBackend::Native(Solvers::NR);
        PhTrialInnerEvidence {
            solve_report: EquilibriumSolveReport {
                policy: SolverPolicy::Single(backend),
                attempts: vec![SolverAttemptReport {
                    backend,
                    outcome: SolverAttemptOutcome::Accepted,
                    metrics: None,
                }],
                accepted_backend: backend,
            },
            multi_start_report: None,
            phase_control_report: None,
            acceptance_report: None,
            extensive_normalization_recovery: None,
        }
    }

    #[test]
    fn monolithic_mode_requires_resolved_thermochemistry_capabilities() {
        assert_eq!(PhSolveMode::default(), PhSolveMode::Auto);
        assert_eq!(
            PhTemperatureSolveOptions::default()
                .with_monolithic_seed_policy(PhMonolithicSeedPolicy::InitialOnly)
                .monolithic_seed_policy,
            PhMonolithicSeedPolicy::InitialOnly
        );

        let mut data = SubsData::new();
        data.set_substances(vec!["A".to_string()]);
        let phase = PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap();
        let resolved =
            ResolvedPhaseSystem::new(vec![phase.clone()], HashMap::from([(None, data)])).unwrap();
        let layout = MultiphaseEquilibriumLayout::new(vec![phase]).unwrap();
        let composition = MultiphaseInitialComposition::from_dense(&layout, vec![1.0]).unwrap();
        let request = ResolvedPhaseEnthalpyRequest::new(
            &resolved,
            composition,
            EquilibriumConstraint::ph(101_325.0, 101_325.0, 0.0, 700.0).unwrap(),
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            EnthalpyModel::from_functions(vec![Arc::new(|_| Ok(0.0))]).unwrap(),
        )
        .unwrap()
        .with_ph_solve_mode(PhSolveMode::Monolithic);

        assert_eq!(request.ph_solve_mode(), PhSolveMode::Monolithic);
        let stages = Arc::new(Mutex::new(Vec::new()));
        let stages_for_sink = Arc::clone(&stages);
        let control = EquilibriumExecutionControl::new().with_progress_sink(move |event| {
            stages_for_sink.lock().unwrap().push(event.stage());
        });
        let (sender, receiver) = mpsc::channel();
        let diagnostics =
            EquilibriumDiagnosticsOptions::enabled(EquilibriumDiagnosticsMode::Summary)
                .with_sink(move |event| sender.send(event).unwrap());
        let auto_request = request
            .cloned_with_ph_solve_mode(PhSolveMode::Auto)
            .with_solve_options(EquilibriumSolveOptions::new().with_diagnostics(diagnostics))
            .with_temperature_options(
                PhTemperatureSolveOptions::default().with_execution_control(control),
            )
            .unwrap();
        assert!(matches!(
            solve_resolved_ph(request),
            Err(ReactionExtentError::InvalidProblem {
                field: "ph_monolithic_thermochemistry",
                ..
            })
        ));
        assert!(matches!(
            solve_resolved_ph(auto_request),
            Err(ReactionExtentError::InvalidProblem {
                field: "ph_monolithic_thermochemistry",
                ..
            })
        ));
        assert!(
            !stages
                .lock()
                .unwrap()
                .contains(&EquilibriumProgressStage::TemperatureTrialStarted)
        );
        assert!(receiver.try_iter().any(|event| matches!(
            event,
            EquilibriumDiagnosticEvent::PhRouteFailed {
                route: PhDiagnosticRoute::Monolithic,
                ..
            }
        )));
    }

    #[test]
    fn auto_fallback_reason_preserves_retryable_backend_classification() {
        let error = ReactionExtentError::BackendFailure {
            backend: "monolithic".to_string(),
            kind: crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::
                BackendFailureKind::NumericalBreakdown,
            message: "synthetic breakdown".to_string(),
        };
        let reason = PhFallbackReason::from_error(&error);

        assert_eq!(reason.error_kind(), ReactionExtentErrorKind::BackendFailure);
        assert!(reason.message().contains("monolithic"));
        assert!(error.is_retryable_backend_failure());
    }

    #[test]
    fn validated_ph_parameter_extraction_rejects_pt_without_panicking() {
        let constraint = EquilibriumConstraint::pt(
            EquilibriumConditions::new(700.0, 101_325.0, 101_325.0).unwrap(),
        );

        let error = validated_ph_parameters(constraint).unwrap_err();
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "constraint",
                ..
            }
        ));
    }

    #[test]
    fn additive_enthalpy_derivative_reports_only_the_explicit_temperature_term() {
        let model = EnthalpyModel::from_functions_with_heat_capacity(
            vec![Arc::new(|temperature| Ok(100.0 + 2.0 * temperature))],
            vec![Some(Arc::new(|_| Ok(2.0)))],
        )
        .unwrap();

        let evaluation = model
            .evaluate_total_with_partial_temperature_derivative(&[3.0], 400.0)
            .unwrap();

        assert_eq!(evaluation.molar_enthalpies(), &[900.0]);
        assert_eq!(evaluation.heat_capacities(), &[2.0]);
        assert_eq!(evaluation.total_enthalpy(), 2_700.0);
        assert_eq!(evaluation.partial_temperature_derivative(), 6.0);
    }

    #[test]
    fn additive_enthalpy_derivative_rejects_missing_heat_capacity() {
        let model = linear_enthalpy_model();
        let error = model
            .evaluate_total_with_partial_temperature_derivative(&[1.0], 400.0)
            .unwrap_err();

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

    #[test]
    fn sampled_non_monotone_branch_is_rejected_by_default_but_explicit_compatibility_allows_it() {
        let branch = |temperature: f64| {
            if temperature <= 850.0 {
                -1.0 - 99.0 * (temperature - 500.0) / 350.0
            } else {
                -100.0 + 101.0 * (temperature - 850.0) / 350.0
            }
        };
        let bounds = TemperatureBounds::new(500.0, 1_200.0).unwrap();
        let scale = EnthalpyScale::new(1.0).unwrap();

        let error = solve_bracketed_temperature(
            bounds,
            scale,
            0.0,
            PhTemperatureSolveOptions::default(),
            |temperature| Ok((temperature, branch(temperature))),
        )
        .unwrap_err();
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "enthalpy_non_monotone",
                ..
            }
        ));

        let compatibility = PhTemperatureSolveOptions::default()
            .with_monotonicity_policy(PhMonotonicityPolicy::AllowBracketedSignSearch);
        let (temperature, enthalpy, _, _) =
            solve_bracketed_temperature(bounds, scale, 0.0, compatibility, |temperature| {
                Ok((temperature, branch(temperature)))
            })
            .unwrap();
        assert!((temperature - (850.0 + 100.0 * 350.0 / 101.0)).abs() < 1.0e-5);
        assert!(enthalpy.abs() < 1.0e-6);
    }

    #[test]
    fn ph_temperature_seed_is_a_real_trial_and_can_accept_the_root() {
        let (temperature, enthalpy, iterations, trials) = solve_bracketed_temperature_from(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            Some(750.0),
            true,
            PhTemperatureSolveOptions::default(),
            Instant::now(),
            |temperature| Ok((temperature, temperature - 750.0)),
        )
        .unwrap();

        assert_eq!(iterations, 0);
        assert_eq!(temperature, 750.0);
        assert_eq!(enthalpy, 0.0);
        assert_eq!(trials.len(), 3);
        assert_eq!(trials[2].temperature(), 750.0);
    }

    #[test]
    fn ph_seed_reports_observed_multiple_brackets_instead_of_selecting_one() {
        let error = solve_bracketed_temperature_from(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            Some(750.0),
            true,
            PhTemperatureSolveOptions::default(),
            Instant::now(),
            |temperature| Ok((temperature, (temperature - 650.0) * (temperature - 850.0))),
        )
        .unwrap_err();

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

    #[test]
    fn safeguarded_scalar_solver_uses_an_interior_secant_step_for_a_linear_branch() {
        let (temperature, enthalpy, iterations, trials) = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            PhTemperatureSolveOptions::default(),
            |temperature| Ok((temperature, temperature - 775.0)),
        )
        .unwrap();

        assert_eq!(iterations, 1);
        assert_eq!(temperature, 775.0);
        assert_eq!(enthalpy, 0.0);
        assert_eq!(trials[2].step_kind(), PhTemperatureStepKind::Interpolation);
    }

    #[test]
    fn phase_control_scalar_path_uses_bisection_without_branch_interpolation() {
        let (temperature, enthalpy, iterations, trials) = solve_bracketed_temperature_from(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            None,
            false,
            PhTemperatureSolveOptions::default(),
            Instant::now(),
            |temperature| Ok((temperature, temperature - 750.0)),
        )
        .unwrap();

        assert_eq!(iterations, 1);
        assert_eq!(temperature, 750.0);
        assert_eq!(enthalpy, 0.0);
        assert_eq!(trials[2].step_kind(), PhTemperatureStepKind::Bisection);
    }

    #[test]
    fn interpolation_step_falls_back_when_secant_hugs_a_bracket_endpoint() {
        assert_eq!(
            safeguarded_interpolation_step(0.0, -1.0, 100.0, 100.0),
            None
        );
        assert_eq!(
            safeguarded_interpolation_step(0.0, -1.0, 100.0, 1.0),
            Some(50.0)
        );
    }

    #[test]
    fn derivative_ready_enthalpy_model_rejects_misaligned_capabilities() {
        let error = match EnthalpyModel::from_functions_with_heat_capacity(
            vec![Arc::new(|temperature| Ok(temperature))],
            Vec::new(),
        ) {
            Ok(_) => panic!("misaligned heat-capacity capabilities must be rejected"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            ReactionExtentError::DimensionMismatch(message)
                if message.contains("heat-capacity functions")
        ));
    }

    #[test]
    fn bracketed_solver_recovers_known_temperature_without_a_chemical_solver() {
        let model = linear_enthalpy_model();
        let target = 7_500.0;
        let scale = EnthalpyScale::from_magnitudes(target, &[1.0], &[7_000.0]).unwrap();
        let options = PhTemperatureSolveOptions {
            scaled_enthalpy_tolerance: 1.0e-10,
            absolute_enthalpy_tolerance_joules: 1.0e-6,
            monolithic_seed_policy: PhMonolithicSeedPolicy::default(),
            temperature_tolerance: 1.0e-10,
            max_iterations: 80,
            max_temperature_evaluations: 82,
            monotonicity_policy: PhMonotonicityPolicy::default(),
            max_inner_backend_attempts: None,
            max_inner_nonlinear_iterations: None,
            max_phase_control_transitions: None,
            max_wall_time: None,
            execution_control: None,
        };
        let (value, enthalpy, _, _) = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            scale,
            target,
            options,
            |temperature| Ok((temperature, model.evaluate_total(&[1.0], temperature)?)),
        )
        .unwrap();

        assert!((value - 750.0).abs() < 1.0e-8);
        assert!((enthalpy - target).abs() < 1.0e-7);
    }

    #[test]
    fn nonreacting_sensible_heat_fixture_recovers_the_analytic_root() {
        // H(T) = 2 * (100 + 4T) + 3 * (-50 + 2T) = 50 + 14T.
        // This deliberately contains no chemistry, so it isolates the outer
        // energy equation from all fixed-P,T equilibrium behavior.
        let model = EnthalpyModel::from_functions(vec![
            Arc::new(|temperature| Ok(100.0 + 4.0 * temperature)),
            Arc::new(|temperature| Ok(-50.0 + 2.0 * temperature)),
        ])
        .unwrap();
        let moles = [2.0, 3.0];
        let target_temperature = 725.0;
        let target = model.evaluate_total(&moles, target_temperature).unwrap();
        let initial_molar = model.evaluate_molar(500.0).unwrap();
        let scale = EnthalpyScale::from_magnitudes(target, &moles, &initial_molar).unwrap();

        let (temperature, enthalpy, _, _) = solve_bracketed_temperature(
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            scale,
            target,
            PhTemperatureSolveOptions::default(),
            |temperature| Ok((temperature, model.evaluate_total(&moles, temperature)?)),
        )
        .unwrap();

        assert!((temperature - target_temperature).abs() < 1.0e-5);
        assert!((enthalpy - target).abs() < 1.0e-4);
    }

    #[test]
    fn inventory_scaling_preserves_temperature_and_mole_fractions() {
        let model = EnthalpyModel::from_functions(vec![
            Arc::new(|temperature| Ok(300.0 + 3.0 * temperature)),
            Arc::new(|temperature| Ok(-100.0 + 5.0 * temperature)),
        ])
        .unwrap();
        let base_moles = [1.5, 2.5];
        let scaled_moles = [1_500.0, 2_500.0];
        let target_temperature = 810.0;
        let base_target = model
            .evaluate_total(&base_moles, target_temperature)
            .unwrap();
        let scaled_target = model
            .evaluate_total(&scaled_moles, target_temperature)
            .unwrap();
        let base_scale = EnthalpyScale::from_magnitudes(
            base_target,
            &base_moles,
            &model.evaluate_molar(400.0).unwrap(),
        )
        .unwrap();
        let scaled_scale = EnthalpyScale::from_magnitudes(
            scaled_target,
            &scaled_moles,
            &model.evaluate_molar(400.0).unwrap(),
        )
        .unwrap();
        let options = PhTemperatureSolveOptions::default();

        let (base_temperature, _, _, _) = solve_bracketed_temperature(
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            base_scale,
            base_target,
            options.clone(),
            |temperature| Ok((temperature, model.evaluate_total(&base_moles, temperature)?)),
        )
        .unwrap();
        let (scaled_temperature, _, _, _) = solve_bracketed_temperature(
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            scaled_scale,
            scaled_target,
            options,
            |temperature| {
                Ok((
                    temperature,
                    model.evaluate_total(&scaled_moles, temperature)?,
                ))
            },
        )
        .unwrap();

        assert!((base_temperature - target_temperature).abs() < 1.0e-5);
        assert!((scaled_temperature - base_temperature).abs() < 1.0e-5);
        let base_fraction = base_moles[0] / base_moles.iter().sum::<f64>();
        let scaled_fraction = scaled_moles[0] / scaled_moles.iter().sum::<f64>();
        assert!((base_fraction - scaled_fraction).abs() < 1.0e-15);
    }

    #[test]
    fn ph_constraint_rejects_nonfinite_target_before_solving() {
        let error = EquilibriumConstraint::ph(101_325.0, 101_325.0, f64::NAN, 700.0).unwrap_err();

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

    #[test]
    fn acceptance_contract_keeps_an_absolute_floor_for_zero_target() {
        let scale = EnthalpyScale::new(1.0e-12).unwrap();
        let options = PhTemperatureSolveOptions {
            scaled_enthalpy_tolerance: 1.0e-12,
            absolute_enthalpy_tolerance_joules: 1.0e-4,
            monolithic_seed_policy: PhMonolithicSeedPolicy::default(),
            temperature_tolerance: 1.0e-8,
            max_iterations: 4,
            max_temperature_evaluations: 6,
            monotonicity_policy: PhMonotonicityPolicy::default(),
            max_inner_backend_attempts: None,
            max_inner_nonlinear_iterations: None,
            max_phase_control_transitions: None,
            max_wall_time: None,
            execution_control: None,
        };

        assert_eq!(options.accepted_enthalpy_error_limit_joules(scale), 1.0e-4);
        assert!(options.accepts_enthalpy_error(5.0e-5, scale));
        assert!(!options.accepts_enthalpy_error(2.0e-4, scale));
    }

    #[test]
    fn inner_backend_budget_is_typed_and_rejects_zero() {
        let invalid = PhTemperatureSolveOptions {
            max_inner_backend_attempts: Some(0),
            ..PhTemperatureSolveOptions::default()
        };
        assert!(matches!(
            invalid.validate(),
            Err(ReactionExtentError::InvalidProblem {
                field: "max_inner_backend_attempts",
                ..
            })
        ));

        let limited = PhTemperatureSolveOptions::default()
            .with_max_inner_backend_attempts(3)
            .unwrap();
        assert_eq!(limited.max_inner_backend_attempts, Some(3));
        assert_eq!(
            limited
                .clone()
                .without_inner_backend_attempt_limit()
                .max_inner_backend_attempts,
            None
        );
        assert!(limited.with_max_inner_backend_attempts(0).is_err());

        let iteration_limited = PhTemperatureSolveOptions::default()
            .with_max_inner_nonlinear_iterations(7)
            .unwrap();
        assert_eq!(iteration_limited.max_inner_nonlinear_iterations, Some(7));
        assert_eq!(
            iteration_limited
                .clone()
                .without_inner_nonlinear_iteration_limit()
                .max_inner_nonlinear_iterations,
            None
        );
        assert!(
            iteration_limited
                .with_max_inner_nonlinear_iterations(0)
                .is_err()
        );

        let transition_limited = PhTemperatureSolveOptions::default()
            .with_max_phase_control_transitions(4)
            .unwrap();
        assert_eq!(transition_limited.max_phase_control_transitions, Some(4));
        assert_eq!(
            transition_limited
                .clone()
                .without_phase_control_transition_limit()
                .max_phase_control_transitions,
            None
        );
        assert!(
            transition_limited
                .with_max_phase_control_transitions(0)
                .is_err()
        );
    }

    #[test]
    fn monolithic_work_gate_enforces_budgets_and_cancellation_before_publication() {
        let backend_limited = PhTemperatureSolveOptions::default()
            .with_max_inner_backend_attempts(1)
            .unwrap();
        assert!(matches!(
            enforce_monolithic_work_limits(&backend_limited, Instant::now(), 2, 0, 0),
            Err(ReactionExtentError::InvalidProblem {
                field: "inner_backend_budget",
                ..
            })
        ));

        let iteration_limited = PhTemperatureSolveOptions::default()
            .with_max_inner_nonlinear_iterations(2)
            .unwrap();
        assert!(matches!(
            enforce_monolithic_work_limits(&iteration_limited, Instant::now(), 1, 3, 0),
            Err(ReactionExtentError::InvalidProblem {
                field: "inner_nonlinear_iteration_budget",
                ..
            })
        ));

        let transition_limited = PhTemperatureSolveOptions::default()
            .with_max_phase_control_transitions(1)
            .unwrap();
        assert!(matches!(
            enforce_monolithic_work_limits(&transition_limited, Instant::now(), 1, 1, 2),
            Err(ReactionExtentError::InvalidProblem {
                field: "phase_control_transition_budget",
                ..
            })
        ));

        let control = EquilibriumExecutionControl::new();
        control.request_cancel();
        let cancelled = PhTemperatureSolveOptions::default().with_execution_control(control);
        assert!(matches!(
            enforce_monolithic_work_limits(&cancelled, Instant::now(), 1, 1, 0),
            Err(ReactionExtentError::Cancelled)
        ));
    }

    #[test]
    fn bracket_solver_does_not_accept_temperature_width_without_energy_accuracy() {
        let scale = EnthalpyScale::new(1.0).unwrap();
        let options = PhTemperatureSolveOptions {
            scaled_enthalpy_tolerance: 1.0e-12,
            absolute_enthalpy_tolerance_joules: 1.0e-12,
            monolithic_seed_policy: PhMonolithicSeedPolicy::default(),
            temperature_tolerance: 10.0,
            max_iterations: 16,
            max_temperature_evaluations: 18,
            monotonicity_policy: PhMonotonicityPolicy::default(),
            max_inner_backend_attempts: None,
            max_inner_nonlinear_iterations: None,
            max_phase_control_transitions: None,
            max_wall_time: None,
            execution_control: None,
        };
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            scale,
            0.0,
            options,
            |temperature| Ok(((), if temperature < 750.0 { -1.0 } else { 1.0 })),
        )
        .unwrap_err();

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

    #[test]
    fn outer_temperature_budget_is_global_across_bracket_and_midpoints() {
        let scale = EnthalpyScale::new(1.0).unwrap();
        let options = PhTemperatureSolveOptions {
            scaled_enthalpy_tolerance: 1.0e-12,
            absolute_enthalpy_tolerance_joules: 1.0e-12,
            monolithic_seed_policy: PhMonolithicSeedPolicy::default(),
            temperature_tolerance: 1.0e-12,
            max_iterations: 80,
            max_temperature_evaluations: 2,
            monotonicity_policy: PhMonotonicityPolicy::default(),
            max_inner_backend_attempts: None,
            max_inner_nonlinear_iterations: None,
            max_phase_control_transitions: None,
            max_wall_time: None,
            execution_control: None,
        };
        let evaluations = std::cell::Cell::new(0usize);
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            scale,
            0.0,
            options,
            |temperature| {
                evaluations.set(evaluations.get() + 1);
                Ok((temperature, temperature - 800.0))
            },
        )
        .unwrap_err();

        assert_eq!(evaluations.get(), 2);
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "temperature_budget",
                ..
            }
        ));
    }

    #[test]
    fn nested_evidence_is_attached_to_trials_without_silent_truncation() {
        let mut trials = vec![PhTemperatureTrial {
            temperature: 700.0,
            step_kind: PhTemperatureStepKind::Bisection,
            total_enthalpy: 10.0,
            enthalpy_error_joules: 0.0,
            scaled_error: 0.0,
            inner_backend_attempts: 0,
            inner_nonlinear_iterations: 0,
            phase_control_transitions: 0,
            preparation: PhTrialPreparation::Unspecified,
            phase_states: Vec::new(),
            inner_timing: EquilibriumTimingReport::default(),
            timing: PhTrialTimingReport::default(),
            inner_evidence: None,
        }];
        let evidence = vec![PhNestedTrialEvidence {
            backend_attempts: 3,
            nonlinear_iterations: 11,
            phase_control_transitions: 2,
            preparation: PhTrialPreparation::BoundedPhaseControlIsolated,
            phase_states: vec![PhTrialPhaseState {
                phase: PhaseId::new(Some("condensed".to_string())),
                status: PhaseStatus::Appeared,
            }],
            timing: EquilibriumTimingReport::default(),
            trial_timing: PhTrialTimingReport {
                enabled: true,
                total: Duration::from_millis(3),
                inner_execution: Duration::from_millis(2),
                inner_equilibrium: Duration::from_millis(2),
                enthalpy_evaluation: Duration::from_micros(10),
                postprocessing: Duration::from_micros(5),
                template_preparation: EquilibriumTimingReport::default(),
            },
            inner_evidence: Some(synthetic_inner_evidence()),
        }];

        let totals = attach_nested_evidence(&mut trials, &evidence).unwrap();
        assert_eq!(totals.0, 3);
        assert_eq!(totals.1, 11);
        assert_eq!(totals.2, 2);
        assert_eq!(trials[0].inner_backend_attempts(), 3);
        assert_eq!(trials[0].inner_nonlinear_iterations(), 11);
        assert_eq!(trials[0].phase_control_transitions(), 2);
        assert_eq!(
            trials[0].preparation(),
            PhTrialPreparation::BoundedPhaseControlIsolated
        );
        assert_eq!(trials[0].phase_states().len(), 1);
        assert_eq!(trials[0].phase_states()[0].status(), PhaseStatus::Appeared);
        assert!(trials[0].timing().enabled());
        assert_eq!(trials[0].timing().total(), Duration::from_millis(3));
        assert_eq!(
            trials[0].timing().inner_equilibrium(),
            Duration::from_millis(2)
        );
        let inner = trials[0]
            .inner_evidence()
            .expect("accepted nested trial must retain its backend trace");
        assert_eq!(inner.solve_report().started_attempt_count(), 1);
        assert!(inner.multi_start_report().is_none());
        assert!(inner.phase_control_report().is_none());

        let mismatch = attach_nested_evidence(&mut trials, &[]).unwrap_err();
        assert!(matches!(
            mismatch,
            ReactionExtentError::InvalidProblem {
                field: "ph_nested_evidence",
                ..
            }
        ));
    }

    #[test]
    fn wall_time_budget_is_validated_and_enforced_by_the_bracket_helper() {
        let invalid = PhTemperatureSolveOptions {
            max_wall_time: Some(Duration::ZERO),
            ..PhTemperatureSolveOptions::default()
        };
        assert!(matches!(
            invalid.validate(),
            Err(ReactionExtentError::InvalidProblem {
                field: "max_wall_time",
                ..
            })
        ));

        let options = PhTemperatureSolveOptions {
            max_wall_time: Some(Duration::from_nanos(1)),
            ..PhTemperatureSolveOptions::default()
        };
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            options,
            |temperature| Ok((temperature, temperature - 800.0)),
        )
        .unwrap_err();
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "wall_time_budget",
                ..
            }
        ));
    }

    #[test]
    fn wall_time_budget_rejects_a_trial_that_finishes_after_the_deadline() {
        let options = PhTemperatureSolveOptions {
            max_wall_time: Some(Duration::from_millis(1)),
            ..PhTemperatureSolveOptions::default()
        };
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            options,
            |temperature| {
                std::thread::sleep(Duration::from_millis(5));
                Ok((temperature, temperature - 800.0))
            },
        )
        .unwrap_err();

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

    #[test]
    fn bracket_solver_reports_endpoint_temperature_on_inner_failure() {
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            PhTemperatureSolveOptions::default(),
            |_| {
                Err::<((), f64), _>(ReactionExtentError::InvalidProblem {
                    field: "inner",
                    message: "synthetic endpoint failure".to_string(),
                })
            },
        )
        .unwrap_err();

        match error {
            ReactionExtentError::TemperatureTrialFailed {
                trial_index,
                temperature,
                cause,
            } => {
                assert_eq!(trial_index, 0);
                assert_eq!(temperature, 500.0);
                assert!(matches!(
                    *cause,
                    ReactionExtentError::InvalidProblem { field: "inner", .. }
                ));
            }
            other => panic!("unexpected endpoint error: {other}"),
        }
    }

    #[test]
    fn bracket_solver_reports_midpoint_temperature_on_inner_failure() {
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            PhTemperatureSolveOptions::default(),
            |temperature| {
                if temperature == 750.0 {
                    Err(ReactionExtentError::InvalidProblem {
                        field: "inner",
                        message: "synthetic midpoint failure".to_string(),
                    })
                } else if temperature < 750.0 {
                    // The secant point would hug the lower endpoint, so the
                    // safeguarded hybrid must deliberately fall back to 750 K.
                    Ok((temperature, -1.0))
                } else {
                    Ok((temperature, 100.0))
                }
            },
        )
        .unwrap_err();

        match error {
            ReactionExtentError::TemperatureTrialFailed {
                trial_index,
                temperature,
                cause,
            } => {
                assert_eq!(trial_index, 2);
                assert_eq!(temperature, 750.0);
                assert!(matches!(
                    *cause,
                    ReactionExtentError::InvalidProblem { field: "inner", .. }
                ));
            }
            other => panic!("unexpected midpoint error: {other}"),
        }
    }

    #[test]
    fn bracket_solver_keeps_inner_cancellation_as_a_top_level_cancellation() {
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            EnthalpyScale::new(1.0).unwrap(),
            0.0,
            PhTemperatureSolveOptions::default(),
            |_| Err::<((), f64), _>(ReactionExtentError::Cancelled),
        )
        .unwrap_err();

        assert!(matches!(error, ReactionExtentError::Cancelled));
    }

    #[test]
    fn cancelled_ph_request_stops_before_an_inner_equilibrium_attempt() {
        let mut data = SubsData::new();
        data.set_substances(vec!["A".to_string()]);
        let phase = PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap();
        let resolved =
            ResolvedPhaseSystem::new(vec![phase], HashMap::from([(None, data)])).unwrap();
        let layout = MultiphaseEquilibriumLayout::new(vec![
            PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap(),
        ])
        .unwrap();
        let composition = MultiphaseInitialComposition::from_dense(&layout, vec![1.0]).unwrap();
        let constraint = EquilibriumConstraint::ph(101_325.0, 101_325.0, 0.0, 700.0).unwrap();
        let control = EquilibriumExecutionControl::new();
        control.request_cancel();
        let options = PhTemperatureSolveOptions::default().with_execution_control(control);
        let request = ResolvedPhaseEnthalpyRequest::new(
            &resolved,
            composition,
            constraint,
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            EnthalpyModel::from_functions(vec![Arc::new(|_| Ok(0.0))]).unwrap(),
        )
        .unwrap()
        .with_temperature_options(options)
        .unwrap();
        // The request owns its resolved snapshot; the caller's source object
        // may be released before the expensive solve begins.
        drop(resolved);

        assert!(matches!(
            solve_resolved_ph(request),
            Err(ReactionExtentError::Cancelled)
        ));
    }

    #[test]
    fn ph_cancellation_after_inner_start_never_publishes_a_result() {
        let mut data = SubsData::new();
        data.set_substances(vec!["A".to_string()]);
        let phase = PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap();
        let resolved =
            ResolvedPhaseSystem::new(vec![phase], HashMap::from([(None, data)])).unwrap();
        let layout = MultiphaseEquilibriumLayout::new(vec![
            PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap(),
        ])
        .unwrap();
        let composition = MultiphaseInitialComposition::from_dense(&layout, vec![1.0]).unwrap();
        let constraint = EquilibriumConstraint::ph(101_325.0, 101_325.0, 0.0, 700.0).unwrap();
        let stages = Arc::new(Mutex::new(Vec::new()));
        let stages_for_sink = Arc::clone(&stages);
        let control = EquilibriumExecutionControl::new();
        let cancellation = control.clone();
        let control = control.with_progress_sink(move |event| {
            stages_for_sink
                .lock()
                .expect("progress stage lock is not poisoned")
                .push(event.stage());
            if event.stage() == EquilibriumProgressStage::InnerSolveStarted {
                cancellation.request_cancel();
            }
        });
        let options = PhTemperatureSolveOptions::default().with_execution_control(control);
        let request = ResolvedPhaseEnthalpyRequest::new(
            &resolved,
            composition,
            constraint,
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            EnthalpyModel::from_functions(vec![Arc::new(|_| Ok(0.0))]).unwrap(),
        )
        .unwrap()
        .with_temperature_options(options)
        .unwrap();

        assert!(matches!(
            solve_resolved_ph(request),
            Err(ReactionExtentError::Cancelled)
        ));
        let stages = stages.lock().unwrap().clone();
        assert!(stages.contains(&EquilibriumProgressStage::InnerSolveStarted));
        assert!(!stages.contains(&EquilibriumProgressStage::PublicationCompleted));
    }

    #[test]
    fn bracketed_solver_rejects_unreachable_target() {
        let model = linear_enthalpy_model();
        let scale = EnthalpyScale::new(10_000.0).unwrap();
        let error = solve_bracketed_temperature(
            TemperatureBounds::new(500.0, 1_000.0).unwrap(),
            scale,
            20_000.0,
            PhTemperatureSolveOptions::default(),
            |temperature| Ok((temperature, model.evaluate_total(&[1.0], temperature)?)),
        )
        .unwrap_err();

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

    #[test]
    fn enthalpy_model_rejects_wrong_component_count() {
        let error = match EnthalpyModel::from_functions(Vec::new()) {
            Ok(_) => panic!("an empty enthalpy model must be rejected"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "enthalpy_functions",
                ..
            }
        ));
    }

    #[test]
    fn resolved_bridge_does_not_trust_unprovenanced_dh_cache() {
        let mut data = SubsData::new();
        data.set_substances(vec!["A".to_string()]);
        data.therm_map_of_fun.insert(
            "A".to_string(),
            HashMap::from([(
                DataType::dH_fun,
                Some(Box::new(|temperature: f64| temperature * 4.0)
                    as Box<dyn Fn(f64) -> f64 + Send + Sync>),
            )]),
        );
        let phase = PhaseSpec::ideal_gas(PhaseId::new(None), vec!["A".to_string()]).unwrap();
        let resolved =
            ResolvedPhaseSystem::new(vec![phase], HashMap::from([(None, data)])).unwrap();

        let error = match EnthalpyModel::from_resolved_system(&resolved) {
            Ok(_) => panic!("an unresolved cache must not bypass thermochemistry provenance"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "thermochemistry_provenance",
                ..
            }
        ));
        assert!(
            resolved
                .phase_data()
                .get(&None)
                .unwrap()
                .get_thermo_function("A", DataType::dH_fun)
                .is_some()
        );
    }

    fn bundle_provenance(label: &str) -> ThermochemistryProvenance {
        ThermochemistryProvenance::new(
            PhaseComponentId::new(PhaseId::new(None), label),
            "synthetic",
            label,
            "gas",
        )
    }

    #[test]
    fn thermochemistry_bundle_keeps_order_and_optional_cp_explicit() {
        let bounds = TemperatureBounds::new(300.0, 1_000.0).unwrap();
        let bundle = ResolvedThermochemistry::from_functions(
            vec![bundle_provenance("A"), bundle_provenance("B")],
            bounds,
            vec![
                Arc::new(|temperature| Ok(temperature + 1.0)),
                Arc::new(|temperature| Ok(temperature + 2.0)),
            ],
            vec![
                Arc::new(|temperature| Ok(2.0 * temperature)),
                Arc::new(|temperature| Ok(3.0 * temperature)),
            ],
            vec![Some(Arc::new(|_| Ok(10.0))), None],
        )
        .unwrap();

        assert_eq!(
            bundle
                .provenance()
                .iter()
                .map(|row| row.component().label())
                .collect::<Vec<_>>(),
            vec!["A", "B"]
        );
        assert_eq!(bundle.evaluate_gibbs(500.0).unwrap(), vec![501.0, 502.0]);
        assert_eq!(
            bundle.evaluate_enthalpy(500.0).unwrap(),
            vec![1_000.0, 1_500.0]
        );
        assert_eq!(
            bundle.evaluate_heat_capacity(500.0).unwrap(),
            vec![Some(10.0), None]
        );
    }

    #[test]
    fn thermochemistry_bundle_rejects_dimension_mismatch_and_domain_escape() {
        let error = match ResolvedThermochemistry::from_functions(
            vec![bundle_provenance("A")],
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            vec![Arc::new(|_| Ok(0.0)), Arc::new(|_| Ok(0.0))],
            vec![Arc::new(|_| Ok(0.0))],
            vec![None],
        ) {
            Ok(_) => panic!("a dimension-mismatched bundle must be rejected"),
            Err(error) => error,
        };
        assert!(matches!(error, ReactionExtentError::DimensionMismatch(_)));

        let bundle = ResolvedThermochemistry::from_functions(
            vec![bundle_provenance("A")],
            TemperatureBounds::new(300.0, 1_000.0).unwrap(),
            vec![Arc::new(|_| Ok(0.0))],
            vec![Arc::new(|_| Ok(0.0))],
            vec![None],
        )
        .unwrap();
        let error = bundle.evaluate_enthalpy(1_001.0).unwrap_err();
        assert!(matches!(
            error,
            ReactionExtentError::InvalidProblem {
                field: "temperature",
                ..
            }
        ));
    }
}