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
//! Typed boundary between resolved thermodynamic data and equilibrium algorithms.
//!
//! The phase subsystem owns lookup, physical-state selection, provenance, and
//! the canonical [`SystemLayout`]. The equilibrium subsystem owns activity
//! models, numerical coordinates, residuals, and nonlinear solver policy. This
//! module is the one-way bridge between those responsibilities:
//!
//! ```text
//! ResolvedPhaseSystem
//!     |  PhaseSpec + SubsData + provenance + SystemLayout
//!     v
//! PhaseEquilibriumBuildRequest
//!     |
//!     v
//! PhaseEquilibriumMetadata
//!     |  qualified components + ordered phases + stable indices
//!     v
//! EquilibriumProblem                 (built in the next adapter layer)
//! ```
//!
//! Structural validation precedes thermochemical extraction. The final builder
//! evaluates `G0(T)` on phase-local working copies, so missing or invalid data
//! cannot mutate the resolved input or publish a partial numerical problem.

use std::collections::{BTreeSet, HashMap};
use std::rc::Rc;

use crate::Thermodynamics::ChemEquilibrium::equilibrium_active_set::independent_column_basis;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_activity::PhaseActivityModel;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_candidate_selection::EquilibriumCandidateSelectionReport;
pub use crate::Thermodynamics::ChemEquilibrium::equilibrium_component::{
    EquilibriumComponentDescriptor, EquilibriumPhaseDescriptor,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_constant_cross_validation::EquilibriumConstantCrossValidationStatus;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_diagnostics::EquilibriumDiagnosticsOptions;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventory;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_seed::{
    ElementFeasibleSeedSettings, build_element_feasible_seed,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ids::PhaseIndex;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::record_phase_equilibrium_build;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::{
    EquilibriumSolverSettings, GibbsFn, compute_element_totals,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::{
    MultiphaseEquilibriumLayout, MultiphaseInitialComposition,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
    EquilibriumPreparationError, ReactionExtentError,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_prepared_runner::{
    PreparedEquilibriumDefaultRoute, PreparedEquilibriumRunner,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
    EquilibriumConditions, EquilibriumProblem, EquilibriumSolution, LogMolesInitialGuess,
    PreparedEquilibriumProblem, TraceSpeciesSeedPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstPreparedProblem;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::EquilibriumSolveReport;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::MultiStartSolveReport;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::{
    EquilibriumTimingCollector, EquilibriumTimingMode, EquilibriumTimingReport,
    EquilibriumTimingStage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{PhaseManager, PhaseSet};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_solution::MultiphaseEquilibriumSolution;
use crate::Thermodynamics::ChemEquilibrium::prepared_phase_control_runner::PreparedPhaseControlRunner;
use crate::Thermodynamics::User_PhaseOrSolution::{
    PhaseModel, ResolvedPhaseSystem, ResolvedPhaseSystemReport,
};
use crate::Thermodynamics::User_substances::SubsData;
use crate::Thermodynamics::User_substances2::SearchSummaryRow;
use crate::Thermodynamics::phase_layout::{
    PhaseComponentId, PhaseId as SemanticPhaseId, SystemLayout,
};
#[cfg(test)]
use RustedSciThe::symbolic::symbolic_engine::Expr;
use nalgebra::{DMatrix, linalg::SVD};
use std::time::{Duration, Instant};

/// Explicit version of the phase-model contract accepted by the bridge.
///
/// A policy value is carried by every build request so extending the phase
/// subsystem cannot silently make the equilibrium solver accept a model whose
/// chemical-potential equation has not been implemented and tested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SupportedPhaseModelPolicy {
    /// Ideal gas, pure condensed, and multicomponent ideal-solution phases
    /// using the canonical constrained-TPD lifecycle.
    #[default]
    IdealPhaseModelsV1,
}

/// Immutable structural projection shared by bridge construction and results.
///
/// The metadata owns the canonical layout and all derived index maps. Callers
/// therefore never have to keep a `Vec<String>`, phase ranges, and provenance
/// aligned by convention.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhaseEquilibriumMetadata {
    /// Canonical ordered phase/component layout from the resolved system.
    layout: SystemLayout,
    /// Stable process-independent fingerprint of the declared layout.
    layout_fingerprint: u64,
    /// All phase-qualified components in canonical solver order.
    components: Vec<EquilibriumComponentDescriptor>,
    /// All phases in canonical solver order with their component ranges.
    phases: Vec<EquilibriumPhaseDescriptor>,
    /// Maps `PhaseComponentId` → dense component index for O(1) lookup.
    component_indices: HashMap<PhaseComponentId, usize>,
    /// Maps semantic `PhaseId` → dense `PhaseIndex` for O(1) lookup.
    phase_indices: HashMap<SemanticPhaseId, PhaseIndex>,
    /// Provenance evidence from the resolved phase system.
    provenance: ResolvedPhaseSystemReport,
}

impl PhaseEquilibriumMetadata {
    /// Projects one resolved phase system into equilibrium-owned descriptors.
    ///
    /// This operation is pure and transactional: all validation and allocation
    /// completes before a metadata value is returned.
    pub fn from_resolved(
        resolved: &ResolvedPhaseSystem,
        policy: SupportedPhaseModelPolicy,
    ) -> Result<Self, ReactionExtentError> {
        match policy {
            SupportedPhaseModelPolicy::IdealPhaseModelsV1 => {}
        }

        let multiphase_layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec())?;
        if multiphase_layout.system_layout() != resolved.layout() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "resolved_phase_layout",
                message:
                    "resolved phase data and phase specifications use different component order"
                        .to_string(),
            });
        }

        let layout = resolved.layout().clone();
        let phase_count = resolved.phase_specs().len();
        let mut phases = Vec::with_capacity(phase_count);
        let mut components = Vec::with_capacity(layout.component_count());
        let mut phase_indices = HashMap::with_capacity(phase_count);
        let mut component_indices = HashMap::with_capacity(layout.component_count());

        for (phase_position, spec) in resolved.phase_specs().iter().enumerate() {
            let id = spec.id().clone();
            let index = PhaseIndex::new(phase_position, phase_count)?;
            let component_range = layout.phase_component_range(&id).cloned().ok_or_else(|| {
                ReactionExtentError::InvalidProblem {
                    field: "resolved_phase_layout",
                    message: format!("phase {:?} has no component range", id.as_option()),
                }
            })?;
            let activity_model = activity_model_for(spec.model());

            if phase_indices.insert(id.clone(), index).is_some() {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "resolved_phase_layout",
                    message: format!("duplicate phase identity {:?}", id.as_option()),
                });
            }

            for component_position in component_range.clone() {
                let id = layout.components()[component_position].clone();
                if component_indices
                    .insert(id.clone(), component_position)
                    .is_some()
                {
                    return Err(ReactionExtentError::InvalidProblem {
                        field: "resolved_phase_layout",
                        message: format!("duplicate component identity '{}'", id.label()),
                    });
                }
                components.push(EquilibriumComponentDescriptor::new(
                    id,
                    spec.physical_state(),
                    spec.model(),
                    activity_model,
                ));
            }

            phases.push(EquilibriumPhaseDescriptor::new(
                id,
                index,
                spec.physical_state(),
                spec.model(),
                activity_model,
                component_range,
            ));
        }

        if components.len() != layout.component_count() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "resolved_phase_layout",
                message: "not every resolved component belongs to a declared phase".to_string(),
            });
        }

        Ok(Self {
            layout,
            layout_fingerprint: multiphase_layout.fingerprint(),
            components,
            phases,
            component_indices,
            phase_indices,
            provenance: resolved.report().clone(),
        })
    }

    /// Canonical ordered phase/component layout.
    pub fn layout(&self) -> &SystemLayout {
        &self.layout
    }

    /// Stable fingerprint used to reject stale compositions and solutions.
    pub fn layout_fingerprint(&self) -> u64 {
        self.layout_fingerprint
    }

    /// Component descriptors in exact solver-vector order.
    pub fn components(&self) -> &[EquilibriumComponentDescriptor] {
        &self.components
    }

    /// Phase descriptors in canonical semantic phase order.
    pub fn phases(&self) -> &[EquilibriumPhaseDescriptor] {
        &self.phases
    }

    /// Finds the solver position of one qualified component.
    pub fn component_index(&self, id: &PhaseComponentId) -> Option<usize> {
        self.component_indices.get(id).copied()
    }

    /// Finds the dense solver index of one semantic phase.
    pub fn phase_index(&self, id: &SemanticPhaseId) -> Option<PhaseIndex> {
        self.phase_indices.get(id).copied()
    }

    /// Immutable lookup report retained from phase-system resolution.
    pub fn provenance(&self) -> &ResolvedPhaseSystemReport {
        &self.provenance
    }
}

/// Complete structural request for building one fixed-`P,T` equilibrium problem.
///
/// Construction validates that the physical composition and resolved records
/// share exactly the same phase-qualified layout. Standard-state Gibbs models
/// are intentionally extracted only by the next adapter pass.
#[derive(Debug)]
pub struct PhaseEquilibriumBuildRequest<'a> {
    resolved: &'a ResolvedPhaseSystem,
    conditions: EquilibriumConditions,
    physical_input: PhaseEquilibriumPhysicalInput,
    trace_seed_policy: TraceSpeciesSeedPolicy,
    model_policy: SupportedPhaseModelPolicy,
    metadata: PhaseEquilibriumMetadata,
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
}

/// Physical information from which a bridge request derives conserved totals.
///
/// This distinction exists only at the application/phase bridge boundary.
/// Numerical solvers receive the same resolved species matrix `A`, conserved
/// vector `b`, and log-mole seed regardless of whether `b` originated from
/// explicitly entered phase-qualified moles or from an elemental inventory.
#[derive(Debug, Clone)]
enum PhaseEquilibriumPhysicalInput {
    Composition(MultiphaseInitialComposition),
    ElementInventory {
        inventory: ElementInventory,
        /// An optional numerical starting point.  It never replaces the
        /// inventory-derived conservation vector `b`.
        numerical_seed: Option<MultiphaseInitialComposition>,
    },
}

impl<'a> PhaseEquilibriumBuildRequest<'a> {
    /// Creates a validated request without evaluating thermochemistry.
    pub fn new(
        resolved: &'a ResolvedPhaseSystem,
        conditions: EquilibriumConditions,
        initial_composition: MultiphaseInitialComposition,
        trace_seed_policy: TraceSpeciesSeedPolicy,
        model_policy: SupportedPhaseModelPolicy,
    ) -> Result<Self, ReactionExtentError> {
        let multiphase_layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec())?;
        initial_composition.validate_for(&multiphase_layout)?;
        let metadata = PhaseEquilibriumMetadata::from_resolved(resolved, model_policy)?;

        Ok(Self {
            resolved,
            conditions,
            physical_input: PhaseEquilibriumPhysicalInput::Composition(initial_composition),
            trace_seed_policy,
            model_policy,
            metadata,
            candidate_selection: None,
        })
    }

    /// Creates a request from a closed elemental inventory rather than a
    /// physical initial composition.
    ///
    /// The inventory is aligned to the resolved real-component matrix during
    /// build. A deterministic element-feasible seed is then created from
    /// those real components; formula-like inventory carriers never become
    /// thermochemical species or artificial phase members.
    pub fn from_element_inventory(
        resolved: &'a ResolvedPhaseSystem,
        conditions: EquilibriumConditions,
        element_inventory: ElementInventory,
        trace_seed_policy: TraceSpeciesSeedPolicy,
        model_policy: SupportedPhaseModelPolicy,
    ) -> Result<Self, ReactionExtentError> {
        let metadata = PhaseEquilibriumMetadata::from_resolved(resolved, model_policy)?;
        if metadata.layout().component_count() == 0 {
            return Err(ReactionExtentError::Preparation(
                EquilibriumPreparationError::EmptySpeciesUniverse,
            ));
        }
        Ok(Self {
            resolved,
            conditions,
            physical_input: PhaseEquilibriumPhysicalInput::ElementInventory {
                inventory: element_inventory,
                numerical_seed: None,
            },
            trace_seed_policy,
            model_policy,
            metadata,
            candidate_selection: None,
        })
    }

    /// Resolved phase-local thermochemical records.
    pub fn resolved(&self) -> &ResolvedPhaseSystem {
        self.resolved
    }

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

    /// Explicit physical composition, when the request originated from one.
    ///
    /// Element-inventory requests intentionally return `None`: their seed is
    /// numerical and must not be reported as a user-specified physical feed.
    pub fn initial_composition(&self) -> Option<&MultiphaseInitialComposition> {
        match &self.physical_input {
            PhaseEquilibriumPhysicalInput::Composition(composition) => Some(composition),
            PhaseEquilibriumPhysicalInput::ElementInventory { .. } => None,
        }
    }

    /// Closed elemental inventory, when this is an element-defined request.
    pub fn element_inventory(&self) -> Option<&ElementInventory> {
        match &self.physical_input {
            PhaseEquilibriumPhysicalInput::Composition(_) => None,
            PhaseEquilibriumPhysicalInput::ElementInventory { inventory, .. } => Some(inventory),
        }
    }

    /// Attaches a numerical seed to an element-defined request.
    ///
    /// The composition is deliberately not promoted to a physical feed: the
    /// bridge continues to build `b` from [`ElementInventory`]. This is the
    /// continuation boundary used by higher-level P,H workflows.
    pub fn with_numerical_seed(
        mut self,
        numerical_seed: MultiphaseInitialComposition,
    ) -> Result<Self, ReactionExtentError> {
        let layout = MultiphaseEquilibriumLayout::new(self.resolved.phase_specs().to_vec())?;
        numerical_seed.validate_for(&layout)?;
        match &mut self.physical_input {
            PhaseEquilibriumPhysicalInput::Composition(_) => {
                Err(ReactionExtentError::InvalidProblem {
                    field: "numerical_seed",
                    message:
                        "a separate numerical seed is valid only for an element-inventory request"
                            .to_string(),
                })
            }
            PhaseEquilibriumPhysicalInput::ElementInventory {
                numerical_seed: stored,
                ..
            } => {
                *stored = Some(numerical_seed);
                Ok(self)
            }
        }
    }

    /// Explicit numerical policy for zero-mole log-coordinate seeds.
    pub fn trace_seed_policy(&self) -> TraceSpeciesSeedPolicy {
        self.trace_seed_policy
    }

    /// Supported phase-model contract selected for this request.
    pub fn model_policy(&self) -> SupportedPhaseModelPolicy {
        self.model_policy
    }

    /// Immutable structural projection prepared transactionally at construction.
    pub fn metadata(&self) -> &PhaseEquilibriumMetadata {
        &self.metadata
    }

    /// Attaches immutable automatic-selection evidence to the preparation
    /// transaction. The report does not alter the selected phase universe.
    pub fn with_candidate_selection(
        mut self,
        selection: EquilibriumCandidateSelectionReport,
    ) -> Self {
        self.candidate_selection = Some(selection);
        self
    }

    /// Candidate-selection evidence, when this request came from an element
    /// search followed by an explicit phase plan.
    pub fn candidate_selection(&self) -> Option<&EquilibriumCandidateSelectionReport> {
        self.candidate_selection.as_ref()
    }
}

/// Immutable provenance and standard-state evidence for one bridge component.
#[derive(Debug, Clone, PartialEq)]
pub struct EquilibriumBridgeComponentReport {
    /// Phase-qualified component described by this report row.
    component: EquilibriumComponentDescriptor,
    /// Physical initial amount before trace seeding, in moles.
    initial_moles: f64,
    /// Standard-state Gibbs energy `G0(T)` checked during preparation, in J/mol.
    standard_gibbs_at_conditions: f64,
    /// Local thermochemical lookup row that supplied this component.
    thermo_source: SearchSummaryRow,
}

impl EquilibriumBridgeComponentReport {
    /// Phase-qualified component described by this report row.
    pub fn component(&self) -> &EquilibriumComponentDescriptor {
        &self.component
    }

    /// Physical initial amount before trace seeding.
    pub fn initial_moles(&self) -> f64 {
        self.initial_moles
    }

    /// Standard-state Gibbs energy `G0(T)` checked during preparation, in J/mol.
    pub fn standard_gibbs_at_conditions(&self) -> f64 {
        self.standard_gibbs_at_conditions
    }

    /// Local thermochemical lookup row that supplied this component.
    pub fn thermo_source(&self) -> &SearchSummaryRow {
        &self.thermo_source
    }
}

/// Read-only evidence emitted when a phase system becomes a solver problem.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseEquilibriumInputKind {
    /// Conserved totals were derived from an explicitly supplied composition.
    ExplicitComposition,
    /// Conserved totals came directly from a closed elemental inventory.
    ElementInventory,
}

/// Provenance for the numerical state used to enter log-mole coordinates.
///
/// This is deliberately separate from [`PhaseEquilibriumInputKind`]: an
/// accepted continuation may provide a seed for an element-defined problem,
/// but it never becomes that problem's physical feed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseEquilibriumSeedSource {
    /// The explicit physical composition was used as the first numerical seed.
    ExplicitComposition,
    /// An answer-independent bounded affine projection built a real-species seed.
    ElementFeasibleProjection,
    /// A caller supplied an already element-conserving numerical continuation seed.
    SuppliedNumericalSeed,
}

/// Immutable feasibility evidence for the initial numerical state.
#[derive(Debug, Clone, PartialEq)]
pub struct PhaseEquilibriumSeedEvidence {
    source: PhaseEquilibriumSeedSource,
    inventory_scale: f64,
    achieved_minimum_fraction: Option<f64>,
    max_element_balance_error: f64,
}

impl PhaseEquilibriumSeedEvidence {
    pub fn source(&self) -> PhaseEquilibriumSeedSource {
        self.source
    }

    pub fn inventory_scale(&self) -> f64 {
        self.inventory_scale
    }

    pub fn achieved_minimum_fraction(&self) -> Option<f64> {
        self.achieved_minimum_fraction
    }

    pub fn max_element_balance_error(&self) -> f64 {
        self.max_element_balance_error
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct PhaseEquilibriumBuildReport {
    /// Fixed pressure-temperature conditions used for standard-state checks.
    conditions: EquilibriumConditions,
    /// Immutable lookup provenance retained from the resolved phase system.
    lookup_report: ResolvedPhaseSystemReport,
    /// Layout fingerprint shared by the input composition and bridge metadata.
    layout_fingerprint: u64,
    /// Origin of the immutable physical conservation vector.
    input_kind: PhaseEquilibriumInputKind,
    /// Numerical trace-coordinate policy, kept separate from physical moles.
    trace_seed_policy: TraceSpeciesSeedPolicy,
    /// Evidence for the seed used before the first backend evaluation.
    seed_evidence: PhaseEquilibriumSeedEvidence,
    /// Full physical element names in deterministic provenance order.
    ///
    /// The solver may remove linearly dependent columns, but the bridge retains
    /// this full list and its totals for conservation evidence and diagnostics.
    element_labels: Vec<String>,
    /// Conserved physical element totals before numerical trace seeding.
    element_totals: Vec<f64>,
    /// Deterministic independent subset of `element_labels` used by the
    /// square log-moles solver formulation.
    solver_element_labels: Vec<String>,
    /// Component reports in exact `SystemLayout` order.
    components: Vec<EquilibriumBridgeComponentReport>,
    /// Immutable selection evidence that produced this resolved universe.
    candidate_selection: Option<EquilibriumCandidateSelectionReport>,
}

impl PhaseEquilibriumBuildReport {
    /// Fixed pressure-temperature conditions used for standard-state checks.
    pub fn conditions(&self) -> EquilibriumConditions {
        self.conditions
    }

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

    /// Layout fingerprint shared by the input composition and bridge metadata.
    pub fn layout_fingerprint(&self) -> u64 {
        self.layout_fingerprint
    }

    /// Origin of the immutable conservation vector retained by this build.
    pub fn input_kind(&self) -> PhaseEquilibriumInputKind {
        self.input_kind
    }

    /// Numerical zero/trace policy used only for log-coordinate initialization.
    pub fn trace_seed_policy(&self) -> TraceSpeciesSeedPolicy {
        self.trace_seed_policy
    }

    /// Feasibility evidence for the initial numerical state.
    pub fn seed_evidence(&self) -> &PhaseEquilibriumSeedEvidence {
        &self.seed_evidence
    }

    /// Full physical element names in deterministic provenance order.
    pub fn element_labels(&self) -> &[String] {
        &self.element_labels
    }

    /// Conserved physical element totals before numerical trace seeding.
    pub fn element_totals(&self) -> &[f64] {
        &self.element_totals
    }

    /// Independent elemental constraints retained by the numerical solver.
    ///
    /// Omitted full columns are linearly dependent on earlier retained columns;
    /// no physical conservation direction is discarded.
    pub fn solver_element_labels(&self) -> &[String] {
        &self.solver_element_labels
    }

    /// Component reports in exact `SystemLayout` order.
    pub fn components(&self) -> &[EquilibriumBridgeComponentReport] {
        &self.components
    }

    /// Automatic candidate-selection evidence, when the universe was selected
    /// from an elemental query. Explicit phase declarations return `None`.
    pub fn candidate_selection(&self) -> Option<&EquilibriumCandidateSelectionReport> {
        self.candidate_selection.as_ref()
    }

    /// Re-evaluates only temperature-dependent standard-state values while
    /// preserving layout, lookup provenance, and conserved element totals.
    pub(crate) fn at_conditions(
        &self,
        conditions: EquilibriumConditions,
        gibbs: &[GibbsFn],
    ) -> Result<Self, ReactionExtentError> {
        if gibbs.len() != self.components.len() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "temperature report has {} components but {} Gibbs closures",
                self.components.len(),
                gibbs.len()
            )));
        }

        let mut components = self.components.clone();
        for (index, component) in components.iter_mut().enumerate() {
            let value = gibbs[index](conditions.temperature());
            if !value.is_finite() {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "standard_gibbs",
                    message: format!(
                        "component '{}' returned non-finite G0 at {} K",
                        component.component.label(),
                        conditions.temperature()
                    ),
                });
            }
            component.standard_gibbs_at_conditions = value;
        }

        Ok(Self {
            conditions,
            lookup_report: self.lookup_report.clone(),
            layout_fingerprint: self.layout_fingerprint,
            input_kind: self.input_kind,
            trace_seed_policy: self.trace_seed_policy,
            seed_evidence: self.seed_evidence.clone(),
            element_labels: self.element_labels.clone(),
            element_totals: self.element_totals.clone(),
            solver_element_labels: self.solver_element_labels.clone(),
            components,
            candidate_selection: self.candidate_selection.clone(),
        })
    }
}

/// Complete immutable product of `ResolvedPhaseSystem -> EquilibriumProblem` preparation.
///
/// The bundle prevents callers from accidentally pairing a numerical problem
/// with a layout, source report, or initial inventory from another resolution.
pub struct PhaseEquilibriumProblemBundle {
    /// Canonical numerical problem ready for the solver.
    problem: EquilibriumProblem,
    /// Phase-qualified layout and lookup metadata.
    metadata: PhaseEquilibriumMetadata,
    /// Immutable thermochemical preparation evidence.
    report: PhaseEquilibriumBuildReport,
    /// Baked symbolic expressions are retained only by test builds for the
    /// independent algebraic oracle. Production RST uses its parameterized
    /// `g0_i` graph and numeric values from `PreparedEquilibriumProblem`.
    #[cfg(test)]
    symbolic_standard_gibbs: Vec<Expr>,
    /// Private working copies used to select the correct coefficient interval
    /// at each temperature-range point without mutating resolved input data.
    thermo_payloads: Vec<SubsData>,
    /// Optional stage timing accumulated during bridge construction and solve.
    timing: EquilibriumTimingReport,
}

impl PhaseEquilibriumProblemBundle {
    /// Numerical problem ready for canonical preparation and solver selection.
    pub fn problem(&self) -> &EquilibriumProblem {
        &self.problem
    }

    /// Phase-qualified ordering and immutable lookup provenance.
    pub fn metadata(&self) -> &PhaseEquilibriumMetadata {
        &self.metadata
    }

    /// Inspectable preparation evidence without invoking a solver.
    pub fn report(&self) -> &PhaseEquilibriumBuildReport {
        &self.report
    }

    /// Optional timing evidence accumulated by the canonical workflow.
    pub fn timing_report(&self) -> &EquilibriumTimingReport {
        &self.timing
    }

    /// Returns the baked symbolic snapshot for the independent bridge oracle.
    /// This accessor and its storage are compiled only for tests.
    #[cfg(test)]
    pub(crate) fn symbolic_standard_gibbs(&self) -> &[Expr] {
        &self.symbolic_standard_gibbs
    }

    /// Consumes the bundle when a solver must own the numerical problem.
    pub fn into_problem(self) -> EquilibriumProblem {
        self.problem
    }

    /// Solves the complete declared phase set through the canonical backend
    /// cascade using its default numerical settings.
    ///
    /// This is deliberately a consuming operation. A failed numerical attempt
    /// cannot leave a mutable partial solution attached to the prepared
    /// thermochemical bundle, while a successful attempt returns all lookup,
    /// preparation, validation, and backend evidence as one immutable value.
    pub fn solve(self) -> Result<PhaseEquilibriumSolutionBundle, ReactionExtentError> {
        self.solve_with(|_| {})
    }

    /// Solves the complete declared phase set after configuring only numerical
    /// controls.
    ///
    /// The callback cannot alter the resolved phase layout, initial physical
    /// inventory, standard-state Gibbs functions, or provenance. It receives
    /// only the canonical solver settings, matching
    /// [`PreparedEquilibriumRunner`].
    pub fn solve_with<F>(
        self,
        configure: F,
    ) -> Result<PhaseEquilibriumSolutionBundle, ReactionExtentError>
    where
        F: FnOnce(&mut EquilibriumSolverSettings),
    {
        let mut timing = EquilibriumTimingCollector::from_report(self.timing);
        let prepared =
            timing.measure(EquilibriumTimingStage::NumericalProblemPreparation, || {
                crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::
                PreparedEquilibriumProblem::new(self.problem)
            })?;
        let mut runner = PreparedEquilibriumRunner::new_production(prepared)?
            .with_timing_enabled(self.timing.enabled());
        configure(runner.configure());
        let outcome = timing.measure(EquilibriumTimingStage::NonlinearSolve, || runner.solve())?;
        timing.record(
            EquilibriumTimingStage::RstPreparation,
            outcome.rst_preparation_duration,
        );
        timing.record_rst_preparation_timing(outcome.rst_preparation_timing);
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );

        Ok(PhaseEquilibriumSolutionBundle {
            metadata: self.metadata,
            build_report: self.report,
            solution: outcome.solution,
            solve_report: outcome.solve_report,
            multi_start_report: outcome.multi_start_report,
            keq_validation_status: outcome.keq_validation_status,
            timing: timing.finish(),
        })
    }

    /// Solves one fixed formulation from explicit ordered log-mole seeds.
    ///
    /// The chemistry, layout, and conserved totals are prepared once. Each
    /// seed is only a numerical starting point; the common acceptance gate
    /// selects the best accepted candidate. The ordinary solve remains the
    /// default; the typed public request opts into this method explicitly.
    /// It is not available on the bounded phase-control path.
    pub fn solve_with_initial_guesses<F>(
        self,
        initial_guesses: Vec<LogMolesInitialGuess>,
        configure: F,
    ) -> Result<PhaseEquilibriumSolutionBundle, ReactionExtentError>
    where
        F: FnOnce(&mut EquilibriumSolverSettings),
    {
        let mut timing = EquilibriumTimingCollector::from_report(self.timing);
        let prepared = timing
            .measure(EquilibriumTimingStage::NumericalProblemPreparation, || {
                PreparedEquilibriumProblem::new(self.problem)
            })?;
        let mut runner = PreparedEquilibriumRunner::new_production(prepared)?
            .with_timing_enabled(self.timing.enabled());
        configure(runner.configure());
        let outcome = timing.measure(EquilibriumTimingStage::NonlinearSolve, || {
            runner.solve_from_initial_guesses(initial_guesses)
        })?;
        timing.record(
            EquilibriumTimingStage::RstPreparation,
            outcome.rst_preparation_duration,
        );
        timing.record_rst_preparation_timing(outcome.rst_preparation_timing);
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );

        Ok(PhaseEquilibriumSolutionBundle {
            metadata: self.metadata,
            build_report: self.report,
            solution: outcome.solution,
            solve_report: outcome.solve_report,
            multi_start_report: outcome.multi_start_report,
            keq_validation_status: outcome.keq_validation_status,
            timing: timing.finish(),
        })
    }

    /// Converts the first point of a temperature sweep into a reusable
    /// immutable formulation template. The reaction basis, element totals,
    /// phase projection, closures, and optional RST symbolic problem are
    /// prepared once and then retargeted point by point.
    pub(crate) fn into_temperature_template(
        self,
        prepare_rst: bool,
        timing_mode: EquilibriumTimingMode,
        rst_frontend: crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstSymbolicFrontend,
    ) -> Result<PreparedPhaseEquilibriumTemplate, ReactionExtentError> {
        let prior_timing = self.timing;
        let started = Instant::now();
        let mut timing = EquilibriumTimingCollector::from_report(prior_timing);
        let prepared =
            timing.measure(EquilibriumTimingStage::NumericalProblemPreparation, || {
                crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::
                PreparedEquilibriumProblem::new(self.problem)
            })?;
        let rst_problem = if prepare_rst {
            let (problem, rst_timing) = timing
                .measure(EquilibriumTimingStage::SymbolicConstruction, || {
                    crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::prepare_rst_symbolic_problem_from_prepared_with_options(
                        &prepared,
                        timing_mode,
                        rst_frontend,
                    )
                })?;
            timing.record(EquilibriumTimingStage::RstPreparation, rst_timing.total());
            timing.record_rst_preparation_timing(rst_timing);
            Some(problem)
        } else {
            None
        };
        if matches!(timing_mode, EquilibriumTimingMode::Enabled) {
            timing.set_total(prior_timing.total() + started.elapsed());
        }

        Ok(PreparedPhaseEquilibriumTemplate {
            prepared,
            metadata: self.metadata,
            report: self.report,
            thermo_payloads: self.thermo_payloads,
            rst_problem,
            timing: timing.finish(),
            // The first point has not yet published its parameter update.
            fixed_pt_parameters_initialized: false,
            last_symbolic_parameter_reused: false,
            last_formulation_build: Duration::ZERO,
        })
    }

    /// Consumes a fixed-active bridge bundle for a formulation that owns a
    /// solved temperature itself, such as monolithic P,H. No symbolic P,T
    /// payload is carried across this boundary because it is not valid after
    /// temperature becomes a nonlinear unknown.
    pub(crate) fn into_prepared_fixed_active_problem(
        self,
    ) -> Result<PreparedFixedActiveProblem, ReactionExtentError> {
        Ok(PreparedFixedActiveProblem {
            prepared: PreparedEquilibriumProblem::new(self.problem)?,
            metadata: self.metadata,
            report: self.report,
            timing: self.timing,
        })
    }

    /// Converts the bundle into a phase-control template with an explicit
    /// observational diagnostics policy retained by its canonical runner.
    pub(crate) fn into_phase_control_template_with_diagnostics<F>(
        self,
        configure_phase_control: F,
        diagnostics: EquilibriumDiagnosticsOptions,
    ) -> Result<PreparedPhaseControlTemplate, ReactionExtentError>
    where
        F: FnOnce(&mut PhaseManager),
    {
        let timing_enabled = self.timing.enabled();
        let mut runner = PreparedPhaseControlRunner::new_with_diagnostics(
            self.problem,
            timing_enabled,
            diagnostics,
            PreparedEquilibriumDefaultRoute::ProductionDefault,
        )?;
        configure_phase_control(runner.configure_phase_control());
        Ok(PreparedPhaseControlTemplate {
            runner,
            metadata: self.metadata,
            report: self.report,
            thermo_payloads: self.thermo_payloads,
            timing: self.timing,
            last_rst_symbolic_reused: false,
            last_formulation_build: Duration::ZERO,
        })
    }

    /// Solves through the bounded active-set phase-control loop and publishes
    /// the accepted result only after the final complementarity gate passes.
    ///
    /// The bridge still owns component identity, local standard-state data,
    /// and provenance. The outer loop receives only numerical controls and a
    /// phase-control policy, so it cannot mutate the resolved phase system.
    /// The outer loop owns only transition state; each inner solve is an
    /// immutable prepared problem. The historical mutable solver is therefore
    /// not part of the canonical resolved-data path.
    pub fn solve_with_bounded_phase_control<F, G>(
        self,
        configure_solver: F,
        configure_phase_control: G,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError>
    where
        F: FnOnce(&mut EquilibriumSolverSettings),
        G: FnOnce(&mut PhaseManager),
    {
        self.solve_with_bounded_phase_control_with_diagnostics(
            configure_solver,
            configure_phase_control,
            EquilibriumDiagnosticsOptions::disabled(),
        )
    }

    /// Solves through bounded phase control with explicit observational
    /// diagnostics. The compatibility overload above keeps diagnostics off.
    pub fn solve_with_bounded_phase_control_with_diagnostics<F, G>(
        self,
        configure_solver: F,
        configure_phase_control: G,
        diagnostics: EquilibriumDiagnosticsOptions,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError>
    where
        F: FnOnce(&mut EquilibriumSolverSettings),
        G: FnOnce(&mut PhaseManager),
    {
        self.solve_with_bounded_phase_control_with_diagnostics_and_seed(
            configure_solver,
            configure_phase_control,
            diagnostics,
            None,
            None,
        )
    }

    /// Internal recovery variant that changes only the nonlinear basin seed.
    /// The physical inventory still determines the initial active phase set.
    pub(crate) fn solve_with_bounded_phase_control_with_diagnostics_and_seed<F, G>(
        self,
        configure_solver: F,
        configure_phase_control: G,
        diagnostics: EquilibriumDiagnosticsOptions,
        basin_seed: Option<LogMolesInitialGuess>,
        continuation_phase_set: Option<PhaseSet>,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError>
    where
        F: FnOnce(&mut EquilibriumSolverSettings),
        G: FnOnce(&mut PhaseManager),
    {
        let timing_enabled = self.timing.enabled();
        let mut timing = EquilibriumTimingCollector::from_report(self.timing);
        let mut runner =
            timing.measure(EquilibriumTimingStage::NumericalProblemPreparation, || {
                PreparedPhaseControlRunner::new_with_diagnostics(
                    self.problem,
                    timing_enabled,
                    diagnostics,
                    PreparedEquilibriumDefaultRoute::ProductionDefault,
                )
            })?;
        configure_solver(runner.configure_solver());
        configure_phase_control(runner.configure_phase_control());
        if let Some(seed) = basin_seed {
            runner.set_independent_basin_seed(seed)?;
        }
        if let Some(phase_set) = continuation_phase_set {
            runner.set_continuation_phase_set(phase_set)?;
        }
        let outcome = timing.measure(EquilibriumTimingStage::PhaseControl, || runner.solve())?;
        timing.record(
            EquilibriumTimingStage::ProjectionBuild,
            outcome.projection_build,
        );
        timing.record(
            EquilibriumTimingStage::ActiveSetFormulationBuild,
            outcome.formulation_build,
        );
        timing.record(
            EquilibriumTimingStage::RstPreparation,
            outcome.rst_preparation,
        );
        timing.record_rst_preparation_timing(outcome.rst_preparation_timing);
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );
        let timing_report = timing.finish();

        MultiphaseEquilibriumSolution::from_phase_control_parts(
            self.metadata,
            self.report,
            outcome.solution,
            outcome.solve_report,
            outcome.keq_validation_status,
            outcome.acceptance_report,
            outcome.phase_statuses,
            timing_report,
        )
        .map(|solution| solution.with_diagnostics(outcome.diagnostics))
    }
}

/// Fixed phase metadata paired with the prepared numerical P,T structure.
///
/// This is deliberately narrower than a temperature-range template: it does
/// not retain mutable closures or an RST payload, because monolithic P,H
/// evaluates thermochemistry from its own capability bundle at every iterate.
pub(crate) struct PreparedFixedActiveProblem {
    pub(crate) prepared: PreparedEquilibriumProblem,
    pub(crate) metadata: PhaseEquilibriumMetadata,
    pub(crate) report: PhaseEquilibriumBuildReport,
    pub(crate) timing: EquilibriumTimingReport,
}

/// Reusable fixed-layout formulation for typed temperature continuation.
///
/// This is deliberately crate-private: callers receive the smaller range
/// facade, while the bridge owns the invariant that all points share one
/// resolved layout and one conserved inventory.
pub(crate) struct PreparedPhaseEquilibriumTemplate {
    prepared:
        crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::PreparedEquilibriumProblem,
    metadata: PhaseEquilibriumMetadata,
    report: PhaseEquilibriumBuildReport,
    thermo_payloads: Vec<SubsData>,
    rst_problem: Option<RstPreparedProblem>,
    timing: EquilibriumTimingReport,
    /// The first point initializes the reusable parameterized RST graph.
    /// Later points only replace `T` and the numeric `G0` parameter vector.
    fixed_pt_parameters_initialized: bool,
    last_symbolic_parameter_reused: bool,
    last_formulation_build: Duration,
}

/// Reusable bounded phase-control formulation for a typed temperature range.
///
/// The fixed structural problem and the phase-control policy live here. The
/// runner carries the accepted active set between points, while the payloads
/// are refreshed into local Gibbs closures for the new temperature.
pub(crate) struct PreparedPhaseControlTemplate {
    runner: PreparedPhaseControlRunner,
    metadata: PhaseEquilibriumMetadata,
    report: PhaseEquilibriumBuildReport,
    thermo_payloads: Vec<SubsData>,
    timing: EquilibriumTimingReport,
    last_rst_symbolic_reused: bool,
    last_formulation_build: Duration,
}

impl PreparedPhaseControlTemplate {
    /// Selects diagnostics for the next independent range point.
    pub(crate) fn set_diagnostics_options(&mut self, diagnostics: EquilibriumDiagnosticsOptions) {
        self.runner.set_diagnostics_options(diagnostics);
    }

    pub(crate) fn build_timing(&self) -> EquilibriumTimingReport {
        self.timing
    }

    pub(crate) fn projection_cache_size(&self) -> usize {
        self.runner.projection_cache_size()
    }

    pub(crate) fn prepared_cache_size(&self) -> usize {
        self.runner.prepared_active_set_cache_size()
    }

    /// Number of reduced active-set entries retaining an RST symbolic
    /// problem. A bounded temperature sweep should grow this only when the
    /// phase-control active mask changes.
    pub(crate) fn rst_cache_size(&self) -> usize {
        self.runner.rst_prepared_cache_size()
    }

    /// TPD elemental-geometry cache evidence retained across accepted points.
    pub(crate) fn phase_stability_geometry_cache_statistics(
        &self,
    ) -> crate::Thermodynamics::ChemEquilibrium::equilibrium_phase_stability::PhaseStabilityGeometryCacheStats
{
        self.runner.phase_stability_geometry_cache_statistics()
    }

    /// Per-active-set formulation timing retained for range diagnostics.
    pub(crate) fn formulation_cache_timings(&self) -> Vec<(Vec<bool>, Duration)> {
        self.runner.prepared_active_set_cache_timings()
    }

    /// Whether the most recent bounded point reused an unchanged RST symbolic
    /// formulation for at least one active-set solve.
    pub(crate) fn last_rst_symbolic_reused(&self) -> bool {
        self.last_rst_symbolic_reused
    }

    /// Duration spent constructing reduced formulations during the most recent
    /// accepted range point. A zero value means the timing mode was disabled
    /// or every required active-set formulation was already cached.
    pub(crate) fn last_formulation_build(&self) -> Duration {
        self.last_formulation_build
    }

    /// Solves one point and returns the accepted bounded result. The caller
    /// must pass the previous accepted seed for every point after the first.
    pub(crate) fn solve_at(
        &mut self,
        conditions: EquilibriumConditions,
        seed: LogMolesInitialGuess,
        settings: EquilibriumSolverSettings,
        timing_mode: EquilibriumTimingMode,
        continuation_phase_set: Option<
            crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::PhaseSet,
        >,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
        let started = Instant::now();
        let mut timing = EquilibriumTimingCollector::new(timing_mode);
        let gibbs = refresh_gibbs_from_payloads(
            &mut self.thermo_payloads,
            &self.metadata,
            conditions.temperature(),
            &mut timing,
        )?;
        // Canonical RST fixed-P,T problems parameterize `G0_i`, so a range
        // point needs only refreshed numeric thermochemistry.
        self.runner
            .retarget_numeric(conditions, seed, gibbs.clone())?;
        if let Some(phase_set) = continuation_phase_set {
            self.runner.set_continuation_phase_set(phase_set)?;
        } else {
            // The first point is an independent solve. `retarget_numeric`
            // receives its numerical coordinate seed for formulation refresh,
            // but it must not turn that construction seed into physical
            // continuation before any state has been accepted.
            self.runner.clear_continuation_state();
        }
        *self.runner.configure_solver() = settings;
        let outcome =
            timing.measure(EquilibriumTimingStage::PhaseControl, || self.runner.solve())?;
        self.last_rst_symbolic_reused = outcome.rst_symbolic_reused;
        self.last_formulation_build = outcome.formulation_build;
        timing.record(
            EquilibriumTimingStage::ProjectionBuild,
            outcome.projection_build,
        );
        timing.record(
            EquilibriumTimingStage::ActiveSetFormulationBuild,
            outcome.formulation_build,
        );
        timing.record(
            EquilibriumTimingStage::RstPreparation,
            outcome.rst_preparation,
        );
        timing.record_rst_preparation_timing(outcome.rst_preparation_timing);
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );
        timing.set_total(started.elapsed());
        let report = self.report.at_conditions(conditions, &gibbs)?;
        MultiphaseEquilibriumSolution::from_phase_control_parts(
            self.metadata.clone(),
            report,
            outcome.solution,
            outcome.solve_report,
            outcome.keq_validation_status,
            outcome.acceptance_report,
            outcome.phase_statuses,
            timing.finish(),
        )
        .map(|solution| solution.with_diagnostics(outcome.diagnostics))
    }

    /// Consumes this phase-control template through a caller-supplied
    /// fixed-active candidate solver. The lifecycle remains identical to the
    /// ordinary bounded P,T path; the adapter may instead solve a coupled P,H
    /// formulation whose candidate owns its temperature.
    pub(crate) fn solve_with_fixed_active_solver<F>(
        mut self,
        settings: EquilibriumSolverSettings,
        mut solve_active_set: F,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError>
    where
        F: FnMut(
            &mut PreparedPhaseControlRunner,
            &[bool],
            &[f64],
            &[usize],
            &[f64],
        ) -> Result<
            crate::Thermodynamics::ChemEquilibrium::prepared_phase_control_runner::
                PreparedActiveSetCandidate,
            ReactionExtentError,
        >,
{
        let started = Instant::now();
        *self.runner.configure_solver() = settings;
        let outcome = self.runner.solve_with_fixed_active_solver(
            |runner, active, seed, species_phase, totals| {
                solve_active_set(runner, active, seed, species_phase, totals)
            },
        )?;
        self.last_rst_symbolic_reused = outcome.rst_symbolic_reused;
        let mut timing = EquilibriumTimingCollector::from_report(self.timing);
        timing.record(
            EquilibriumTimingStage::ProjectionBuild,
            outcome.projection_build,
        );
        timing.record(
            EquilibriumTimingStage::ActiveSetFormulationBuild,
            outcome.formulation_build,
        );
        timing.record(
            EquilibriumTimingStage::RstPreparation,
            outcome.rst_preparation,
        );
        timing.record_rst_preparation_timing(outcome.rst_preparation_timing);
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );
        timing.set_total(started.elapsed());
        let gibbs = refresh_gibbs_from_payloads(
            &mut self.thermo_payloads,
            &self.metadata,
            outcome.solution.conditions().temperature(),
            &mut timing,
        )?;
        let report = self
            .report
            .at_conditions(outcome.solution.conditions(), &gibbs)?;
        MultiphaseEquilibriumSolution::from_phase_control_parts(
            self.metadata,
            report,
            outcome.solution,
            outcome.solve_report,
            outcome.keq_validation_status,
            outcome.acceptance_report,
            outcome.phase_statuses,
            timing.finish(),
        )
        .map(|solution| solution.with_diagnostics(outcome.diagnostics))
    }
}

impl PreparedPhaseEquilibriumTemplate {
    /// Timing accumulated while the reusable formulation was first built.
    pub(crate) fn build_timing(&self) -> EquilibriumTimingReport {
        self.timing
    }

    /// Whether RST symbolic preparation was retained for parameter reuse.
    pub(crate) fn symbolic_problem_reused(&self) -> bool {
        self.rst_problem.is_some()
    }

    /// Whether the most recent point used an in-place symbolic `T` update.
    pub(crate) fn last_symbolic_parameter_reused(&self) -> bool {
        self.last_symbolic_parameter_reused
    }

    /// Duration spent rebuilding the symbolic formulation during the most
    /// recent accepted range point. Initial construction is reported by
    /// [`Self::build_timing`]; this value covers later interval/formulation
    /// rebuilds only.
    pub(crate) fn last_formulation_build(&self) -> Duration {
        self.last_formulation_build
    }

    /// Solves one point from a typed continuation seed.
    pub(crate) fn solve_at(
        &mut self,
        conditions: EquilibriumConditions,
        seed: LogMolesInitialGuess,
        settings: EquilibriumSolverSettings,
        timing_mode: EquilibriumTimingMode,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
        self.solve_at_with_seeds(conditions, vec![seed], settings, timing_mode)
    }

    /// Solves one retargeted point from deterministic candidates while
    /// reusing the phase layout and, when applicable, the prepared RST
    /// symbolic problem.
    ///
    /// This is intentionally crate-private: temperature-continuation and
    /// fixed-`P,H` workflows need the same multi-start recovery contract, but
    /// callers must not observe or mutate the reusable formulation itself.
    pub(crate) fn solve_at_with_initial_guesses(
        &mut self,
        conditions: EquilibriumConditions,
        seeds: Vec<LogMolesInitialGuess>,
        settings: EquilibriumSolverSettings,
        timing_mode: EquilibriumTimingMode,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
        self.solve_at_with_seeds(conditions, seeds, settings, timing_mode)
    }

    fn solve_at_with_seeds(
        &mut self,
        conditions: EquilibriumConditions,
        seeds: Vec<LogMolesInitialGuess>,
        settings: EquilibriumSolverSettings,
        timing_mode: EquilibriumTimingMode,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
        if seeds.is_empty() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "temperature_template_seeds",
                message: "at least one fixed-formulation seed is required".to_string(),
            });
        }
        // Retargeting needs one initial vector to instantiate the local
        // prepared problem. Candidate selection still receives every seed
        // below, preserving deterministic multi-start recovery.
        let retarget_seed = seeds[0].clone();
        let started = Instant::now();
        let mut timing = EquilibriumTimingCollector::new(timing_mode);
        let gibbs = refresh_gibbs_from_payloads(
            &mut self.thermo_payloads,
            &self.metadata,
            conditions.temperature(),
            &mut timing,
        )?;
        let prepared = self
            .prepared
            .retarget_with_gibbs(conditions, retarget_seed, gibbs)?;
        if let Some(rst_problem) = self.rst_problem.as_mut() {
            // The canonical fixed-P,T RST formulation owns `G0_i` as equation
            // parameters. Coefficient-interval changes therefore update only
            // numeric values, never its symbolic graph or Jacobian.
            rst_problem.set_fixed_pt_thermochemistry_from_prepared(&prepared)?;
            self.last_symbolic_parameter_reused = self.fixed_pt_parameters_initialized;
            self.fixed_pt_parameters_initialized = true;
        } else {
            self.last_symbolic_parameter_reused = false;
        }
        self.last_formulation_build = Duration::ZERO;
        let report = self
            .report
            .at_conditions(conditions, prepared.problem().gibbs())?;
        let mut runner = PreparedEquilibriumRunner::new_production(prepared)?
            .with_timing_enabled(self.timing.enabled());
        *runner.configure() = settings.clone();
        let outcome = timing.measure(EquilibriumTimingStage::NonlinearSolve, || {
            if seeds.len() == 1 {
                let seed = seeds.into_iter().next().ok_or_else(|| {
                    ReactionExtentError::InvalidProblem {
                        field: "temperature_template_seeds",
                        message: "fixed-formulation seed disappeared before solving".to_string(),
                    }
                })?;
                match self.rst_problem.as_ref() {
                    Some(rst_problem) => runner.solve_from_seed_with_rst(seed, rst_problem),
                    None => runner.solve_from_seed(seed),
                }
            } else {
                match self.rst_problem.as_ref() {
                    Some(rst_problem) => {
                        runner.solve_from_initial_guesses_with_rst(seeds, rst_problem)
                    }
                    None => runner.solve_from_initial_guesses(seeds),
                }
            }
        })?;
        timing.record(
            EquilibriumTimingStage::Validation,
            outcome.validation_duration,
        );
        timing.set_total(started.elapsed());

        let bundle = PhaseEquilibriumSolutionBundle {
            metadata: self.metadata.clone(),
            build_report: report,
            solution: outcome.solution,
            solve_report: outcome.solve_report,
            multi_start_report: outcome.multi_start_report,
            keq_validation_status: outcome.keq_validation_status,
            timing: timing.finish(),
        };
        bundle.into_multiphase_solution()
    }
}

/// Immutable accepted result of a phase-system equilibrium solve.
///
/// The result owns the same metadata and preparation report that produced the
/// numerical problem. This keeps phase-qualified identities, source
/// provenance, elemental totals, the accepted solution, and the backend trace
/// in one transactional publication unit.
#[derive(Debug, Clone, PartialEq)]
pub struct PhaseEquilibriumSolutionBundle {
    /// Phase-qualified layout and lookup provenance for this accepted result.
    metadata: PhaseEquilibriumMetadata,
    /// Immutable thermochemical preparation evidence for this accepted result.
    build_report: PhaseEquilibriumBuildReport,
    /// Accepted physical/log-mole solution in `SystemLayout` component order.
    solution: EquilibriumSolution,
    /// Ordered backend cascade evidence for the accepted result.
    solve_report: EquilibriumSolveReport,
    /// Optional explicit multi-start seed comparison evidence.
    multi_start_report: Option<MultiStartSolveReport>,
    /// Optional independent equilibrium-constant validation evidence.
    keq_validation_status: Option<EquilibriumConstantCrossValidationStatus>,
    /// Optional stage timing accumulated during the complete solve.
    timing: EquilibriumTimingReport,
}

impl PhaseEquilibriumSolutionBundle {
    /// Moves the accepted bundle payload into the public result builder.
    ///
    /// The bundle is consumed exactly once, so the immutable solution layer
    /// does not need to clone evidence that already has a single owner.
    pub(crate) fn into_parts(
        self,
    ) -> (
        PhaseEquilibriumMetadata,
        PhaseEquilibriumBuildReport,
        EquilibriumSolution,
        EquilibriumSolveReport,
        Option<MultiStartSolveReport>,
        Option<EquilibriumConstantCrossValidationStatus>,
        EquilibriumTimingReport,
    ) {
        (
            self.metadata,
            self.build_report,
            self.solution,
            self.solve_report,
            self.multi_start_report,
            self.keq_validation_status,
            self.timing,
        )
    }

    /// Phase-qualified layout and lookup provenance for this accepted result.
    pub fn metadata(&self) -> &PhaseEquilibriumMetadata {
        &self.metadata
    }

    /// Immutable thermochemical preparation evidence for this accepted result.
    pub fn build_report(&self) -> &PhaseEquilibriumBuildReport {
        &self.build_report
    }

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

    /// Accepted physical/log-mole solution in `SystemLayout` component order.
    pub fn solution(&self) -> &EquilibriumSolution {
        &self.solution
    }

    /// Ordered backend cascade evidence for the accepted result.
    pub fn solve_report(&self) -> &EquilibriumSolveReport {
        &self.solve_report
    }

    /// Explicit multi-start evidence, when the caller requested it.
    pub fn multi_start_report(&self) -> Option<&MultiStartSolveReport> {
        self.multi_start_report.as_ref()
    }

    /// Optional independent equilibrium-constant validation evidence.
    pub fn keq_validation_status(&self) -> Option<&EquilibriumConstantCrossValidationStatus> {
        self.keq_validation_status.as_ref()
    }

    /// Optional timing evidence accumulated by the canonical workflow.
    pub fn timing_report(&self) -> &EquilibriumTimingReport {
        &self.timing
    }

    /// Converts this accepted fixed-active-set result into the public
    /// phase-aware query model.
    pub fn into_multiphase_solution(
        self,
    ) -> Result<MultiphaseEquilibriumSolution, ReactionExtentError> {
        let timing_enabled = self.timing_report().enabled();
        let started = std::time::Instant::now();
        let solution = MultiphaseEquilibriumSolution::from_fixed_active_bundle(self)?;
        if timing_enabled {
            Ok(solution
                .with_timing_stage(EquilibriumTimingStage::Postprocessing, started.elapsed()))
        } else {
            Ok(solution)
        }
    }
}

/// Builds the canonical numerical equilibrium input from resolved phase data.
///
/// Every phase payload is cloned into a private working copy while extracting
/// `G0(T)` closures and elemental composition. The resolved phase system stays
/// immutable, and no bundle is returned until all components, provenance rows,
/// element coefficients, and fixed-temperature standard-state values validate.
pub fn build_phase_equilibrium_problem(
    request: PhaseEquilibriumBuildRequest<'_>,
) -> Result<PhaseEquilibriumProblemBundle, ReactionExtentError> {
    build_phase_equilibrium_problem_with_timing(request, EquilibriumTimingMode::Disabled)
}

/// Internal bridge builder with optional stage timing for the canonical facade.
pub(crate) fn build_phase_equilibrium_problem_with_timing(
    request: PhaseEquilibriumBuildRequest<'_>,
    timing_mode: EquilibriumTimingMode,
) -> Result<PhaseEquilibriumProblemBundle, ReactionExtentError> {
    record_phase_equilibrium_build();
    let started = Instant::now();
    let mut timing = EquilibriumTimingCollector::new(timing_mode);
    let metadata = request.metadata.clone();
    let conditions = request.conditions;
    let mut phase_data = HashMap::with_capacity(metadata.phases().len());
    let mut thermo_payloads = Vec::with_capacity(metadata.phases().len());
    let mut all_elements = BTreeSet::new();

    for phase in metadata.phases() {
        let payload = request
            .resolved
            .phase_data()
            .get(phase.id().as_option())
            .ok_or_else(|| ReactionExtentError::InvalidProblem {
                field: "resolved_phase_data",
                message: format!(
                    "missing data payload for phase {:?}",
                    phase.id().as_option()
                ),
            })?;
        thermo_payloads.push(payload.clone());
        let prepared =
            prepare_phase_thermochemistry(payload, request.conditions.temperature(), &mut timing)?;
        all_elements.extend(
            prepared
                .element_compositions
                .values()
                .flat_map(|composition| composition.keys().cloned()),
        );
        phase_data.insert(phase.id().clone(), prepared);
    }

    if all_elements.is_empty() {
        return Err(ReactionExtentError::InvalidProblem {
            field: "element_composition",
            message: "resolved phase system contains no elemental composition".to_string(),
        });
    }
    let element_labels = all_elements.into_iter().collect::<Vec<_>>();
    let component_count = metadata.components().len();
    let mut element_composition = DMatrix::zeros(component_count, element_labels.len());
    let mut gibbs = Vec::with_capacity(component_count);
    #[cfg(test)]
    let mut symbolic_standard_gibbs = Vec::with_capacity(component_count);
    let mut component_reports = Vec::with_capacity(component_count);
    let mut composition_by_substance = HashMap::<String, HashMap<String, f64>>::new();

    for (index, component) in metadata.components().iter().enumerate() {
        let phase = phase_data.get(&component.id().phase).ok_or_else(|| {
            ReactionExtentError::InvalidProblem {
                field: "resolved_phase_data",
                message: format!(
                    "missing prepared phase data for component '{}'",
                    component.label()
                ),
            }
        })?;
        let composition = phase
            .element_compositions
            .get(component.substance())
            .ok_or_else(|| ReactionExtentError::InvalidProblem {
                field: "element_composition",
                message: format!(
                    "missing elemental composition for component '{}'",
                    component.label()
                ),
            })?;

        if let Some(reference) = composition_by_substance.get(component.substance()) {
            if reference != composition {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "element_composition",
                    message: format!(
                        "component '{}' has a molecular composition inconsistent with another phase record",
                        component.substance()
                    ),
                });
            }
        } else {
            composition_by_substance.insert(component.substance().to_string(), composition.clone());
        }

        for (element_index, element) in element_labels.iter().enumerate() {
            element_composition[(index, element_index)] =
                composition.get(element).copied().unwrap_or(0.0);
        }

        let thermo_source = thermo_source_for(&metadata, component)?;
        let function = phase
            .gibbs_functions
            .get(component.substance())
            .ok_or_else(|| ReactionExtentError::InvalidProblem {
                field: "standard_gibbs",
                message: format!(
                    "missing standard Gibbs function for component '{}' from {}:{}",
                    component.label(),
                    thermo_source.library(),
                    thermo_source.record_key()
                ),
            })?;
        let standard_gibbs_at_conditions = function(conditions.temperature());
        if !standard_gibbs_at_conditions.is_finite() {
            return Err(ReactionExtentError::InvalidProblem {
                field: "standard_gibbs",
                message: format!(
                    "component '{}' from {}:{} returned non-finite G0 at {} K",
                    component.label(),
                    thermo_source.library(),
                    thermo_source.record_key(),
                    conditions.temperature()
                ),
            });
        }

        let function = std::sync::Arc::clone(function);
        gibbs.push(Rc::new(move |temperature: f64| function(temperature)) as GibbsFn);
        #[cfg(test)]
        {
            let symbolic = phase
                .symbolic_gibbs_functions
                .get(component.substance())
                .ok_or_else(|| ReactionExtentError::InvalidProblem {
                    field: "symbolic_standard_gibbs",
                    message: format!(
                        "missing symbolic standard Gibbs expression for component '{}' from {}:{}",
                        component.label(),
                        thermo_source.library(),
                        thermo_source.record_key()
                    ),
                })?;
            symbolic_standard_gibbs.push(symbolic.clone());
        }
        component_reports.push(EquilibriumBridgeComponentReport {
            component: component.clone(),
            // Filled after the complete real-component matrix has been built.
            // Element-defined inputs require that matrix before a feasible
            // numerical seed can be constructed.
            initial_moles: 0.0,
            standard_gibbs_at_conditions,
            thermo_source,
        });
    }

    let (initial_moles, element_totals, input_kind, seed_evidence) = match &request.physical_input {
        PhaseEquilibriumPhysicalInput::Composition(composition) => {
            let initial_moles = composition.moles().to_vec();
            let totals = compute_element_totals(&element_composition, &initial_moles)?
                .iter()
                .copied()
                .collect::<Vec<_>>();
            let inventory_scale = totals.iter().copied().fold(0.0_f64, f64::max);
            let balance = max_element_balance_error(&totals, &totals);
            (
                initial_moles,
                totals,
                PhaseEquilibriumInputKind::ExplicitComposition,
                PhaseEquilibriumSeedEvidence {
                    source: PhaseEquilibriumSeedSource::ExplicitComposition,
                    inventory_scale,
                    achieved_minimum_fraction: None,
                    max_element_balance_error: balance,
                },
            )
        }
        PhaseEquilibriumPhysicalInput::ElementInventory {
            inventory,
            numerical_seed,
        } => {
            let totals = inventory.aligned_to(&element_labels)?;
            let (seed, source, achieved_minimum_fraction, max_element_balance_error) =
                match numerical_seed {
                    Some(seed) => {
                        let seed_moles = seed.moles().to_vec();
                        let reconstructed =
                            compute_element_totals(&element_composition, &seed_moles)?;
                        for (element, (actual, expected)) in
                            reconstructed.iter().zip(totals.iter()).enumerate()
                        {
                            let tolerance = 1.0e-8 * expected.abs().max(1.0);
                            if (actual - expected).abs() > tolerance {
                                return Err(ReactionExtentError::InvalidProblem {
                                    field: "numerical_seed",
                                    message: format!(
                                        "seed does not preserve element '{}' (expected {expected:e}, got {actual:e})",
                                        element_labels[element]
                                    ),
                                });
                            }
                        }
                        (
                            seed_moles,
                            PhaseEquilibriumSeedSource::SuppliedNumericalSeed,
                            None,
                            max_element_balance_error(reconstructed.as_slice(), &totals),
                        )
                    }
                    None => {
                        let seed = build_element_feasible_seed(
                            &element_composition,
                            &totals,
                            ElementFeasibleSeedSettings::default(),
                        )?;
                        (
                            seed.physical_moles().to_vec(),
                            PhaseEquilibriumSeedSource::ElementFeasibleProjection,
                            Some(seed.achieved_minimum_fraction()),
                            seed.max_element_balance_error(),
                        )
                    }
                };
            let inventory_scale = totals.iter().copied().fold(0.0_f64, f64::max);
            (
                seed,
                totals,
                PhaseEquilibriumInputKind::ElementInventory,
                PhaseEquilibriumSeedEvidence {
                    source,
                    inventory_scale,
                    achieved_minimum_fraction,
                    max_element_balance_error,
                },
            )
        }
    };
    let initial_log_moles =
        LogMolesInitialGuess::from_moles_with_policy(&initial_moles, request.trace_seed_policy)?;
    for (report, initial_moles) in component_reports.iter_mut().zip(&initial_moles) {
        report.initial_moles = *initial_moles;
    }
    let independent_element_columns = deterministic_element_basis(&element_composition, 1e-6)?;
    let solver_element_labels = independent_element_columns
        .iter()
        .map(|&column| element_labels[column].clone())
        .collect::<Vec<_>>();
    let solver_element_composition = DMatrix::from_fn(
        component_count,
        independent_element_columns.len(),
        |row, column| element_composition[(row, independent_element_columns[column])],
    );
    let solver_element_totals = independent_element_columns
        .iter()
        .map(|&column| element_totals[column])
        .collect::<Vec<_>>();
    let problem = timing.measure(EquilibriumTimingStage::EquationConstruction, || {
        EquilibriumProblem::new_with_phase_descriptors(
            metadata.components().to_vec(),
            initial_moles,
            initial_log_moles,
            solver_element_composition,
            gibbs,
            metadata.phases().to_vec(),
            conditions,
        )
        .and_then(|problem| problem.with_conserved_element_totals(solver_element_totals))
    })?;
    let report = PhaseEquilibriumBuildReport {
        conditions,
        lookup_report: metadata.provenance().clone(),
        layout_fingerprint: metadata.layout_fingerprint(),
        input_kind,
        trace_seed_policy: request.trace_seed_policy,
        seed_evidence,
        element_labels,
        element_totals,
        solver_element_labels,
        components: component_reports,
        candidate_selection: request.candidate_selection.clone(),
    };

    timing.set_total(started.elapsed());
    Ok(PhaseEquilibriumProblemBundle {
        problem,
        metadata,
        report,
        #[cfg(test)]
        symbolic_standard_gibbs,
        thermo_payloads,
        timing: timing.finish(),
    })
}

#[derive(Clone)]
struct PreparedPhaseThermochemistry {
    gibbs_functions: HashMap<String, std::sync::Arc<dyn Fn(f64) -> f64 + Send + Sync>>,
    #[cfg(test)]
    symbolic_gibbs_functions: HashMap<String, Expr>,
    element_compositions: HashMap<String, HashMap<String, f64>>,
}

fn prepare_phase_thermochemistry(
    resolved_payload: &SubsData,
    temperature: f64,
    timing: &mut EquilibriumTimingCollector,
) -> Result<PreparedPhaseThermochemistry, ReactionExtentError> {
    let mut working = resolved_payload.clone();
    // Parsing exposes every polynomial range, but closure construction reads
    // the calculator's currently selected coefficient interval. Select that
    // interval at the fixed solve temperature before snapshotting G0; otherwise
    // a freshly resolved NASA record still carries its zero-initialized
    // coefficient tuple and silently publishes G0(T) = 0.
    timing.measure(EquilibriumTimingStage::ThermochemistryPreparation, || {
        working.extract_all_thermal_coeffs(temperature)
    })?;
    let gibbs_functions = timing
        .measure(EquilibriumTimingStage::NumericClosureConstruction, || {
            working.calculate_dG0_fun_one_phase_in_place()
        })?;
    #[cfg(test)]
    let symbolic_gibbs_functions = timing
        .measure(EquilibriumTimingStage::SymbolicConstruction, || {
            working.calculate_dG0_sym_one_phase()
        })?;
    let (_, compositions, _) = timing
        .measure(EquilibriumTimingStage::ThermochemistryPreparation, || {
            SubsData::calculate_elem_composition_and_molar_mass_local(&mut working, None)
        })?;
    if compositions.len() != working.substances().len() {
        return Err(ReactionExtentError::DimensionMismatch(format!(
            "phase thermochemistry produced {} compositions for {} substances",
            compositions.len(),
            working.substances().len()
        )));
    }

    let mut element_compositions = HashMap::with_capacity(compositions.len());
    for (substance, composition) in working.substances().iter().cloned().zip(compositions) {
        if element_compositions
            .insert(substance.clone(), composition)
            .is_some()
        {
            return Err(ReactionExtentError::InvalidProblem {
                field: "phase_thermochemistry",
                message: format!("duplicate local substance '{substance}'"),
            });
        }
    }

    Ok(PreparedPhaseThermochemistry {
        gibbs_functions: gibbs_functions
            .into_iter()
            .map(|(substance, function)| {
                (
                    substance,
                    std::sync::Arc::from(function)
                        as std::sync::Arc<dyn Fn(f64) -> f64 + Send + Sync>,
                )
            })
            .collect(),
        #[cfg(test)]
        symbolic_gibbs_functions,
        element_compositions,
    })
}

/// Refreshes phase-local thermochemistry and returns closures in canonical
/// component order. Only the private working payloads are mutated; resolved
/// repository data remains untouched across temperature-range points.
fn refresh_gibbs_from_payloads(
    thermo_payloads: &mut [SubsData],
    metadata: &PhaseEquilibriumMetadata,
    temperature: f64,
    timing: &mut EquilibriumTimingCollector,
) -> Result<Vec<GibbsFn>, ReactionExtentError> {
    let mut phase_functions = Vec::with_capacity(thermo_payloads.len());
    for payload in thermo_payloads {
        timing.measure(EquilibriumTimingStage::ThermochemistryPreparation, || {
            payload.extract_all_thermal_coeffs(temperature)
        })?;
        let functions = timing
            .measure(EquilibriumTimingStage::NumericClosureConstruction, || {
                payload.calculate_dG0_fun_one_phase_in_place()
            })?;
        phase_functions.push(
            functions
                .into_iter()
                .map(|(substance, function)| {
                    (
                        substance,
                        std::sync::Arc::from(function)
                            as std::sync::Arc<dyn Fn(f64) -> f64 + Send + Sync>,
                    )
                })
                .collect::<HashMap<_, _>>(),
        );
    }

    metadata
        .components()
        .iter()
        .map(|component| {
            let phase_index = metadata
                .phase_index(&component.id().phase)
                .ok_or_else(|| ReactionExtentError::InvalidProblem {
                    field: "temperature_range_phase",
                    message: format!("missing phase for component '{}'", component.label()),
                })?
                .index();
            let function = phase_functions
                .get(phase_index)
                .and_then(|functions| functions.get(component.substance()))
                .ok_or_else(|| ReactionExtentError::InvalidProblem {
                    field: "temperature_range_gibbs",
                    message: format!("missing Gibbs closure for '{}'", component.label()),
                })?;
            let function = std::sync::Arc::clone(function);
            Ok(Rc::new(move |temperature: f64| function(temperature)) as GibbsFn)
        })
        .collect()
}

fn thermo_source_for(
    metadata: &PhaseEquilibriumMetadata,
    component: &EquilibriumComponentDescriptor,
) -> Result<SearchSummaryRow, ReactionExtentError> {
    metadata
        .provenance()
        .phase(&component.id().phase)
        .and_then(|phase| {
            phase.search().rows().iter().find(|row| {
                row.substance() == component.substance()
                    && row.property() == "Thermo"
                    && row.state() == "Found"
            })
        })
        .cloned()
        .ok_or_else(|| ReactionExtentError::InvalidProblem {
            field: "thermochemical_provenance",
            message: format!(
                "component '{}' has no resolved thermochemical provenance row",
                component.label()
            ),
        })
}

/// Largest absolute conservation residual for one physical mole vector.
///
/// Kept beside bridge construction rather than the nonlinear validation layer:
/// it characterizes a pre-solver seed and must not imply that the seed itself
/// was accepted equilibrium output.
fn max_element_balance_error(actual_totals: &[f64], totals: &[f64]) -> f64 {
    actual_totals
        .iter()
        .zip(totals)
        .map(|(actual, expected)| (actual - expected).abs())
        .fold(0.0_f64, f64::max)
}

/// Selects a deterministic independent element-column basis for fixed-phase
/// bridge problems.
///
/// A system may declare both H and O while every present component is H2O.
/// Those columns represent the same closed-system direction and make the raw
/// log-moles equations overdetermined. The first columns that raise SVD rank
/// are retained for the solver; the full matrix and totals stay in the report.
fn deterministic_element_basis(
    element_composition: &DMatrix<f64>,
    tolerance: f64,
) -> Result<Vec<usize>, ReactionExtentError> {
    if !tolerance.is_finite() || tolerance <= 0.0 {
        return Err(ReactionExtentError::InvalidProblem {
            field: "element_basis",
            message: "rank tolerance must be finite and positive".to_owned(),
        });
    }
    let full_rank = SVD::new(element_composition.clone(), false, false)
        .singular_values
        .iter()
        .filter(|&&value| value > tolerance)
        .count();
    if full_rank == 0 {
        return Err(ReactionExtentError::InvalidProblem {
            field: "element_basis",
            message: "element composition has no independent conservation direction".to_owned(),
        });
    }

    independent_column_basis(element_composition, full_rank, tolerance, "element_basis")
}

fn activity_model_for(model: PhaseModel) -> PhaseActivityModel {
    match model {
        PhaseModel::IdealGas => PhaseActivityModel::IdealGas,
        PhaseModel::IdealSolution => PhaseActivityModel::IdealSolution,
        PhaseModel::PureCondensed => PhaseActivityModel::IdealSolution,
    }
}