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
//! Fixed-active-set monolithic `P,H` nonlinear runner.
//!
//! The runner solves `[ln(n_1), ..., ln(n_m), theta_T]` in one nonlinear
//! system. It deliberately owns no phase lifecycle: activation, destruction,
//! hysteresis, and transactional publication stay at the phase-control
//! boundary. This separation lets the numerical formulation be tested without
//! mutating a broader multiphase workflow.
//!
//! RustedSciThe backends receive a dedicated symbolic `(ln(n), theta_T)`
//! payload. The retained native solvers consume the independently implemented
//! analytical Jacobian from `equilibrium_ph_formulation`, which remains a
//! valuable validation and fallback route.

use std::cell::Cell;
#[cfg(not(feature = "equilibrium-benchmark-no-trial-cache"))]
use std::cell::RefCell;
use std::time::{Duration, Instant};

use nalgebra::DMatrix;

use crate::Thermodynamics::ChemEquilibrium::equilibrium_active_set::ActiveSetProjection;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_backend_adapter::{
    EquilibriumNonlinearBackend, solve_backend_cascade_with_control_and_telemetry,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::{
    EnthalpyScale, TemperatureBounds,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ids::PhaseIndex;
#[cfg(not(feature = "equilibrium-benchmark-no-trial-cache"))]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::record_residual_evaluation;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::rst_solver_telemetry_mode;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::EquilibriumSolverSettings;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::PhMonolithicSeedFailure;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::ReactionExtentError;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_formulation::{
    PhCandidateSnapshot, PreparedPhFormulation,
};
#[cfg(test)]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_options::{
    PhAcceptanceOptions, PhMonolithicSeedPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_options::{
    PhMonolithicOptions, PhMonolithicSeedAttemptReport, PhMonolithicSeedRecoveryReport,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_thermochemistry::ResolvedThermochemistry;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
    EquilibriumConditions, EquilibriumProblem, LogMolesInitialGuess, PreparedEquilibriumProblem,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::prepare_rst_symbolic_ph_problem_with_timing;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
    EquilibriumSolveReport, SolverBackend, SolverCascadeBudget, SolverPolicy,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::{
    EquilibriumTimingMode, RstPreparationTimingReport,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_validation::{
    EquilibriumAcceptanceCriteria, EquilibriumCandidateReport, EquilibriumCandidateResiduals,
    validate_equilibrium_candidate,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{
    PhaseTotalSeedPolicy, seed_activated_phase_with_composition,
};
use crate::Thermodynamics::ChemEquilibrium::prepared_phase_control_runner::{
    PreparedActiveSetCandidate, PreparedPhaseControlRunner, PreparedStabilityGibbs,
};

/// Accepted fixed-active-set monolithic P,H candidate.
// This is intentionally wider than the first runner consumer. The facade
// will need the original unknowns and P,T validation evidence when it starts
// publishing a unified nested/monolithic diagnostic report.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) struct MonolithicPhSolveOutcome {
    /// Full nonlinear coordinate `[ln(n), theta_T]` accepted by the backend cascade.
    pub(crate) unknowns: Vec<f64>,
    /// Physical values and residuals evaluated at the accepted coordinate.
    pub(crate) snapshot: PhCandidateSnapshot,
    /// Common fixed-P,T conservation and affinity validation report.
    pub(crate) pt_validation: EquilibriumCandidateReport,
    /// Deterministic record of attempted numerical backends.
    pub(crate) solve_report: EquilibriumSolveReport,
    /// Ordered physical-temperature starts attempted before acceptance.
    pub(crate) temperature_seed_report: PhMonolithicSeedRecoveryReport,
    /// Time spent materializing an RST symbolic payload for this accepted
    /// seed. Zero when the selected policy does not need RST or timing is off.
    pub(crate) rst_preparation: Duration,
    /// Fine-grained RST symbolic/problem preparation evidence.
    pub(crate) rst_preparation_timing: RstPreparationTimingReport,
    /// Wall-clock time spent in the backend cascade after payload preparation.
    pub(crate) backend_execution: Duration,
    /// Time spent validating candidate snapshots produced by the cascade.
    pub(crate) validation_duration: Duration,
}

/// Immutable numerical runner for one already fixed active phase set.
#[derive(Clone)]
pub(crate) struct PreparedMonolithicPhRunner {
    formulation: PreparedPhFormulation,
    settings: EquilibriumSolverSettings,
    options: PhMonolithicOptions,
    timing_enabled: bool,
}

impl PreparedMonolithicPhRunner {
    /// Creates a runner after validating common solver and enthalpy controls.
    pub(crate) fn new(
        formulation: PreparedPhFormulation,
        settings: EquilibriumSolverSettings,
        options: PhMonolithicOptions,
    ) -> Result<Self, ReactionExtentError> {
        settings.validate()?;
        Ok(Self {
            formulation,
            settings,
            options,
            timing_enabled: false,
        })
    }

    /// Enables optional substage timing without changing the default runner
    /// contract or adding clock reads to ordinary production solves.
    pub(crate) fn with_timing_enabled(mut self, enabled: bool) -> Self {
        self.timing_enabled = enabled;
        self
    }

    /// Solves the coupled composition-temperature equations from one physical
    /// temperature seed. No state is published on failure.
    pub(crate) fn solve_from_temperature_seed(
        &self,
        temperature_seed: f64,
    ) -> Result<MonolithicPhSolveOutcome, ReactionExtentError> {
        let temperatures = self
            .formulation
            .temperature_seed_candidates(temperature_seed, self.options.seed_policy())?;
        self.solve_from_temperature_candidates(temperatures, None, |temperature| {
            self.formulation.initial_unknowns(temperature)
        })
    }

    /// Solves from an accepted `[log-moles, temperature]` continuation state.
    /// An optional prepared RST problem is reused when supplied; legacy
    /// backends continue to use the same analytical formulation.
    pub(crate) fn solve_from_log_moles_and_temperature_seed(
        &self,
        log_moles: &crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::
            LogMolesInitialGuess,
        temperature_seed: f64,
        rst_problem: Option<
            &crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstPreparedProblem,
        >,
    ) -> Result<MonolithicPhSolveOutcome, ReactionExtentError> {
        let temperatures = self
            .formulation
            .temperature_seed_candidates(temperature_seed, self.options.seed_policy())?;
        self.solve_from_temperature_candidates(temperatures, rst_problem, |temperature| {
            self.formulation
                .initial_unknowns_from_log_moles(log_moles, temperature)
        })
    }

    /// Executes fresh backend cascades from ordered temperature starts and
    /// stops at the first candidate accepted by the common physical gate.
    fn solve_from_temperature_candidates<F>(
        &self,
        temperatures: Vec<f64>,
        rst_problem: Option<
            &crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstPreparedProblem,
        >,
        mut build_unknowns: F,
    ) -> Result<MonolithicPhSolveOutcome, ReactionExtentError>
    where
        F: FnMut(f64) -> Result<Vec<f64>, ReactionExtentError>,
    {
        let policy = self.options.seed_policy();
        let total = temperatures.len();
        let mut attempts = Vec::with_capacity(total);
        let mut failures = Vec::with_capacity(total);
        for (start_index, temperature_seed_k) in temperatures.into_iter().enumerate() {
            let initial_unknowns = build_unknowns(temperature_seed_k)?;
            match self.solve_from_initial_unknowns(initial_unknowns, rst_problem) {
                Ok(mut outcome) => {
                    attempts.push(PhMonolithicSeedAttemptReport {
                        temperature_seed_k,
                        accepted: true,
                        failure_kind: None,
                        error: None,
                        started_backend_attempts: outcome.solve_report.started_attempt_count(),
                        nonlinear_iterations: outcome.solve_report.nonlinear_iterations(),
                    });
                    outcome.temperature_seed_report = PhMonolithicSeedRecoveryReport {
                        policy,
                        attempts,
                        selected_attempt: start_index,
                    };
                    return Ok(outcome);
                }
                Err(error) => {
                    let retryable = error.is_retryable_formulation_failure();
                    attempts.push(PhMonolithicSeedAttemptReport {
                        temperature_seed_k,
                        accepted: false,
                        failure_kind: Some(error.kind()),
                        error: Some(error.to_string()),
                        started_backend_attempts: error.started_backend_attempts(),
                        nonlinear_iterations: error.nonlinear_iterations(),
                    });
                    if !retryable {
                        return Err(error);
                    }
                    failures.push(PhMonolithicSeedFailure::new(temperature_seed_k, error));
                    if start_index + 1 == total {
                        if failures.len() == 1 {
                            return Err(failures.pop().expect("one seed failure").into_cause());
                        }
                        return Err(ReactionExtentError::PhMonolithicSeedRecoveryFailed {
                            attempts: failures,
                        });
                    }
                }
            }
        }
        unreachable!("validated monolithic seed policy always produces one candidate")
    }

    /// Core dispatch for the monolithic `[log-moles, theta_T]` unknown vector.
    ///
    /// Resolves the solver policy and cascade budget, then delegates to the
    /// common backend adapter. The optional RST symbolic problem is forwarded
    /// when the policy selects a RustedSciThe backend; native backends receive
    /// the analytical formulation from [`PhFormulation`].
    fn solve_from_initial_unknowns(
        &self,
        initial_unknowns: Vec<f64>,
        prepared_rst_problem: Option<
            &crate::Thermodynamics::ChemEquilibrium::equilibrium_rst_backend::RstPreparedProblem,
        >,
    ) -> Result<MonolithicPhSolveOutcome, ReactionExtentError> {
        let policy = self.monolithic_policy()?;
        let backends = policy.ordered_backends();
        let budget = self.settings.solver_budget.unwrap_or_else(|| {
            SolverCascadeBudget::new(
                backends.len(),
                self.settings.solver_params.max_iter,
                self.settings
                    .solver_params
                    .max_iter
                    .saturating_mul(backends.len()),
            )
        });
        let backend_refs: Vec<&dyn EquilibriumNonlinearBackend> = backends
            .iter()
            .map(|backend| backend as &dyn EquilibriumNonlinearBackend)
            .collect();
        let owned_rst_problem = if prepared_rst_problem.is_none()
            && backends
                .iter()
                .any(|backend| matches!(backend, SolverBackend::RustedSciThe(_)))
        {
            let started = self.timing_enabled.then(Instant::now);
            let timing_mode = if self.timing_enabled {
                EquilibriumTimingMode::Enabled
            } else {
                EquilibriumTimingMode::Disabled
            };
            let (problem, preparation_report) = prepare_rst_symbolic_ph_problem_with_timing(
                &self.formulation,
                timing_mode,
                self.settings.rst_symbolic_frontend,
            )?;
            let elapsed = started.map_or(Duration::ZERO, |started| started.elapsed());
            Some((
                problem,
                elapsed,
                preparation_report.rst_preparation_timing(),
            ))
        } else {
            None
        };
        let rst_preparation = owned_rst_problem
            .as_ref()
            .map_or(Duration::ZERO, |(_, elapsed, _)| *elapsed);
        let rst_preparation_timing = owned_rst_problem
            .as_ref()
            .map_or_else(RstPreparationTimingReport::default, |(_, _, timing)| {
                *timing
            });
        let owned_rst_problem = owned_rst_problem.map(|(problem, _, _)| problem);
        let rst_problem = prepared_rst_problem.or(owned_rst_problem.as_ref());
        #[cfg(not(feature = "equilibrium-benchmark-no-trial-cache"))]
        let feasible_trial_snapshot = RefCell::new(None::<(Vec<f64>, PhCandidateSnapshot)>);
        #[cfg(not(feature = "equilibrium-benchmark-no-trial-cache"))]
        let residual = |unknowns: &[f64]| {
            let cached = feasible_trial_snapshot.borrow_mut().take();
            if let Some((cached_unknowns, snapshot)) = cached {
                if cached_unknowns.as_slice() == unknowns {
                    record_residual_evaluation();
                    let mut residual = snapshot.scaled_pt_residual;
                    residual.push(snapshot.scaled_enthalpy_error);
                    return Ok(residual);
                }
            }
            self.formulation.residual(unknowns)
        };
        #[cfg(feature = "equilibrium-benchmark-no-trial-cache")]
        let residual = |unknowns: &[f64]| self.formulation.residual(unknowns);
        let jacobian = |unknowns: &[f64]| self.formulation.jacobian(unknowns);
        #[cfg(not(feature = "equilibrium-benchmark-no-trial-cache"))]
        let feasible = |unknowns: &[f64]| {
            let Some(snapshot) = self.formulation.feasible_candidate_snapshot(unknowns) else {
                feasible_trial_snapshot.borrow_mut().take();
                return false;
            };
            *feasible_trial_snapshot.borrow_mut() = Some((unknowns.to_vec(), snapshot));
            true
        };
        #[cfg(feature = "equilibrium-benchmark-no-trial-cache")]
        let feasible = |unknowns: &[f64]| self.formulation.is_feasible(unknowns);
        let solver_tolerance = self.settings.solver_params.tol;
        let element_tolerance = 10.0 * solver_tolerance.max(1.0e-8);
        let candidate_validation_duration = Cell::new(Duration::ZERO);
        let validate_candidate = |unknowns: &[f64]| {
            let started = self.timing_enabled.then(Instant::now);
            let result = (|| {
                let snapshot = self.formulation.candidate_snapshot(unknowns)?;
                let validation = validate_equilibrium_candidate(
                    EquilibriumCandidateResiduals {
                        log_moles: &snapshot.log_moles,
                        raw_residual: &snapshot.raw_pt_residual,
                        acceptance_residual: &snapshot.scaled_pt_residual,
                    },
                    EquilibriumAcceptanceCriteria::new(
                        solver_tolerance,
                        element_tolerance,
                        solver_tolerance,
                    )?
                    .with_element_balance_relative_tolerance(element_tolerance)?,
                    self.formulation
                        .prepared_pt()
                        .problem()
                        .element_composition(),
                    self.formulation.prepared_pt().element_totals(),
                )?;
                if !self.options.acceptance().accepts_enthalpy_error(
                    snapshot.enthalpy_error,
                    self.formulation.enthalpy_scale(),
                ) {
                    return Err(ReactionExtentError::InvalidCandidate {
                        field: "candidate_enthalpy",
                        message: format!(
                            "enthalpy error {} J exceeds the P,H acceptance limit",
                            snapshot.enthalpy_error
                        ),
                    });
                }
                Ok(validation)
            })();
            if let Some(started) = started {
                candidate_validation_duration
                    .set(candidate_validation_duration.get() + started.elapsed());
            }
            result
        };
        let backend_started = self.timing_enabled.then(Instant::now);
        let (unknowns, pt_validation, solve_report) =
            solve_backend_cascade_with_control_and_telemetry(
                &backend_refs,
                initial_unknowns,
                &residual,
                Some(&jacobian as &dyn Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>),
                &feasible,
                &validate_candidate,
                policy,
                budget,
                &self.settings.solver_params,
                rst_problem,
                None,
                rst_solver_telemetry_mode(self.timing_enabled),
            )?;
        let backend_execution = backend_started.map_or(Duration::ZERO, |started| started.elapsed());
        let snapshot = self.formulation.candidate_snapshot(&unknowns)?;
        Ok(MonolithicPhSolveOutcome {
            unknowns,
            snapshot,
            pt_validation,
            solve_report,
            temperature_seed_report: PhMonolithicSeedRecoveryReport {
                policy: self.options.seed_policy(),
                attempts: Vec::new(),
                selected_attempt: 0,
            },
            rst_preparation,
            rst_preparation_timing,
            backend_execution,
            validation_duration: candidate_validation_duration.get(),
        })
    }

    /// Resolves the effective solver policy for the monolithic `P,H` runner.
    ///
    /// Returns the explicit policy when one has been installed, or falls back
    /// to [`SolverPolicy::native_default`] using the preferred native backend.
    /// This keeps the monolithic path consistent with the fixed-`P,T` cascade
    /// contract without requiring every caller to supply a policy.
    fn monolithic_policy(&self) -> Result<SolverPolicy, ReactionExtentError> {
        let policy = self
            .settings
            .solver_policy
            .clone()
            .unwrap_or_else(|| SolverPolicy::native_default(self.settings.solver));
        Ok(policy)
    }
}

/// Solves one active mask for the shared phase-control lifecycle.
///
/// The callback boundary deliberately carries only a fixed active mask and a
/// log-mole restart seed. It projects the numerical problem and the resolved
/// thermochemistry together, so component order cannot drift between the
/// conservation matrix, Gibbs functions, enthalpy, or Cp. The full candidate
/// returned to the lifecycle contains Gibbs capabilities at the solved
/// temperature for phase-stability decisions.
#[cfg(test)]
pub(crate) fn solve_monolithic_active_set_candidate(
    runner: &mut PreparedPhaseControlRunner,
    active: &[bool],
    full_seed: &[f64],
    species_phase: &[usize],
    full_element_totals: &[f64],
    thermochemistry: &ResolvedThermochemistry,
    temperature_bounds: TemperatureBounds,
    target_enthalpy: f64,
    enthalpy_scale: EnthalpyScale,
    temperature_seed: &mut f64,
    monolithic_options: &PhMonolithicOptions,
) -> Result<PreparedActiveSetCandidate, ReactionExtentError> {
    solve_monolithic_active_set_candidate_with_seed_report(
        runner,
        active,
        full_seed,
        species_phase,
        full_element_totals,
        thermochemistry,
        temperature_bounds,
        target_enthalpy,
        enthalpy_scale,
        temperature_seed,
        monolithic_options,
    )
    .map(|(candidate, _)| candidate)
}

/// Variant used by the production P,H facade to retain seed-recovery
/// evidence without coupling the generic phase-control runner to P,H types.
pub(crate) fn solve_monolithic_active_set_candidate_with_seed_report(
    runner: &mut PreparedPhaseControlRunner,
    active: &[bool],
    full_seed: &[f64],
    species_phase: &[usize],
    full_element_totals: &[f64],
    thermochemistry: &ResolvedThermochemistry,
    temperature_bounds: TemperatureBounds,
    target_enthalpy: f64,
    enthalpy_scale: EnthalpyScale,
    temperature_seed: &mut f64,
    monolithic_options: &PhMonolithicOptions,
) -> Result<(PreparedActiveSetCandidate, PhMonolithicSeedRecoveryReport), ReactionExtentError> {
    // A P,H root may lie on a branch where a phase absent from the initial
    // inventory becomes thermodynamically required. The ordinary active-set
    // lifecycle starts such a phase inactive, but a fixed monolithic system
    // cannot discover that branch if the current reduced problem has no
    // enthalpy root at all. Probe the full trace-seeded layout as a recovery
    // candidate; the phase manager still owns the subsequent activation or
    // rejection decision and the final physical publication remains
    // transactional.
    if active.iter().any(|is_active| !is_active) {
        let all_active = vec![true; active.len()];
        match solve_monolithic_active_set_candidate_inner(
            runner,
            active,
            full_seed,
            species_phase,
            full_element_totals,
            thermochemistry,
            temperature_bounds,
            target_enthalpy,
            enthalpy_scale,
            temperature_seed,
            monolithic_options,
        ) {
            Ok(candidate) => return Ok(candidate),
            Err(primary_error) => {
                // A single trace floor can be too far from a condensed-phase
                // branch for a legacy Newton-like backend. Keep this bounded
                // and deterministic: a few physically positive continuation
                // seeds are cheaper and more honest than pretending that one
                // failed nonlinear start proves the phase set impossible.
                for fraction in [1.0e-8, 1.0e-4, 1.0e-2, 1.0e-1] {
                    let mut probe_seed = full_seed.to_vec();
                    for phase_index in 0..all_active.len() {
                        if !active[phase_index] {
                            let component_count = species_phase
                                .iter()
                                .filter(|&&phase| phase == phase_index)
                                .count();
                            if component_count == 0 {
                                return Err(ReactionExtentError::InvalidProblem {
                                    field: "monolithic_ph_probe_seed",
                                    message: format!(
                                        "inactive phase {phase_index} has no declared components"
                                    ),
                                });
                            }
                            // This is a numerical all-active recovery probe,
                            // not a physical phase-appearance decision. The
                            // later TPD lifecycle replaces this neutral seed
                            // with its accepted minimizer composition.
                            let neutral_composition =
                                vec![1.0 / component_count as f64; component_count];
                            seed_activated_phase_with_composition(
                                &mut probe_seed,
                                PhaseIndex::new(phase_index, all_active.len())?,
                                species_phase,
                                &neutral_composition,
                                PhaseTotalSeedPolicy::RelativeToSystemTotal {
                                    fraction,
                                    minimum: 1.0e-12,
                                },
                            )?;
                        }
                    }
                    if let Ok((mut candidate, seed_report)) =
                        solve_monolithic_active_set_candidate_inner(
                            runner,
                            &all_active,
                            &probe_seed,
                            species_phase,
                            full_element_totals,
                            thermochemistry,
                            temperature_bounds,
                            target_enthalpy,
                            enthalpy_scale,
                            temperature_seed,
                            monolithic_options,
                        )
                    {
                        candidate.solved_active_mask = all_active.clone();
                        return Ok((candidate, seed_report));
                    }
                }
                return Err(primary_error);
            }
        }
    }

    let primary = solve_monolithic_active_set_candidate_inner(
        runner,
        active,
        full_seed,
        species_phase,
        full_element_totals,
        thermochemistry,
        temperature_bounds,
        target_enthalpy,
        enthalpy_scale,
        temperature_seed,
        monolithic_options,
    );
    if primary.is_ok() || active.iter().any(|is_active| !is_active) {
        return primary;
    }

    // A phase accepted by the TPD lifecycle starts from a deliberately small
    // positive inventory. When that all-active monolithic solve is numerically
    // rejected, retry a short deterministic set of larger *numerical* seeds.
    // These are not new phase decisions and cannot publish independently: the
    // caller still validates the returned candidate and owns every transition.
    let primary_error = match primary {
        Err(error) => error,
        Ok(_) => unreachable!("successful candidate returned before trace-seed recovery"),
    };
    let system_total = full_seed.iter().map(|value| value.exp()).sum::<f64>();
    let trace_threshold = (system_total * 1.0e-7).max(1.0e-12);
    let trace_active_phases = (0..active.len())
        .filter(|&phase| {
            active[phase]
                && full_seed
                    .iter()
                    .zip(species_phase)
                    .filter(|&(_, &candidate_phase)| candidate_phase == phase)
                    .map(|(log_moles, _)| log_moles.exp())
                    .sum::<f64>()
                    <= trace_threshold
        })
        .collect::<Vec<_>>();
    if trace_active_phases.is_empty() {
        return Err(primary_error);
    }
    for fraction in [1.0e-6, 1.0e-4, 1.0e-2, 1.0e-1] {
        let mut retry_seed = full_seed.to_vec();
        for phase_index in &trace_active_phases {
            let component_count = species_phase
                .iter()
                .filter(|&&phase| phase == *phase_index)
                .count();
            if component_count == 0 {
                return Err(ReactionExtentError::InvalidProblem {
                    field: "monolithic_ph_trace_retry",
                    message: format!("active phase {phase_index} has no declared components"),
                });
            }
            seed_activated_phase_with_composition(
                &mut retry_seed,
                PhaseIndex::new(*phase_index, active.len())?,
                species_phase,
                &vec![1.0 / component_count as f64; component_count],
                PhaseTotalSeedPolicy::RelativeToSystemTotal {
                    fraction,
                    minimum: 1.0e-12,
                },
            )?;
        }
        if let Ok(candidate) = solve_monolithic_active_set_candidate_inner(
            runner,
            active,
            &retry_seed,
            species_phase,
            full_element_totals,
            thermochemistry,
            temperature_bounds,
            target_enthalpy,
            enthalpy_scale,
            temperature_seed,
            monolithic_options,
        ) {
            return Ok(candidate);
        }
    }
    Err(primary_error)
}

fn solve_monolithic_active_set_candidate_inner(
    runner: &mut PreparedPhaseControlRunner,
    active: &[bool],
    full_seed: &[f64],
    species_phase: &[usize],
    full_element_totals: &[f64],
    thermochemistry: &ResolvedThermochemistry,
    temperature_bounds: TemperatureBounds,
    target_enthalpy: f64,
    enthalpy_scale: EnthalpyScale,
    temperature_seed: &mut f64,
    monolithic_options: &PhMonolithicOptions,
) -> Result<(PreparedActiveSetCandidate, PhMonolithicSeedRecoveryReport), ReactionExtentError> {
    let started = Instant::now();
    let problem = runner.prepared_problem();
    let settings = runner.solver_settings();
    let projection = ActiveSetProjection::build(
        problem.problem().phases(),
        species_phase,
        problem.problem().element_composition(),
        active,
        settings.solver_params.tol,
    )?;
    projection
        .validate_element_totals_representable(full_element_totals, settings.solver_params.tol)?;

    let reduced_log_seed = projection.project_log_moles(full_seed)?;
    let indices = projection
        .active_species
        .iter()
        .map(|species| species.index())
        .collect::<Vec<_>>();
    let reduced_components = indices
        .iter()
        .map(|&index| problem.problem().components()[index].clone())
        .collect::<Vec<_>>();
    let reduced_moles = reduced_log_seed
        .iter()
        .map(|value| value.exp())
        .collect::<Vec<_>>();
    let reduced_thermochemistry = thermochemistry.subset(&indices)?;
    // `PreparedEquilibriumProblem` still carries the historical infallible
    // Gibbs closure even though the monolithic formulation evaluates the
    // typed thermochemistry bundle directly.  Cross that boundary only with
    // a fully validated finite snapshot; never encode a source error as NaN.
    let reduced_gibbs =
        reduced_thermochemistry.gibbs_snapshot_for_legacy_boundary(*temperature_seed)?;
    let conditions = EquilibriumConditions::new(
        *temperature_seed,
        problem.problem().conditions().pressure(),
        problem.problem().conditions().reference_pressure(),
    )?;
    let reduced_totals = projection.reduced_element_totals(full_element_totals)?;
    let reduced_problem = EquilibriumProblem::new(
        reduced_components,
        reduced_moles,
        LogMolesInitialGuess::new(reduced_log_seed.clone())?,
        projection.element_composition.clone(),
        reduced_gibbs,
        projection.phases.clone(),
        conditions,
    )?;
    let prepared =
        PreparedEquilibriumProblem::new_with_element_totals(reduced_problem, Some(reduced_totals))?;
    let formulation = PreparedPhFormulation::new(
        prepared,
        reduced_thermochemistry,
        temperature_bounds,
        target_enthalpy,
        enthalpy_scale,
    )?;
    let monolithic = PreparedMonolithicPhRunner::new(formulation, settings, *monolithic_options)?;
    let outcome = monolithic.solve_from_temperature_seed(*temperature_seed)?;
    let temperature_seed_report = outcome.temperature_seed_report.clone();
    *temperature_seed = outcome.snapshot.temperature;
    let solved_conditions = EquilibriumConditions::new(
        outcome.snapshot.temperature,
        problem.problem().conditions().pressure(),
        problem.problem().conditions().reference_pressure(),
    )?;
    let log_moles = projection.scatter_log_moles(
        &outcome.snapshot.log_moles,
        crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::
            PHASE_CONTROL_TRACE_MOLE_FLOOR
            .ln(),
    )?;
    // Stability is evaluated at `outcome.snapshot.temperature` by the phase
    // lifecycle. Keep the validated numeric values at that exact point so the
    // stability boundary does not rebuild constant Gibbs callbacks.
    let stability_gibbs = thermochemistry.evaluate_gibbs(outcome.snapshot.temperature)?;
    Ok((
        PreparedActiveSetCandidate {
            log_moles,
            solved_active_mask: active.to_vec(),
            validation_report: outcome.pt_validation,
            solve_report: outcome.solve_report,
            keq_validation_status: None,
            stability_gibbs: PreparedStabilityGibbs::StandardValues(stability_gibbs),
            conditions: solved_conditions,
            projection_build: started.elapsed(),
            formulation_build: Duration::ZERO,
            rst_preparation: Duration::ZERO,
            rst_preparation_timing: RstPreparationTimingReport::default(),
            validation_duration: Duration::ZERO,
            rst_symbolic_reused: false,
        },
        temperature_seed_report,
    ))
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;
    use std::sync::Arc;

    use RustedSciThe::symbolic::symbolic_engine::Expr;
    use nalgebra::DMatrix;

    use super::*;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_constraints::{
        EnthalpyScale, TemperatureBounds,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::{
        GibbsFn, Phase, PhaseKind, Solvers,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_ph_workflow::{
        MolarThermoFunction, ResolvedThermochemistry, ThermochemistryProvenance,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
        EquilibriumConditions, EquilibriumProblem, LogMolesInitialGuess, PreparedEquilibriumProblem,
    };
    use crate::Thermodynamics::phase_layout::{PhaseComponentId, PhaseId};

    fn one_species_formulation(with_symbolic_capability: bool) -> PreparedPhFormulation {
        one_species_formulation_at_target(with_symbolic_capability, 1_000.0)
    }

    fn one_species_formulation_at_target(
        with_symbolic_capability: bool,
        target_temperature: f64,
    ) -> PreparedPhFormulation {
        let initial_moles = vec![1.0];
        let problem = EquilibriumProblem::new(
            vec!["A".to_string()],
            initial_moles.clone(),
            LogMolesInitialGuess::from_initial_moles(&initial_moles).unwrap(),
            DMatrix::from_row_slice(1, 1, &[1.0]),
            vec![Rc::new(|_| 0.0) as GibbsFn],
            vec![Phase {
                kind: PhaseKind::IdealGas,
                species: vec![0],
            }],
            EquilibriumConditions::new(900.0, 101_325.0, 101_325.0).unwrap(),
        )
        .unwrap();
        let phase = PhaseId::new(None);
        let thermochemistry = ResolvedThermochemistry::from_functions(
            vec![ThermochemistryProvenance::new(
                PhaseComponentId::new(phase, "A"),
                "synthetic",
                "A",
                "gas",
            )],
            TemperatureBounds::new(300.0, 2_000.0).unwrap(),
            vec![Arc::new(|_| Ok(0.0)) as MolarThermoFunction],
            vec![Arc::new(|temperature| Ok(10.0 * temperature)) as MolarThermoFunction],
            vec![Some(Arc::new(|_| Ok(10.0)) as MolarThermoFunction)],
        )
        .unwrap();
        let thermochemistry = if with_symbolic_capability {
            thermochemistry
                .with_symbolic_expressions(
                    vec![Expr::Const(0.0)],
                    vec![Expr::Const(10.0) * Expr::Var("T".to_string())],
                )
                .unwrap()
        } else {
            thermochemistry
        };
        PreparedPhFormulation::new(
            PreparedEquilibriumProblem::new(problem).unwrap(),
            thermochemistry,
            TemperatureBounds::new(500.0, 1_500.0).unwrap(),
            10.0 * target_temperature,
            EnthalpyScale::new(10.0 * target_temperature).unwrap(),
        )
        .unwrap()
    }

    fn monolithic_options(
        scaled_tolerance: f64,
        absolute_tolerance: f64,
        seed_policy: PhMonolithicSeedPolicy,
    ) -> PhMonolithicOptions {
        PhMonolithicOptions::new(
            PhAcceptanceOptions::new(scaled_tolerance, absolute_tolerance).unwrap(),
            seed_policy,
        )
    }

    #[test]
    fn monolithic_runner_solves_composition_and_temperature_together() {
        let mut settings = EquilibriumSolverSettings::default();
        settings.solver = Solvers::NR;
        let runner = PreparedMonolithicPhRunner::new(
            one_species_formulation(false),
            settings,
            monolithic_options(
                1.0e-8,
                1.0e-6,
                PhMonolithicSeedPolicy::DeterministicBoundedRecovery,
            ),
        )
        .unwrap();

        let outcome = runner.solve_from_temperature_seed(900.0).unwrap();
        assert!((outcome.snapshot.temperature - 1_000.0).abs() < 1.0e-5);
        assert!((outcome.snapshot.moles[0] - 1.0).abs() < 1.0e-10);
        assert!(outcome.snapshot.enthalpy_error.abs() < 1.0e-5);
        assert!(matches!(
            outcome.solve_report.accepted_backend,
            SolverBackend::Native(_)
        ));
        assert_eq!(outcome.temperature_seed_report.attempts().len(), 1);
        assert!(!outcome.temperature_seed_report.recovered_after_retry());
    }

    #[test]
    fn bounded_temperature_recovery_uses_a_fresh_midpoint_transaction() {
        let mut settings = EquilibriumSolverSettings::default();
        settings.solver = Solvers::NR;
        settings.solver_params.max_iter = 1;

        let strict = PreparedMonolithicPhRunner::new(
            one_species_formulation(false),
            settings.clone(),
            monolithic_options(1.0e-8, 1.0e-6, PhMonolithicSeedPolicy::InitialOnly),
        )
        .unwrap();
        assert!(strict.solve_from_temperature_seed(600.0).is_err());

        let recovered = PreparedMonolithicPhRunner::new(
            one_species_formulation(false),
            settings,
            monolithic_options(
                1.0e-8,
                1.0e-6,
                PhMonolithicSeedPolicy::DeterministicBoundedRecovery,
            ),
        )
        .unwrap()
        .solve_from_temperature_seed(600.0)
        .unwrap();

        assert!((recovered.snapshot.temperature - 1_000.0).abs() < 1.0e-10);
        assert_eq!(recovered.temperature_seed_report.attempts().len(), 2);
        assert!(!recovered.temperature_seed_report.attempts()[0].accepted());
        assert!(recovered.temperature_seed_report.attempts()[1].accepted());
        assert_eq!(
            recovered.temperature_seed_report.attempts()[1].temperature_seed_k(),
            1_000.0
        );
        assert!(recovered.temperature_seed_report.recovered_after_retry());
    }

    #[test]
    fn exhausted_temperature_recovery_preserves_every_typed_seed_failure() {
        let mut settings = EquilibriumSolverSettings::default();
        settings.solver = Solvers::NR;
        settings.solver_params.max_iter = 1;

        let error = PreparedMonolithicPhRunner::new(
            one_species_formulation_at_target(false, 1_137.0),
            settings,
            monolithic_options(
                1.0e-12,
                1.0e-12,
                PhMonolithicSeedPolicy::DeterministicBoundedRecovery,
            ),
        )
        .unwrap()
        .solve_from_temperature_seed(600.0)
        .unwrap_err();

        let ReactionExtentError::PhMonolithicSeedRecoveryFailed { attempts } = error else {
            panic!("expected typed monolithic seed-recovery failure, got {error}");
        };
        assert_eq!(attempts.len(), 4);
        assert_eq!(attempts[0].temperature_seed_k(), 600.0);
        assert_eq!(attempts[1].temperature_seed_k(), 1_000.0);
        assert_eq!(attempts[2].temperature_seed_k(), 750.0);
        assert_eq!(attempts[3].temperature_seed_k(), 1_250.0);
        assert!(
            attempts
                .iter()
                .all(|attempt| { attempt.cause().is_retryable_formulation_failure() })
        );
    }

    #[test]
    fn monolithic_runner_rejects_rst_without_symbolic_ph_capabilities() {
        let mut settings = EquilibriumSolverSettings::default();
        settings.solver_policy = Some(SolverPolicy::rusted_scithe_default());
        let runner = PreparedMonolithicPhRunner::new(
            one_species_formulation(false),
            settings,
            monolithic_options(
                1.0e-8,
                1.0e-6,
                PhMonolithicSeedPolicy::DeterministicBoundedRecovery,
            ),
        )
        .unwrap();

        assert!(matches!(
            runner.solve_from_temperature_seed(900.0),
            Err(ReactionExtentError::UnsupportedBackendCapability {
                backend,
                capability: "monolithic_p_h_symbolic_thermochemistry",
                ..
            }) if backend == "RustedSciThe"
        ));
    }

    #[test]
    fn monolithic_runner_lets_rst_differentiate_the_coupled_ph_system() {
        let mut settings = EquilibriumSolverSettings::default();
        settings.solver_policy = Some(SolverPolicy::rusted_scithe_default());
        let runner = PreparedMonolithicPhRunner::new(
            one_species_formulation(true),
            settings,
            // RST's own default termination is looser than the legacy test
            // fixture's 1e-8 scaled energy gate. This test exercises the
            // symbolic route under an explicitly compatible physical gate.
            monolithic_options(
                1.0e-7,
                1.0e-6,
                PhMonolithicSeedPolicy::DeterministicBoundedRecovery,
            ),
        )
        .unwrap();

        let outcome = runner.solve_from_temperature_seed(900.0).unwrap();
        assert!((outcome.snapshot.temperature - 1_000.0).abs() < 1.0e-3);
        assert!(outcome.snapshot.enthalpy_error.abs() < 1.0e-3);
        assert!(matches!(
            outcome.solve_report.accepted_backend,
            SolverBackend::RustedSciThe(_)
        ));
    }
}