Skip to main content

pounce_algorithm/
application.rs

1//! User-facing application object — port of `Interfaces/IpIpoptApplication.{hpp,cpp}`.
2//!
3//! # Crate placement
4//!
5//! `IpoptApplication` lives in `pounce-algorithm` (rather than
6//! alongside the other Interfaces-side ports in `pounce-nlp`) because
7//! `optimize_tnlp` needs to drive the full IPM: it constructs a
8//! `TNLPAdapter` + `OrigIpoptNlp` (from `pounce-nlp`) and hands the
9//! NLP off to an [`IpoptAlgorithm`] (this crate). `pounce-nlp` cannot
10//! depend on `pounce-algorithm` (the reverse already exists), so
11//! orchestration must live on the algorithm side. Public callers
12//! continue to import via `pounce_algorithm::IpoptApplication`.
13//!
14//! `optimize_tnlp` routes every problem — constrained or not —
15//! through the same primal-dual IPM, exactly as upstream Ipopt does:
16//! it builds the algorithm via [`crate::alg_builder::AlgorithmBuilder`]
17//! (default backend MA57 from `pounce-hsl`) and runs
18//! [`IpoptAlgorithm::optimize`].
19
20use crate::alg_builder::{
21    AlgorithmBuilder, HessianApproxChoice, LineSearchChoice, LinearBackendFactory,
22    LinearSolverChoice, MuStrategyChoice,
23};
24use crate::hess::lim_mem_quasi_newton::UpdateType;
25use crate::ipopt_alg::{DUAL_DIV_RETRY_DU_FLOOR, IpoptAlgorithm};
26use crate::ipopt_cq::IpoptCalculatedQuantities;
27use crate::ipopt_data::IpoptData as AlgIpoptData;
28use crate::ipopt_nlp::IpoptNlp;
29use crate::iterates_vector::IteratesVector;
30use crate::restoration::RestorationPhase;
31use crate::upstream_options::register_all_upstream_options;
32
33/// Options-file names probed in the working directory when the caller
34/// names none, in probe order: pounce's own name first, then upstream's
35/// so an `ipopt.opt` written for Ipopt is honored unchanged.
36///
37/// Upstream probes only `ipopt.opt` (the registered default of
38/// `option_file_name`). Both are read here because a port that answers
39/// to `ipopt.opt` but not to its own name is the more surprising of the
40/// two behaviours — and gh#518 reported trying both.
41pub const DEFAULT_OPTION_FILE_NAMES: &[&str] = &["pounce.opt", "ipopt.opt"];
42
43/// gh#887 — how far the *runaway* must dominate everything else in the
44/// answer a solve finally reports, before
45/// [`IpoptApplication::run_with_dual_divergence_retry`] will spend a cold
46/// re-solve on it.
47///
48/// gh#884's defect is a point that is converged **except** that one
49/// multiplier ran away: the primal is exact, complementarity is met, and
50/// the entire residual is dual infeasibility. That is the shape
51/// `perturb_always_cd` repairs. A point whose other residuals are within
52/// a few orders of its dual one is not that — it is an ordinary
53/// unconverged answer, and re-solving it cold is what
54/// `mu_strategy_fallback` and the second-opinion ladder already are.
55///
56/// So the retry requires `max(viol, compl) <= 1e-6 * dual_inf`, all
57/// unscaled. Measured on every run in the corpus that reaches the test:
58///
59/// | run | dual inf | viol | compl | ratio |
60/// |---|---|---|---|---|
61/// | reproducer, `.nl` route | `7.90e4` | `1.1e-16` | `1.1e-9` | `1.5e-14` |
62/// | reproducer, TNLP route | `3.25e11` | `2.5e-16` | `2.8e-3` | `8.7e-15` |
63/// | `deb7` + L-BFGS + rung | `9.90e1` | `8.0e-13` | `4.65e0` | `4.7e-2` |
64///
65/// Twelve orders between the keeps and the reject, and `1e-6` leaves
66/// eight orders of margin on the tightest keep and four on the reject.
67///
68/// It is a **ratio of two residuals of the same answer**, so it carries
69/// no units and does not move with the model's scaling — and, unlike any
70/// test on the trajectory, it cannot depend on which attempt fired or on
71/// how a platform rounded its way there. That is not hypothetical: the
72/// first version of this gate compared the reported answer against the
73/// runaway the detector had seen, and `deb7`'s detector value is `9.2e5`
74/// on one attempt and `8.7e2` on another, differing between build
75/// profiles and again on CI's Linux runner, where the retry ran anyway.
76///
77/// Deliberately a constant and not an option. It does not express a
78/// tolerance a caller trades against — it says "the runaway is the whole
79/// residual" — and the escape hatch for the remedy is
80/// `dual_divergence_retry=no`.
81const DUAL_DIV_RETRY_DOMINANCE: Number = 1e-6;
82
83/// Does this answer have gh#884's *shape*?
84///
85/// gh#884's defect is a point converged **except** that one multiplier
86/// ran away: the primal is exact, complementarity is met, and the entire
87/// residual is dual infeasibility. `perturb_always_cd` has something to
88/// repair only there, so this is what opens the retry (gh#887).
89///
90/// All three arguments are in the **model's own units**, never the
91/// `s_d`-normalised frame the convergence gate reads — that frame is what
92/// hid gh#884 in the first place. The test is a ratio *within one
93/// answer*, so it carries no units and cannot depend on which attempt
94/// produced it or on how a platform rounded. That is the property that
95/// matters, not the margin; see the module tests for what happened to
96/// the two gates that did not have it.
97///
98/// Non-finite input disables the retry rather than enabling it: a NaN
99/// compares false everywhere, and writing this so a NaN *passed* would
100/// turn "we cannot tell" into "retry anyway". A non-positive dual
101/// residual cannot be a runaway either, and makes the ratio meaningless.
102///
103/// **The dominance ratio alone is not the whole test, and reading it as
104/// one is how a `dual_inf` of `0.44` opened a retry.** The ratio says the
105/// dual residual *dominates* the other two; it cannot say the residual is
106/// large, because a point converged to `1e-30` primal and `4.4e-1` dual
107/// passes it as comfortably as gh#884's `7.9e+04` does. So `dual_inf`
108/// must also clear the same absolute floor the detector's third conjunct
109/// applies to the iterate (`dual_divergence_retry_du_floor`, default
110/// `1e2`) — the doc above says "the entire residual is dual
111/// infeasibility", and without the floor the code only said "the largest
112/// third of it is".
113///
114/// The floor is the *detector's own*, deliberately, rather than a new
115/// constant: the detector fires on an iterate and this asks whether the
116/// **answer** still exhibits what the detector saw, so the two have to be
117/// asking about the same magnitude or the answer-level gate is a strictly
118/// looser copy of the iterate-level one. Measured on the 400-model QPEC
119/// family in `dev-notes/mpcc-biactive-dual-divergence.md`, this alone
120/// removes 7 of 68 promotions, every one of them on an answer whose
121/// reported dual residual was below `1e2` and therefore not a runaway by
122/// the issue's own description.
123fn runaway_is_the_whole_residual(
124    dual_inf: Number,
125    viol: Number,
126    compl: Number,
127    du_floor: Number,
128) -> bool {
129    dual_inf.is_finite()
130        && dual_inf > 0.0
131        && dual_inf >= du_floor
132        && viol.is_finite()
133        && compl.is_finite()
134        && viol.max(compl) <= DUAL_DIV_RETRY_DOMINANCE * dual_inf
135}
136
137/// gh#983: which scaling defect a success verdict shows.
138#[derive(Debug, Clone, Copy, PartialEq)]
139enum ScaleAudit {
140    /// Gradient-based scaling froze a tiny factor at a huge-gradient start:
141    /// re-evaluate it at the returned point and solve again from there.
142    Rescale,
143    /// The model's gradient is tiny and nothing scales it up: multiply the
144    /// objective by the carried factor (`1 / g`, `g` the gradient scale).
145    Upscale(Number),
146    /// The same small-objective signature, but a re-solve would not move the
147    /// objective's scale materially (`1/g` below [`SCALE_AUDIT_MATERIAL`]):
148    /// warn, do not re-solve.
149    SmallObjective,
150}
151
152/// A complementarity above this fraction of the objective's own gradient scale
153/// is read as "the objective is too small for the absolute tolerances".
154///
155/// gh#983 review item 4: a single threshold, used both to re-solve and to
156/// warn, so there is no band in which a run gets neither. Measured on the
157/// issue's reactor model (`issue_983_review.rs::cstr_*`), whose relative
158/// objective error is `~1.9x` this ratio: `fs = 1` reads `2.5e-10` (error
159/// `3.5e-8`), `fs = 1e-3` `2.5e-7` (`4.3e-7`), `3e-4` `8.4e-7` (`1.5e-6`),
160/// `1e-4` `2.5e-6` (`4.7e-6`), `3e-5` `8.4e-6` (`1.6e-5`), `1e-6` `2.5e-4`
161/// (`4.7e-4`). The first-pass value `1e-5` left `fs` in `[3e-5, 1e-3]` with
162/// errors up to `1.6e-5` and no signal at all. `1e-7` is a tenth of the default
163/// `acceptable_tol`: every run whose objective is predicted to be good to
164/// worse than about `2e-7` relative is either re-solved or warned about.
165const SCALE_AUDIT_COMPL_REL: Number = 1e-7;
166/// The small-objective audit only applies when the caller's `tol` is at most
167/// this (the default is `1e-8`).
168const SCALE_AUDIT_MAX_TOL: Number = 1e-6;
169/// The re-solve never multiplies the objective by more than this.
170const SCALE_AUDIT_MAX_UPSCALE: Number = 1e10;
171/// gh#983 review item 2: a re-solve is spent only when it would change the
172/// objective's scale by at least this factor. Below it the re-solve is the
173/// same solve again -- the first pass measured `hs71` times `1e8` paying a
174/// declined re-solve whose factor, re-evaluated at the optimum, was the one
175/// it already had.
176const SCALE_AUDIT_MATERIAL: Number = 10.0;
177/// The re-solve's iteration budget is this multiple of the base solve's
178/// iterations (never more than the caller's `max_iter`, never less than
179/// [`SCALE_AUDIT_RETRY_MIN_ITER`]).
180///
181/// The re-solve is a bet placed after the run has already succeeded, so it is
182/// bounded by what the run cost. Measured over the 64 audited solves of the
183/// 1,345-problem release sweep (`origin/main` @ `68e438d0`): every promoted
184/// re-solve but one took at most 2.4x the base iterations, or fewer than 50
185/// (`sreadin3` 8 -> 19, `reading2` 15 -> 29, `camshape_6400` 88 -> 112). The
186/// exception is `robot_b`, 271 -> 1425 iterations and 23 s -> 178 s for a
187/// 1.3e-6 relative move in the objective; it now keeps its base answer, which
188/// was already `Solve_Succeeded`. The declined side is where the cost was:
189/// `meyer3` 256 -> 3000 + 3000 (the re-solve's own mu flip), and the
190/// `brainpc` family, where a 1-2 s solve was followed by a re-solve of a
191/// minute or more that was then discarded -- under the benchmark's 300 s
192/// wall it never returned, so the base `Optimal` was lost as a timeout.
193const SCALE_AUDIT_RETRY_ITER_FACTOR: Index = 3;
194/// Floor on the re-solve's iteration budget, so a base solve of a handful of
195/// iterations still leaves the re-solve room to move.
196const SCALE_AUDIT_RETRY_MIN_ITER: Index = 50;
197/// Under a warm start, an objective gradient measured at an *answer* (the
198/// seed, or the returned point) that is within this factor of the run's
199/// unscaled complementarity is what the barrier alone leaves behind
200/// (`grad f = z_L - z_U` with `z ~ mu / s`) and carries no model scale.
201///
202/// Measured on `pounce-rs`'s `session::tests::cold_then_warm_through_presolve`
203/// (an interior optimum, objective `(x0 - 2)^2`): the cold solve reads a start
204/// gradient of `4` and is left alone, while the warm re-solve of the identical
205/// model starts at that answer (`grad f = 1.0e-11`) and returns at
206/// `grad f = 3.73e-9` against a complementarity of `3.72e-9` -- a ratio of
207/// `1.001`, which read as a "tiny objective" and paid a `2.7e8` up-scaled
208/// re-solve that doubled the warm solve's iterations. The reactor population
209/// the small-objective branch exists for has an answer gradient at least
210/// `4e3` times its complementarity (`fs = 1e-6`: `1e-5` against `2.5e-9`), so
211/// `10` -- the audit's own predicted relative error of `0.1` -- separates the
212/// two by more than two orders.
213const SCALE_AUDIT_BARRIER_GRAD: Number = 10.0;
214
215/// What the audit reads off a success verdict.
216#[derive(Debug, Clone, Copy)]
217struct ScaleAuditInput {
218    /// The caller's `tol`.
219    tol: Number,
220    /// The solver-computed (gradient-based) objective factor the run used.
221    obj_scale: Number,
222    /// The factor gradient-based scaling would compute **at the returned
223    /// point** (`gradient_obj_scale(max|grad f(x*)|)`), `NaN` if unknown.
224    rescaled_obj_scale: Number,
225    /// `max|grad f|` at the starting point (`NaN` when not measured).
226    start_grad_max: Number,
227    /// `max|grad f|` at the returned point (`NaN` when not measured).
228    final_grad_max: Number,
229    unscaled_kkt: Number,
230    unscaled_compl: Number,
231    acceptable_tol: Number,
232    masked_threshold: Number,
233    /// `warm_start_init_point=yes`: the start is an earlier answer, not an
234    /// independent measurement of the model.
235    warm_start: bool,
236}
237
238impl ScaleAuditInput {
239    /// The objective's gradient scale: the larger of the two measurements, so
240    /// a start that happens to sit near a stationary point (`grad f(x0) ~
241    /// 1e-7`, `grad f(x*) ~ 1`) does not read as a tiny objective.
242    ///
243    /// A start gradient measured as exactly `0` is a start *at* a stationary
244    /// point, which carries no scale at all; the answer's gradient is then ~0
245    /// too wherever the optimum is unconstrained (`scaled_feasible_a`, a
246    /// zero-residual least squares whose `x0` is its minimizer, reads `2e-4`
247    /// there against data of `1e5`). So that case reports no scale (`0`, the
248    /// audit stays out). An *unmeasured* start (`NaN`: the caller owns the
249    /// scaling) defers to the returned point.
250    ///
251    /// Under a warm start both measurements are taken at answers, so the
252    /// same reasoning applies to each of them: one that sits at the barrier
253    /// level ([`SCALE_AUDIT_BARRIER_GRAD`] times the complementarity) is the
254    /// stationary point's noise, not the model's scale, and when neither
255    /// clears it the audit stays out. Without this the verdict depended on
256    /// the start rather than the model: a cold solve of an interior optimum
257    /// is left alone, and a warm re-solve of the *same* data from its answer
258    /// was up-scaled and re-solved.
259    fn grad_scale(&self) -> Number {
260        let fin = |v: Number| if v.is_finite() && v > 0.0 { v } else { 0.0 };
261        if self.start_grad_max == 0.0 {
262            return 0.0;
263        }
264        if self.warm_start && self.unscaled_compl.is_finite() {
265            let floor = SCALE_AUDIT_BARRIER_GRAD * self.unscaled_compl;
266            let answer = |v: Number| if fin(v) > floor { v } else { 0.0 };
267            return answer(self.start_grad_max).max(answer(self.final_grad_max));
268        }
269        fin(self.start_grad_max).max(fin(self.final_grad_max))
270    }
271}
272
273/// Does a success verdict need the gh#983 scale audit, and which kind?
274///
275/// Pure so the thresholds are unit-testable.
276///
277/// gh#983 review item 2: neither branch is a function of the objective's
278/// magnitude alone. The re-scale branch requires the factor re-evaluated at
279/// the returned point to differ materially from the frozen one (a
280/// legitimately large objective re-evaluates to the factor it already has),
281/// and the small-objective branch reads the gradient at both ends of the run.
282fn scale_audit_trigger(inp: ScaleAuditInput) -> Option<ScaleAudit> {
283    use crate::conv_check::opt_error::certificate_masked;
284    if inp.obj_scale.is_finite()
285        && inp.obj_scale > 0.0
286        && inp.unscaled_kkt.is_finite()
287        && certificate_masked(
288            inp.obj_scale,
289            inp.unscaled_kkt,
290            inp.masked_threshold,
291            inp.acceptable_tol,
292        )
293        && inp.rescaled_obj_scale.is_finite()
294        && inp.rescaled_obj_scale >= SCALE_AUDIT_MATERIAL * inp.obj_scale
295    {
296        return Some(ScaleAudit::Rescale);
297    }
298    // The small-objective branch is about a *tight* absolute tolerance that is
299    // crude relative to the objective. A caller who loosened `tol` themselves
300    // (`tol = 5e-2` in `test_loose_mu_reports_ambiguous`) asked for the
301    // complementarity they got.
302    let g = inp.grad_scale();
303    if inp.tol <= SCALE_AUDIT_MAX_TOL
304        && g > 0.0
305        && g < 1.0
306        && inp.unscaled_compl.is_finite()
307        && inp.unscaled_compl / g > SCALE_AUDIT_COMPL_REL
308    {
309        let k = (1.0 / g).min(SCALE_AUDIT_MAX_UPSCALE);
310        return Some(if k >= SCALE_AUDIT_MATERIAL {
311            ScaleAudit::Upscale(k)
312        } else {
313            ScaleAudit::SmallObjective
314        });
315    }
316    None
317}
318
319/// Text of the structured warning for an audit that was not (or could not be)
320/// resolved by a re-solve. `outcome` completes "A re-solve ... <outcome>".
321fn scale_audit_warning(
322    kind: ScaleAudit,
323    base: &SolveStatistics,
324    grad_scale: Number,
325    acceptable_tol: Number,
326    outcome: &str,
327) -> String {
328    match kind {
329        ScaleAudit::Rescale => format!(
330            "unscaled_stationarity_above_tol: gradient-based scaling froze the objective \
331             factor at {:.2e} at the starting point and the reported point's unscaled KKT \
332             error is {:.2e} (acceptable_tol {:.0e}); the scaled test passed in a space \
333             where the objective gradient is shrunk by that factor. A re-solve from this \
334             point with the scaling re-evaluated {outcome}.",
335            base.final_obj_scaling_factor, base.final_unscaled_kkt_error, acceptable_tol
336        ),
337        ScaleAudit::Upscale(k) => format!(
338            "objective_scale_small: the objective gradient is at most {:.2e} (start and \
339             returned point) and nothing scales it up, so the unscaled complementarity {:.2e} \
340             is {:.1e} of that scale -- the objective is only good to about that relative \
341             error. A re-solve with the objective multiplied by {:.1e} {outcome}. Rescale the \
342             objective (e.g. obj_scaling_factor) to silence this.",
343            grad_scale,
344            base.final_unscaled_compl,
345            base.final_unscaled_compl / grad_scale,
346            k
347        ),
348        ScaleAudit::SmallObjective => format!(
349            "objective_scale_small: the objective gradient is at most {:.2e} (start and \
350             returned point), so the unscaled complementarity {:.2e} is {:.1e} of that scale \
351             -- the objective is only good to about that relative error. No re-solve: \
352             scaling the objective up by {:.1e} is below the factor of {SCALE_AUDIT_MATERIAL} \
353             that would change the solve. Rescale the objective (e.g. obj_scaling_factor) or \
354             tighten tol to silence this.",
355            grad_scale,
356            base.final_unscaled_compl,
357            base.final_unscaled_compl / grad_scale,
358            1.0 / grad_scale
359        ),
360    }
361}
362
363/// Model-scale caveats on a success verdict that need no re-solve.
364///
365/// * `large_dual_scale`: the terms the stationarity residual is made of
366///   reach `1e8` or more *and* the residual exceeds `acceptable_tol`, which is
367///   the failed-constraint-qualification signature (the cusp of gh#983 item 1 has multipliers of `3.5e9` and a
368///   residual of `0.144`). The scale-relative floor (gh#532) judges such a
369///   point against that scale, so it is accepted; the warning is how the
370///   caller finds out. It is not capped, because the cap that rejects the
371///   cusp (`~0.1`) also rejects Vanderbei's `orthrds2` (`89.7` at scale
372///   `1.6e10`), which is stationary to nine digits relative to its scale.
373///   Under `bound_relax_factor = 0` it names that option: every model of
374///   gh#1000 items II.22, II.23 and I.15 that carried it (pump network,
375///   process-network superstructure, Haverly multistart) had an active
376///   bound coinciding with a dependent row, and each ends `Solve_Succeeded`
377///   at the default relaxation. Ipopt follows the same trajectory at `0`.
378/// * `unscaled_stationarity_above_tol`: the unscaled residual sits above
379///   `1e-3` while the strict gate, which tolerates up to `dual_inf_tol`
380///   (`1` by default), passed it.
381fn quality_warnings(
382    status: ApplicationReturnStatus,
383    unscaled_dual_inf: Number,
384    dual_scale: Number,
385    dual_inf_tol: Number,
386    acceptable_tol: Number,
387    bound_relax_off: bool,
388) -> Vec<String> {
389    let mut out = Vec::new();
390    if !matches!(
391        status,
392        ApplicationReturnStatus::SolveSucceeded | ApplicationReturnStatus::SolvedToAcceptableLevel
393    ) {
394        return out;
395    }
396    // Only when the residual is itself above `acceptable_tol`: a legitimately
397    // large objective (`hs71` times `1e8`) has terms of `1e9` and a residual of
398    // `3e-7`, which is not a symptom of anything.
399    if dual_scale.is_finite()
400        && dual_scale >= 1e8
401        && unscaled_dual_inf.is_finite()
402        && unscaled_dual_inf > acceptable_tol
403    {
404        out.push(format!(
405            "large_dual_scale: the stationarity residual is assembled from terms of size {dual_scale:.2e} \
406             (multipliers or gradients this large usually mean a failed constraint qualification), \
407             so the unscaled dual infeasibility {unscaled_dual_inf:.2e} was judged relative to that scale{}",
408            if bound_relax_off {
409                ". bound_relax_factor = 0 is set: an active bound that coincides with a \
410                 dependent row has no interior there, and the default relaxation (1e-8) \
411                 usually removes this"
412            } else {
413                ""
414            }
415        ));
416    }
417    if unscaled_dual_inf.is_finite()
418        && unscaled_dual_inf > UNSCALED_DUAL_WARN
419        && unscaled_dual_inf > acceptable_tol
420    {
421        out.push(format!(
422            "unscaled_dual_inf_above_acceptable: the unscaled dual infeasibility is {unscaled_dual_inf:.2e}, \
423             above acceptable_tol {acceptable_tol:.0e}; the strict gate tolerates up to dual_inf_tol \
424             = {dual_inf_tol:.0e}. Verify stationarity in your own units"
425        ));
426    }
427    out
428}
429
430/// See [`quality_warnings`].
431///
432/// Also the bar for the gh#983 item-5 downgrade (`finalize_quality_verdict`).
433/// Measured population near it (gh#983 review), over the CLI fixture corpus on
434/// both sweep legs: six runs return `Solve_Succeeded` with the gh#884
435/// signature, at unscaled dual infeasibilities of `1.6e-9`
436/// (`linear_eq_collapsed_box`), `2.8e-9` (`autocorr_bern55-06`), `1.0e-8` /
437/// `1.1e-8` (`pooling_rt2stp`, both legs), `5.5e-8`
438/// (`mpcc_qpec_small_biactive`) and `3.6e-6` (`deb7`) -- the largest two and a
439/// half orders below the bar. The runs the bar exists for sit above it: the
440/// cusp with the floor opted back in at `1.44e-1`, and the first pass's
441/// toll-pricing report at `3.3e-2` (since gh#1000 exempt as roundoff, see
442/// [`UNSCALED_DUAL_ROUNDOFF_ULPS`]). So the threshold falls in an empty band of
443/// the measured population; nothing between `3.6e-6` and `3.3e-2` was observed,
444/// and the corpus says nothing about how dense that band is elsewhere (the
445/// 400-model QPEC family of `dev-notes/mpcc-biactive-dual-divergence.md` was
446/// not re-measured for this).
447const UNSCALED_DUAL_WARN: Number = 1e-3;
448
449/// gh#1000 (II.22): how many ulps of its own terms an unscaled stationarity
450/// residual may read and still be roundoff rather than a measured miss.
451///
452/// The residual `∇f + Jᵀλ + z` is assembled from terms of size
453/// `final_unscaled_dual_scale`, so in floating point it cannot read much below
454/// `ε·scale` however exact the point is. Under `bound_relax_factor = 0` an
455/// active bound and a row can be linearly dependent, the multipliers drift
456/// along the unbounded ray of valid ones, and the scale follows them: the
457/// pump-network NLP of the issue ends with multipliers near `1e13`, a residual
458/// of `5.5e-3` -- 1.6 ulps of its terms -- and an objective right to `5e-9`
459/// relative, and was downgraded on that `5.5e-3` alone. The measured
460/// population on either side, as `residual / scale`: that run at `3.5e-16`
461/// (`2.8e-16` on the Python path), and gh#983's toll-pricing MPCC at
462/// `bound_relax_factor = 0` at `1.1e-16` (`3.3e-2` against `3e14`, objective
463/// `9e-10` from the default-options solve), which gh#983 had pinned as a
464/// downgrade and which this exempts too; the downgrades that are correct --
465/// Haverly at `2e-13` (objective `7e-8` off, complementarity `1.8e-6`), the
466/// process network's all-zero-flow subproblem at `6.6e-13` (`6e-7` off) --
467/// and the cusp the downgrade was built for at `4e-11`. 64 ulps (`1.4e-14`)
468/// sits forty times above the first and fourteen times below the nearest
469/// correct downgrade.
470///
471/// What this cannot see: on a model with no finite multiplier (the cusp) the
472/// residual falls as the multipliers grow and the floor rises with them, so a
473/// run that drove them far enough would cross it. None measured has; the
474/// cusp sits more than three orders above. The `large_dual_scale` caveat
475/// still attaches to every run this exempts.
476const UNSCALED_DUAL_ROUNDOFF_ULPS: Number = 64.0;
477
478/// Is `du` within [`UNSCALED_DUAL_ROUNDOFF_ULPS`] of the rounding error of
479/// the terms it was assembled from? `false` whenever either input is not
480/// finite, so a path that does not measure the scale keeps the downgrade.
481fn unscaled_dual_inf_is_roundoff(du: Number, scale: Number) -> bool {
482    du.is_finite()
483        && scale.is_finite()
484        && scale > 0.0
485        && du <= UNSCALED_DUAL_ROUNDOFF_ULPS * Number::EPSILON * scale
486}
487
488/// The code of a structured warning: the text before the first `:`.
489fn warning_code(w: &str) -> &str {
490    w.split(':').next().unwrap_or(w)
491}
492
493/// Push `w` unless a warning with the same code is already attached
494/// (gh#983 review item 7: `unscaled_dual_inf_above_acceptable` was pushed
495/// twice, once by the downgrade and once by the caveat list).
496fn push_warning_once(warnings: &mut Vec<String>, w: String) {
497    if !warnings.iter().any(|x| warning_code(x) == warning_code(&w)) {
498        warnings.push(w);
499    }
500}
501
502/// gh#983 item 4: a retry violation at or below this is arithmetic noise, not
503/// "primal slack". Rule 2 compared the retry's violation to the base's with no
504/// floor, so a base at `3e-38` refused a retry at `2e-13` that halved the
505/// objective (`x*y == 0` from `(0.3, 0.3)`: base `f = 2` with unscaled dual
506/// infeasibility `1.4e9`, retry `f = 1`). The floor is a few hundred ulps of 1;
507/// the case rule 2 exists for, `scholtes4`, buys `6.6e-05` of objective with a
508/// violation of `1.09e-09` -- four orders above it, so it is still refused.
509const RETRY_VIOL_NOISE_FLOOR: Number = 1e-12;
510
511/// gh#983 review item 5: how many orders a retry's unscaled KKT error must sit
512/// below the base attempt's before it may be promoted without reaching
513/// `acceptable_tol` itself.
514const RETRY_DOMINANCE_ORDERS: Number = 1e-6;
515
516/// gh#983 review item 5: the second way conjunct 4 of the gh#884 promotion
517/// gate can hold.
518///
519/// Conjunct 4 demanded the retry's unscaled KKT error be at or below
520/// `acceptable_tol`. On the toll-pricing MPCC at `bound_relax_factor = 0` the
521/// base attempt returns `Solved_To_Acceptable_Level` at an unscaled dual
522/// infeasibility of `1.03e5` and the retry `Solve_Succeeded` at `1.69e-5`:
523/// ten orders better, and refused because `1.69e-5 > 1e-6`. That is a
524/// certificate an ordinary first solve would ship as `Solve_Succeeded`
525/// without a second look (it is under `1e-3`, the bar
526/// `finalize_quality_verdict` holds strict verdicts to), held to a stricter
527/// standard only because it was a retry, while the answer reported instead is
528/// one whose residual is the runaway itself.
529///
530/// So the retry's certificate also counts as real when **all** of:
531/// * it is at least six orders below the base attempt's
532///   (`RETRY_DOMINANCE_ORDERS`) -- not "better", *categorically* better;
533/// * it is at or below `UNSCALED_DUAL_WARN` (`1e-3`) in absolute terms, the
534///   same bar a strict verdict is held to everywhere else, so no promotion
535///   ships a residual the audit would flag on a first solve;
536/// * the retry's unscaled constraint violation is within `acceptable_tol`
537///   (the primal half is not relaxed at all).
538///
539/// The answer rules ([`retry_answer_is_admissible`]) and the `Solve_Succeeded`
540/// conjunct are unchanged and still apply. Why this does not let `ralph1`
541/// through: `ralph1`'s defect is that `perturb_always_cd` returns a wrong
542/// answer reported as success, and what keeps it out is that the retry is
543/// never *opened* there -- the detector's scale-relative step conjunct and
544/// the `1e2` dual floor on the reported answer
545/// (`runaway_is_the_whole_residual`), neither of which this touches. Within an
546/// opened retry the base residual is at least that floor, so the dominance
547/// conjunct alone would admit `1e-4`; the absolute `1e-3` cap and the
548/// unchanged answer rules are what bound it, and `issue884_*` pins both
549/// barriers (`ralph1` is in that corpus).
550fn retry_certificate_dominates(
551    base_unscaled_kkt: Number,
552    retry_unscaled_kkt: Number,
553    retry_viol: Number,
554    accept_tol: Number,
555) -> bool {
556    base_unscaled_kkt.is_finite()
557        && retry_unscaled_kkt.is_finite()
558        && retry_viol.is_finite()
559        && retry_unscaled_kkt <= RETRY_DOMINANCE_ORDERS * base_unscaled_kkt
560        && retry_unscaled_kkt <= UNSCALED_DUAL_WARN
561        && retry_viol <= accept_tol
562}
563
564/// Is the retry's answer admissible *as an answer*, next to the base
565/// attempt's — independent of which has the better multiplier?
566///
567/// gh#884's promotion gate ranked the two attempts on unscaled KKT error
568/// alone. That is a statement about the **certificate**, and it was
569/// allowed to decide which **point** shipped, on the argument that
570/// "conjunct 4 requires the promoted answer to satisfy the KKT conditions
571/// in the model's own units" — so, unlike the μ flip, this retry could not
572/// return a different local solution. The inference does not hold: *any*
573/// other KKT point satisfies the KKT conditions in the model's own units
574/// too. Measured on 400 random QPECs (`prod_eq` lowering), 42 of 68
575/// promotions moved the objective materially, i.e. returned a different
576/// local solution, and three returned a **worse feasible point** — worst
577/// case `-13.0057 → -1.2072`, both independently verified feasible.
578///
579/// Two rules, and both are about the *answer* rather than its certificate:
580///
581/// 1. **Never hand back a feasible point whose objective is worse than one
582///    this run already computed.** The base attempt's point is feasible
583///    and in hand; returning a worse one is a regression no certificate
584///    buys back.
585/// 2. **An objective *improvement* may not be bought with primal slack.**
586///    Two costs this carries, named rather than hidden (R3). It is an exact
587///    non-increase with **no noise floor**, so it fires the same on
588///    `2.07e-25 -> 1.09e-09` (where the move is the whole defect) as on
589///    `1e-17 -> 1.1e-17` (where which side a retry lands on is arithmetic):
590///    of the 45 promotions this PR removes, ~35 are improvements refused
591///    because the violation ticked up somewhere far below any tolerance. The
592///    direction is conservative — the base answer is feasible and in hand —
593///    but "refuses purchases, not improvements" is only true above the noise.
594///    And the rule detects *the primal moved*, not *below the optimum*: had
595///    `scholtes4`'s retry **held** its violation, `f = -6.6088e-05` would have
596///    been admitted, which the second assertion of
597///    `an_improvement_bought_with_primal_slack_is_refused` states outright.
598///    On that model the two coincided.
599///    The remedy is for a *dual* defect — the premise is that the primal
600///    has settled — so a retry that lands further outside the constraints
601///    *and* reports a better objective has not repaired the runaway, it
602///    has moved somewhere the model does not reach. This is what
603///    `scholtes4` does: from a base at `f = +1.82e-09` with a constraint
604///    violation of `2.07e-25` it promotes `f = -6.61e-05` at `1.09e-09`,
605///    below the model's exactly-known `f* = 0`, and reports
606///    `Optimal Solution Found`.
607///
608/// Both comparisons are skipped when the base attempt is not itself
609/// feasible within [`IpoptApplication::dual_divergence_retry_accept_tol`]:
610/// there is then no admissible point to protect, and the retry's is
611/// strictly better information.
612///
613/// `tol` is that same acceptable tolerance, scaled by
614/// `max(1, |base_obj|)` so the comparison is relative on a large
615/// objective and absolute on a small one — the convention
616/// `sigma_forward_error_is_small` uses for `‖x‖` and for the same reason.
617/// It is not a fitted constant: the objective moves this has to admit
618/// (`qpec_small`, `5.8e-11`) and the ones it has to refuse (`r201`,
619/// `0.198`; `scholtes4`, `6.6e-05`) sit four and five orders away from it
620/// on either side.
621///
622/// `sense` is `+1` for a minimization and `-1` for a maximization, and both
623/// objectives are multiplied by it before either rule looks at them.
624/// [`SolveStatistics::final_objective`] is the objective evaluated on the
625/// **user** TNLP — signed, and *not* premultiplied by `obj_scaling_factor` —
626/// and a negative `obj_scaling_factor` is the documented way to pose a
627/// maximization. Without the normalization both rules invert under it: rule 1
628/// would refuse genuine *improvements* (a regression against the behaviour
629/// before this conjunct existed) and rule 2 would admit strictly worse
630/// answers, re-arming the exact class the conjunct was added to block. The
631/// repo has shipped one defect from this sign already —
632/// `masked_certificate_fuzz.rs::the_veto_is_not_disabled_by_a_negative_objective_scaling_factor`,
633/// whose fix took `.abs()` in the residual accessors, which is also what keeps
634/// the detector firing under maximization and so keeps this path reachable.
635fn retry_answer_is_admissible(
636    base_obj: Number,
637    base_viol: Number,
638    retry_obj: Number,
639    retry_viol: Number,
640    accept_tol: Number,
641    sense: Number,
642) -> bool {
643    // Nothing to compare against: a non-finite or infeasible base answer
644    // is not a point worth protecting.
645    if !base_obj.is_finite() || !base_viol.is_finite() || base_viol > accept_tol {
646        return true;
647    }
648    // A non-finite retry objective is refused rather than admitted, for
649    // the same reason `runaway_is_the_whole_residual` refuses a NaN.
650    if !retry_obj.is_finite() {
651        return false;
652    }
653    // Both into a minimization frame, so "lower is better" below is true
654    // whichever sense the caller posed.
655    let base_obj = sense * base_obj;
656    let retry_obj = sense * retry_obj;
657    let tol = accept_tol * base_obj.abs().max(1.0);
658    if retry_obj > base_obj + tol {
659        return false; // rule 1: strictly worse feasible point
660    }
661    if retry_obj < base_obj - tol {
662        // Rule 2: an improvement is admissible only if the retry did not
663        // give up primal accuracy to get it.
664        return retry_viol.is_finite() && retry_viol <= base_viol.max(RETRY_VIOL_NOISE_FLOOR);
665    }
666    true
667}
668
669/// How far `x` sits outside the declared box, **relative to each bound's own
670/// magnitude**: `max_i viol_i / max(1, |b_i|)`, where `b_i` is the bound
671/// `x_i` crosses and bounds at or beyond the infinity sentinels are absent.
672///
673/// Relative because the quantity it is compared on is: `bound_relax_factor`
674/// widens bound `b` by `factor · max(1, |b|)` (capped at `constr_viol_tol`),
675/// so a point pinned to the widened bound sits a *relative* distance from the
676/// box that does not depend on `|b|`, while its rounding is one ulp of `|b|`
677/// -- `1.2e-10` at `|b| = 1e6`, two orders above any absolute floor that
678/// still separates `1e-8` from noise on a unit bound.
679///
680/// A variable fixed by its declared box (`x_L == x_U`) is skipped. Under
681/// `fixed_variable_treatment=relax_bounds` it stays in the iterate with its
682/// point widened into a band -- in the base attempt and the re-solve alike,
683/// since a barrier needs an interior -- so where it lands inside that band is
684/// barrier noise, not a choice to use the widening: on a fixed `z = 0.5`
685/// beside three bound-active controls the base attempt returned it `1.2e-11`
686/// off and the re-solve `2.0e-11`, and counting it declined a re-solve whose
687/// controls were all inside their box. Under the default `make_parameter` it
688/// is spliced in at its exact value and reads `0` either way.
689///
690/// `NaN` when the lengths disagree (nothing to measure against).
691fn declared_box_relative_violation(
692    x: &[Number],
693    x_l: &[Number],
694    x_u: &[Number],
695    lower_inf: Number,
696    upper_inf: Number,
697) -> Number {
698    if x.len() != x_l.len() || x.len() != x_u.len() {
699        return Number::NAN;
700    }
701    let mut worst = 0.0_f64;
702    for i in 0..x.len() {
703        let (l, u) = (x_l[i], x_u[i]);
704        if l == u {
705            continue;
706        }
707        if l > lower_inf && x[i] < l {
708            worst = worst.max((l - x[i]) / l.abs().max(1.0));
709        }
710        if u < upper_inf && x[i] > u {
711            worst = worst.max((x[i] - u) / u.abs().max(1.0));
712        }
713    }
714    worst
715}
716
717/// A relative declared-box violation at or below this is rounding, not use of
718/// the widening: four ulps of the bound's magnitude (`4 · ε ≈ 8.9e-16`).
719///
720/// Measured populations on either side of it. Rounding: a point pinned to a
721/// bound reads at most one ulp off it, `ε/2 .. ε` relative at any magnitude.
722/// Genuine use of the widening, from the bound-magnitude probe (the
723/// `scale_audit_bound_active` model with `x_U` in `{1, 10, 1e2, 1e3, 1e4,
724/// 1e6}`, each with the box at `[0, x_U]` and at `[x_U − 1, x_U]`, under a
725/// named `bound_relax_factor=1e-8`): the re-solve's excess over the base
726/// attempt is `4.97e-9` relative at `x_U = 1`, `9.5e-9` at `10`, `9.9e-9` at
727/// `1e2`, `2.5e-9` at `1e3`, `2.5e-10` at `1e4` and `2.5e-12` at `1e6` (the
728/// last three are where `constr_viol_tol = 1e-4` caps the widening). The
729/// smallest of those is three and a half orders above this floor, the
730/// largest rounding three times below it.
731const RETRY_BOX_REL_NOISE: Number = 4.0 * Number::EPSILON;
732
733/// May a retry's point ship, as far as the box the caller *declared* goes?
734///
735/// Only when it sits no further outside that box than the base attempt's
736/// point does, measured relative to each bound's magnitude
737/// ([`declared_box_relative_violation`]) and up to [`RETRY_BOX_REL_NOISE`].
738/// Every interior-point solve runs on bounds widened by `bound_relax_factor`,
739/// so "outside the declared box" is something any converged point can be, by
740/// up to the widening; what this refuses is a retry that *uses more of it*
741/// than the answer already in hand. That is the gh#983 scale audit's failure
742/// mode exactly: its re-solve drives complementarity down, which on a
743/// bound-active variable is the same as driving the point onto the widened
744/// bound, so `ex1_320`'s re-solve shipped `1.0e-8` outside the box its base
745/// attempt satisfied exactly.
746///
747/// Unconditional, unlike rule 2 of [`retry_answer_is_admissible`]: a point
748/// outside the box is the defect whatever the objective did, and a re-solve
749/// whose objective move is under that rule's tolerance shipped it all the
750/// same. When the caller left `bound_relax_factor` alone the scale audit's
751/// re-solve keeps the variable box as declared (its inequality rows are
752/// still widened, as in the base attempt), so there this conjunct is a
753/// backstop. It bites when the caller named a widening: both attempts then
754/// solve the widened box, and the re-solve may not exploit it further.
755///
756/// `NaN` means "not measured". A retry that cannot be measured is refused
757/// unless the base could not be either: there is then nothing to compare and
758/// the rule has no opinion.
759fn retry_keeps_declared_box(base_rel_viol: Number, retry_rel_viol: Number) -> bool {
760    if retry_rel_viol.is_nan() {
761        return base_rel_viol.is_nan();
762    }
763    let base = if base_rel_viol.is_nan() {
764        0.0
765    } else {
766        base_rel_viol.max(0.0)
767    };
768    retry_rel_viol <= base + RETRY_BOX_REL_NOISE
769}
770
771/// What [`IpoptApplication::initialize_with_option_file`] did — enough
772/// for a caller to tell the user which file (if any) configured the run.
773#[derive(Debug, Default, Clone)]
774pub struct OptionFileLoad {
775    /// The file actually read. `None` means no options file was read:
776    /// nobody named one and neither default was present.
777    pub path: Option<PathBuf>,
778    /// Whether [`Self::path`] was named by the caller rather than found
779    /// by probing the working directory.
780    pub explicit: bool,
781    /// Non-fatal notes about option-file settings that did *not* take
782    /// effect. Nothing here stops a solve; the point is that it not
783    /// happen silently.
784    pub warnings: Vec<String>,
785}
786
787/// Opaque snapshot of an application's linear-solver summaries; see
788/// [`IpoptApplication::linear_solver_summary_state`].
789#[derive(Debug, Clone)]
790pub struct LinearSolverSummaryState {
791    main: LinearSolverSummary,
792    restoration: LinearSolverSummary,
793}
794
795/// Factory that constructs a fresh restoration-phase strategy on
796/// demand. The outer algorithm owns at most one restoration object,
797/// so the factory is invoked once per `optimize_tnlp` call. The
798/// factory is `FnMut` to allow callers to capture a builder that
799/// internally reuses caches across builds.
800pub type RestorationFactory = Box<dyn FnMut() -> Box<dyn RestorationPhase>>;
801
802/// Provider that mints fresh [`RestorationFactory`] instances on
803/// demand. Used by drivers that need to run the inner IPM more than
804/// once per `optimize_tnlp` call — notably the Phase-3 ℓ₁-exact
805/// penalty-barrier outer loop (pounce#10), which the existing
806/// `RestorationFactory` cannot support because pounce's default
807/// `make_default_restoration_factory` is a one-shot. Callers wire
808/// this via [`IpoptApplication::set_restoration_factory_provider`].
809pub type RestorationFactoryProvider = Box<dyn FnMut() -> RestorationFactory>;
810
811/// Running totals over the passes of a multi-pass solve (the ℓ₁ exact-penalty
812/// ρ loop, and the plain attempt that precedes it under
813/// `l1_fallback_on_restoration_failure`). Every pass starts from reset
814/// statistics, so the passes are summed here and written back once, after
815/// the last, as the **total** `iteration_count` plus a `passes` summary
816/// (gh#987 item 6). Everything else in the statistics keeps describing the
817/// last pass — the one that produced the returned point.
818#[derive(Default)]
819struct MultiPassTotals {
820    iterations: Index,
821    rows: Vec<pounce_nlp::solve_statistics::IterRecord>,
822    obj_evals: Index,
823    constr_evals: Index,
824    grad_evals: Index,
825    jac_evals: Index,
826    hess_evals: Index,
827    restoration_calls: Index,
828    restoration_inner_iters: Index,
829    restoration_outer_iters: Index,
830    passes: Vec<pounce_nlp::SolvePassRecord>,
831}
832
833impl MultiPassTotals {
834    fn push_pass(
835        &mut self,
836        st: &SolveStatistics,
837        rho: Option<Number>,
838        status: ApplicationReturnStatus,
839    ) {
840        self.passes.push(pounce_nlp::SolvePassRecord {
841            rho,
842            iterations: st.iteration_count,
843            first_row: self.rows.len(),
844            slack_sum: None,
845            constraint_violation: None,
846            status: format!("{status:?}"),
847        });
848        self.iterations += st.iteration_count;
849        self.rows.extend(st.iterations.iter().cloned());
850        self.obj_evals += st.num_obj_evals;
851        self.constr_evals += st.num_constr_evals;
852        self.grad_evals += st.num_obj_grad_evals;
853        self.jac_evals += st.num_constr_jac_evals;
854        self.hess_evals += st.num_hess_evals;
855        self.restoration_calls += st.restoration_calls;
856        self.restoration_inner_iters += st.restoration_inner_iters;
857        self.restoration_outer_iters += st.restoration_outer_iters;
858    }
859
860    fn set_slack_sum(&mut self, v: Number) {
861        if let Some(p) = self.passes.last_mut() {
862            p.slack_sum = v.is_finite().then_some(v);
863        }
864    }
865
866    fn set_violation(&mut self, v: Number) {
867        if let Some(p) = self.passes.last_mut() {
868            p.constraint_violation = v.is_finite().then_some(v);
869        }
870    }
871
872    fn apply(&self, st: &mut SolveStatistics) {
873        if self.passes.is_empty() {
874            return;
875        }
876        st.iteration_count = self.iterations;
877        st.iterations = self.rows.clone();
878        st.num_obj_evals = self.obj_evals;
879        st.num_constr_evals = self.constr_evals;
880        st.num_obj_grad_evals = self.grad_evals;
881        st.num_constr_jac_evals = self.jac_evals;
882        st.num_hess_evals = self.hess_evals;
883        st.restoration_calls = self.restoration_calls;
884        st.restoration_inner_iters = self.restoration_inner_iters;
885        st.restoration_outer_iters = self.restoration_outer_iters;
886        st.passes = self.passes.clone();
887    }
888}
889
890/// Callback fired by [`IpoptApplication::optimize_constrained`] once
891/// the IPM has converged (status `SolveSucceeded` or
892/// `SolvedToAcceptableLevel`) and before the user TNLP's
893/// `finalize_solution` runs. Receives borrowed handles into the
894/// algorithm's converged state.
895///
896/// **Use case**: post-optimal sensitivity analysis (pounce#7 /
897/// `pounce-sensitivity`). The callback receives a shared handle to
898/// the PD solver so a `SensBacksolver` adapter can run backsolves
899/// against the converged KKT factor — and so that handle may outlive
900/// the call frame (e.g. the public `Solver` session API retains the
901/// factor for repeated `parametric_step` / `kkt_solve` calls);
902/// receives the data / cq / nlp handles so the adapter can reproduce
903/// the augmented-system coefficient layout the IPM converged at.
904///
905/// **Not** the same as `set_intermediate_callback` (per-iteration
906/// progress notification) — this fires exactly once per `optimize_*`
907/// call, only on success.
908pub type ConvergedCallback = Box<
909    dyn FnMut(
910        &crate::ipopt_data::IpoptDataHandle,
911        &crate::ipopt_cq::IpoptCqHandle,
912        &Rc<RefCell<dyn pounce_nlp::ipopt_nlp::IpoptNlp>>,
913        Rc<RefCell<crate::kkt::pd_full_space_solver::PdFullSpaceSolver>>,
914    ),
915>;
916use pounce_common::diagnostics::DiagnosticsState;
917use pounce_common::exception::{ExceptionKind, SolverException};
918use pounce_common::journalist::{JournalLevel, Journalist};
919use pounce_common::options_list::OptionsList;
920use pounce_common::reg_options::{PrintOptionsMode, RegisteredOptions};
921use pounce_common::timing::TimingStatistics;
922use pounce_common::types::{Index, Number};
923use pounce_linalg::dense_vector::DenseVectorSpace;
924use pounce_linsol::SparseSymLinearSolverInterface;
925use pounce_linsol::summary::LinearSolverSummary;
926use pounce_nlp::alg_types::SolverReturn;
927use pounce_nlp::derivative_test::{DerivativeTest, DerivativeTestOptions};
928use pounce_nlp::orig_ipopt_nlp::{ConstObjScaling, OrigIpoptNlp, ScalingMethod};
929use pounce_nlp::return_codes::ApplicationReturnStatus;
930use pounce_nlp::solve_statistics::SolveStatistics;
931use pounce_nlp::tnlp::{
932    BoundsInfo, IpoptCq as TnlpIpoptCq, IpoptData as TnlpIpoptData, NlpInfo, Solution, TNLP,
933};
934use pounce_nlp::tnlp_adapter::{
935    DEFAULT_NLP_LOWER_BOUND_INF, DEFAULT_NLP_UPPER_BOUND_INF, FixedVarTreatment, TNLPAdapter,
936};
937use std::cell::RefCell;
938use std::fmt;
939use std::path::{Path, PathBuf};
940use std::rc::Rc;
941use std::sync::{Arc, Mutex};
942use std::time::Instant;
943
944/// Smallest `n + m` at which `algorithm=active-set-sqp` starts from the
945/// interior point; see [`IpoptApplication::sqp_auto_handover`]. The fixture
946/// corpus (largest model 813 variables) sits far below it.
947pub const AUTO_HANDOVER_MIN_DIM: usize = 5_000;
948
949pub struct IpoptApplication {
950    options: OptionsList,
951    /// Diagnostics from the safeguarded `least_square_init_primal`
952    /// initializer step of the most recent solve (gh#605). `None` when
953    /// the step was not run. Read with
954    /// [`Self::least_square_init_report`].
955    least_square_init_report: Option<crate::init::default::LeastSquareInitReport>,
956    /// Per-variable scaling factors applied by the wrapper installed in
957    /// [`Self::optimize_tnlp`] (gh#486). Recorded so consumers that read
958    /// the algorithm's own iterate rather than the `finalize_solution`
959    /// payload — the CLI's `on_converged` hook feeding the `.sol` and
960    /// the JSON report — can undo the substitution. `None` when no
961    /// variable scaling was applied.
962    variable_scaling: RefCell<Option<Vec<Number>>>,
963    /// Whether the most recent `optimize_constrained` ran with per-row
964    /// constraint scaling active (`c_scale_vec`/`d_scale_vec` present).
965    ///
966    /// Read by [`Self::run_l1_penalty_outer_loop`], which measures the
967    /// user's rows in the model's own units and so may only write that
968    /// number into the `final_unscaled_*` family. `SolveStatistics`
969    /// documents `final_*` as the internally-scaled residuals and
970    /// `final_unscaled_*` as the same quantities in original units,
971    /// *equal when no scaling is active* — so the measurement may be
972    /// mirrored into the scaled family exactly when this is `false`
973    /// (gh#794 review). `None` when no solve has run.
974    row_scaling_active: std::cell::Cell<Option<bool>>,
975    /// Whether the submitted TNLP has already been explicitly wrapped by the
976    /// caller's presolve layer.
977    presolve_already_applied: bool,
978    reg_options: Rc<RegisteredOptions>,
979    journalist: Rc<Journalist>,
980    statistics: RefCell<SolveStatistics>,
981    /// Shared per-subsystem timing accumulator. Re-created at the top of
982    /// every solve (so back-to-back `optimize_tnlp` calls don't bleed
983    /// timings across invocations) and handed to the data, the NLP, and
984    /// any other consumer via `Rc`. Reported by [`Self::timing_stats`]
985    /// after the solve completes.
986    timing: RefCell<Rc<TimingStatistics>>,
987    /// Optional override factory for the symmetric linear-solver
988    /// backend. When `None`, we ship the workspace default (MA57 via
989    /// `pounce-hsl`). Tests can plug a stub via [`Self::set_linear_backend_factory`].
990    linear_backend_factory: Option<LinearBackendFactory>,
991    /// Optional factory for the restoration phase. Lives outside this
992    /// crate because `pounce-algorithm` cannot depend on
993    /// `pounce-restoration` (the dep edge is the other way). Callers
994    /// that need restoration plug a factory via
995    /// [`Self::set_restoration_factory`]; when unset, the outer
996    /// algorithm runs without a restoration fallback and surfaces
997    /// `RestorationFailure` as soon as the line-search would otherwise
998    /// jump into restoration.
999    restoration_factory: Option<RestorationFactory>,
1000    /// Shared diagnostic-dump state, installed by the CLI when the
1001    /// user passes `--dump <cat>:<spec>`. When set, the application
1002    /// propagates an `Rc<DiagnosticsState>` into [`IpoptAlgorithm`]
1003    /// via [`IpoptAlgorithm::with_diagnostics`] so the KKT solver and
1004    /// other dump sites can consult per-iter gating.
1005    diagnostics: Option<Rc<DiagnosticsState>>,
1006    /// Optional interactive debugger hook. When set, it is moved into
1007    /// the main [`IpoptAlgorithm`] for the next `optimize_*` call via
1008    /// [`IpoptAlgorithm::with_debug_hook`], so a REPL or agent can pause
1009    /// at each iteration to inspect / mutate live state. Consumed on use
1010    /// (one solve per installed hook).
1011    debug_hook: Option<std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>>,
1012    /// Provider for the BNW outer loop (pounce#10 Phase 3). When set,
1013    /// `optimize_constrained` consults the provider before each inner
1014    /// solve, replacing `restoration_factory` with a fresh one so
1015    /// multi-pass drivers can run the inner IPM repeatedly without
1016    /// tripping the default factory's one-shot guard.
1017    restoration_factory_provider: Option<RestorationFactoryProvider>,
1018    /// Optional hook fired once per `optimize_*` call on convergence,
1019    /// before the user TNLP's `finalize_solution`. See
1020    /// [`ConvergedCallback`].
1021    on_converged: Option<ConvergedCallback>,
1022    /// Re-evaluate `W` at the converged point before `on_converged` fires.
1023    /// See [`Self::set_on_converged_refreshes_hessian`].
1024    on_converged_refreshes_hessian: bool,
1025    /// Ids handed out so far to `on_converged` firings; the next firing gets
1026    /// one more. Never reset, so an id is unique over the application's life.
1027    /// See [`IpoptData::on_converged_id`](crate::ipopt_data::IpoptData).
1028    on_converged_fired: std::cell::Cell<u64>,
1029    /// When `true`, the per-iteration `IterRecord` trajectory is
1030    /// captured into [`SolveStatistics::iterations`] for downstream
1031    /// consumers (the JSON solve report in pounce-cli, pounce#8). Off
1032    /// by default so library callers that never read the iterations
1033    /// vector don't pay the per-iter alloc.
1034    record_iter_history: bool,
1035    /// Whether [`Self::initialize_with_option_file`] ran — i.e. whether
1036    /// anything on this application actually consulted
1037    /// `option_file_name` and resolved it to a file. Only the `pounce`
1038    /// CLI does; a library caller sets its options directly. The guard
1039    /// in [`Self::unhonored_option_file_name`] reads this so that
1040    /// setting the option on a surface that cannot honor it is refused
1041    /// rather than dropped (gh#518).
1042    option_file_resolved: bool,
1043    /// Whether this caller can route a model to the convex LP/QP/SOCP
1044    /// engines — i.e. whether the `qp_*` knobs those engines read
1045    /// configure anything here. Only the `pounce` CLI can (it owns the
1046    /// `.nl` structure extraction that classifies a model), and it says
1047    /// so via [`Self::set_convex_routing_available`]. The guard in
1048    /// [`Self::unhonored_convex_option`] reads this, on the same
1049    /// contract as `option_file_resolved` above (gh#604).
1050    convex_routing_available: bool,
1051    /// Whether the backend-knob warnings (gh#551) have already been
1052    /// printed for this application. The CLI emits them before routing —
1053    /// a convex model never reaches `optimize_tnlp` — and `optimize_tnlp`
1054    /// emits them for every other frontend; without this flag a CLI run
1055    /// would print each line twice, which is how a warning teaches its
1056    /// reader to skip it.
1057    backend_warnings_emitted: bool,
1058    /// Shared sink that the linear-solver backend writes a rolling
1059    /// [`LinearSolverSummary`] into after every factor. Reset at the
1060    /// top of every solve (so back-to-back `optimize_tnlp` calls don't
1061    /// bleed stats across invocations) and read out via
1062    /// [`Self::linear_solver_summary`] once the solve returns. Only
1063    /// the workspace-default FERAL backend (via
1064    /// [`default_backend_factory_with_sink`]) wires the sink today;
1065    /// custom factories plugged through [`Self::set_linear_backend_factory`]
1066    /// and the HSL MA57 backend leave the sink empty.
1067    linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1068    /// Companion to [`Self::linsol_summary_sink`] for the restoration
1069    /// phase's sub-solves. The frontends that wire a restoration factory
1070    /// install it via [`Self::restoration_summary_sink`]; it is reset with
1071    /// the main sink and surfaces as [`LinearSolverSummary::restoration`].
1072    resto_linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1073    /// The block-parallel KKT partition this solve resolved, published for
1074    /// the restoration sub-IPM (structured-KKT Phase 5b). Restoration's inner
1075    /// builder is minted by the frontend *before* the solve — before the KKT
1076    /// layout, and so the mapping onto it, exists — so the labels cannot be
1077    /// installed on it directly. They are written here as the outer algorithm
1078    /// is built and read when restoration runs. `AugRestoSystemSolver` reduces
1079    /// the restoration KKT onto the original 4-block system before delegating,
1080    /// so the matrix the inner solver factors is the one these labels
1081    /// describe. Reset with the sinks at the top of every solve.
1082    kkt_blocks_published: crate::alg_builder::KktBlocksCell,
1083    /// Shared tally of successful linear-solver quality escalations for
1084    /// the current solve (gh#857). Handed to every `AlgorithmBuilder`
1085    /// this application mints — [`Self::algorithm_builder_from_options`]
1086    /// and [`Self::algorithm_builder_snapshot`] — which is how the
1087    /// restoration sub-solve counts into the same total: each frontend
1088    /// builds the restoration provider's inner builder from
1089    /// `algorithm_builder_from_options`, so it receives this same `Rc`
1090    /// without any frontend having to know the counter exists.
1091    ///
1092    /// Reset at the top of every solve, beside the linear-solver summary
1093    /// sink and for the same reason: a second-opinion retry, or two
1094    /// back-to-back `optimize_tnlp` calls, must not inherit the previous
1095    /// solve's count. Read out into
1096    /// [`SolveStatistics::quality_escalations`] once the solve returns.
1097    quality_escalations: Rc<std::cell::Cell<u64>>,
1098    /// gh#990: the `mu_strategy` value in the option table was written by a
1099    /// POUNCE frontend (the Python no-`hessian` path pins `monotone`), not by
1100    /// the caller. See [`Self::mark_mu_strategy_pounce_chosen`].
1101    mu_strategy_pounce_chosen: bool,
1102    /// gh#884. Set when the running [`IpoptAlgorithm`] observed the
1103    /// biactive dual-divergence signature — a converged primal, a step
1104    /// that has gone to zero on a scale-relative measure, and an
1105    /// *unscaled* dual infeasibility still far above `dual_inf_tol`, all
1106    /// at the same iterate.
1107    ///
1108    /// Read out of the algorithm once `optimize_constrained` returns, so
1109    /// [`Self::run_with_dual_divergence_retry`] — which sits above that
1110    /// call — can see it. Reset at the top of every solve for the same
1111    /// reason as `quality_escalations`: a retry must not inherit the
1112    /// previous attempt's verdict. Also copied into
1113    /// [`SolveStatistics::dual_divergence_signature`].
1114    dual_divergence_signature: std::cell::Cell<bool>,
1115    /// gh#990 item 3: the derivative checker's structured result for the
1116    /// current solve; copied onto the statistics when the solve finishes.
1117    derivative_check: RefCell<Option<pounce_nlp::derivative_test::DerivativeCheckSummary>>,
1118    /// gh#990 item 13: some attempt of this run refused a termination
1119    /// certificate the objective scaling had masked (strict, acceptable).
1120    /// Sticky across the attempts a retry driver spends, like
1121    /// `dual_divergence_signature`: the returned run is often a re-solve, and
1122    /// the decision that led to it belongs on the record.
1123    obj_scale_refused: std::cell::Cell<(bool, bool)>,
1124    /// gh#884. Set when a dual-divergence retry actually replaced the base
1125    /// attempt's answer. Copied into
1126    /// [`SolveStatistics::dual_divergence_retry_promoted`].
1127    dual_divergence_retry_promoted: std::cell::Cell<bool>,
1128    /// gh#1042 C1. What the `mu_strategy_fallback` retry did in this solve,
1129    /// if it ran. Copied into [`SolveStatistics::mu_strategy_fallback`] by
1130    /// every attempt that follows it, and written into the statistics
1131    /// directly once the retry has decided — so a promoted re-solve no
1132    /// longer hides the first attempt's verdict and cost.
1133    mu_strategy_fallback_record: RefCell<Option<pounce_nlp::MuStrategyFallbackRecord>>,
1134    /// Set when a losing retry's answer was thrown away and an earlier
1135    /// attempt's replayed through `FinalizeSnapshot::replay` — by the μ
1136    /// fallback (pounce#870) or the gh#884 dual-divergence retry.
1137    ///
1138    /// It exists because [`Self::set_on_converged`] fires **per attempt**
1139    /// and the floor does not reach it. A losing retry that reached
1140    /// `Solve_Succeeded` has already run the callback, so a consumer
1141    /// capturing the converged iterate there — the CLI's `nominal_capture`,
1142    /// which is where `.sol` `x`, the JSON's `solution.x` and the dual
1143    /// block all come from — holds the *discarded* attempt's point while
1144    /// the status, objective and every statistic beside it have been
1145    /// floored back to the attempt that won. Measured before this flag
1146    /// existed: on a declined retry the `.sol` carried `f = -6.3274` while
1147    /// the JSON report next to it said `-6.1768`, and `pounce verify` on
1148    /// the `.sol` confirmed the file held the losing point.
1149    ///
1150    /// The `finalize_solution` payload does not have this problem — the
1151    /// replay *is* a `finalize_solution` call, so the last one always
1152    /// carries the answer being reported — which is why the fix is to tell
1153    /// the caller "prefer that payload", not to re-run the callback (the
1154    /// converged KKT state the callback borrows belongs to the retry by
1155    /// then, and cannot be rewound). Consumers of that state select the
1156    /// reported attempt's firing through [`Self::reported_on_converged_id`].
1157    answer_restored_from_floor: std::cell::Cell<bool>,
1158    /// Set only for the duration of the gh#983 scale audit's re-solve: the
1159    /// interior-point arm then widens the inequality rows by
1160    /// `bound_relax_factor` as usual but leaves the **variable box as the
1161    /// caller declared it** (`OrigIpoptNlp::relax_bounds_keeping_box`). See
1162    /// `run_scale_retry` for why.
1163    retry_keeps_declared_box: std::cell::Cell<bool>,
1164    /// The payload of the most recent `finalize_solution` POUNCE sent to the
1165    /// user's TNLP, so a second-opinion retry that loses can put the winning
1166    /// attempt's answer back (pounce#870).
1167    ///
1168    /// Written by [`finalize_via_orig_nlp`] and [`finalize_via_sqp`], which are
1169    /// free functions and so take this as a sink rather than reaching for
1170    /// `self`, and by [`Self::restore_floor`] when a floor is replayed, so it
1171    /// always holds the answer currently delivered. Cleared at the start of
1172    /// each solve. Read by the retry wrappers (each floors to it) and by
1173    /// [`Self::reported_on_converged_id`].
1174    last_finalize: RefCell<Option<FinalizeSnapshot>>,
1175    /// The last `IterStats` sent to the user's `intermediate_callback`
1176    /// (pounce#870), shared with the running `IpoptAlgorithm`.
1177    last_iter_stats: Rc<RefCell<Option<pounce_nlp::tnlp::IterStats>>>,
1178    /// Phase 5c (§6) SQP warm-start input. When `Some`, the next
1179    /// `optimize_tnlp` call on the SQP path consumes the iterate
1180    /// instead of cold-starting; consumed once per solve, then
1181    /// auto-cleared. The IPM path ignores this field. Wire-set
1182    /// via [`Self::set_sqp_warm_start`].
1183    sqp_warm_start: Option<crate::sqp::SqpIterates>,
1184    /// Phase 5c (§6) SQP warm-start output. Populated by every
1185    /// `optimize_sqp_tnlp` call with the final QP working set.
1186    /// Stays valid until the next solve (which overwrites it).
1187    /// Accessed via [`Self::last_sqp_working_set`].
1188    sqp_last_working_set: Option<pounce_qp::WorkingSet>,
1189    /// gh#986 review item 10: the fixed-variable elimination of the solve in
1190    /// progress, `(x_not_fixed_map, n_full_x)`. Working sets are published in
1191    /// the caller's full space (fixed variables marked `Fixed`) and warm
1192    /// starts are mapped through it, so a working set recorded on one node
1193    /// lands on the right columns of a node that fixes different variables.
1194    x_elimination: Option<(Vec<Index>, usize)>,
1195    /// What the post-convergence crossover phase did on the most recent
1196    /// IPM solve (gh#612). `None` when `crossover=no` (the default) or
1197    /// when the solve did not converge — crossover only runs on a
1198    /// converged interior iterate. Read via [`Self::crossover_report`].
1199    ///
1200    /// Kept separate from `sqp_last_working_set`, which crossover *also*
1201    /// populates on success: that field answers "what can the next solve
1202    /// warm-start from", this one answers "was the active set I am about
1203    /// to trust actually identified, or merely inferred".
1204    crossover_report: Option<crate::crossover::CrossoverReport>,
1205    /// What the interior-point → active-set handover did on the most recent
1206    /// IPM solve (gh#1054). `None` when `ipm_sqp_handover=no` (the default).
1207    /// Read via [`Self::handover_report`].
1208    handover_report: Option<crate::handover::HandoverReport>,
1209    /// Whether the current solve is an `algorithm=active-set-sqp` request
1210    /// run as interior point plus handover; see [`Self::sqp_auto_handover`].
1211    auto_handover: std::cell::Cell<bool>,
1212    /// Full primal-dual warm-start iterate for the IPM path, captured by
1213    /// the interactive debugger's `resolve` command. When `Some`, the
1214    /// next `optimize_tnlp` installs this 8-vector (algorithm space)
1215    /// directly onto `data.curr` before the iterate initializer runs, so
1216    /// a warm `resolve` continues from the paused interior point rather
1217    /// than cold-restarting the duals. Consumed once per solve, then
1218    /// auto-cleared. Requires `warm_start_init_point=yes` so the
1219    /// re-optimize branch of `WarmStartIterateInitializer` keeps the
1220    /// installed iterate. Wire-set via [`Self::set_warm_start_iterate`].
1221    warm_start_iterate: Option<crate::debug::IterateSnapshot>,
1222    /// The warm-start initializer's verdict on the most recent solve's
1223    /// supplied iterate (gh#606). Lifted off the solve-local
1224    /// `IpoptData` so a caller can read it after `optimize_tnlp`
1225    /// returns; `None` when the last solve was a cold start.
1226    warm_start_diag: RefCell<Option<crate::init::warm_start::WarmStartDiagnostics>>,
1227    /// Caller-supplied fill-reducing permutation for the KKT linear
1228    /// solver (pounce#180 item 1 / FERAL#107). When `Some`, it overrides
1229    /// whatever `feral_ordering` / `POUNCE_FERAL_ORDERING` resolves to,
1230    /// installing [`pounce_feral::OrderingMethod::External`] on the FERAL
1231    /// backend for the next solve. The vector is a **0-based, new-to-old
1232    /// permutation** whose length must equal the augmented KKT system
1233    /// dimension; FERAL validates it as a bijection and returns
1234    /// `InvalidInput` (never panics) on a wrong length / index. Unlike the
1235    /// warm-start hooks this is treated as persistent config — it is *not*
1236    /// auto-cleared after a solve, so a caller sets it once for a run.
1237    /// Wire-set via [`Self::set_external_ordering`]. Ignored by non-FERAL
1238    /// backends and by any custom factory plugged via
1239    /// [`Self::set_linear_backend_factory`].
1240    external_ordering: Option<Vec<usize>>,
1241    /// Caller-supplied block-triangular / Schur KKT partition (pounce#180
1242    /// item 2). When `Some`, the next IPM solve on the feral + exact-Hessian
1243    /// path routes the KKT linear solve through a
1244    /// [`crate::kkt::SchurAugSystemSolver`] over these **KKT-space indices**
1245    /// (`0..dim` in the `x, s, c, d` block order the aug-system solver
1246    /// assembles): the `S` block is Schur-complemented out and only the two
1247    /// diagonal blocks are factorized, with inertia recovered via Sylvester's
1248    /// law. Beneficial only when `|S| ≪` the eliminated block; the Schur solver
1249    /// falls back to the standard full-space solver transparently when the
1250    /// partition is unsuitable (too large, malformed, or the backend errors),
1251    /// so a stray hook never breaks a solve. Persistent config (not
1252    /// auto-cleared). Wire-set via [`Self::set_kkt_schur_block`].
1253    kkt_schur_block: Option<Vec<usize>>,
1254    /// Block-parallel KKT partition (structured-KKT Phase 5b): KKT-space block
1255    /// labels, `< 0` for the shared border, **empty** meaning "detect".
1256    /// Wire-set via [`Self::set_kkt_block_structure`].
1257    kkt_blocks: Option<Vec<i32>>,
1258    /// The same partition declared in the *model's* own terms — one block per
1259    /// variable and per constraint — which [`map_block_structure_to_kkt`]
1260    /// turns into `kkt_blocks` once the NLP layout is known. Wire-set via
1261    /// [`Self::set_block_structure`].
1262    model_blocks: Option<(Vec<i32>, Vec<i32>)>,
1263    /// The problem-statistics block most recently printed during the current
1264    /// run, so a retry attempt does not reprint an identical one.
1265    ///
1266    /// Every retry driver — the ℓ₁ fallback, the μ-strategy fallback, the
1267    /// second-opinion ladder, the dual-divergence retry — re-enters the solve
1268    /// routine that emits this block, so a run that retried once printed the
1269    /// whole Ipopt-style header twice with nothing between the copies saying a
1270    /// second attempt had started. Read as "the solver printed everything
1271    /// twice", which is what it looked like.
1272    ///
1273    /// Scoped to one run: reset at the top of
1274    /// [`Self::optimize_tnlp_with_derivative_test_tnlp`], which every entry
1275    /// point funnels through. Without that reset a library caller's second
1276    /// deliberate `optimize_tnlp` on the same application would lose its
1277    /// header, which is a different thing entirely from a retry inside one
1278    /// call.
1279    ///
1280    /// Compared rather than counted because the block can legitimately differ
1281    /// between attempts: the ℓ₁ wrapper adds slack variables, so its retry
1282    /// solves a genuinely larger problem and reprinting is informative.
1283    last_printed_problem_stats: RefCell<Option<pounce_solve_report::console::ProblemStats>>,
1284    /// Set while an *outside* retry driver is re-entering `optimize_tnlp` for
1285    /// another attempt on the same problem — today only
1286    /// `pounce_restoration::second_opinion_driver::run_second_opinion_ladder`.
1287    ///
1288    /// The retries that nest INSIDE one `optimize_tnlp` call (the ℓ₁ fallback,
1289    /// the μ-strategy fallback) are covered by `last_printed_problem_stats`
1290    /// alone, because the funnel that resets it runs once for all of them. The
1291    /// ladder's rungs are `optimize_tnlp` calls in their own right, so without
1292    /// this flag each one resets the memo and reprints the header — which is
1293    /// how a four-rung ladder printed five identical copies of it.
1294    ///
1295    /// It also decides who explains the retry. The ladder narrates every rung
1296    /// on stderr, naming the knob it varies and whether the rung recovered, so
1297    /// `emit_problem_stats` stays quiet and lets that narration stand. The
1298    /// in-call fallbacks say nothing at all, so there the suppressed header is
1299    /// replaced by a line announcing the attempt.
1300    in_retry_sequence: std::cell::Cell<bool>,
1301    /// Nesting depth of retry drivers that have taken ownership of the
1302    /// run-ending `EXIT:` / `POUNCE <version>:` verdict.
1303    ///
1304    /// `emit_end_summary` prints the per-attempt statistics block whatever
1305    /// this reads, and prints the verdict only at zero. A driver raises it
1306    /// before its first attempt and lowers it after its last, then prints the
1307    /// verdict once with the status it is actually returning.
1308    ///
1309    /// A counter rather than a flag because the drivers nest: the ℓ₁ fallback
1310    /// can wrap the μ-strategy fallback, which the dual-divergence retry can
1311    /// wrap in turn, and the CLI brackets the whole lot again around the
1312    /// second-opinion ladder. Only the outermost knows the run is over, and
1313    /// "outermost" is exactly "the one that brings this back to zero".
1314    end_verdict_deferrals: std::cell::Cell<u32>,
1315}
1316
1317impl fmt::Debug for IpoptApplication {
1318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1319        f.debug_struct("IpoptApplication")
1320            .field("options", &self.options)
1321            .field("statistics", &self.statistics)
1322            .finish_non_exhaustive()
1323    }
1324}
1325
1326impl Default for IpoptApplication {
1327    fn default() -> Self {
1328        Self::new()
1329    }
1330}
1331
1332impl IpoptApplication {
1333    /// New application with empty options and a default journalist.
1334    /// Equivalent to `IpoptApplication::IpoptApplication(true,true)`.
1335    pub fn new() -> Self {
1336        let reg = RegisteredOptions::default();
1337        // Registration of a fresh registry can only fail on a duplicate
1338        // name, which would be a programming error in `reg_op`.
1339        register_all_upstream_options(&reg)
1340            .unwrap_or_else(|e| panic!("Upstream options registration failed: {e}"));
1341        pounce_presolve::register_options(&reg)
1342            .unwrap_or_else(|e| panic!("Presolve options registration failed: {e}"));
1343        let reg = Rc::new(reg);
1344        Self {
1345            options: OptionsList::with_registered(Rc::clone(&reg)),
1346            least_square_init_report: None,
1347            variable_scaling: RefCell::new(None),
1348            row_scaling_active: std::cell::Cell::new(None),
1349            presolve_already_applied: false,
1350            reg_options: reg,
1351            journalist: Rc::new(Journalist::new()),
1352            statistics: RefCell::new(SolveStatistics::new()),
1353            timing: RefCell::new(Rc::new(TimingStatistics::new())),
1354            linear_backend_factory: None,
1355            restoration_factory: None,
1356            diagnostics: None,
1357            debug_hook: None,
1358            restoration_factory_provider: None,
1359            on_converged: None,
1360            on_converged_refreshes_hessian: true,
1361            on_converged_fired: std::cell::Cell::new(0),
1362            record_iter_history: false,
1363            option_file_resolved: false,
1364            convex_routing_available: false,
1365            backend_warnings_emitted: false,
1366            linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1367            resto_linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1368            kkt_blocks_published: Arc::new(Mutex::new(None)),
1369            quality_escalations: Rc::new(std::cell::Cell::new(0)),
1370            mu_strategy_pounce_chosen: false,
1371            dual_divergence_signature: std::cell::Cell::new(false),
1372            derivative_check: RefCell::new(None),
1373            obj_scale_refused: std::cell::Cell::new((false, false)),
1374            dual_divergence_retry_promoted: std::cell::Cell::new(false),
1375            mu_strategy_fallback_record: RefCell::new(None),
1376            answer_restored_from_floor: std::cell::Cell::new(false),
1377            retry_keeps_declared_box: std::cell::Cell::new(false),
1378            last_finalize: RefCell::new(None),
1379            last_iter_stats: Rc::new(RefCell::new(None)),
1380            sqp_warm_start: None,
1381            sqp_last_working_set: None,
1382            x_elimination: None,
1383            crossover_report: None,
1384            handover_report: None,
1385            auto_handover: std::cell::Cell::new(false),
1386            warm_start_iterate: None,
1387            warm_start_diag: RefCell::new(None),
1388            external_ordering: None,
1389            kkt_schur_block: None,
1390            kkt_blocks: None,
1391            model_blocks: None,
1392            last_printed_problem_stats: RefCell::new(None),
1393            in_retry_sequence: std::cell::Cell::new(false),
1394            end_verdict_deferrals: std::cell::Cell::new(0),
1395        }
1396    }
1397
1398    pub fn options(&self) -> &OptionsList {
1399        &self.options
1400    }
1401
1402    pub fn options_mut(&mut self) -> &mut OptionsList {
1403        &mut self.options
1404    }
1405
1406    /// Declare whether callers have already applied an explicit presolve
1407    /// wrapper to the TNLPs submitted to [`Self::optimize_tnlp`].
1408    ///
1409    /// When set, `optimize_tnlp` leaves its input TNLP unchanged even if the
1410    /// `presolve` option is enabled. This preserves the option table for
1411    /// reporting and debugger use while allowing specialized frontends to
1412    /// supply a wrapper with capabilities unavailable to generic callback
1413    /// TNLPs, such as an expression provider for FBBT.
1414    pub fn set_presolve_already_applied(&mut self, applied: bool) {
1415        self.presolve_already_applied = applied;
1416    }
1417
1418    /// Solve without materializing the generic presolve wrapper.
1419    ///
1420    /// This is for consumers that require the original TNLP coordinate system
1421    /// for the solve's KKT matrix, such as sensitivity and reduced-Hessian
1422    /// drivers. It is scoped to this invocation and does not change the
1423    /// application's `presolve` option or persistent explicit-wrapper setting.
1424    pub fn optimize_tnlp_without_presolve(
1425        &mut self,
1426        tnlp: Rc<RefCell<dyn TNLP>>,
1427    ) -> ApplicationReturnStatus {
1428        let explicit_wrapper = self.presolve_already_applied;
1429        self.presolve_already_applied = true;
1430        let status = self.optimize_tnlp(tnlp);
1431        self.presolve_already_applied = explicit_wrapper;
1432        status
1433    }
1434
1435    pub fn registered_options(&self) -> &Rc<RegisteredOptions> {
1436        &self.reg_options
1437    }
1438
1439    pub fn journalist(&self) -> &Rc<Journalist> {
1440        &self.journalist
1441    }
1442
1443    /// Plug a custom symmetric-linear-solver factory. Useful for tests
1444    /// that want to swap MA57 for a stub. Production callers should
1445    /// leave this unset — the default ([`default_backend_factory`])
1446    /// returns the workspace's MA57 binding.
1447    pub fn set_linear_backend_factory(&mut self, factory: LinearBackendFactory) {
1448        self.linear_backend_factory = Some(factory);
1449    }
1450
1451    /// Plug a restoration-phase factory. Called once per
1452    /// `optimize_tnlp` invocation to mint a fresh
1453    /// `Box<dyn RestorationPhase>` that the outer algorithm uses as
1454    /// its line-search restoration fallback. Lives behind a setter
1455    /// (rather than at construction) because the concrete restoration
1456    /// strategies live in `pounce-restoration`, which depends on this
1457    /// crate; consumers in `pounce-cli` / integration tests wire the
1458    /// factory at the application boundary.
1459    pub fn set_restoration_factory(&mut self, factory: RestorationFactory) {
1460        self.restoration_factory = Some(factory);
1461    }
1462
1463    /// Install the shared diagnostics state. Once set, every
1464    /// subsequent `optimize_tnlp` call forwards the state into the
1465    /// algorithm via [`IpoptAlgorithm::with_diagnostics`] so the KKT
1466    /// solver can emit `--dump kkt:...` artifacts.
1467    pub fn set_diagnostics(&mut self, diag: Rc<DiagnosticsState>) {
1468        self.diagnostics = Some(diag);
1469    }
1470
1471    /// Install an interactive debugger hook for the next `optimize_*`
1472    /// call. The hook is moved into the main [`IpoptAlgorithm`] and
1473    /// consumed by that solve; reinstall it to debug a subsequent solve.
1474    pub fn set_debug_hook(
1475        &mut self,
1476        hook: std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>,
1477    ) {
1478        self.debug_hook = Some(hook);
1479    }
1480
1481    /// Read-side accessor for the installed diagnostics state, if any.
1482    /// Lets the CLI write the top-level manifest/timing files after
1483    /// the solve completes.
1484    pub fn diagnostics(&self) -> Option<Rc<DiagnosticsState>> {
1485        self.diagnostics.as_ref().map(Rc::clone)
1486    }
1487
1488    /// The three options that decide how the TNLP is *classified* before any
1489    /// algorithm sees it: the two infinity thresholds and the fixed-variable
1490    /// treatment.
1491    ///
1492    /// One reader, because there were three copies and they drifted. The
1493    /// active-set SQP path built its adapter with `TNLPAdapter::new`, which
1494    /// hard-codes the same three defaults — so the options were accepted and
1495    /// discarded on that arm, and a model with `fixed_variable_treatment=
1496    /// relax_bounds` or a non-default `nlp_upper_bound_inf` was classified one
1497    /// way for the interior-point arm and another for this one. Silently: the
1498    /// defaults coincide, so it only diverges for a caller who sets them, and
1499    /// nothing reported the difference.
1500    ///
1501    /// `make_constraint` / `make_parameter_nodual` are not implemented and
1502    /// fall back to `make_parameter`; the adapter auto-retries to
1503    /// `relax_bounds` when `make_parameter` would leave `n_x_var < n_c`
1504    /// (upstream `IpTNLPAdapter.cpp:623-633`).
1505    fn adapter_options(&self) -> (Number, Number, FixedVarTreatment) {
1506        let lo_inf = self
1507            .options
1508            .get_numeric_value("nlp_lower_bound_inf", "")
1509            .ok()
1510            .and_then(|(v, f)| f.then_some(v))
1511            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF);
1512        let up_inf = self
1513            .options
1514            .get_numeric_value("nlp_upper_bound_inf", "")
1515            .ok()
1516            .and_then(|(v, f)| f.then_some(v))
1517            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF);
1518        let fixed_treatment = match self
1519            .options
1520            .get_string_value("fixed_variable_treatment", "")
1521            .ok()
1522            .and_then(|(v, f)| f.then_some(v))
1523            .as_deref()
1524        {
1525            Some("relax_bounds") => FixedVarTreatment::RelaxBounds,
1526            _ => FixedVarTreatment::MakeParameter,
1527        };
1528        (lo_inf, up_inf, fixed_treatment)
1529    }
1530
1531    /// Whether the final solution reports bound multipliers for variables
1532    /// `make_parameter` removed (see
1533    /// `OrigIpoptNlp::complete_fixed_var_bound_multipliers`).
1534    /// Ipopt 3.14 does, for every treatment except `make_parameter_nodual`,
1535    /// which exists to ask it not to.
1536    pub fn reports_fixed_var_duals(&self) -> bool {
1537        !matches!(
1538            self.options
1539                .get_string_value("fixed_variable_treatment", "")
1540                .ok()
1541                .map(|(v, _)| v)
1542                .as_deref(),
1543            Some("make_parameter_nodual")
1544        )
1545    }
1546
1547    /// Mark that the next `optimize_*` calls are further **attempts at the
1548    /// same problem**, driven from outside, rather than new solves.
1549    ///
1550    /// Retry drivers that re-enter `optimize_tnlp` per attempt — the
1551    /// second-opinion ladder is the only one today — bracket their attempts
1552    /// with `true` … `false`. The effect is confined to console presentation:
1553    /// the Ipopt-style problem-statistics header is printed once for the run
1554    /// instead of once per attempt. Nothing about the solve changes.
1555    ///
1556    /// Callers must clear it on every exit path, including the early returns a
1557    /// ladder takes when a rung promotes; a stuck `true` costs a later solve
1558    /// its header and nothing worse.
1559    pub fn set_in_retry_sequence(&self, active: bool) {
1560        self.in_retry_sequence.set(active);
1561    }
1562
1563    /// Take ownership of the run-ending `EXIT:` / `POUNCE <version>:` verdict
1564    /// for the attempts that follow.
1565    ///
1566    /// Between this and [`Self::release_end_verdict`] the per-attempt end
1567    /// summary prints its statistics block but not the verdict, so a retried
1568    /// run no longer reports a mid-run verdict that reads as the final answer.
1569    /// The releaser prints it once, with the status it is returning.
1570    ///
1571    /// Callers must pair the two on every exit path. An unmatched acquire
1572    /// costs the run its verdict line; the counter saturates rather than
1573    /// wrapping, so an unmatched release cannot make a nested driver print
1574    /// one early.
1575    pub fn defer_end_verdict(&self) {
1576        self.end_verdict_deferrals
1577            .set(self.end_verdict_deferrals.get().saturating_add(1));
1578    }
1579
1580    /// Release one [`Self::defer_end_verdict`]. Returns `true` when this was
1581    /// the outermost one — i.e. when the caller now owns printing the verdict.
1582    #[must_use]
1583    pub fn release_end_verdict(&self) -> bool {
1584        let next = self.end_verdict_deferrals.get().saturating_sub(1);
1585        self.end_verdict_deferrals.set(next);
1586        next == 0
1587    }
1588
1589    /// Print the run-ending verdict, honouring `print_level`.
1590    ///
1591    /// The gate matches `emit_end_summary`'s, which is the block this follows:
1592    /// at `print_level 0` there is no summary for it to end.
1593    pub fn print_end_verdict(&self, status: ApplicationReturnStatus) {
1594        let console_output = match self.options.get_integer_value("print_level", "") {
1595            Ok((v, true)) => v >= 1,
1596            _ => true,
1597        };
1598        if console_output {
1599            pounce_solve_report::console::print_exit_verdict(status);
1600        }
1601    }
1602
1603    /// Plug a restoration-phase **factory provider** for drivers that
1604    /// need to run the inner IPM more than once per `optimize_tnlp`
1605    /// call (notably the Phase-3 ℓ₁-exact penalty-barrier outer loop,
1606    /// pounce#10). On each inner solve, the application consults the
1607    /// provider to mint a fresh [`RestorationFactory`], replacing any
1608    /// stale one, so the default one-shot restoration factory does
1609    /// not panic on its second invocation. If both `set_restoration_factory`
1610    /// and this are configured, the provider wins.
1611    pub fn set_restoration_factory_provider(&mut self, provider: RestorationFactoryProvider) {
1612        self.restoration_factory_provider = Some(provider);
1613    }
1614
1615    /// Register a callback to run once the IPM has converged (status
1616    /// [`ApplicationReturnStatus::SolveSucceeded`] or
1617    /// [`ApplicationReturnStatus::SolvedToAcceptableLevel`]) but before
1618    /// `finalize_solution` flows back to the TNLP. See
1619    /// [`ConvergedCallback`] for the use case (post-optimal sensitivity).
1620    pub fn set_on_converged(&mut self, cb: ConvergedCallback) {
1621        self.on_converged = Some(cb);
1622    }
1623
1624    /// Remove and return the registered on-converged callback, if any, so a
1625    /// caller that installs its own for a while can put the previous one
1626    /// back (`pounce_minima::IpoptLocalSolve` does, gh#966).
1627    pub fn take_on_converged(&mut self) -> Option<ConvergedCallback> {
1628        self.on_converged.take()
1629    }
1630
1631    /// Whether `data.w` is re-evaluated at the converged point `w*` before
1632    /// the [`Self::set_on_converged`] hook fires. On by default.
1633    ///
1634    /// The main loop checks convergence before it updates the Hessian, so at
1635    /// that moment `data.w` is still `W(w_k)` from the final Newton step,
1636    /// while the Jacobians, slacks, multipliers and `Σ` are read at `w*`. A
1637    /// hook that factors the KKT matrix (post-optimal sensitivity) needs the
1638    /// Hessian at `w*` too, or it factors a hybrid of two iterates.
1639    ///
1640    /// The refresh costs one Hessian evaluation, counted in the solve's
1641    /// statistics like any other. A hook that only reads the iterate and
1642    /// never factors (the CLI collecting duals for a `.sol` file) can turn it
1643    /// off so a plain solve reports the same evaluation counts with or
1644    /// without the hook installed.
1645    pub fn set_on_converged_refreshes_hessian(&mut self, refresh: bool) {
1646        self.on_converged_refreshes_hessian = refresh;
1647    }
1648
1649    /// Was the reported answer replayed from an earlier attempt's floor,
1650    /// after a later attempt lost?
1651    ///
1652    /// **A caller that captures the solution in [`Self::set_on_converged`]
1653    /// must consult this.** That callback fires once per *attempt*, and a
1654    /// losing retry that converged has already run it, so the capture
1655    /// belongs to the discarded point while everything else — status,
1656    /// objective, statistics — has been floored back. When this is `true`,
1657    /// take `x` and the multipliers from the last `finalize_solution`
1658    /// payload instead; that one is always the answer being reported,
1659    /// because the floor restores it *by* calling `finalize_solution`.
1660    ///
1661    /// The payload is in the **model's own units** and in the **reduced**
1662    /// presolve space: `CountingTnlp`-style consumers sit inside the gh#486
1663    /// scaling wrapper (so `x /= d`, `z *= d` have already been applied) and
1664    /// outside the presolve one (so the row/column lift has not). A caller
1665    /// swapping it in must therefore skip its own scaling correction and keep
1666    /// its own lift; getting that backwards squares the factor, which is a
1667    /// silent wrong answer of exactly the shape this flag exists to remove.
1668    ///
1669    /// A [`Self::set_on_converged`] consumer that needs more than the point --
1670    /// the converged KKT state and its factorization, which the payload does
1671    /// not carry and which cannot be rewound -- uses
1672    /// [`Self::reported_on_converged_id`] instead: it keeps each firing under
1673    /// its id and holds the one the solve reported, whose handles keep that
1674    /// attempt's state alive. `pounce-sensitivity`'s `Solver` and `SensSolve`
1675    /// and the CLI's hook do.
1676    ///
1677    /// `false` on every solve that never spent a second attempt, which is
1678    /// almost all of them, so the ordinary path is unaffected.
1679    pub fn answer_restored_from_floor(&self) -> bool {
1680        self.answer_restored_from_floor.get()
1681    }
1682
1683    /// The [`Self::set_on_converged`] firing whose attempt produced the
1684    /// answer the last solve reported, or `None` if that attempt did not fire
1685    /// the hook (it did not converge, or it was not the interior-point arm).
1686    ///
1687    /// The hook fires once per converged attempt, and when a later attempt
1688    /// loses the answer is replayed from an earlier one, so the most recent
1689    /// firing is not necessarily the reported one. A hook that keeps state
1690    /// files it under [`IpoptData::on_converged_id`](crate::ipopt_data::IpoptData)
1691    /// and keeps the firing this names; everything else it captured describes
1692    /// an attempt the solver discarded.
1693    pub fn reported_on_converged_id(&self) -> Option<u64> {
1694        self.last_finalize
1695            .borrow()
1696            .as_ref()
1697            .and_then(|s| s.on_converged_id)
1698    }
1699
1700    /// When the last solve ended in local infeasibility, probe the point it
1701    /// reported for a nearby point with less constraint violation
1702    /// ([`crate::infeasibility_saddle`]). `None` when the last solve reported
1703    /// anything else, or when the probe finds no such point.
1704    ///
1705    /// The point probed is the payload the user's TNLP was handed, so it is
1706    /// the reported point after any retry's floor; it is cleared at the start
1707    /// of every solve, so a stale point cannot be probed. `tnlp` must be the
1708    /// TNLP that solve ran on. Read by the second-opinion ladder.
1709    pub fn local_infeasibility_saddle_escape(
1710        &self,
1711        tnlp: &Rc<RefCell<dyn TNLP>>,
1712    ) -> Option<crate::infeasibility_saddle::SaddleEscape> {
1713        let x = self
1714            .last_finalize
1715            .borrow()
1716            .as_ref()
1717            .filter(|s| s.status == SolverReturn::LocalInfeasibility)
1718            .map(|s| s.x.clone())?;
1719        crate::infeasibility_saddle::infeasibility_saddle_escape(
1720            tnlp,
1721            &x,
1722            self.nlp_lower_bound_inf(),
1723            self.nlp_upper_bound_inf(),
1724        )
1725    }
1726
1727    /// Put a losing retry's floor back: re-deliver the winning attempt's
1728    /// payload to the user's TNLP and make it the recorded answer again.
1729    ///
1730    /// Recording it matters beyond this call. The retries nest -- the gh#884
1731    /// retry wraps the μ fallback and the scale audit -- and each takes its
1732    /// floor from `last_finalize`, so a replay that only re-delivered the
1733    /// payload left the *losing* inner retry's payload there for the outer
1734    /// wrapper to floor to, and to deliver as the answer: measured on
1735    /// `mpcc_scholtes4_biactive` with `mu_strategy_fallback=yes`, a declined
1736    /// μ retry and then a declined gh#884 retry
1737    /// (`pounce-sensitivity/tests/floored_solve_retry_wrappers.rs`).
1738    /// `reported_on_converged_id` reads it too, so without the record even a
1739    /// single declined retry would name its own firing.
1740    fn restore_floor(&self, floor: &FinalizeSnapshot, tnlp: &Rc<RefCell<dyn TNLP>>) {
1741        floor.replay(tnlp);
1742        *self.last_finalize.borrow_mut() = Some(floor.clone());
1743        self.answer_restored_from_floor.set(true);
1744    }
1745
1746    /// Enable per-iteration trajectory capture. After the solve
1747    /// returns, [`Self::statistics()`] exposes
1748    /// [`pounce_nlp::solve_statistics::SolveStatistics::iterations`]
1749    /// populated with one [`pounce_nlp::solve_statistics::IterRecord`]
1750    /// per accepted iterate. Off by default — the `pounce_sens` and
1751    /// `pounce` binaries opt in when `--json-output` is passed.
1752    pub fn enable_iter_history(&mut self) {
1753        self.record_iter_history = true;
1754    }
1755
1756    /// Whether [`Self::enable_iter_history`] is in force — read by a stage
1757    /// that produces a verdict outside `optimize_tnlp` (the second-opinion
1758    /// ladder's square-system stage) so its statistics keep the same
1759    /// `iterations` / `iteration_count` pairing.
1760    pub fn iter_history_enabled(&self) -> bool {
1761        self.record_iter_history
1762    }
1763
1764    /// Read the run's options file, resolving *which* file the way
1765    /// upstream's `IpoptApplication::Initialize` does — with one
1766    /// deliberate difference, below.
1767    ///
1768    /// `explicit` is the file the caller named (upstream: the
1769    /// `option_file_name` option, read out of the option store before
1770    /// this point). With `None`, the working directory is probed for
1771    /// [`DEFAULT_OPTION_FILE_NAMES`] and the first hit is read; an
1772    /// absent default file is not an error, it just means "no file".
1773    ///
1774    /// The difference: upstream opens a named file with a bare
1775    /// `std::ifstream` and reads nothing if the open fails, so a typo'd
1776    /// `option_file_name` runs at stock defaults without a word. That
1777    /// silence is what gh#518 was reported for — a benchmark that
1778    /// measured defaults while claiming to measure a configuration — so
1779    /// a named file that cannot be read is an error here.
1780    pub fn initialize_with_option_file(
1781        &mut self,
1782        explicit: Option<&Path>,
1783    ) -> Result<OptionFileLoad, SolverException> {
1784        let mut load = OptionFileLoad::default();
1785        // Set before the early returns below: what this flag records is
1786        // that `option_file_name` was *consulted*, not that a file turned
1787        // up. A caller on this path who names nothing and has no
1788        // `pounce.opt` to find still gets the option honored — there was
1789        // simply nothing to read.
1790        self.option_file_resolved = true;
1791        let path = match explicit {
1792            Some(p) => {
1793                if !p.is_file() {
1794                    return Err(SolverException::new(
1795                        ExceptionKind::IPOPT_APPLICATION_ERROR,
1796                        format!(
1797                            "options file \"{}\" does not exist. It was named by \
1798                             --options-file / option_file_name, so the run would \
1799                             otherwise proceed at stock defaults with none of its \
1800                             settings applied.",
1801                            p.display()
1802                        ),
1803                        file!(),
1804                        line!() as Index,
1805                    ));
1806                }
1807                load.explicit = true;
1808                p.to_path_buf()
1809            }
1810            None => {
1811                let present: Vec<&&str> = DEFAULT_OPTION_FILE_NAMES
1812                    .iter()
1813                    .filter(|n| Path::new(n).is_file())
1814                    .collect();
1815                let Some(first) = present.first() else {
1816                    return Ok(load);
1817                };
1818                // Both default names in one directory: say which one lost,
1819                // rather than let the unread one look applied.
1820                for other in &present[1..] {
1821                    load.warnings.push(format!(
1822                        "`{first}` and `{other}` are both present; reading `{first}` \
1823                         only (pounce's own name wins). Pass \
1824                         `option_file_name={other}` to read that one instead."
1825                    ));
1826                }
1827                PathBuf::from(**first)
1828            }
1829        };
1830        self.initialize_with_options_file(&path)?;
1831        // `option_file_name` set *inside* an options file chains nowhere —
1832        // by the time it is read, the file naming it has already been
1833        // chosen. Upstream documents that ("it does not make any sense to
1834        // specify this option within the options file") and then ignores
1835        // it; name it instead, since an ignored setting that looks live is
1836        // the whole complaint behind gh#518.
1837        if let Ok((named, true)) = self.options.get_string_value("option_file_name", "")
1838            && !named.is_empty()
1839            && Path::new(&named) != path
1840        {
1841            load.warnings.push(format!(
1842                "`{}` sets option_file_name to `{named}`, which has no effect: \
1843                 the options file is chosen before it is read. Pass \
1844                 `option_file_name={named}` on the command line to read that file.",
1845                path.display()
1846            ));
1847        }
1848        load.path = Some(path);
1849        Ok(load)
1850    }
1851
1852    /// Read an `ipopt.opt`-format options file. Equivalent to
1853    /// `IpoptApplication::Initialize(const std::string& options_file)`.
1854    pub fn initialize_with_options_file(&mut self, path: &Path) -> Result<(), SolverException> {
1855        let txt = std::fs::read_to_string(path).map_err(|e| {
1856            SolverException::new(
1857                ExceptionKind::IPOPT_APPLICATION_ERROR,
1858                format!("could not read options file {}: {}", path.display(), e),
1859                file!(),
1860                line!() as Index,
1861            )
1862        })?;
1863        self.options.read_from_str(&txt, true)?;
1864        self.open_output_file_journal();
1865        Ok(())
1866    }
1867
1868    /// Read options from a string in `ipopt.opt` format. Useful for
1869    /// tests and embedded callers.
1870    pub fn initialize_with_options_str(&mut self, s: &str) -> Result<(), SolverException> {
1871        self.options.read_from_str(s, true)?;
1872        self.open_output_file_journal();
1873        Ok(())
1874    }
1875
1876    /// Honor `output_file` / `file_print_level` / `file_append`: when
1877    /// `output_file` is non-empty, attach a `FileJournal` named
1878    /// `"OutputFile:<fname>"` at the requested level. Mirrors
1879    /// `IpoptApplication::OpenOutputFile` (called from `Initialize`).
1880    /// No-op if `output_file` is unset, empty, or could not be opened.
1881    ///
1882    /// NOTE: pounce's iteration output currently bypasses the
1883    /// journalist and writes directly to stdout. The file journal is
1884    /// attached and the timing report (gated by `print_timing_statistics`)
1885    /// is mirrored to it; per-iter rows will start landing in the file
1886    /// once the iter-output path is routed through the journalist.
1887    fn open_output_file_journal(&self) {
1888        let fname = match self.options.get_string_value("output_file", "") {
1889            Ok((v, true)) if !v.is_empty() => v,
1890            _ => return,
1891        };
1892        let level_int = self
1893            .options
1894            .get_integer_value("file_print_level", "")
1895            .ok()
1896            .and_then(|(v, f)| f.then_some(v))
1897            .unwrap_or(5);
1898        let level = journal_level_from_int(level_int);
1899        let append = self
1900            .options
1901            .get_bool_value("file_append", "")
1902            .ok()
1903            .and_then(|(v, f)| f.then_some(v))
1904            .unwrap_or(false);
1905        let jname = format!("OutputFile:{}", fname);
1906        let _ = self
1907            .journalist
1908            .add_file_journal(&jname, &fname, level, append);
1909    }
1910
1911    /// No-op initialize (just succeeds). Mirrors
1912    /// `IpoptApplication::Initialize(bool allow_clobber)` with no
1913    /// options file.
1914    pub fn initialize(&mut self) -> Result<(), SolverException> {
1915        Ok(())
1916    }
1917
1918    /// Mirror `IpoptApplication::OpenOutputFile`. Sets the `output_file`
1919    /// / `file_print_level` options and attaches a matching
1920    /// `FileJournal` named `OutputFile:<fname>` to the journalist.
1921    /// Returns `false` if the file could not be opened or the option
1922    /// store rejected the request (e.g. clamped print level).
1923    pub fn open_output_file(&mut self, fname: &str, print_level: i32) -> bool {
1924        if self
1925            .options
1926            .set_string_value("output_file", fname, true, false)
1927            .is_err()
1928        {
1929            return false;
1930        }
1931        if self
1932            .options
1933            .set_integer_value("file_print_level", print_level as Index, true, false)
1934            .is_err()
1935        {
1936            return false;
1937        }
1938        let level = journal_level_from_int(print_level);
1939        let jname = format!("OutputFile:{}", fname);
1940        // Drop any previous file journal so a second call switches files
1941        // cleanly. `add_file_journal` would otherwise refuse to attach
1942        // a duplicate by name; remove-by-name isn't in the journalist
1943        // API, so we settle for the name-collision case here.
1944        self.journalist
1945            .add_file_journal(&jname, fname, level, false)
1946            .is_some()
1947    }
1948
1949    /// Wrap a TNLP and report problem dimensions. Used in tests until
1950    /// the full IPM path covers every entry shape.
1951    pub fn problem_dimensions(&self, tnlp: &mut dyn TNLP) -> Option<NlpInfo> {
1952        tnlp.get_nlp_info()
1953    }
1954
1955    /// Diagnostics from the safeguarded `least_square_init_primal`
1956    /// initializer step of the last solve (gh#605): the nonlinear
1957    /// violation before and after, the accepted step norm, how many
1958    /// backtracking trials were rejected, and why it stopped. `None`
1959    /// when `least_square_init_primal` was off or the model had no
1960    /// constraints.
1961    pub fn least_square_init_report(&self) -> Option<crate::init::default::LeastSquareInitReport> {
1962        self.least_square_init_report.clone()
1963    }
1964
1965    pub fn statistics(&self) -> SolveStatistics {
1966        self.statistics.borrow().clone()
1967    }
1968
1969    /// What the warm-start initializer made of the iterate the caller
1970    /// supplied to the most recent solve (gh#606): the residuals it
1971    /// measured, whether each multiplier block was accepted,
1972    /// reconstructed or discarded, and the barrier parameter it
1973    /// settled on.
1974    ///
1975    /// `None` when the last solve was a cold start
1976    /// (`warm_start_init_point=no`), or when no solve has run. Reset at
1977    /// the top of every solve, like [`Self::timing_stats`].
1978    pub fn warm_start_diagnostics(&self) -> Option<crate::init::warm_start::WarmStartDiagnostics> {
1979        self.warm_start_diag.borrow().clone()
1980    }
1981
1982    /// Shared timing accumulator from the most recent `optimize_tnlp`
1983    /// call. Each subsystem (algorithm, NLP, KKT solver) bumped its own
1984    /// fields during the solve; consumers read totals out of the
1985    /// returned `Rc`. The instance is replaced at the top of every
1986    /// subsequent solve, so cloning the `Rc` and holding it past a
1987    /// re-solve will give you the previous solve's timings — by design.
1988    pub fn timing_stats(&self) -> Rc<TimingStatistics> {
1989        Rc::clone(&self.timing.borrow())
1990    }
1991
1992    /// Aggregate linear-solver post-mortem from the most recent
1993    /// `optimize_tnlp` call. `Some` when the workspace-default FERAL
1994    /// backend ran at least one factor; `None` when no factors were
1995    /// recorded (custom factory plugged via
1996    /// [`Self::set_linear_backend_factory`], or solve aborted before
1997    /// the first KKT factor). Reset at the top of every solve.
1998    ///
1999    /// Restoration-phase factorizations are attached as
2000    /// [`LinearSolverSummary::restoration`] when the frontend wired
2001    /// [`Self::restoration_summary_sink`] into its restoration factory.
2002    pub fn linear_solver_summary(&self) -> Option<LinearSolverSummary> {
2003        let mut main = self.linsol_summary_sink.lock().ok()?.clone();
2004        let resto = self
2005            .resto_linsol_summary_sink
2006            .lock()
2007            .ok()
2008            .map(|g| g.clone())
2009            .filter(|r| !r.is_empty());
2010        if main.is_empty() && resto.is_none() {
2011            return None;
2012        }
2013        main.restoration = resto.map(Box::new);
2014        // gh#990 item 7: name what was asked for beside what ran.
2015        main.requested = self
2016            .options
2017            .get_string_value("linear_solver", "")
2018            .ok()
2019            .map(|(v, _)| v);
2020        Some(main)
2021    }
2022
2023    /// Snapshot of both linear-solver summary sinks (main and
2024    /// restoration), for a driver that re-solves and must report the
2025    /// summary of the solve whose verdict it keeps. The second-opinion
2026    /// ladder takes one before its rungs and restores it when no rung is
2027    /// promoted, exactly as it does for the statistics.
2028    pub fn linear_solver_summary_state(&self) -> LinearSolverSummaryState {
2029        let read =
2030            |s: &Arc<Mutex<LinearSolverSummary>>| s.lock().map(|g| g.clone()).unwrap_or_default();
2031        LinearSolverSummaryState {
2032            main: read(&self.linsol_summary_sink),
2033            restoration: read(&self.resto_linsol_summary_sink),
2034        }
2035    }
2036
2037    /// Put back a [`Self::linear_solver_summary_state`] snapshot.
2038    pub fn restore_linear_solver_summary_state(&self, state: LinearSolverSummaryState) {
2039        if let Ok(mut g) = self.linsol_summary_sink.lock() {
2040            *g = state.main;
2041        }
2042        if let Ok(mut g) = self.resto_linsol_summary_sink.lock() {
2043            *g = state.restoration;
2044        }
2045    }
2046
2047    /// The sink a restoration backend factory should record into, e.g.
2048    /// through [`default_backend_factory_with_sink`]. Kept separate from
2049    /// the main solve's sink so the main-solve totals stay about the main
2050    /// solve.
2051    pub fn restoration_summary_sink(&self) -> Arc<Mutex<LinearSolverSummary>> {
2052        Arc::clone(&self.resto_linsol_summary_sink)
2053    }
2054
2055    /// Drive a solve.
2056    ///
2057    /// * Constrained problems (`m > 0`) take the primal-dual IPM path:
2058    ///   build a `TNLPAdapter` → `OrigIpoptNlp`, run the
2059    ///   [`AlgorithmBuilder`] with the workspace MA57 backend, and
2060    ///   call [`IpoptAlgorithm::optimize`]. The `SolverReturn` →
2061    ///   `ApplicationReturnStatus` mapping mirrors the table in
2062    ///   `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception →
2063    ///   SolverReturn map").
2064    /// * Unconstrained problems (`m == 0`) keep going through the
2065    ///   in-`pounce-nlp` Newton driver so the trivial path is
2066    ///   independent of the linear-solver backend.
2067    /// Wrap `tnlp` so per-variable scaling factors are applied as a
2068    /// change of variables, when `nlp_scaling_method=user-scaling` is
2069    /// in effect and the problem supplies non-unit factors (gh#486).
2070    ///
2071    /// Returns the TNLP unchanged under any other scaling method, or
2072    /// when the problem asks for no variable scaling, so an unscaled
2073    /// solve pays nothing. The `Err` carries a message ready to print.
2074    fn install_variable_scaling(
2075        &self,
2076        tnlp: Rc<RefCell<dyn TNLP>>,
2077    ) -> Result<Rc<RefCell<dyn TNLP>>, String> {
2078        // Cleared first so the accessor describes *this* solve. An
2079        // application is reusable across solves (`pounce-cinterface`
2080        // holds one across `IpoptSolve` calls), and a stale vector
2081        // would have a later unscaled solve reporting the previous
2082        // solve's factors.
2083        *self.variable_scaling.borrow_mut() = None;
2084        let method = self
2085            .options
2086            .get_string_value("nlp_scaling_method", "")
2087            .ok()
2088            .and_then(|(v, f)| f.then_some(v))
2089            .unwrap_or_else(|| "gradient-based".to_string());
2090        // `curvature-based` (gh #703) delivers its factors through the
2091        // same `get_scaling_parameters` callback, so the per-variable half
2092        // needs the same substitution wrapper user factors get.
2093        if method != "user-scaling" && method != "curvature-based" {
2094            return Ok(tnlp);
2095        }
2096        match pounce_nlp::scaling_tnlp::wrap_with_scaling(
2097            Rc::clone(&tnlp),
2098            self.nlp_lower_bound_inf(),
2099            self.nlp_upper_bound_inf(),
2100        ) {
2101            Ok(Some(wrapped)) => {
2102                *self.variable_scaling.borrow_mut() =
2103                    pounce_nlp::scaling_tnlp::factors_of(&wrapped);
2104                Ok(wrapped)
2105            }
2106            Ok(None) => Ok(tnlp),
2107            Err(why) => Err(format!(
2108                // The trailing newline belongs to the message: the
2109                // caller emits it with `eprint!` and hands the same
2110                // string to the journalist, as the refusals below do.
2111                "pounce: nlp_scaling_method={method} supplied per-variable \
2112                 scaling factors that cannot be applied. {why}. Correct the \
2113                 factors, or drop nlp_scaling_method={method}.\n"
2114            )),
2115        }
2116    }
2117
2118    /// The per-variable scaling factors applied to the last solve, if
2119    /// any (gh#486). A consumer reading the algorithm's iterate rather
2120    /// than the `finalize_solution` payload sees scaled coordinates and
2121    /// must divide `x` by these, and multiply bound multipliers.
2122    pub fn variable_scaling(&self) -> Option<Vec<Number>> {
2123        self.variable_scaling.borrow().clone()
2124    }
2125
2126    /// Install a starting-point conditioner, if one is asked for.
2127    ///
2128    /// Returns the TNLP unchanged when neither `start_point_perturbation` nor
2129    /// `start_point_conditioner` is set, which is the default — so an ordinary
2130    /// solve pays nothing and its trajectory is untouched.
2131    ///
2132    /// Sits *above* the presolve wrapper and *below* the variable-scaling one,
2133    /// so the point it conditions is the point the algorithm will actually
2134    /// start from, in the coordinates the algorithm will see. Both
2135    /// conditioners override only `get_starting_point`; every other callback
2136    /// forwards, so the solve that follows is the solve pounce would have run
2137    /// had the conditioned point been submitted directly.
2138    ///
2139    /// The two are mutually exclusive by construction rather than by refusal:
2140    /// the displacement is the failure-recovery rung and the Adam warm-up is a
2141    /// user opt-in, and stacking them would put random noise on top of a point
2142    /// the warm-up just spent 200 evaluations choosing. The displacement wins
2143    /// when both are set, because the only thing that sets it is a solve that
2144    /// has already failed.
2145    fn install_start_conditioner(&self, tnlp: Rc<RefCell<dyn TNLP>>) -> Rc<RefCell<dyn TNLP>> {
2146        use pounce_nlp::start_conditioner::{AdamConfig, ConditionedStartTnlp, StartConditioner};
2147        // Each option is read with its literal tag rather than through a
2148        // `|name, fallback|` helper. A helper reads better and costs the
2149        // wiring guard in `tests/init_options_wiring.rs` its evidence: that
2150        // test scans the source for `get_*_value("<tag>"` to prove every
2151        // registered Initialization option is actually consumed, and a tag
2152        // passed as a variable is invisible to it. A registered knob nothing
2153        // reads validates, accepts a value, and lies.
2154        let perturbation = self
2155            .options
2156            .get_numeric_value("start_point_perturbation", "")
2157            .map(|(v, _found)| v)
2158            .unwrap_or(0.0);
2159        let conditioner = if perturbation > 0.0 {
2160            let seed = self
2161                .options
2162                .get_integer_value("start_point_perturbation_seed", "")
2163                .map(|(v, _found)| v)
2164                .unwrap_or(0);
2165            StartConditioner::Jitter {
2166                // `Index` is signed and the option is lower-bounded at 0, so
2167                // this cast cannot lose a set bit for any accepted value.
2168                seed: seed.max(0) as u64,
2169                scale: perturbation,
2170            }
2171        } else {
2172            let which = self
2173                .options
2174                .get_string_value("start_point_conditioner", "")
2175                .map(|(v, _found)| v)
2176                .unwrap_or_else(|_| "none".to_string());
2177            if which != "adam" {
2178                return tnlp;
2179            }
2180            let d = AdamConfig::default();
2181            StartConditioner::Adam(AdamConfig {
2182                iters: self
2183                    .options
2184                    .get_integer_value("adam_warmup_iters", "")
2185                    .map(|(v, _found)| v.max(0) as usize)
2186                    .unwrap_or(d.iters),
2187                lr: self
2188                    .options
2189                    .get_numeric_value("adam_warmup_learning_rate", "")
2190                    .map(|(v, _found)| v)
2191                    .unwrap_or(d.lr),
2192                rho: self
2193                    .options
2194                    .get_numeric_value("adam_warmup_penalty", "")
2195                    .map(|(v, _found)| v)
2196                    .unwrap_or(d.rho),
2197                ..d
2198            })
2199        };
2200        // The sentinels have to come from the options, not from the
2201        // conditioner's own default: a caller who moved `nlp_lower_bound_inf`
2202        // would otherwise have a bound the algorithm treats as absent clipped
2203        // against as if it were real.
2204        //
2205        // Passed through unclamped. These were once `lower.min(-DEFAULT)` /
2206        // `upper.max(DEFAULT)`, which honours only a *loosened* sentinel and
2207        // leaves the failure above intact for a tightened one: at
2208        // `nlp_lower_bound_inf=-1e10` the conditioner still used `-1e19`, so a
2209        // `-1e15` bound was absent to the algorithm and present to the
2210        // clipper — the exact case the comment exists to rule out. The
2211        // sentinel means "absent"; there is only one right answer for what it
2212        // is, and it is the caller's.
2213        let lower = self.nlp_lower_bound_inf();
2214        let upper = self.nlp_upper_bound_inf();
2215        let wrapped = ConditionedStartTnlp::new(tnlp, conditioner).with_bound_inf(lower, upper);
2216        Rc::new(RefCell::new(wrapped))
2217    }
2218
2219    pub fn optimize_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2220        self.optimize_tnlp_with_derivative_test_tnlp(tnlp, None)
2221    }
2222
2223    /// Solve through `tnlp`, optionally overriding the derivative-test target.
2224    /// `None` tests the scaled and conditioned TNLP.
2225    pub fn optimize_tnlp_with_derivative_test_tnlp(
2226        &mut self,
2227        tnlp: Rc<RefCell<dyn TNLP>>,
2228        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2229    ) -> ApplicationReturnStatus {
2230        // gh#983 review item 1: warnings belong to this solve. Cleared here as
2231        // well as per attempt, so a solve that returns before any attempt runs
2232        // (an option refusal, a presolve proof) does not report the previous
2233        // solve's.
2234        self.statistics.borrow_mut().warnings.clear();
2235        self.statistics.borrow_mut().sqp_warm_working_set_applied = false;
2236        // Belongs to the scale audit's re-solve alone, which runs below this
2237        // entry point (`optimize_constrained`, never `optimize_tnlp`), so no
2238        // solve that starts here may inherit it. `RetryOptionScope` clears it
2239        // on every exit already; this is the belt to that, for a solve on an
2240        // application a caught panic left behind.
2241        self.retry_keeps_declared_box.set(false);
2242        let status = self.optimize_tnlp_dispatch(tnlp, derivative_test_tnlp);
2243        // Printed once, for the run whose point is returned. They used to be
2244        // printed by every audited attempt, so a promoted retry's console
2245        // carried the discarded base attempt's `WARNING:` lines too.
2246        let console_output = match self.options.get_integer_value("print_level", "") {
2247            Ok((v, true)) => v >= 1,
2248            _ => true,
2249        };
2250        if console_output {
2251            for w in &self.statistics.borrow().warnings {
2252                println!("WARNING: {w}");
2253            }
2254        }
2255        status
2256    }
2257
2258    /// The body of [`Self::optimize_tnlp_with_derivative_test_tnlp`].
2259    fn optimize_tnlp_dispatch(
2260        &mut self,
2261        tnlp: Rc<RefCell<dyn TNLP>>,
2262        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2263    ) -> ApplicationReturnStatus {
2264        // gh#884. Both belong to this solve, not to whatever ran before
2265        // it. Reset *here* rather than in `optimize_constrained`, which
2266        // runs once per attempt: the signature accumulates across the
2267        // attempts a lower wrapper may spend, so
2268        // `run_with_dual_divergence_retry` reads "some attempt of the base
2269        // solve saw it" rather than "the last one did".
2270        self.dual_divergence_signature.set(false);
2271        self.obj_scale_refused.set((false, false));
2272        self.dual_divergence_retry_promoted.set(false);
2273        *self.mu_strategy_fallback_record.borrow_mut() = None;
2274        self.answer_restored_from_floor.set(false);
2275        // The answer this solve reports is whatever it finalizes; a payload
2276        // left from an earlier solve must not stand in for one this solve
2277        // never wrote, since `reported_on_converged_id` reads it.
2278        *self.last_finalize.borrow_mut() = None;
2279        // Same scoping argument as the three above, for the same reason: the
2280        // memo suppresses a REPEATED header within one run, so it must not
2281        // carry across runs. A library caller solving twice on one
2282        // application gets its header both times — which is exactly what the
2283        // guard protects: an outside retry driver re-entering here for another
2284        // attempt is not such a caller, and says so by setting the flag.
2285        if !self.in_retry_sequence.get() {
2286            *self.last_printed_problem_stats.borrow_mut() = None;
2287        }
2288        // gh#486 stage 2: per-variable `scaling_factor` is applied by
2289        // substituting variables one level below the algorithm, since
2290        // the core's scaling models the objective and the constraint
2291        // rows only. The wrapper consumes the variable factors and
2292        // forwards the rest, so `OrigIpoptNlp` sees exactly what it
2293        // has always handled. Installed here because every entry point
2294        // funnels through this method, and only under `user-scaling`,
2295        // the one method that consults the TNLP for factors at all.
2296        let tnlp = match self.install_variable_scaling(tnlp) {
2297            Ok(t) => t,
2298            Err(msg) => {
2299                use pounce_common::journalist::JournalCategory;
2300                eprint!("{msg}");
2301                self.journalist
2302                    .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2303                return ApplicationReturnStatus::InvalidOption;
2304            }
2305        };
2306
2307        // Starting-point conditioning (`start_point_perturbation`,
2308        // `start_point_conditioner`). A no-op unless one is set, and set by
2309        // nothing automatic except the local-infeasibility ladder's third
2310        // rung, which only runs after a solve has already failed.
2311        let tnlp = self.install_start_conditioner(tnlp);
2312        let derivative_test_tnlp = derivative_test_tnlp.as_ref().unwrap_or(&tnlp);
2313
2314        if let Some(value) = self.unsupported_library_solver_selection() {
2315            use pounce_common::journalist::JournalCategory;
2316            self.journalist.print(
2317                JournalLevel::J_ERROR,
2318                JournalCategory::J_MAIN,
2319                &format!(
2320                    "pounce: solver_selection={value} routing is only available \
2321                     through the pounce CLI (.nl input); library consumers can use \
2322                     qp-active-set, nlp, or auto.\n"
2323                ),
2324            );
2325            return ApplicationReturnStatus::InvalidOption;
2326        }
2327
2328        // A `linear_solver` pounce does not implement is refused rather
2329        // than quietly served by FERAL (gh#483 follow-up). Checked here,
2330        // before any work, so a library consumer gets the same verdict the
2331        // CLI gives before its banner.
2332        if let Some(value) = self.unimplemented_linear_solver() {
2333            use pounce_common::journalist::JournalCategory;
2334            let msg = format!("{}\n", Self::unimplemented_linear_solver_message(&value));
2335            eprint!("{msg}");
2336            self.journalist
2337                .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2338            return ApplicationReturnStatus::InvalidOption;
2339        }
2340
2341        // gh#483 follow-up: an option naming a feature pounce does not
2342        // implement is refused, not shrugged off. See
2343        // `unimplemented_options` for how membership was established and
2344        // why an explicitly-set *default* is deliberately still allowed.
2345        // gh#518: same treatment for `option_file_name` on an entry point
2346        // that cannot resolve it. Separate from the table above because
2347        // the *feature* now exists — just not here.
2348        // gh#604: same treatment one level down, for a registered *value*
2349        // of an option pounce otherwise reads (`bound_mult_init_method=
2350        // mu-based`).
2351        // gh#604: and for a convex-engine knob on an entry point that
2352        // cannot route to that engine — `option_file_name`'s case, one
2353        // feature over.
2354        if let Some(msg) = self
2355            .unimplemented_option_refusal()
2356            .or_else(|| self.unimplemented_option_value_refusal())
2357            .or_else(|| self.unhonored_option_file_name())
2358            .or_else(|| self.unhonored_convex_option())
2359        {
2360            use pounce_common::journalist::JournalCategory;
2361            eprintln!("{msg}");
2362            self.journalist.print(
2363                JournalLevel::J_ERROR,
2364                JournalCategory::J_MAIN,
2365                &format!("{msg}\n"),
2366            );
2367            return ApplicationReturnStatus::InvalidOption;
2368        }
2369        // A `ma57_pivtolmax` the user set *below* `ma57_pivtol` is a
2370        // contradiction — the escalation ceiling under its floor — and
2371        // upstream refuses it outright
2372        // (`IpMa57TSolverInterface.cpp:313`, `OPTION_INVALID`). pounce
2373        // used to silently rewrite it to `ma57_pivtol`. That was
2374        // unreachable while gh#825 was live, since no `ma57_*` value
2375        // reached the backend at all, and became reachable the moment
2376        // that was fixed — so it is refused here rather than shipped as
2377        // a new way to be quietly ignored.
2378        if let Some(msg) = self.ma57_pivtol_bracket_refusal() {
2379            use pounce_common::journalist::JournalCategory;
2380            eprintln!("{msg}");
2381            self.journalist.print(
2382                JournalLevel::J_ERROR,
2383                JournalCategory::J_MAIN,
2384                &format!("{msg}\n"),
2385            );
2386            return ApplicationReturnStatus::InvalidOption;
2387        }
2388
2389        let backend_warnings = self.take_unimplemented_backend_warnings();
2390        for warning in self
2391            .unexploited_hint_warnings()
2392            .into_iter()
2393            .chain(backend_warnings)
2394        {
2395            eprintln!("{warning}");
2396        }
2397
2398        // Test before presolve, using the requested coordinate space.
2399        self.run_derivative_test(derivative_test_tnlp);
2400
2401        // Top-level algorithm dispatch (Phase 5b §7.1). When the
2402        // `algorithm` option resolves to "active-set-sqp", route
2403        // to the Phase 5b SQP path; otherwise fall through to the
2404        // existing IPM flow unchanged.
2405        // Materialize generic TNLP presolve once at the public entry point.
2406        // The wrapper owns the submitted callback TNLP, so every algorithm
2407        // path below (including retry paths) continues to postsolve into
2408        // the original user-facing space. With `presolve=no`, this returns
2409        // the exact same Rc unchanged.
2410        let tnlp = if self.presolve_already_applied {
2411            tnlp
2412        } else {
2413            match pounce_presolve::wrap_from_options(tnlp, &self.options) {
2414                Ok(tnlp) => tnlp,
2415                Err(err) => {
2416                    use pounce_common::journalist::JournalCategory;
2417                    self.journalist.print(
2418                        JournalLevel::J_ERROR,
2419                        JournalCategory::J_MAIN,
2420                        &format!("pounce: could not materialize presolve options: {err}\n"),
2421                    );
2422                    return ApplicationReturnStatus::InvalidOption;
2423                }
2424            }
2425        };
2426
2427        if self.is_sqp_algorithm_selected() {
2428            let dims = tnlp
2429                .borrow_mut()
2430                .get_nlp_info()
2431                .map(|i| (i.n.max(0) as usize, i.m.max(0) as usize));
2432            let auto = dims.is_some_and(|(n, m)| self.sqp_auto_handover(n, m));
2433            self.auto_handover.set(auto);
2434            if !auto {
2435                return self.optimize_sqp_tnlp(tnlp);
2436            }
2437            use pounce_common::journalist::JournalCategory;
2438            self.journalist.print(
2439                JournalLevel::J_SUMMARY,
2440                JournalCategory::J_MAIN,
2441                &format!(
2442                    "pounce: active-set SQP on a model this size (n + m ≥ {AUTO_HANDOVER_MIN_DIM}) \
2443                     starts from the interior point and hands over \
2444                     (ipm_sqp_handover=no for a cold active-set SQP).\n"
2445                ),
2446            );
2447        } else {
2448            self.auto_handover.set(false);
2449        }
2450        let info = match tnlp.borrow_mut().get_nlp_info() {
2451            Some(info) => info,
2452            None => return ApplicationReturnStatus::InvalidProblemDefinition,
2453        };
2454
2455        // Presolve-certified infeasibility. `get_nlp_info` above is what forces
2456        // the (lazy) presolve init, so this is the first point at which the
2457        // proof exists. If bound propagation or FBBT established that the
2458        // feasible region is empty, there is nothing left to compute: return
2459        // the verdict directly.
2460        //
2461        // Short-circuiting *here*, before dispatch, is deliberate. Running the
2462        // solve anyway would only re-derive a strictly weaker result — a
2463        // stationary point of the constraint violation, which for a nonconvex
2464        // problem proves nothing globally — and would also hand an
2465        // `InfeasibleProblemDetected` to the ℓ₁ auto-fallback below
2466        // (`is_l1_fallback_trigger`), which would then burn a whole second
2467        // solve retrying a problem already proved to have no solution.
2468        //
2469        // Soundness rests on `presolve_infeasibility_proof` returning `Some`
2470        // only for a contradiction derived on an *un-clamped* box — a
2471        // detection made while a Phase-0 auxiliary elimination is in force can
2472        // be an artifact of that elimination and is re-checked after rollback
2473        // before it is certified. See `PresolveState::certified_infeasible`.
2474        if let Some(proof) = tnlp.borrow().presolve_infeasibility_proof() {
2475            use pounce_common::journalist::JournalCategory;
2476            let detail = match proof {
2477                pounce_nlp::tnlp::InfeasibilityProof::BoundPropagation => {
2478                    "bound propagation crossed a variable's bounds".to_string()
2479                }
2480                pounce_nlp::tnlp::InfeasibilityProof::IntervalArithmetic { witness } => {
2481                    format!("interval arithmetic emptied constraint {witness}'s range")
2482                }
2483            };
2484            self.journalist.print(
2485                JournalLevel::J_SUMMARY,
2486                JournalCategory::J_MAIN,
2487                &format!(
2488                    "\nEXIT: Presolve detected the feasible region is empty ({detail}).\n\
2489                     No feasible point exists; the solve was not run.\n"
2490                ),
2491            );
2492            return ApplicationReturnStatus::InfeasibleProblemDetected;
2493        }
2494        // ℓ₁-exact penalty-barrier opt-in (pounce#10).
2495        // Phase 3 wraps the user TNLP and runs an outer Byrd-Nocedal-
2496        // Waltz ρ-escalation loop around the constrained IPM, with a
2497        // honest-infeasibility status upgrade when the slacks fail to
2498        // collapse at saturated ρ. Phase-1/2 one-shot use is preserved
2499        // when `l1_penalty_max_outer_iter == 1`. The wrapper is a
2500        // no-op for problems with no equality rows, so the
2501        // unconstrained dispatch below is unaffected when there is
2502        // nothing to wrap.
2503        if info.m > 0 && self.is_l1_penalty_enabled() {
2504            if let Some(status) = self.run_l1_penalty_outer_loop(Rc::clone(&tnlp)) {
2505                return status;
2506            }
2507            // Falls through: wrapper construction failed (inner refused
2508            // get_nlp_info / get_bounds_info) or no equality rows to
2509            // slack. Standard dispatch runs unmodified.
2510        }
2511        // Phase 3.5 auto-fallback (pounce#10): if the standard solve
2512        // ends in a trigger-class status, retry transparently with
2513        // the wrapper. Promote the retry's status only if it returns
2514        // SolveSucceeded — otherwise return the original. Skipped if
2515        // the user already opted into the wrapper above (this avoids
2516        // a double pass and keeps semantics predictable).
2517        if info.m > 0 && self.is_l1_fallback_enabled() && !self.is_l1_penalty_enabled() {
2518            return self.run_with_l1_fallback(tnlp);
2519        }
2520        // Biactive dual-divergence retry (gh#884): if the solve settles
2521        // its primal while its multipliers run away, throw the iterate
2522        // away and solve again from scratch with the constraint-Jacobian
2523        // perturbation on. Outermost of the two retry wrappers, so its
2524        // "base solve" is the whole standard dispatch below including the
2525        // μ flip — the signature is about a *solve*, and spending the μ
2526        // flip first is strictly cheaper than spending this one first.
2527        let status = if self.is_dual_divergence_retry_enabled() {
2528            self.run_with_dual_divergence_retry(tnlp)
2529        } else {
2530            self.dispatch_standard_solve(tnlp)
2531        };
2532        // gh#983 review item 3: the verdict-level audit runs once, on the
2533        // final verdict, after every retry and fallback has decided.
2534        self.finalize_quality_verdict(status)
2535    }
2536
2537    /// The standard solve dispatch: the μ-strategy fallback if it is
2538    /// enabled, otherwise one `optimize_constrained` call.
2539    ///
2540    /// Factored out of `optimize_tnlp_with_derivative_test_tnlp` so
2541    /// [`Self::run_with_dual_divergence_retry`] can wrap the whole of it
2542    /// rather than only the bare IPM call (gh#884).
2543    fn dispatch_standard_solve(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2544        let status = self.dispatch_standard_solve_inner(Rc::clone(&tnlp));
2545        self.audit_solve_quality(tnlp, status)
2546    }
2547
2548    /// [`Self::dispatch_standard_solve`] without the gh#983 quality audit.
2549    fn dispatch_standard_solve_inner(
2550        &mut self,
2551        tnlp: Rc<RefCell<dyn TNLP>>,
2552    ) -> ApplicationReturnStatus {
2553        // μ-strategy auto-fallback (pounce#138): if the standard solve
2554        // stalls, retry once with the opposite mu_strategy and promote
2555        // only on Solve_Succeeded. Which stalls qualify depends on
2556        // whether the caller asked for the retry — see
2557        // `run_with_mu_strategy_fallback` (pounce#748).
2558        // Applies to constrained and unconstrained alike (both run the
2559        // same IPM). Independent of, and lower priority than, the ℓ₁
2560        // fallback above.
2561        if self.is_mu_strategy_fallback_enabled() {
2562            return self.run_with_mu_strategy_fallback(tnlp);
2563        }
2564        // Every problem — constrained or not — goes through the same
2565        // primal-dual IPM, exactly as upstream Ipopt does. There is no
2566        // separate "unconstrained Newton" path: the linear-solver
2567        // backend (FERAL/MA57) handles the augmented system, so the
2568        // sparse IPM covers `m == 0` at any `n` without a dense-Hessian
2569        // blowup.
2570        self.optimize_constrained(tnlp)
2571    }
2572
2573    /// Read the ℓ₁ wrapper master switch from the OptionsList.
2574    /// Default `false` when the option is not set.
2575    fn is_l1_penalty_enabled(&self) -> bool {
2576        self.options
2577            .get_bool_value("l1_exact_penalty_barrier", "")
2578            .ok()
2579            .and_then(|(v, found)| found.then_some(v))
2580            .unwrap_or(false)
2581    }
2582
2583    fn l1_penalty_init(&self) -> Number {
2584        self.options
2585            .get_numeric_value("l1_penalty_init", "")
2586            .ok()
2587            .and_then(|(v, found)| found.then_some(v))
2588            .unwrap_or(1.0)
2589    }
2590    fn l1_penalty_max(&self) -> Number {
2591        self.options
2592            .get_numeric_value("l1_penalty_max", "")
2593            .ok()
2594            .and_then(|(v, found)| found.then_some(v))
2595            .unwrap_or(1.0e6)
2596    }
2597    fn l1_penalty_increase_factor(&self) -> Number {
2598        self.options
2599            .get_numeric_value("l1_penalty_increase_factor", "")
2600            .ok()
2601            .and_then(|(v, found)| found.then_some(v))
2602            .unwrap_or(8.0)
2603    }
2604    fn l1_penalty_max_outer_iter(&self) -> usize {
2605        self.options
2606            .get_integer_value("l1_penalty_max_outer_iter", "")
2607            .ok()
2608            .and_then(|(v, found)| found.then_some(v))
2609            .unwrap_or(8) as usize
2610    }
2611    fn l1_slack_tol(&self) -> Number {
2612        self.options
2613            .get_numeric_value("l1_slack_tol", "")
2614            .ok()
2615            .and_then(|(v, found)| found.then_some(v))
2616            .unwrap_or(1.0e-6)
2617    }
2618    fn l1_steering_factor(&self) -> Number {
2619        self.options
2620            .get_numeric_value("l1_steering_factor", "")
2621            .ok()
2622            .and_then(|(v, found)| found.then_some(v))
2623            .unwrap_or(10.0)
2624    }
2625    fn is_l1_fallback_enabled(&self) -> bool {
2626        self.options
2627            .get_bool_value("l1_fallback_on_restoration_failure", "")
2628            .ok()
2629            .and_then(|(v, found)| found.then_some(v))
2630            .unwrap_or(false)
2631    }
2632
2633    /// Did the caller set `mu_strategy` explicitly?
2634    ///
2635    /// The answer decides whether the limited-memory default applies
2636    /// (see `algorithm_builder_from_options`): upstream only substitutes
2637    /// `adaptive` for the registered `monotone` when the option is
2638    /// absent from the list.
2639    fn mu_strategy_was_set(&self) -> bool {
2640        matches!(
2641            self.options.get_string_value("mu_strategy", ""),
2642            Ok((_, true))
2643        )
2644    }
2645
2646    /// Did the caller set `mu_strategy_fallback` themselves? Separates
2647    /// the opted-in retry from the default-on one, which triggers on a
2648    /// narrower set of statuses (pounce#748).
2649    ///
2650    /// True for an explicit `no` as well as an explicit `yes`, which is
2651    /// harmless: this is only ever read downstream of
2652    /// [`Self::is_mu_strategy_fallback_enabled`], and an explicit `no`
2653    /// stops there.
2654    fn mu_strategy_fallback_was_set(&self) -> bool {
2655        matches!(
2656            self.options.get_bool_value("mu_strategy_fallback", ""),
2657            Ok((_, true))
2658        )
2659    }
2660
2661    /// Options whose presence means a `Solved_To_Acceptable_Level`
2662    /// exit may be something the *caller* asked for rather than a stall
2663    /// POUNCE fell into (gh #757).
2664    ///
2665    /// Every one of them either moves the bar a certificate has to clear
2666    /// (`tol` and the component tolerances, the `acceptable_*` family),
2667    /// arms a guard that refuses a certificate the iterate would
2668    /// otherwise have earned (`kkt_fidelity_tol`, the certificate-mask
2669    /// and noise-floor kappas, the divergence / infeasibility streaks,
2670    /// the restoration-decline pair).
2671    ///
2672    /// Options that only move the *starting point* are deliberately not
2673    /// here. `least_square_init_primal` was tried and removed: a caller
2674    /// who picks an initialization heuristic has said nothing about what
2675    /// convergence means, and listing it made an explicit `=no` behave
2676    /// differently from omitting the option, which is a distinction the
2677    /// rest of the solver does not draw.
2678    const TERMINATION_POLICY_OPTIONS: &'static [&'static str] = &[
2679        "tol",
2680        "dual_inf_tol",
2681        "constr_viol_tol",
2682        "compl_inf_tol",
2683        "acceptable_tol",
2684        "acceptable_iter",
2685        "acceptable_dual_inf_tol",
2686        "acceptable_constr_viol_tol",
2687        "acceptable_compl_inf_tol",
2688        "acceptable_obj_change_tol",
2689        "kkt_fidelity_tol",
2690        "obj_scale_certificate_threshold",
2691        "dual_inf_scale_kappa",
2692        "primal_noise_floor_kappa",
2693        "dual_diverging_streak",
2694        "infeas_max_streak",
2695        "resto_decline_deferrals",
2696        "resto_decline_progress_ratio",
2697        "neg_curv_escapes",
2698        "limited_memory_ls_failure_restarts",
2699    ];
2700
2701    /// Did the caller set any option from
2702    /// [`Self::TERMINATION_POLICY_OPTIONS`]?
2703    ///
2704    /// This is what separates the two readings of a
2705    /// `Solved_To_Acceptable_Level` exit. Under stock convergence
2706    /// settings it means POUNCE's own schedule parked the dual term
2707    /// above `tol` and a flipped schedule is worth one try. Under a
2708    /// caller-modified one it may be the signal the caller armed the
2709    /// option to receive, and erasing it with a retry is exactly the
2710    /// laundering pounce#748 refused to do by default.
2711    fn caller_set_termination_policy(&self) -> bool {
2712        Self::TERMINATION_POLICY_OPTIONS.iter().any(|name| {
2713            matches!(self.options.get_numeric_value(name, ""), Ok((_, true)))
2714                || matches!(self.options.get_integer_value(name, ""), Ok((_, true)))
2715                || matches!(self.options.get_bool_value(name, ""), Ok((_, true)))
2716                || matches!(self.options.get_string_value(name, ""), Ok((_, true)))
2717        })
2718    }
2719
2720    /// The μ strategy this option table actually resolves to, as
2721    /// `algorithm_builder_from_options` will build it: the explicit
2722    /// value when there is one, otherwise `adaptive` for a
2723    /// limited-memory Hessian and `monotone` for anything else.
2724    ///
2725    /// The fallback below flips *this*, not the registered default —
2726    /// flipping the registered default under limited-memory would
2727    /// "retry" with the strategy that just failed.
2728    fn effective_mu_strategy_is_adaptive(&self) -> bool {
2729        mu_strategy_resolves_to_adaptive(&self.options)
2730    }
2731
2732    /// Read the μ-strategy auto-fallback switch (pounce#138).
2733    ///
2734    /// An explicit setting always wins. Absent one the default is **on**
2735    /// (pounce#748) — but only while the user has not chosen a
2736    /// `mu_strategy` themselves. Retrying under the other schedule is a
2737    /// recovery for a solve that stalled on a strategy POUNCE picked; it
2738    /// is not licence to override a strategy the caller named. Without
2739    /// that condition, flipping the default would silently contaminate
2740    /// every controlled comparison that pins `mu_strategy` on purpose,
2741    /// this repository's own benchmark arms included. The motivating
2742    /// case is unaffected: `dirichlet120` stalls under the
2743    /// limited-memory substitution (pounce#746), which by definition
2744    /// only happens when `mu_strategy` is unset.
2745    fn is_mu_strategy_fallback_enabled(&self) -> bool {
2746        match self.options.get_bool_value("mu_strategy_fallback", "") {
2747            Ok((v, true)) => v,
2748            _ => !self.mu_strategy_was_set() || self.mu_strategy_pounce_chosen,
2749        }
2750    }
2751
2752    /// Record that the `mu_strategy` now in the option table was chosen by a
2753    /// POUNCE frontend, not by the caller (gh#990).
2754    ///
2755    /// The Python path for a problem without `hessian` writes
2756    /// `mu_strategy=monotone` so that gh#746's limited-memory -> adaptive
2757    /// substitution does not read a barrier preference out of a Hessian
2758    /// choice POUNCE made itself. Written as an ordinary option, that pin
2759    /// also read as "the caller named a strategy" to
2760    /// [`Self::is_mu_strategy_fallback_enabled`], which switched off the
2761    /// default-on stall retry (gh#748) on exactly that path — the same
2762    /// set-ness defect the second-opinion ladder's write-backs once had.
2763    /// With this mark the pin still decides the schedule, and the fallback
2764    /// stays on. A frontend calls it only when the caller's own options carry
2765    /// no `mu_strategy`.
2766    pub fn mark_mu_strategy_pounce_chosen(&mut self) {
2767        self.mu_strategy_pounce_chosen = true;
2768    }
2769
2770    /// Has the user set `algorithm = active-set-sqp`? Reads the
2771    /// string option and matches case-insensitively against the
2772    /// design-note §7.1 spelling. Any value other than
2773    /// "active-set-sqp" (including absence) routes to the
2774    /// default IPM path.
2775    /// Stash a warm-start iterate for the SQP path. Consumed by
2776    /// the next `optimize_tnlp` call when the `algorithm` option
2777    /// resolves to `active-set-sqp`; the IPM path ignores it.
2778    /// Phase 5c (§6) — the parametric / MPC warm-start hand-off.
2779    ///
2780    /// The iterate is auto-cleared after use, so a follow-up
2781    /// solve without an intervening `set_sqp_warm_start` call
2782    /// cold-starts.
2783    ///
2784    /// `x`, `lambda_g` and `lambda_x` are in the **caller's** space — what
2785    /// `finalize_solution` reports: full-`n` `x` in model units, `lambda_g`
2786    /// in `g` order on the unscaled Lagrangian `f + λᵀg`, and
2787    /// `lambda_x = z_L − z_U`. The solve maps them into the algorithm's
2788    /// space (fixed variables dropped, `[y_c; y_d]` row order, objective,
2789    /// constraint and per-variable scaling) itself, so a converged solve's
2790    /// reported multipliers can be fed back unchanged. The working set is in
2791    /// the same space: bound statuses full-`n` in variable order (fixed
2792    /// variables' entries are ignored), constraint statuses one per `g` row
2793    /// in the user's row order — exactly what [`Self::last_sqp_working_set`]
2794    /// publishes, so a published set can be fed back as-is.
2795    pub fn set_sqp_warm_start(&mut self, warm: crate::sqp::SqpIterates) {
2796        self.sqp_warm_start = Some(warm);
2797    }
2798
2799    /// Drop any pending warm-start iterate without solving.
2800    pub fn clear_sqp_warm_start(&mut self) {
2801        self.sqp_warm_start = None;
2802    }
2803
2804    /// What the crossover phase did on the most recent solve (gh#612).
2805    ///
2806    /// `None` means crossover never ran — either `crossover=no` (the
2807    /// default) or the solve did not converge. A `Some` whose
2808    /// [`CrossoverReport::accepted`] is false means it ran and *declined*;
2809    /// the two are different facts about a solve and consumers that reason
2810    /// about active-set certainty (sensitivity's AMBIGUOUS class, a
2811    /// downstream `var_status`) need to tell them apart.
2812    ///
2813    /// [`CrossoverReport::accepted`]: crate::crossover::CrossoverReport::accepted
2814    pub fn crossover_report(&self) -> Option<&crate::crossover::CrossoverReport> {
2815        self.crossover_report.as_ref()
2816    }
2817
2818    /// What the interior-point → active-set handover did on the most recent
2819    /// solve (gh#1054); `None` unless `ipm_sqp_handover=yes`.
2820    pub fn handover_report(&self) -> Option<&crate::handover::HandoverReport> {
2821        self.handover_report.as_ref()
2822    }
2823
2824    /// Install a full primal-dual warm-start iterate for the next IPM
2825    /// `optimize_tnlp`. Captured by the debugger's `resolve` so the
2826    /// re-solve continues from the paused interior point. The caller is
2827    /// responsible for also enabling `warm_start_init_point=yes` (and
2828    /// usually `warm_start_target_mu=<μ>`) so the re-optimize branch of
2829    /// `WarmStartIterateInitializer` preserves the installed iterate.
2830    /// Consumed once per solve, then auto-cleared.
2831    pub fn set_warm_start_iterate(&mut self, snap: crate::debug::IterateSnapshot) {
2832        self.warm_start_iterate = Some(snap);
2833    }
2834
2835    /// Install a caller-supplied fill-reducing permutation for the KKT
2836    /// linear solver (pounce#180 item 1). The next `optimize_*` builds
2837    /// the FERAL backend with [`pounce_feral::OrderingMethod::External`],
2838    /// overriding the `feral_ordering` string option / env var. Use this
2839    /// to inject a block-triangular / Schur ordering a generic algorithm
2840    /// cannot see (Parker, Garcia & Bent, arXiv:2602.17968) or a tearing
2841    /// ordering from equation-oriented decomposition.
2842    ///
2843    /// `perm` is a **0-based, new-to-old permutation** (`perm[k]` is the
2844    /// original index that becomes index `k`), and its length must equal
2845    /// the augmented KKT system dimension (variables + slacks +
2846    /// constraint duals), *not* the problem's `n`. A wrong length or a
2847    /// non-bijection is rejected by FERAL at the first factorization with
2848    /// an `InvalidInput` error (never a panic), surfacing as a solver
2849    /// failure rather than a silently-wrong solve — the ordering only
2850    /// affects fill/time, never the computed solution.
2851    ///
2852    /// Persistent config: unlike the warm-start hooks it is *not*
2853    /// auto-cleared after a solve. Call [`Self::clear_external_ordering`]
2854    /// to drop it. Ignored by non-FERAL backends and by any custom
2855    /// factory plugged via [`Self::set_linear_backend_factory`].
2856    pub fn set_external_ordering(&mut self, perm: Vec<usize>) {
2857        self.external_ordering = Some(perm);
2858    }
2859
2860    /// Drop any installed external KKT ordering, restoring the
2861    /// `feral_ordering`-driven default for subsequent solves.
2862    pub fn clear_external_ordering(&mut self) {
2863        self.external_ordering = None;
2864    }
2865
2866    /// The currently-installed external KKT ordering, if any.
2867    pub fn external_ordering(&self) -> Option<&[usize]> {
2868        self.external_ordering.as_deref()
2869    }
2870
2871    /// Install a block-triangular / Schur KKT partition (pounce#180 item 2).
2872    /// `indices` are KKT-space indices (`0..dim` in the `x, s, c, d` block
2873    /// order the aug-system solver assembles) naming the Schur block `S`; that
2874    /// block is Schur-complemented out and only the two diagonal blocks are
2875    /// factorized (inertia via Sylvester's law). Honored on the IPM + feral +
2876    /// exact-Hessian path; the Schur solver falls back to the standard
2877    /// full-space solver transparently when the partition is unsuitable (too
2878    /// large a fraction of the system, malformed, or a backend error), so a
2879    /// stray hook never breaks a solve. Persistent config (not auto-cleared);
2880    /// drop it via [`Self::clear_kkt_schur_block`].
2881    /// Declare the block structure in the **model's own terms**: one block id
2882    /// per variable and per constraint, negative for the shared ones
2883    /// (structured-KKT Phase 5b). Blocks must couple only through the shared
2884    /// entries; the solver checks that against the assembled KKT and falls
2885    /// back when it does not hold.
2886    ///
2887    /// This is the form a model can produce — "`pg[g]` is shared, everything
2888    /// in contingency `k` is block `k`" — and pounce maps it to KKT indices
2889    /// itself, accounting for fixed variables and the equality / inequality
2890    /// split. Lengths are the problem's own `n` and `m`; a mismatch is
2891    /// reported and the solve proceeds monolithically.
2892    ///
2893    /// Persistent config; drop it with [`Self::clear_block_structure`].
2894    pub fn set_block_structure(&mut self, var_blocks: Vec<i32>, con_blocks: Vec<i32>) {
2895        self.model_blocks = Some((var_blocks, con_blocks));
2896    }
2897
2898    /// Drop any declared model-space block structure.
2899    pub fn clear_block_structure(&mut self) {
2900        self.model_blocks = None;
2901    }
2902
2903    /// The declared model-space block structure, if any.
2904    pub fn block_structure(&self) -> Option<(&[i32], &[i32])> {
2905        self.model_blocks
2906            .as_ref()
2907            .map(|(v, c)| (v.as_slice(), c.as_slice()))
2908    }
2909
2910    /// Install a block-parallel KKT partition (structured-KKT Phase 5b).
2911    /// `labels` are KKT-space block ids in the solver's internal
2912    /// `x, slack, eq-dual, ineq-dual` order, `< 0` for the shared border; an
2913    /// **empty** vector asks the solver to detect the structure from the
2914    /// assembled KKT. Honored on the IPM + feral + exact-Hessian path, with a
2915    /// transparent fallback to the standard solver when the partition does not
2916    /// match the matrix. Persistent config; drop it with
2917    /// [`Self::clear_kkt_block_structure`].
2918    pub fn set_kkt_block_structure(&mut self, labels: Vec<i32>) {
2919        self.kkt_blocks = Some(labels);
2920    }
2921
2922    /// Drop any installed block partition.
2923    pub fn clear_kkt_block_structure(&mut self) {
2924        self.kkt_blocks = None;
2925    }
2926
2927    /// The currently-installed block partition, if any.
2928    pub fn kkt_block_structure(&self) -> Option<&[i32]> {
2929        self.kkt_blocks.as_deref()
2930    }
2931
2932    pub fn set_kkt_schur_block(&mut self, indices: Vec<usize>) {
2933        self.kkt_schur_block = Some(indices);
2934    }
2935
2936    /// Drop any installed Schur KKT partition, restoring the standard
2937    /// full-space solver for subsequent solves.
2938    pub fn clear_kkt_schur_block(&mut self) {
2939        self.kkt_schur_block = None;
2940    }
2941
2942    /// The currently-installed Schur KKT partition, if any.
2943    pub fn kkt_schur_block(&self) -> Option<&[usize]> {
2944        self.kkt_schur_block.as_deref()
2945    }
2946
2947    /// Return the final QP working set from the most recent SQP
2948    /// solve, or `None` if the last solve wasn't SQP, didn't
2949    /// produce a working set (cold-start declared the iterate
2950    /// optimal before solving any QP), or no SQP solve has run.
2951    ///
2952    /// The set is in the **caller's** index spaces, the ones
2953    /// `finalize_solution` uses: `bounds[j]` is variable `j` of the full
2954    /// `n` (a variable `fixed_variable_treatment = make_parameter` removed
2955    /// reads `Fixed`), and `constraints[i]` is `g` row `i` in the model's
2956    /// own row order — not the SQP's internal equalities-first order. It is
2957    /// the form [`Self::set_sqp_warm_start`] takes back.
2958    pub fn last_sqp_working_set(&self) -> Option<&pounce_qp::WorkingSet> {
2959        self.sqp_last_working_set.as_ref()
2960    }
2961
2962    /// A working set computed in the solve's algorithm space, mapped to the
2963    /// caller's: bound statuses lifted to the full variable vector (gh#986
2964    /// review item 10 — fixed variables are `Fixed`), constraint statuses
2965    /// moved from the algorithm's `[c; d]` row order (equalities first) to
2966    /// the user's `g` row order through the NLP's `c_map` / `d_map`. A
2967    /// bound vector that is not reduced-sized is left as it is.
2968    fn working_set_to_user(
2969        &self,
2970        nlp: &dyn IpoptNlp,
2971        ws: pounce_qp::WorkingSet,
2972    ) -> pounce_qp::WorkingSet {
2973        let bounds = match &self.x_elimination {
2974            Some((map, n_full)) if ws.bounds.len() == map.len() && map.len() != *n_full => {
2975                let mut bounds = vec![pounce_qp::BoundStatus::Fixed; *n_full];
2976                for (k, &j) in map.iter().enumerate() {
2977                    bounds[j as usize] = ws.bounds[k];
2978                }
2979                bounds
2980            }
2981            _ => ws.bounds,
2982        };
2983        pounce_qp::WorkingSet {
2984            bounds,
2985            constraints: working_set_rows_to_user(nlp, ws.constraints),
2986        }
2987    }
2988
2989    /// If `solver_selection` is explicitly set to a value whose routing lives
2990    /// only in the CLI's `.nl` dispatch, return  it; otherwise `None`.
2991    /// `optimize_tnlp` uses this to reject a forced convex selection a library
2992    /// consumer cannot honor.
2993    fn unsupported_library_solver_selection(&self) -> Option<&'static str> {
2994        let (v, found) = self.options.get_string_value("solver_selection", "").ok()?;
2995        if !found {
2996            return None;
2997        }
2998        ["lp-ipm", "qp-ipm", "socp"]
2999            .into_iter()
3000            .find(|c| v.eq_ignore_ascii_case(c))
3001    }
3002
3003    /// The `linear_solver` value when the caller explicitly asked for a
3004    /// backend pounce does not implement; `None` when the request can be
3005    /// served (or was never made).
3006    ///
3007    /// pounce ships two: **FERAL** (pure Rust, the effective default) and
3008    /// **MA57** (HSL, behind the `ma57` feature). The option's valid-value
3009    /// list is a faithful port of upstream Ipopt's — `ma27`, `ma77`,
3010    /// `ma86`, `ma97`, `mumps`, `pardiso`, `pardisomkl`, `spral`, `wsmp`,
3011    /// `custom` — so an `ipopt.opt` written for Ipopt parses here, and
3012    /// every one of those names used to fall through a `_ =>` arm to
3013    /// FERAL. A run "using MUMPS" was a FERAL run; a benchmark comparing
3014    /// backends compared FERAL with itself (gh#483 follow-up).
3015    ///
3016    /// The registered default is `feral`, which pounce implements, so no
3017    /// explicit-vs-default distinction is needed: whatever the option
3018    /// resolves to must be a backend that exists. (It is checked
3019    /// unconditionally on purpose — a future default naming something
3020    /// unimplemented should trip this, not slip past it.)
3021    ///
3022    /// Explicit `ma57` on a build that lacks the feature is *not* refused;
3023    /// that fallback is reported in the banner ("ma57 requested but not
3024    /// compiled"), so it is visible rather than silent, and failing a
3025    /// portable `ipopt.opt` over a build flag would cost more than it buys.
3026    pub fn unimplemented_linear_solver(&self) -> Option<String> {
3027        let (v, _) = self.options.get_string_value("linear_solver", "").ok()?;
3028        ["feral", "ma57"]
3029            .iter()
3030            .all(|ok| !v.eq_ignore_ascii_case(ok))
3031            .then_some(v)
3032    }
3033
3034    /// The message for the first option the caller set that names a
3035    /// feature pounce does not implement, or `None`. Public so the CLI
3036    /// can refuse before routing — the convex dispatch never reaches
3037    /// `optimize_tnlp`. See [`crate::unimplemented_options`].
3038    ///
3039    /// A run configuring nothing but backends pounce does not ship is
3040    /// refused here too, after the per-option table has had its say —
3041    /// see [`crate::unimplemented_options::backend_only_refusal`]. It
3042    /// is folded in rather than given its own accessor so that every
3043    /// surface already refusing on this method refuses on it as well;
3044    /// the CLI is not the only frontend, and a condition worth failing
3045    /// on is not worth failing on only from the CLI.
3046    pub fn unimplemented_option_refusal(&self) -> Option<String> {
3047        crate::unimplemented_options::refusal(&self.options, &self.reg_options).or_else(|| {
3048            crate::unimplemented_options::backend_only_refusal(&self.options, &self.reg_options)
3049        })
3050    }
3051
3052    /// The message for the first string option the caller set to a
3053    /// registered *value* pounce does not implement, or `None`.
3054    ///
3055    /// Separate from [`Self::unimplemented_option_refusal`] because the
3056    /// option itself is read and its other values work — it is one mode
3057    /// that is missing, not the feature. See
3058    /// [`crate::unimplemented_options::UNIMPLEMENTED_VALUES`].
3059    pub fn unimplemented_option_value_refusal(&self) -> Option<String> {
3060        crate::unimplemented_options::value_refusal(&self.options)
3061    }
3062
3063    /// `option_file_name` set on a surface that never resolves it.
3064    ///
3065    /// The option reaches a file through exactly one path —
3066    /// [`Self::initialize_with_option_file`], which the `pounce` CLI
3067    /// drives. A library caller (Python, the C interface, WASM) sets its
3068    /// options directly and calls no such thing, so on those surfaces the
3069    /// option names a whole configuration and applies none of it: gh#518's
3070    /// failure mode, one surface over. It used to be caught by the blanket
3071    /// [`crate::unimplemented_options`] refusal, which no longer covers it
3072    /// now that the feature exists; this keeps the guard exactly where the
3073    /// feature still doesn't.
3074    ///
3075    /// Deliberately *not* fixed by having the library read an options file
3076    /// too: an implicit `./ipopt.opt` lookup under Python or the GAMS C
3077    /// link would be a surprising action at a distance, and `pounce.opt`
3078    /// already means something else to GAMS.
3079    pub fn unhonored_option_file_name(&self) -> Option<String> {
3080        if self.option_file_resolved {
3081            return None;
3082        }
3083        // Same default gate as the table: an explicitly-set *default*
3084        // asks for nothing, so it must not fail. `option_file_name`
3085        // defaults to `ipopt.opt`, and a caller round-tripping a full
3086        // option dump — or a generated config that spells out every
3087        // registered name — hits that value without asking for anything.
3088        if !crate::unimplemented_options::set_to_a_non_default(
3089            &self.options,
3090            &self.reg_options,
3091            "option_file_name",
3092        ) {
3093            return None;
3094        }
3095        match self.options.get_string_value("option_file_name", "") {
3096            Ok((name, true)) if !name.is_empty() => Some(format!(
3097                "pounce: `option_file_name` was set to `{name}`, but this entry \
3098                 point does not read options files — it would configure nothing. \
3099                 The `pounce` CLI honors it (and `./pounce.opt` / `./ipopt.opt`); \
3100                 from a library, read the file yourself and pass its contents to \
3101                 `initialize_with_options_str`, or set the options directly. \
3102                 Tracking issue: https://github.com/jkitchin/pounce/issues/518"
3103            )),
3104            _ => None,
3105        }
3106    }
3107
3108    /// Declare that this caller can route a model to the convex LP/QP /
3109    /// SOCP engines, so the `qp_*` knobs they read configure something.
3110    ///
3111    /// The `pounce` CLI calls this: it owns the `.nl` structure
3112    /// extraction that classifies a model, which is the whole of what
3113    /// `solver_selection`'s convex values need. No library frontend can
3114    /// (see [`Self::unsupported_library_solver_selection`]), so the
3115    /// default is `false` and [`Self::unhonored_convex_option`] refuses
3116    /// the knobs there.
3117    ///
3118    /// Declaring it also covers the CLI's *fallback*: a convex attempt
3119    /// that returns no verified point hands the model to
3120    /// [`Self::optimize_tnlp`], and the `qp_*` values it was given
3121    /// configured that attempt for real. Refusing them at the handoff
3122    /// would fail a run that used them.
3123    pub fn set_convex_routing_available(&mut self, available: bool) {
3124        self.convex_routing_available = available;
3125    }
3126
3127    /// The convex LP/QP knobs are registered core-side so every frontend
3128    /// parses them — but only the CLI can reach the engines that read
3129    /// them. On any other entry point the option names a whole
3130    /// configuration and applies none of it; this is the message that
3131    /// says so, in place of the silence.
3132    ///
3133    /// gh#604. Same shape and same default gate as
3134    /// [`Self::unhonored_option_file_name`]: an explicitly-set *default*
3135    /// asks for nothing and must keep working, so only a value that
3136    /// differs is refused.
3137    pub fn unhonored_convex_option(&self) -> Option<String> {
3138        if self.convex_routing_available {
3139            return None;
3140        }
3141        const CONVEX_ONLY: &[&str] = &[
3142            "qp_presolve",
3143            "qp_tau",
3144            "qp_tau_max",
3145            "qp_reg",
3146            "qp_gondzio_corr",
3147            "qp_infeas_tol",
3148            "qp_hsde",
3149            "qp_equilibrate",
3150            "qp_crossover",
3151        ];
3152        let name = CONVEX_ONLY.iter().find(|name| {
3153            crate::unimplemented_options::set_to_a_non_default(
3154                &self.options,
3155                &self.reg_options,
3156                name,
3157            )
3158        })?;
3159        Some(format!(
3160            "pounce: `{name}` tunes the convex LP/QP interior-point engine, but \
3161             this entry point cannot route a model to it — the option would \
3162             configure nothing. The `pounce` CLI reaches that engine on `.nl` \
3163             input (`solver_selection=lp-ipm` / `qp-ipm` / `socp`, or `auto` on \
3164             a model that classifies as one); the `qp_*` options themselves are \
3165             read only there and by `pounce.solve_qp`. From Python, \
3166             `pounce.solve_qp` drives the engine directly and takes `qp_presolve`, \
3167             `qp_reg`, `qp_hsde`, `qp_equilibrate` and `qp_crossover` as keyword \
3168             arguments (presolve is off there unless asked for). \
3169             On this path, `solver_selection=qp-active-set` \
3170             (or `algorithm=active-set-sqp`) is the nearest thing, tuned by the \
3171             `sqp_qp_*` options. Tracking issue: \
3172             https://github.com/jkitchin/pounce/issues/604"
3173        ))
3174    }
3175
3176    /// Warnings for caching hints pounce does not exploit. These never
3177    /// block a solve: the answer is identical either way, so refusing
3178    /// would cost the caller more than the silence did.
3179    pub fn unexploited_hint_warnings(&self) -> Vec<String> {
3180        crate::unimplemented_options::hint_warnings(&self.options, &self.reg_options)
3181    }
3182
3183    /// Warnings for the constant-derivative hints when the solve routes to
3184    /// `pounce-convex` instead of here. Call site is the convex dispatch
3185    /// in the CLI, next to the other guards that live there for the same
3186    /// reason: that dispatch never reaches [`Self::optimize_tnlp`], so
3187    /// `install_constant_derivative_hints` never runs and the hints are
3188    /// unread. On the NLP route they are honoured, so this must not be
3189    /// called there.
3190    pub fn convex_unexploited_hint_warnings(&self) -> Vec<String> {
3191        crate::unimplemented_options::convex_hint_warnings(&self.options, &self.reg_options)
3192    }
3193
3194    /// Which of the four constant-derivative hints the caller actually
3195    /// asserted, in [`pounce_nlp::constant_derivatives::HINT_OPTIONS`]
3196    /// order — the order [`reconcile`] pairs against the model's own
3197    /// proofs.
3198    ///
3199    /// Each name is read as a literal rather than through the loop
3200    /// variable the caller used to use. The registered-but-unread scan
3201    /// (`tests/no_silent_options.rs`) keys on the option name as it
3202    /// appears at the accessor, so `get_bool_value(name, "")` over an
3203    /// array read as "no key here" and left all four sitting in the
3204    /// silent list while they were fully wired and consumed (#551 /
3205    /// #677).
3206    ///
3207    /// Matching over `HINT_OPTIONS` rather than writing a bare array
3208    /// keeps the slots right by construction, and a fifth hint added to
3209    /// `HINT_OPTIONS` trips the fallback arm instead of silently reading
3210    /// as "not asserted" — which is the failure mode this whole line of
3211    /// work exists to kill.
3212    fn asserted_constant_derivative_hints(&self) -> [bool; 4] {
3213        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
3214        let read_yes = |key: &str| matches!(self.options.get_bool_value(key, ""), Ok((true, true)));
3215        HINT_OPTIONS.map(|name| match name {
3216            "grad_f_constant" => read_yes("grad_f_constant"),
3217            "hessian_constant" => read_yes("hessian_constant"),
3218            "jac_c_constant" => read_yes("jac_c_constant"),
3219            "jac_d_constant" => read_yes("jac_d_constant"),
3220            other => unreachable!("`{other}` is in HINT_OPTIONS with no read site"),
3221        })
3222    }
3223
3224    /// Resolve the four constant-derivative hints for this solve and
3225    /// install the result on the NLP (gh #588, phase Q6).
3226    ///
3227    /// `grad_f_constant` / `hessian_constant` / `jac_c_constant` /
3228    /// `jac_d_constant` are, upstream, unchecked user assertions: Ipopt
3229    /// reuses the derivative and returns a wrong answer if the assertion
3230    /// was false. pounce asks the model first. Where the model *proves*
3231    /// the derivative constant, the reuse happens whether or not the
3232    /// option was set — the hint is redundant. Where the model proves it
3233    /// **varies** and the option was set anyway, the option is refused
3234    /// with a warning, which is the deliberate divergence. Where the
3235    /// model can prove nothing — every callback front end, both GAMS
3236    /// links — the user's assertion is honoured on trust, exactly as
3237    /// upstream, because "unproved" is not "disproved" and silently
3238    /// overriding the caller there would be its own wrong answer.
3239    fn install_constant_derivative_hints(&self, orig_nlp: &mut OrigIpoptNlp) {
3240        use pounce_common::journalist::JournalCategory;
3241        use pounce_nlp::constant_derivatives::reconcile;
3242
3243        // Each name is read as a literal rather than through the loop
3244        // variable: the registered-but-unread scan
3245        // (`tests/no_silent_options.rs`) keys on the option name as it
3246        // appears at the accessor, so `get_bool_value(name, "")` read as
3247        // "no key here" and left all four of these sitting in the silent
3248        // list while they were fully wired and consumed (#551 / #677).
3249        //
3250        // Matching over `HINT_OPTIONS` rather than writing a bare array
3251        // keeps the order right by construction — `reconcile` pairs
3252        // `asserted[k]` with `proofs[k]` — and a fifth hint added to
3253        // `HINT_OPTIONS` trips the fallback arm instead of silently
3254        // reading as "not asserted", which is the failure mode this
3255        // whole line of work exists to kill.
3256        let asserted = self.asserted_constant_derivative_hints();
3257        let proofs = orig_nlp.derivative_proofs();
3258        let (outcomes, enabled) = reconcile(proofs, asserted);
3259
3260        for outcome in &outcomes {
3261            if let Some(warning) = outcome.warning() {
3262                eprintln!("{warning}");
3263                self.journalist.print(
3264                    JournalLevel::J_STRONGWARNING,
3265                    JournalCategory::J_MAIN,
3266                    &format!("{warning}\n"),
3267                );
3268            }
3269        }
3270        if std::env::var("POUNCE_DBG_CONSTDERIV").is_ok() {
3271            for outcome in &outcomes {
3272                eprintln!(
3273                    "[const deriv] {:<15} proof={:?} asserted={} reused={}",
3274                    outcome.name, outcome.proof, outcome.asserted, outcome.honoured,
3275                );
3276            }
3277        }
3278        orig_nlp.set_constant_derivatives(enabled);
3279    }
3280
3281    /// Warnings for knobs of a linear-solver backend pounce does not
3282    /// ship (`ma97_*`, `pardiso_*`, …), one line per backend family.
3283    ///
3284    /// Warnings and not refusals: an `ipopt.opt` carrying settings for
3285    /// several backends so that one file runs everywhere is exactly what
3286    /// the registry exists to accept, and refusing it would fail a run
3287    /// over knobs it never touches. See the "Backend knobs warn, they do
3288    /// not refuse" section of [`crate::unimplemented_options`]. gh#551.
3289    pub fn unimplemented_backend_warnings(&self) -> Vec<String> {
3290        crate::unimplemented_options::backend_warnings(&self.options, &self.reg_options)
3291    }
3292
3293    /// The same warnings, but at most once per application: the second
3294    /// caller gets nothing.
3295    ///
3296    /// Two sites emit them — the CLI, before routing, because a convex
3297    /// model never reaches [`Self::optimize_tnlp`], and `optimize_tnlp`
3298    /// itself, for every frontend that is not the CLI. A CLI run passes
3299    /// through both, and printing the identical paragraph twice is how a
3300    /// warning teaches its reader to skip warnings.
3301    pub fn take_unimplemented_backend_warnings(&mut self) -> Vec<String> {
3302        if self.backend_warnings_emitted {
3303            return Vec::new();
3304        }
3305        self.backend_warnings_emitted = true;
3306        self.unimplemented_backend_warnings()
3307    }
3308
3309    /// Resolve the five registered `derivative_test*` knobs. Every one
3310    /// of them was registered and never read, so `derivative_test=
3311    /// first-order` ran no test and printed nothing — a checker that
3312    /// silently checks nothing reports success by omission (gh#483
3313    /// follow-up).
3314    ///
3315    /// The numeric helper is named `read_num` to match the accessor
3316    /// idiom the rest of this file uses: the registered-but-unread scan
3317    /// (`tests/no_silent_options.rs`) discovers `read_*` helpers and the
3318    /// literal key passed to them, so a differently-named local closure
3319    /// made `derivative_test_perturbation` and `derivative_test_tol`
3320    /// read as silent when they are wired and consumed (#677, #551).
3321    fn derivative_test_options(&self) -> DerivativeTestOptions {
3322        let read_num = |key: &str, default: Number| -> Number {
3323            self.options
3324                .get_numeric_value(key, "")
3325                .ok()
3326                .and_then(|(v, f)| f.then_some(v))
3327                .unwrap_or(default)
3328        };
3329        DerivativeTestOptions {
3330            mode: self
3331                .options
3332                .get_string_value("derivative_test", "")
3333                .ok()
3334                .and_then(|(v, f)| f.then_some(v))
3335                .map(|v| DerivativeTest::from_option(&v))
3336                .unwrap_or_default(),
3337            perturbation: read_num("derivative_test_perturbation", 1e-8),
3338            tol: read_num("derivative_test_tol", 1e-4),
3339            first_index: self
3340                .options
3341                .get_integer_value("derivative_test_first_index", "")
3342                .ok()
3343                .and_then(|(v, f)| f.then_some(v))
3344                .unwrap_or(-2),
3345            print_all: self
3346                .options
3347                .get_bool_value("derivative_test_print_all", "")
3348                .ok()
3349                .and_then(|(v, f)| f.then_some(v))
3350                .unwrap_or(false),
3351        }
3352    }
3353
3354    /// The derivative checker's structured verdict from the most recent
3355    /// [`Self::run_derivative_test`], or `None` when no test ran (gh#990).
3356    /// The IPM and SQP drains copy it into `SolveStatistics`; a caller that
3357    /// builds its own report (the CLI's convex route) reads it here.
3358    pub fn derivative_check(&self) -> Option<pounce_nlp::derivative_test::DerivativeCheckSummary> {
3359        self.derivative_check.borrow().clone()
3360    }
3361
3362    /// Run the derivative checker, if requested, against `tnlp`.
3363    ///
3364    /// Advisory, like upstream: a suspicious entry is reported and the
3365    /// solve continues. The report goes to stderr so it survives
3366    /// `print_level=0` and leaves `--json-output`'s stdout clean.
3367    pub fn run_derivative_test(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
3368        // gh#990 item 3: the structured result belongs to this solve; a solve
3369        // that asks for no test must not inherit the previous one's.
3370        *self.derivative_check.borrow_mut() = None;
3371        let opts = self.derivative_test_options();
3372        if matches!(opts.mode, DerivativeTest::None) {
3373            return;
3374        }
3375        let report = {
3376            let mut borrowed = tnlp.borrow_mut();
3377            pounce_nlp::derivative_test::run(&mut *borrowed, &opts)
3378        };
3379        let Some(report) = report else {
3380            eprintln!(
3381                "pounce: derivative_test was requested but the TNLP declined to \
3382                 supply the information the check needs (dimensions, bounds, or \
3383                 a starting point); no test was run."
3384            );
3385            return;
3386        };
3387        *self.derivative_check.borrow_mut() = Some(report.summary.clone());
3388        use pounce_common::journalist::JournalCategory;
3389        for line in &report.lines {
3390            eprintln!("{line}");
3391            self.journalist.print(
3392                JournalLevel::J_SUMMARY,
3393                JournalCategory::J_MAIN,
3394                &format!("{line}\n"),
3395            );
3396        }
3397    }
3398
3399    /// The message [`Self::unimplemented_linear_solver`] earns, shared by
3400    /// every frontend so they cannot drift apart.
3401    pub fn unimplemented_linear_solver_message(value: &str) -> String {
3402        format!(
3403            "pounce: linear_solver={value} is not implemented. pounce provides \
3404             `feral` (pure-Rust sparse symmetric, the default) and `ma57` (HSL, \
3405             in a `--features ma57` build); the other names in the option's \
3406             list come from the upstream Ipopt registry so an ipopt.opt written \
3407             for Ipopt still parses. Selecting one used to run FERAL silently, \
3408             which makes a backend comparison measure nothing — so it is \
3409             refused instead. Use linear_solver=feral or linear_solver=ma57."
3410        )
3411    }
3412
3413    /// Will the next `optimize_tnlp` run the active-set SQP driver rather
3414    /// than the interior-point one?
3415    ///
3416    /// Public because the dispatch decision has to be *reportable*, not just
3417    /// taken: before this was reachable, the CLI's `Selected solver:` line
3418    /// and the JSON report's `solution.engine` both named the filter-IPM on
3419    /// every `algorithm=active-set-sqp` run, because the only thing either
3420    /// consulted was `solver_selection` — which is `auto` on a general NLP
3421    /// however the `algorithm` option is set. Reading the same predicate
3422    /// `optimize_tnlp` dispatches on is what keeps the report and the run
3423    /// from disagreeing; deriving it a second time in the CLI is how they
3424    /// drifted in the first place.
3425    pub fn is_sqp_algorithm_selected(&self) -> bool {
3426        // `algorithm` is the primary selector.
3427        // `solver_selection = qp-active-set` selects the
3428        // same active-set SQP engine.
3429        let algo_sqp = matches!(
3430            self.options.get_string_value("algorithm", ""),
3431            Ok((v, true)) if v.eq_ignore_ascii_case("active-set-sqp")
3432        );
3433        let selection_sqp = matches!(
3434            self.options.get_string_value("solver_selection", ""),
3435            Ok((v, true)) if v.eq_ignore_ascii_case("qp-active-set")
3436        );
3437        algo_sqp || selection_sqp
3438    }
3439
3440    /// Whether an active-set SQP request on a model with `n` variables and
3441    /// `m` constraints runs as the interior point with the IPM→SQP handover
3442    /// and post-convergence crossover, instead of a cold active-set SQP
3443    /// (gh#1061).
3444    ///
3445    /// A primal active-set QP started cold changes its working set one row or
3446    /// bound per iteration, so the SQP's first step QP needs on the order of
3447    /// one iteration per active constraint, each a KKT update the size of the
3448    /// model. Measured on four 9–20 k-variable equality-heavy NLPs
3449    /// (`brainpc2`, `robot_1600`, `WM_CFy`, `ubh5`): not one first QP finished
3450    /// in 300 s. Started from the interior point instead, `ubh5` solves in
3451    /// 0.5 s and `robot_1600` in 6 s. The active-set SQP produces the answer
3452    /// when a handover attempt is accepted; when every attempt declines, the
3453    /// converged interior point is the answer, exactly as under
3454    /// `ipm_sqp_handover=yes`. Post-convergence `crossover` is not turned on
3455    /// as well: measured, it bought `robot_1600` its active-set answer for
3456    /// 6 s → 41 s, and on `brainpc2` declined after a 194 s step-3 QP, past
3457    /// the wall-time limit.
3458    ///
3459    /// Only above [`AUTO_HANDOVER_MIN_DIM`], where a cold SQP is the problem,
3460    /// and only when `ipm_sqp_handover` was not set: `ipm_sqp_handover=no`
3461    /// asks for the cold active-set SQP and gets it.
3462    pub fn sqp_auto_handover(&self, n: usize, m: usize) -> bool {
3463        self.is_sqp_algorithm_selected()
3464            && n + m >= AUTO_HANDOVER_MIN_DIM
3465            && !matches!(
3466                self.options.get_bool_value("ipm_sqp_handover", ""),
3467                Ok((_, true))
3468            )
3469    }
3470
3471    /// Whether the most recent solve was run as interior point plus handover
3472    /// under [`Self::sqp_auto_handover`].
3473    pub fn auto_handover_ran(&self) -> bool {
3474        self.auto_handover.get()
3475    }
3476
3477    /// Whether the active-set SQP produced the most recent solve's point:
3478    /// always on the cold SQP route, and on the auto-handover route when a
3479    /// handover attempt (or a crossover the user asked for) was accepted.
3480    pub fn answer_from_active_set_sqp(&self) -> bool {
3481        if !self.auto_handover.get() {
3482            return self.is_sqp_algorithm_selected();
3483        }
3484        self.handover_report
3485            .as_ref()
3486            .is_some_and(|r| r.accepted_at_iter.is_some())
3487            || self.crossover_report.as_ref().is_some_and(|r| r.accepted())
3488    }
3489
3490    /// Phase 5b SQP entry point. Builds the same NLP chain
3491    /// (`TNLPAdapter` → `OrigIpoptNlp` → `IpoptNlpAdapter`) the
3492    /// IPM uses, then runs `SqpAlgorithm::optimize`. Maps the
3493    /// `SqpResult.status` back to `ApplicationReturnStatus` and
3494    /// hands the final iterate to the user TNLP's
3495    /// `finalize_solution` callback via `finalize_via_sqp`.
3496    fn optimize_sqp_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
3497        use pounce_nlp::ConstObjScaling;
3498        use pounce_nlp::orig_ipopt_nlp::OrigIpoptNlp;
3499        use pounce_nlp::tnlp_adapter::TNLPAdapter;
3500
3501        // Wall-clock for the whole SQP solve, mirroring the IPM path's
3502        // `t_start` (see the `total_wallclock_time_secs` assignment in
3503        // `optimize_tnlp`). Without this the field stayed at its struct
3504        // default of 0.0 on every active-set solve, so `--json-output`
3505        // reported an instantaneous solve regardless of actual runtime and
3506        // the engine could not be speed-compared against qp-ipm at all
3507        // (benchmarks/scripts/compare_qp_four_way.py had to skip the column).
3508        let t_start = std::time::Instant::now();
3509
3510        // `new_with_options`, not `new`: the latter hard-codes the same three
3511        // defaults, so `fixed_variable_treatment`, `nlp_lower_bound_inf` and
3512        // `nlp_upper_bound_inf` were accepted and discarded on this arm. The
3513        // defaults coincide, which is why it went unnoticed — it diverges only
3514        // for a caller who sets one, and then the two arms CLASSIFY THE MODEL
3515        // DIFFERENTLY: a bound at the caller's own infinity threshold is a
3516        // bound here and no bound there, and a fixed variable is eliminated on
3517        // one arm and relaxed on the other. That is a different problem, not a
3518        // different trajectory on one.
3519        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
3520        let adapter = match TNLPAdapter::new_with_options(
3521            Rc::clone(&tnlp),
3522            lo_inf,
3523            up_inf,
3524            fixed_treatment,
3525        ) {
3526            Ok(a) => Rc::new(RefCell::new(a)),
3527            Err(_) => return ApplicationReturnStatus::InvalidProblemDefinition,
3528        };
3529        // The SQP path never runs gradient-based scaling, but the
3530        // constant `obj_scaling_factor` (negative ⇒ maximize) still
3531        // applies via the OrigIpoptNlp constructor.
3532        let obj_scaling_factor = self
3533            .options
3534            .get_numeric_value("obj_scaling_factor", "")
3535            .ok()
3536            .and_then(|(v, f)| f.then_some(v))
3537            .unwrap_or(1.0);
3538        let mut orig_nlp = match OrigIpoptNlp::new(
3539            Rc::clone(&adapter),
3540            Rc::new(ConstObjScaling(obj_scaling_factor)),
3541        ) {
3542            Ok(n) => n,
3543            Err(_) => return ApplicationReturnStatus::InternalError,
3544        };
3545        // Same Q6 reconciliation as the IPM route: the SQP driver
3546        // evaluates the same derivatives through the same NLP object.
3547        self.install_constant_derivative_hints(&mut orig_nlp);
3548        // `bound_relax_factor`, on the convex arm's rule (gh#745's
3549        // `convex_bound_relax`), because this arm's position is the convex
3550        // arm's and not the interior-point arm's.
3551        //
3552        // The widening is a change to the MODEL, and its error is one-signed:
3553        // enlarging the feasible set can only flatter the objective, by `δ`
3554        // times the bound's multiplier, with nothing bounding that product and
3555        // no amount of tightening `tol` closing it. On `LISWET1` it buys `9.0`
3556        // of objective (`27.1221` against the true `36.1224`); over the
3557        // 91-instance netlib LP corpus, dropping it took the median objective
3558        // error from `1.2e-08` to `3.8e-11`.
3559        //
3560        // The interior-point arm keeps it and must: it is a feasible-iterate
3561        // log-barrier that needs `x` strictly inside its bounds, and matching
3562        // Ipopt is that arm's contract — the fixture sweep at
3563        // `bound_relax_factor=0` turns `square_flowsheet_resto` into
3564        // `InfeasibleProblemDetected`. An active-set QP needs none of it: its
3565        // iterates are feasible for the box by construction, which is why this
3566        // arm has always run un-widened without incident.
3567        //
3568        // So: unset means solve the model as declared, which is what this arm
3569        // already did. What it did NOT do is honour an explicit request — the
3570        // option was accepted and discarded, the gh#677 shape, and a caller
3571        // comparing arms under a named `bound_relax_factor` was comparing two
3572        // different models without being told. Set means the caller asked by
3573        // name and gets exactly the interior-point arm's model.
3574        //
3575        // Either branch snapshots the declared bounds first (`relax_bounds`
3576        // does it before widening), which `declared_box_violation` needs: its
3577        // absence is what printed `Variable bound violation: nan` here.
3578        let requested_relax = self
3579            .options
3580            .get_numeric_value("bound_relax_factor", "")
3581            .ok()
3582            .and_then(|(v, set)| set.then_some(v));
3583        match requested_relax {
3584            Some(factor) => {
3585                let cap = self
3586                    .options
3587                    .get_numeric_value("constr_viol_tol", "")
3588                    .ok()
3589                    .and_then(|(v, set)| set.then_some(v))
3590                    .unwrap_or(1e-4);
3591                orig_nlp.relax_bounds(factor, cap);
3592            }
3593            None => orig_nlp.snapshot_declared_bounds(),
3594        }
3595        let nlp_rc: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
3596
3597        let mut sqp_adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(&nlp_rc));
3598
3599        let mut builder = self.algorithm_builder_snapshot();
3600        builder.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
3601        // `max_wall_time` / `max_cpu_time` on this arm (gh#1054). They were
3602        // registered, documented as solve-wide, and read only by the
3603        // interior-point convergence check, so an active-set solve stuck in
3604        // its first QP ran until something outside POUNCE killed it.
3605        builder.sqp.deadline = Some(self.solve_deadline());
3606        // Prefer a caller-installed factory, exactly as `optimize_constrained`
3607        // does, so an embedder that plugs its own backend gets it on both
3608        // arms. `take()` matches the IPM's one-shot semantics rather than
3609        // introducing a second, different lifetime for the same hook.
3610        //
3611        // `maybe_crossover` deliberately does NOT do this: it runs after the
3612        // IPM solve has already taken the factory, so there is never one left
3613        // to find, and its two closures cannot both hold `&mut self` anyway.
3614        let factory = self
3615            .linear_backend_factory
3616            .take()
3617            .unwrap_or_else(|| self.make_backend_factory());
3618        let mut alg = match builder.build_sqp_with_backend(factory) {
3619            Some(a) => a,
3620            None => return ApplicationReturnStatus::InternalError,
3621        };
3622
3623        // Problem statistics + end-of-run summary are emitted by the engine
3624        // itself here (#206), gated on the main `print_level`, so the SQP
3625        // route matches the IPM route across every frontend (CLI, Python, C).
3626        // The SQP's own per-iteration rows stay gated on the separate
3627        // `sqp_print_level`.
3628        let console_output = match self.options.get_integer_value("print_level", "") {
3629            Ok((v, true)) => v >= 1,
3630            _ => true,
3631        };
3632        self.emit_problem_stats(&tnlp, console_output);
3633
3634        // Phase 5c (§6): consume any stashed warm-start iterate.
3635        // `optimize_with_warm_start(warm=None)` is equivalent to
3636        // `optimize`, so cold callers see no change.
3637        let mut warm = self.sqp_warm_start.take();
3638        // gh#986 review item 10: map a warm start given in the caller's full
3639        // variable space through this problem's fixed-variable elimination.
3640        // The working set this application publishes is in that space
3641        // (`working_set_to_user`), and so is what Python's
3642        // `solve(..., working_set=...)` decodes, so a child that fixes `x1`
3643        // gets the parent's statuses for exactly the columns it still has.
3644        // The first pass compared lengths only: a fixed variable made the
3645        // full-space hint "the wrong size" and it was dropped (a cold solve
3646        // and `info["working_set"] = None`), while a reduced-space hint from a
3647        // sibling that fixed a *different* variable had the right size and was
3648        // applied to the wrong columns.
3649        let (x_map, n_full) = {
3650            let a = adapter.borrow();
3651            let cls = a.classification();
3652            (cls.x_not_fixed_map.clone(), cls.n_full_x as usize)
3653        };
3654        let reduced = x_map.len() != n_full;
3655        let prev_elimination = self.x_elimination.replace((x_map.clone(), n_full));
3656        if let Some(w) = warm.as_mut() {
3657            // The staged iterate is in the caller's (user) space; the
3658            // algorithm's is not. Converted here, once, for every frontend.
3659            sqp_warm_start_to_algorithm(&*nlp_rc.borrow(), w);
3660            if reduced {
3661                let mut drop_reason: Option<String> = None;
3662                if let Some(ws) = w.working.as_mut() {
3663                    if ws.bounds.len() == n_full {
3664                        ws.bounds = x_map.iter().map(|&j| ws.bounds[j as usize]).collect();
3665                    } else if ws.bounds.len() == x_map.len()
3666                        && prev_elimination.as_ref() != Some(&(x_map.clone(), n_full))
3667                    {
3668                        // A reduced-space working set from a solve that
3669                        // eliminated *different* variables: its columns do
3670                        // not line up with this problem's, however equal the
3671                        // count.
3672                        drop_reason = Some(
3673                            "its bound statuses are in the reduced space of a solve that \
3674                             fixed different variables"
3675                                .into(),
3676                        );
3677                    }
3678                }
3679                if let Some(why) = drop_reason {
3680                    tracing::warn!(
3681                        target: "pounce::sqp",
3682                        "SQP warm-start working set dropped: {why}; pass the full-space \
3683                         working set (last_sqp_working_set / info[\"working_set\"]) instead"
3684                    );
3685                    w.working = None;
3686                }
3687            }
3688        }
3689        // `warm_start_init_point=yes` with nothing staged: take the TNLP's
3690        // own starting multipliers, as the interior-point arm does. They
3691        // arrive through the same `IpoptNlp` projections the IPM's warm
3692        // initializer uses, so they are already in algorithm space (scaled,
3693        // compressed, `[y_c; y_d]`). Without this the SQP arm read only the
3694        // primal: a `.nl` `d` segment or `ipopt_z*_in` suffix, or a Python
3695        // `lagrange=` start, began from zero multipliers on this arm alone.
3696        if warm.is_none()
3697            && matches!(
3698                self.options.get_bool_value("warm_start_init_point", ""),
3699                Ok((true, _))
3700            )
3701        {
3702            warm = sqp_tnlp_warm_start(&nlp_rc);
3703        }
3704        // gh#986: a warm start recorded on one problem is dimensioned for
3705        // that problem. A child that fixes a variable (branching) reaches
3706        // here with a smaller reduced `n` (and possibly `m`), where the
3707        // algorithm's contract is to refuse a mismatched iterate outright —
3708        // which surfaced as `Internal_Error` on a perfectly legal solve.
3709        // A warm start is only a hint, so drop it with a warning and solve
3710        // cold instead.
3711        if let Some(w) = warm.as_ref() {
3712            use crate::sqp::SqpProblemSpec;
3713            let (n, m) = (sqp_adapter.n(), sqp_adapter.m());
3714            let fits = w.x.len() == n
3715                && w.lambda_x.len() == n
3716                && w.lambda_g.len() == m
3717                && w.working
3718                    .as_ref()
3719                    .map(|ws| ws.validate_dims(n, m).is_ok())
3720                    .unwrap_or(true);
3721            if !fits {
3722                tracing::warn!(
3723                    target: "pounce::sqp",
3724                    "SQP warm start dropped: it is sized for a problem with n = {}, m = {} \
3725                     but this one has n = {n}, m = {m} (a fixed variable or removed row \
3726                     changes the reduced dimensions); solving cold",
3727                    w.x.len(),
3728                    w.lambda_g.len(),
3729                );
3730                warm = None;
3731            }
3732        }
3733        let warm_working_set_applied = warm.as_ref().is_some_and(|w| w.working.is_some());
3734        // gh#1015: the user's `intermediate_callback`, once per iteration,
3735        // with `GetIpoptCurrentIterate` answering from the SQP iterate. The
3736        // snapshot is built before the callback runs because the callback
3737        // holds the TNLP; nothing in it may call back into the user's
3738        // `eval_*`.
3739        {
3740            let hook_nlp = Rc::clone(&nlp_rc);
3741            let hook_tnlp = Rc::clone(&tnlp);
3742            let fixed_var_duals = self.reports_fixed_var_duals();
3743            alg.set_iteration_hook(Box::new(move |info| {
3744                // Built only for a TNLP that reads it, as on the
3745                // interior-point arm: the fixed-variable recovery is not
3746                // free, and most callbacks read only the stats.
3747                let _guard = hook_tnlp.borrow().wants_current_iterate().then(|| {
3748                    crate::intermediate::UserIterateGuard::install(sqp_user_iterate(
3749                        &hook_nlp,
3750                        info.x,
3751                        info.lambda_g,
3752                        info.lambda_x,
3753                        info.c_vals,
3754                        info.grad_lag_x,
3755                        fixed_var_duals,
3756                    ))
3757                });
3758                let stats = pounce_nlp::tnlp::IterStats {
3759                    mode: pounce_nlp::return_codes::AlgorithmMode::RegularMode,
3760                    iter: info.iter as Index,
3761                    obj_value: info.obj,
3762                    inf_pr: info.inf_pr,
3763                    inf_du: info.inf_du,
3764                    // No barrier, no regularisation, no dual step length.
3765                    mu: 0.0,
3766                    d_norm: info.p_inf,
3767                    regularization_size: 0.0,
3768                    alpha_du: 0.0,
3769                    alpha_pr: info.alpha,
3770                    ls_trials: 0,
3771                };
3772                hook_tnlp.borrow_mut().intermediate_callback(
3773                    stats,
3774                    &pounce_nlp::tnlp::IpoptData::default(),
3775                    &pounce_nlp::tnlp::IpoptCq::default(),
3776                )
3777            }));
3778        }
3779        let res = match alg.optimize_with_warm_start(&mut sqp_adapter, warm) {
3780            Ok(r) => r,
3781            Err(e) => {
3782                // Always surface this. It used to be gated on the
3783                // undocumented `POUNCE_DBG_SQP`, so the only thing a user saw
3784                // was a bare `Internal_Error` with no indication of what went
3785                // wrong -- the underlying message here was
3786                // `QpFailure(LinearSolverFailure("QP subproblem returned
3787                // status unbounded"))`, which points straight at the cause.
3788                // A solve that is about to fail is exactly when the reason
3789                // should be cheapest to obtain.
3790                tracing::warn!(
3791                    target: "pounce::sqp",
3792                    "SQP solve failed: {e:?}"
3793                );
3794                return ApplicationReturnStatus::InternalError;
3795            }
3796        };
3797        // Stash the result's working set so the next solve in a
3798        // sequence can fetch it via `last_sqp_working_set` -- in the caller's
3799        // full variable space (gh#986 review item 10).
3800        self.sqp_last_working_set = res
3801            .working_set
3802            .clone()
3803            .map(|ws| self.working_set_to_user(&*nlp_rc.borrow(), ws));
3804        // Populate the shared `SolveStatistics` so the Python /
3805        // C-API post-solve accessors (`GetIpoptIterCount`,
3806        // `info["iter_count"]`, etc.) report the SQP outer-iter
3807        // count rather than zero. Constraint-violation /
3808        // dual-infeasibility residuals get the SQP-side values
3809        // too. The IPM path overwrites this dict on its own
3810        // solves, so SQP-vs-IPM mixing across solves stays
3811        // honest.
3812        {
3813            let mut stats = self.statistics.borrow_mut();
3814            stats.iteration_count = res.n_iter as Index;
3815            // Subproblem counters. The outer iteration count alone
3816            // cannot show what a working-set warm start bought — the
3817            // saved work is inside the QPs — so both are reported.
3818            stats.sqp_qp_solves = res.n_qp_solves as Index;
3819            stats.sqp_qp_working_set_changes = res.n_qp_working_set_changes as Index;
3820            stats.sqp_warm_working_set_applied = warm_working_set_applied;
3821            stats.final_objective = res.obj;
3822            // `final_scaled_objective` defaults to NaN; the SQP path does not
3823            // thread nlp_scaling through the objective (same as the residuals
3824            // mirrored below), so the scaled objective equals the unscaled
3825            // one. Without this it stayed NaN and the console printed
3826            // "Objective ...: nan  <unscaled>" on every active-set solve
3827            // (gh #313), even on a clean optimal solve.
3828            stats.final_scaled_objective = res.obj;
3829            stats.final_dual_inf = res.final_stationarity;
3830            stats.final_constr_viol = res.final_constr_viol;
3831            stats.final_compl = 0.0; // SQP has no barrier — no compl term.
3832            // Overall KKT error. This was previously left at the struct
3833            // default, which made every successful SQP solve report an
3834            // overall error of exactly 0.0 — indistinguishable from a
3835            // genuinely perfect solve, and enough on its own to make
3836            // `pounce.minimize`'s acceptable-KKT fallback upgrade any status
3837            // on this path to `success=True`. Same expression as the unscaled
3838            // twin below; the two agree because the SQP path does not thread
3839            // nlp_scaling through its residuals.
3840            stats.final_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3841            // Unscaled residuals (pounce#173). The SQP path does not thread
3842            // the nlp_scaling factors through to its residuals yet, so these
3843            // mirror the SQP-side values: correct when no scaling is active
3844            // (the common case) and a conservative proxy otherwise. Populated
3845            // here so the info dict's `final_unscaled_*` keys are honest
3846            // rather than left at the 0.0 default.
3847            stats.final_unscaled_dual_inf = res.final_stationarity;
3848            stats.final_unscaled_constr_viol = res.final_constr_viol;
3849            stats.final_unscaled_compl = 0.0;
3850            stats.final_unscaled_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3851            // Ipopt's `Variable bound violation` — how far the returned point
3852            // sits outside the box the caller wrote. Left at its `NaN` default
3853            // until now, which printed `nan` on this arm's every summary.
3854            //
3855            // Measured through the same `declared_box_violation` accessor the
3856            // interior-point arm reads (`curr_declared_box_violation_max`), so
3857            // the two arms cannot drift into reporting different quantities
3858            // under one heading. gh#900 is the precedent and the warning: it
3859            // fixed this row on the NLP and convex arms and noted the two were
3860            // "independent code paths, so a test that exercised one would say
3861            // nothing about the other" — this is the third, and it was missed.
3862            //
3863            // `res.x` is algorithm-space, which is what the accessor expects
3864            // (it lifts to full-x itself); `finalize_via_sqp` wraps it exactly
3865            // this way for the same reason.
3866            stats.final_declared_box_viol = {
3867                use pounce_linalg::dense_vector::DenseVectorSpace;
3868                let nlp_borrow = nlp_rc.borrow();
3869                let x_space = DenseVectorSpace::new(nlp_borrow.n());
3870                let mut x_dv = x_space.make_new_dense();
3871                x_dv.set_values(&res.x);
3872                // `NaN`, not `0.0`, on the abstention — deliberately unlike
3873                // the IPM path's `unwrap_or(0.0)`.
3874                //
3875                // `None` from this accessor means one thing only: the declared
3876                // bounds were never snapshotted. It is NOT "the model has no
3877                // finite bounds" — an unbounded model still snapshots, the
3878                // loops find nothing, and the answer is a measured `Some(0.0)`.
3879                // So on this arm `None` can only mean the
3880                // `snapshot_declared_bounds` call above was lost, and mapping
3881                // that to zero would replace a visible "no answer" with an
3882                // invisible false claim that the point is inside its box.
3883                // gh#900's subject is exactly that: a zero that must not be
3884                // fabricated. Checked by mutation — delete the snapshot call
3885                // and this row goes back to `nan` rather than quietly reading
3886                // `0.00e+00`.
3887                nlp_borrow
3888                    .declared_box_violation(&x_dv)
3889                    .unwrap_or(Number::NAN)
3890            };
3891            // gh#990: the derivative checker's verdict reaches `info` and the
3892            // report on this arm too; it was copied on the IPM drain only.
3893            stats.derivative_check = self.derivative_check.borrow().clone();
3894            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
3895        }
3896        let (app_status, solver_status) = match res.status {
3897            crate::sqp::SqpStatus::Optimal => (
3898                ApplicationReturnStatus::SolveSucceeded,
3899                pounce_nlp::SolverReturn::Success,
3900            ),
3901            crate::sqp::SqpStatus::MaxIter => (
3902                ApplicationReturnStatus::MaximumIterationsExceeded,
3903                pounce_nlp::SolverReturn::MaxiterExceeded,
3904            ),
3905            crate::sqp::SqpStatus::InfeasibleSubproblem => (
3906                ApplicationReturnStatus::InfeasibleProblemDetected,
3907                pounce_nlp::SolverReturn::LocalInfeasibility,
3908            ),
3909            crate::sqp::SqpStatus::LineSearchFailed => (
3910                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3911                pounce_nlp::SolverReturn::ErrorInStepComputation,
3912            ),
3913            // Honest non-committal QP-subproblem failure (#282): the QP
3914            // solver could not compute a step and did NOT certify
3915            // infeasibility. Never report Infeasible_Problem_Detected here
3916            // — a feasible problem has no infeasibility certificate.
3917            crate::sqp::SqpStatus::QpStepFailed => (
3918                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3919                pounce_nlp::SolverReturn::ErrorInStepComputation,
3920            ),
3921            // The QP subproblem ran out of its own iteration budget. Same
3922            // #282 guarantee — no infeasibility is asserted — but reported as
3923            // the budget exhaustion it is, so the user sees a limit they can
3924            // raise (`sqp_qp_max_iter`) instead of a step-size stall with no
3925            // remedy. See `SqpStatus::QpIterationLimit` for why these were
3926            // split.
3927            crate::sqp::SqpStatus::QpIterationLimit => (
3928                ApplicationReturnStatus::MaximumIterationsExceeded,
3929                pounce_nlp::SolverReturn::MaxiterExceeded,
3930            ),
3931            // Unbounded below, with a recession ray verified against the
3932            // true NLP (gh #388). `Diverging_Iterates` is POUNCE's (Ipopt's)
3933            // unboundedness verdict and maps to AMPL `solve_result_num=300`
3934            // — the same answer the IPM selectors give on the same model,
3935            // instead of the `Internal_Error` / 500 ("the solver broke")
3936            // this path used to report.
3937            crate::sqp::SqpStatus::Unbounded => (
3938                ApplicationReturnStatus::DivergingIterates,
3939                pounce_nlp::SolverReturn::DivergingIterates,
3940            ),
3941            // A non-finite iterate or constraint value (gh #876). Same
3942            // verdict, from the same condition, as the interior-point arm's
3943            // `if !nlp_err.is_finite()` screen — the two arms must not
3944            // disagree about what a `NaN` iterate means.
3945            crate::sqp::SqpStatus::InvalidNumber => (
3946                ApplicationReturnStatus::InvalidNumberDetected,
3947                pounce_nlp::SolverReturn::InvalidNumberDetected,
3948            ),
3949            crate::sqp::SqpStatus::UserRequestedStop => (
3950                ApplicationReturnStatus::UserRequestedStop,
3951                pounce_nlp::SolverReturn::UserRequestedStop,
3952            ),
3953            // gh#1054: the same verdicts the interior-point arm's
3954            // convergence check gives on the same budgets.
3955            crate::sqp::SqpStatus::WallTimeExceeded => (
3956                ApplicationReturnStatus::MaximumWallTimeExceeded,
3957                pounce_nlp::SolverReturn::WallTimeExceeded,
3958            ),
3959            crate::sqp::SqpStatus::CpuTimeExceeded => (
3960                ApplicationReturnStatus::MaximumCpuTimeExceeded,
3961                pounce_nlp::SolverReturn::CpuTimeExceeded,
3962            ),
3963        };
3964
3965        // Same gate as the IPM path: an infeasible-subproblem exit is a
3966        // numerical inference, and a feasible starting point disproves it
3967        // (gh #379). Only the infeasibility verdict is rewritten — every other
3968        // status passes through untouched, so the pair stays in lockstep.
3969        let refuted = withdraw_infeasibility_if_refuted(
3970            &tnlp,
3971            solver_status,
3972            self.nlp_lower_bound_inf(),
3973            self.nlp_upper_bound_inf(),
3974            self.user_tol(),
3975        );
3976        let (app_status, solver_status) = if refuted == solver_status {
3977            (app_status, solver_status)
3978        } else {
3979            (solver_return_to_app_status(refuted), refuted)
3980        };
3981
3982        // Forward to the user TNLP's finalize_solution. We pass
3983        // the SQP iterate and recovered multipliers via the
3984        // OrigIpoptNlp's lifting hooks. Failure here is silent
3985        // (we still return the algorithm's status) — the user
3986        // sees the right ApplicationReturnStatus regardless.
3987        let _ = finalize_via_sqp(
3988            &nlp_rc,
3989            &res,
3990            solver_status,
3991            &tnlp,
3992            &self.last_finalize,
3993            self.reports_fixed_var_duals(),
3994        );
3995
3996        // Honor the opt-in status-fidelity gate on the SQP path too
3997        // (pounce#173), then emit the end-of-run summary with the final
3998        // (possibly downgraded) status so the console matches the returned
3999        // ApplicationReturnStatus.
4000        let final_status = self.apply_kkt_fidelity_gate(app_status);
4001        self.emit_end_summary(final_status, &nlp_rc, console_output);
4002        final_status
4003    }
4004
4005    /// Opt-in status-fidelity gate (pounce#173), shared by the IPM and
4006    /// SQP solve paths. When the user sets a positive `kkt_fidelity_tol`,
4007    /// a reported `Solve_Succeeded` whose max-norm UNSCALED KKT error
4008    /// (`SolveStatistics::final_unscaled_kkt_error`) exceeds it is
4009    /// downgraded to `Solved_To_Acceptable_Level` — the honest "this is a
4010    /// point, but not converged to the requested fidelity" status. This
4011    /// catches the ill-conditioned / nlp_scaling-deflated case where the
4012    /// scaled convergence test passes but the user-space duals have
4013    /// drifted. It is a pure relabel at termination (no extra iterations);
4014    /// unset or non-positive (the default) is a strict no-op, so every
4015    /// existing caller keeps the Ipopt-faithful status.
4016    fn apply_kkt_fidelity_gate(
4017        &self,
4018        app_status: ApplicationReturnStatus,
4019    ) -> ApplicationReturnStatus {
4020        if !matches!(app_status, ApplicationReturnStatus::SolveSucceeded) {
4021            return app_status;
4022        }
4023        if let Ok((ftol, true)) = self.options.get_numeric_value("kkt_fidelity_tol", "") {
4024            if ftol > 0.0 {
4025                let unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
4026                if unscaled_kkt > ftol {
4027                    tracing::info!(target: "pounce::diagnostics",
4028                        "kkt_fidelity_tol={ftol:.3e}: unscaled KKT error {unscaled_kkt:.3e} \
4029                         exceeds it — downgrading Solve_Succeeded → \
4030                         Solved_To_Acceptable_Level (pounce#173)");
4031                    return ApplicationReturnStatus::SolvedToAcceptableLevel;
4032                }
4033            }
4034        }
4035        app_status
4036    }
4037
4038    /// `nlp_lower_bound_inf` — the magnitude at or below which a bound is
4039    /// treated as absent.
4040    fn nlp_lower_bound_inf(&self) -> Number {
4041        self.options
4042            .get_numeric_value("nlp_lower_bound_inf", "")
4043            .ok()
4044            .and_then(|(v, f)| f.then_some(v))
4045            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF)
4046    }
4047
4048    /// `nlp_upper_bound_inf` — the magnitude at or above which a bound is
4049    /// treated as absent.
4050    fn nlp_upper_bound_inf(&self) -> Number {
4051        self.options
4052            .get_numeric_value("nlp_upper_bound_inf", "")
4053            .ok()
4054            .and_then(|(v, f)| f.then_some(v))
4055            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF)
4056    }
4057
4058    /// The user's convergence tolerance `tol`.
4059    fn user_tol(&self) -> Number {
4060        self.options
4061            .get_numeric_value("tol", "")
4062            .ok()
4063            .and_then(|(v, f)| f.then_some(v))
4064            .unwrap_or(1e-8)
4065    }
4066
4067    /// The user's `acceptable_tol` — the standard behind
4068    /// `Solved_To_Acceptable_Level`.
4069    fn user_acceptable_tol(&self) -> Number {
4070        self.options
4071            .get_numeric_value("acceptable_tol", "")
4072            .ok()
4073            .and_then(|(v, f)| f.then_some(v))
4074            .unwrap_or(1e-6)
4075    }
4076
4077    /// The user's `constr_viol_tol` — the **absolute** feasibility standard
4078    /// the strict gate's primal component judges by
4079    /// (`OptErrorConvCheck::primal_component_passes`).
4080    fn user_constr_viol_tol(&self) -> Number {
4081        self.options
4082            .get_numeric_value("constr_viol_tol", "")
4083            .ok()
4084            .and_then(|(v, f)| f.then_some(v))
4085            .unwrap_or(1e-4)
4086    }
4087
4088    /// The user's `acceptable_constr_viol_tol` — the same standard at the
4089    /// acceptable tier.
4090    fn user_acceptable_constr_viol_tol(&self) -> Number {
4091        self.options
4092            .get_numeric_value("acceptable_constr_viol_tol", "")
4093            .ok()
4094            .and_then(|(v, f)| f.then_some(v))
4095            .unwrap_or(1e-2)
4096    }
4097
4098    /// `primal_noise_floor_kappa` — the safety factor on the per-row
4099    /// floating-point noise floor (gh#528/gh#590). `0` opts out.
4100    fn user_primal_noise_floor_kappa(&self) -> Number {
4101        self.options
4102            .get_numeric_value("primal_noise_floor_kappa", "")
4103            .ok()
4104            .and_then(|(v, f)| f.then_some(v))
4105            .unwrap_or(64.0)
4106    }
4107
4108    /// Emit the Ipopt-style problem-statistics block (#206) from the
4109    /// engine's own reduced problem, gated on `console_output`
4110    /// (print_level >= 1). Shared by the IPM (`optimize_tnlp`) and SQP
4111    /// (`optimize_sqp_tnlp`) entry points so every algorithm and every
4112    /// frontend (CLI, Python, C) gets the identical block. Built from the
4113    /// same `collect_stats` inputs the CLI used, so the output is
4114    /// byte-identical to the historical CLI block.
4115    fn emit_problem_stats(&self, tnlp: &Rc<RefCell<dyn TNLP>>, console_output: bool) {
4116        if !console_output {
4117            return;
4118        }
4119        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
4120        if let Some(stats) =
4121            pounce_solve_report::console::collect_stats(tnlp, lo_inf, up_inf, fixed_treatment)
4122        {
4123            // A retry re-enters here with the same problem. Reprinting the
4124            // block verbatim is what made a retried run look like it had
4125            // printed its whole report twice for no reason, so say what is
4126            // actually happening instead: a new attempt on an unchanged
4127            // problem. One line, in place of seventeen that carry no
4128            // information the reader does not already have.
4129            //
4130            // The attempt is announced rather than merely suppressed because
4131            // the iteration table below it restarts at iteration 0 either way.
4132            // Silence would leave that table appearing from nowhere — trading
4133            // a confusing duplicate for a confusing gap.
4134            let mut memo = self.last_printed_problem_stats.borrow_mut();
4135            if memo.as_ref() == Some(&stats) {
4136                // Silent under an outside retry driver, which narrates its own
4137                // attempts in more detail than this line could ("pounce:
4138                // second opinion — re-solving with feral_scaling=mc64…").
4139                // Printing both would be two announcements of one event.
4140                if !self.in_retry_sequence.get() {
4141                    println!("Re-solving the same problem (a further attempt follows).");
4142                    println!();
4143                }
4144            } else {
4145                pounce_solve_report::console::print_problem_stats(&stats);
4146                *memo = Some(stats);
4147            }
4148        }
4149    }
4150
4151    /// Drain the NLP's per-eval counters into the shared `SolveStatistics`
4152    /// and emit the Ipopt-style end-of-run summary (#206). Shared by both
4153    /// solve paths. The counts are read from the NLP AFTER the solve (so the
4154    /// final solution evaluation is included, matching the historical count)
4155    /// and written into `SolveStatistics` so the post-solve API accessors
4156    /// (`info["n_obj_evals"]`, …) report them even when the console is
4157    /// silent. c/d (and jac_c/jac_d) are per-subsystem, so the max recovers
4158    /// the eval_g / eval_jac_g call count. The console summary itself is
4159    /// gated on `console_output` (print_level >= 1).
4160    fn emit_end_summary(
4161        &self,
4162        app_status: ApplicationReturnStatus,
4163        nlp: &Rc<RefCell<dyn IpoptNlp>>,
4164        console_output: bool,
4165    ) {
4166        {
4167            let ec = nlp.borrow().eval_counts();
4168            let mut stats = self.statistics.borrow_mut();
4169            stats.num_obj_evals = ec[0];
4170            stats.num_obj_grad_evals = ec[1];
4171            stats.num_constr_evals = ec[2].max(ec[3]);
4172            stats.num_constr_jac_evals = ec[4].max(ec[5]);
4173            stats.num_hess_evals = ec[6];
4174        }
4175        if !console_output {
4176            return;
4177        }
4178        let stats = self.statistics.borrow();
4179        let counts = pounce_solve_report::console::EvalCounts {
4180            n_obj: stats.num_obj_evals as u64,
4181            n_grad_f: stats.num_obj_grad_evals as u64,
4182            n_g: stats.num_constr_evals as u64,
4183            n_jac_g: stats.num_constr_jac_evals as u64,
4184            n_h: stats.num_hess_evals as u64,
4185        };
4186        // gh#987: no widening at `bound_relax_factor = 0`, so the console's
4187        // "before the bound_relax_factor widening" line has nothing to report.
4188        let widening_applied = self
4189            .options
4190            .get_numeric_value("bound_relax_factor", "")
4191            .map(|(v, _)| v > 0.0)
4192            .unwrap_or(true);
4193        pounce_solve_report::console::print_summary_with_widening(
4194            app_status,
4195            &stats,
4196            &counts,
4197            widening_applied,
4198        );
4199        // The verdict belongs to the run, not to the attempt. Held back while
4200        // any retry driver is managing attempts; that driver prints it once,
4201        // with the status it actually returns.
4202        if self.end_verdict_deferrals.get() == 0 {
4203            pounce_solve_report::console::print_exit_verdict(app_status);
4204        }
4205    }
4206
4207    /// Build a *copy* of the algorithm builder configured per the
4208    /// current options. The SQP path uses this so it gets a
4209    /// fresh builder without mutating the application's state.
4210    /// Read the `ipm_sqp_handover*` option family into a
4211    /// [`crate::handover::HandoverOptions`].
4212    fn handover_options(&self) -> crate::handover::HandoverOptions {
4213        let mut o = crate::handover::HandoverOptions::default();
4214        // `sqp_auto_handover` only fires when this option was not set.
4215        o.enabled = self.auto_handover.get();
4216        if let Ok((v, true)) = self.options.get_bool_value("ipm_sqp_handover", "") {
4217            o.enabled = v;
4218        }
4219        if let Ok((v, true)) = self.options.get_numeric_value("ipm_sqp_handover_tol", "") {
4220            o.tol = v;
4221        }
4222        if let Ok((v, true)) = self
4223            .options
4224            .get_integer_value("ipm_sqp_handover_stall_iter", "")
4225        {
4226            o.stall_iter = v.max(0);
4227        }
4228        if let Ok((v, true)) = self
4229            .options
4230            .get_integer_value("ipm_sqp_handover_max_attempts", "")
4231        {
4232            o.max_attempts = v.max(0) as u32;
4233        }
4234        o
4235    }
4236
4237    /// Install the interior-point → active-set handover hook on `alg` when
4238    /// `ipm_sqp_handover=yes` (gh#1054; see [`crate::handover`]). Returns
4239    /// the cells the hook reports into — the report, and the working set of
4240    /// an accepted attempt — for [`Self::finish_handover`] to read after the
4241    /// solve.
4242    #[allow(clippy::type_complexity)]
4243    fn install_handover(
4244        &self,
4245        alg: &mut IpoptAlgorithm,
4246        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4247    ) -> Option<(
4248        Rc<RefCell<crate::handover::HandoverReport>>,
4249        Rc<RefCell<Option<pounce_qp::WorkingSet>>>,
4250    )> {
4251        let hopts = self.handover_options();
4252        if !hopts.enabled {
4253            return None;
4254        }
4255        let mut trigger = crate::handover::HandoverTrigger::new(hopts);
4256        let xopts = crate::crossover::CrossoverOptions {
4257            enabled: true,
4258            ..self.crossover_options()
4259        };
4260        let snapshot = self.algorithm_builder_snapshot();
4261        let qp_opts = snapshot.sqp_qp.clone();
4262        let data = Rc::clone(&alg.data);
4263        let nlp = Rc::clone(nlp_handle);
4264        // One factory serves every backend the attempts build: a factory is
4265        // reusable, but `build_sqp_with_backend` takes one by value, so the
4266        // step-4 SQP gets a forwarding closure onto the shared one.
4267        let backend = Rc::new(RefCell::new(self.make_backend_factory()));
4268        let tols = self.user_tolerances();
4269        let report = Rc::new(RefCell::new(crate::handover::HandoverReport::default()));
4270        let working = Rc::new(RefCell::new(None));
4271        let (report_out, working_out) = (Rc::clone(&report), Rc::clone(&working));
4272        let (wall0, cpu0) = (
4273            pounce_common::utils::wallclock_time(),
4274            pounce_common::utils::cpu_time(),
4275        );
4276        alg.handover = Some(Box::new(move |curr, iter, err, mu| {
4277            if !trigger.should_try(iter, err) {
4278                return None;
4279            }
4280            let seed = crossover_seed(&nlp, curr);
4281            let x = crate::crossover::CrossoverOptions {
4282                primal_tol: crate::handover::identification_primal_tol(xopts.primal_tol, mu),
4283                ..xopts.clone()
4284            };
4285            // An attempt may spend at most what the interior method has
4286            // spent so far (floor 1 s), and never past the solve's own
4287            // budget. Without a cap a declined attempt is unbounded: on
4288            // `deb7` (813 variables) one ran the crossover fallback for
4289            // minutes, against a 114-iteration interior solve. With it, a
4290            // declined attempt costs at most a doubling — the right scale
4291            // for a bet on shortening the tail.
4292            let (wall_left, cpu_left) = data
4293                .borrow()
4294                .deadline
4295                .as_ref()
4296                .map_or((Number::INFINITY, Number::INFINITY), |d| {
4297                    (d.remaining_wall(), d.remaining_cpu())
4298                });
4299            let spent_wall = (pounce_common::utils::wallclock_time() - wall0).max(1.0);
4300            let spent_cpu = (pounce_common::utils::cpu_time() - cpu0).max(1.0);
4301            let sqp_opts = crate::sqp::SqpOptions {
4302                deadline: Some(pounce_common::timing::Deadline::new(
4303                    spent_wall.min(wall_left),
4304                    spent_cpu.min(cpu_left),
4305                )),
4306                ..snapshot.sqp.clone()
4307            };
4308            // Declared bounds, for the reason `maybe_crossover` gives.
4309            let mut adapter =
4310                crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(&nlp));
4311            let (mut rep, mut accepted) = crate::crossover::run(
4312                &mut adapter,
4313                &seed,
4314                &x,
4315                &sqp_opts,
4316                &qp_opts,
4317                || (backend.borrow_mut())(crate::alg_builder::LinearSolverChoice::Feral),
4318                |step4_opts| {
4319                    let mut b = snapshot.clone();
4320                    b.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
4321                    b.sqp = step4_opts;
4322                    let shared = Rc::clone(&backend);
4323                    b.build_sqp_with_backend(Box::new(move |c| (shared.borrow_mut())(c)))
4324                },
4325            );
4326            // The interior-point verdict this replaces is issued in user
4327            // units on the declared model; so is this one.
4328            if let Some(res) = &accepted
4329                && !meets_user_tolerances(&nlp, res, &rep, &tols)
4330            {
4331                rep = rep.decline(crate::crossover::CrossoverDecline::UserTolerances);
4332                accepted = None;
4333            }
4334            tracing::info!(
4335                target: "pounce::handover",
4336                "IPM→SQP handover attempt {} at iteration {iter} (error {err:.2e}, mu {mu:.2e}): {}",
4337                trigger.attempts(),
4338                if rep.accepted() { "accepted" } else { "declined" }
4339            );
4340            tracing::debug!(target: "pounce::handover", "handover: {rep:?}");
4341            let mut r = report.borrow_mut();
4342            r.attempts = trigger.attempts();
4343            r.last = Some(rep);
4344            let res = accepted?;
4345            let next = crossover_iterate(&nlp, curr, &res)?;
4346            r.accepted_at_iter = Some(iter);
4347            *working.borrow_mut() = res.working_set;
4348            Some(next)
4349        }));
4350        Some((report_out, working_out))
4351    }
4352
4353    /// After the solve: publish the handover report, and an accepted
4354    /// attempt's working set as the next SQP solve's warm start (the same
4355    /// hand-off crossover makes).
4356    fn finish_handover(
4357        &mut self,
4358        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4359        cells: Option<(
4360            Rc<RefCell<crate::handover::HandoverReport>>,
4361            Rc<RefCell<Option<pounce_qp::WorkingSet>>>,
4362        )>,
4363    ) {
4364        self.handover_report = None;
4365        let Some((report, working)) = cells else {
4366            return;
4367        };
4368        let report = report.borrow().clone();
4369        if report.accepted_at_iter.is_some()
4370            && let Some(ws) = working.borrow_mut().take()
4371        {
4372            self.sqp_last_working_set = Some(self.working_set_to_user(&*nlp_handle.borrow(), ws));
4373        }
4374        self.handover_report = Some(report);
4375    }
4376
4377    /// The interior-point arm's user-unit tolerances, which a crossed-over
4378    /// point must also meet (see [`meets_user_tolerances`]).
4379    fn user_tolerances(&self) -> UserTolerances {
4380        let read = |name: &str, default: Number| {
4381            self.options
4382                .get_numeric_value(name, "")
4383                .map_or(default, |(v, _)| v)
4384        };
4385        UserTolerances {
4386            constr_viol: read("constr_viol_tol", 1e-4),
4387            dual_inf: read("dual_inf_tol", 1.0),
4388            compl_inf: read("compl_inf_tol", 1e-4),
4389        }
4390    }
4391
4392    /// A [`pounce_common::timing::Deadline`] for `max_wall_time` /
4393    /// `max_cpu_time`, starting now.
4394    fn solve_deadline(&self) -> pounce_common::timing::Deadline {
4395        let read = |name: &str| {
4396            self.options
4397                .get_numeric_value(name, "")
4398                .map_or(1e6, |(v, _)| v)
4399        };
4400        pounce_common::timing::Deadline::new(read("max_wall_time"), read("max_cpu_time"))
4401    }
4402
4403    /// Read the `crossover*` option family into a [`CrossoverOptions`].
4404    fn crossover_options(&self) -> crate::crossover::CrossoverOptions {
4405        let mut o = crate::crossover::CrossoverOptions::default();
4406        if let Ok((v, true)) = self.options.get_bool_value("crossover", "") {
4407            o.enabled = v;
4408        }
4409        if let Ok((v, true)) = self.options.get_integer_value("crossover_max_iter", "") {
4410            o.max_iter = v.max(0) as u32;
4411        }
4412        if let Ok((v, true)) = self.options.get_numeric_value("crossover_mult_tol", "") {
4413            o.mult_tol = v;
4414        }
4415        if let Ok((v, true)) = self.options.get_numeric_value("crossover_primal_tol", "") {
4416            o.primal_tol = v;
4417        }
4418        o
4419    }
4420
4421    /// Post-convergence crossover (gh#612): hand the converged interior
4422    /// iterate to the active-set path so the solve ends on an exact active
4423    /// set. See [`crate::crossover`] for the algorithm.
4424    ///
4425    /// On acceptance this **replaces `data.curr`** rather than reporting
4426    /// alongside it. Everything downstream — the residual drain, the KKT
4427    /// fidelity gate, `on_converged`, `finalize_via_orig_nlp`, the end
4428    /// summary — already reads that one iterate, so replacing it is what
4429    /// makes the crossed-over point the solution instead of an annotation on
4430    /// it, and it does so without a second copy of the unscaling path.
4431    ///
4432    /// A no-op unless `crossover=yes` and the solve converged: an
4433    /// unconverged interior point is not a KKT point, so there is no active
4434    /// set at it worth identifying.
4435    fn maybe_crossover(
4436        &mut self,
4437        alg: &mut IpoptAlgorithm,
4438        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4439        solver_status: SolverReturn,
4440    ) {
4441        self.crossover_report = None;
4442        // Cleared on every entry, alongside the report, so the flag
4443        // describes this solve and not a previous one — the same reason
4444        // `crossover_report` is reset here rather than only written on
4445        // the accept path.
4446        //
4447        // Except when the in-solve handover installed the iterate (gh#1054):
4448        // then the flag was set during *this* solve and is still true of the
4449        // point in `curr` — clearing it here mislabelled the handover's
4450        // declared-frame point as an interior one, and its complementarity
4451        // was reported in the relaxed frame (`0.1` on `jit1`).
4452        let handover_point = self
4453            .handover_report
4454            .as_ref()
4455            .is_some_and(|h| h.accepted_at_iter.is_some());
4456        if !handover_point {
4457            alg.data.borrow_mut().curr_from_crossover = false;
4458        }
4459        let xopts = self.crossover_options();
4460        if !xopts.enabled {
4461            return;
4462        }
4463        if !matches!(
4464            solver_status,
4465            SolverReturn::Success | SolverReturn::StopAtAcceptablePoint
4466        ) {
4467            return;
4468        }
4469        let Some(curr) = alg.data.borrow().curr.clone() else {
4470            return;
4471        };
4472
4473        let seed = crossover_seed(nlp_handle, &curr);
4474
4475        let snapshot = self.algorithm_builder_snapshot();
4476        let mut sqp_opts = snapshot.sqp.clone();
4477        // The interior-point phase's own deadline, not a fresh one:
4478        // crossover is part of the same solve, so it spends what the IPM
4479        // left of `max_wall_time` / `max_cpu_time` (gh#1054). Before this it
4480        // had no budget at all and could outlive the solve's by any amount.
4481        sqp_opts.deadline = alg
4482            .data
4483            .borrow()
4484            .deadline
4485            .clone()
4486            .or_else(|| Some(self.solve_deadline()));
4487        let qp_opts = snapshot.sqp_qp.clone();
4488        // Declared bounds, not the live relaxed ones: crossover's whole claim
4489        // is that the returned point sits *on* the constraints the user
4490        // wrote. Against the `bound_relax_factor`-widened box it would pivot
4491        // to a point `1e-8` shy of every one of them and then correctly
4492        // report an empty active set.
4493        let mut adapter =
4494            crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(nlp_handle));
4495        let (report, accepted) = crate::crossover::run(
4496            &mut adapter,
4497            &seed,
4498            &xopts,
4499            &sqp_opts,
4500            &qp_opts,
4501            || {
4502                let mut f = self.make_backend_factory();
4503                // `make_backend_factory` ships the workspace-default
4504                // backend regardless of the choice passed, exactly as the
4505                // SQP path's `build_sqp_with_backend` call does; naming
4506                // `Feral` here keeps that visible rather than implicit.
4507                f(crate::alg_builder::LinearSolverChoice::Feral)
4508            },
4509            |step4_opts| {
4510                let mut b = self.algorithm_builder_snapshot();
4511                b.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
4512                b.sqp = step4_opts;
4513                b.build_sqp_with_backend(self.make_backend_factory())
4514            },
4515        );
4516
4517        let tols = self.user_tolerances();
4518        let (report, accepted) = match accepted {
4519            Some(res) if !meets_user_tolerances(nlp_handle, &res, &report, &tols) => (
4520                report.decline(crate::crossover::CrossoverDecline::UserTolerances),
4521                None,
4522            ),
4523            other => (report, other),
4524        };
4525        if let Some(res) = accepted {
4526            self.install_crossover_iterate(alg, nlp_handle, &curr, &res);
4527            // Publish the identified set as the SQP warm-start output. This
4528            // is the IPM → SQP handoff the active-set path never had: a
4529            // sequence whose first solve wants the interior method can now
4530            // feed the next `algorithm=active-set-sqp` solve a working set.
4531            self.sqp_last_working_set = res
4532                .working_set
4533                .clone()
4534                .map(|ws| self.working_set_to_user(&*nlp_handle.borrow(), ws));
4535        }
4536        tracing::debug!(target: "pounce::crossover", "crossover: {report:?}");
4537        self.crossover_report = Some(report);
4538    }
4539
4540    /// Write an accepted crossover result back onto the IPM iterate (built by
4541    /// [`crossover_iterate`]).
4542    fn install_crossover_iterate(
4543        &self,
4544        alg: &mut IpoptAlgorithm,
4545        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4546        curr: &crate::iterates_vector::IteratesVector,
4547        res: &crate::sqp::SqpResult,
4548    ) {
4549        let Some(out) = crossover_iterate(nlp_handle, curr, res) else {
4550            return;
4551        };
4552        let mut d = alg.data.borrow_mut();
4553        d.set_curr(out);
4554        // Mark which frame the installed iterate belongs to. It sits on the
4555        // *declared* bounds, and every barrier quantity built off `curr` —
4556        // slacks, and through them `Σ = z/s` — is measured against the
4557        // `bound_relax_factor`-widened ones, so a consumer that wants the
4558        // point's own geometry rather than the barrier's has to know this
4559        // happened (gh#654). Set only on the path that actually replaced
4560        // `curr`: a declined or abandoned crossover leaves the interior
4561        // iterate, which is an interior-frame point.
4562        d.curr_from_crossover = true;
4563    }
4564
4565    fn algorithm_builder_snapshot(&self) -> AlgorithmBuilder {
4566        let mut builder = AlgorithmBuilder {
4567            quality_escalation_counter: Some(Rc::clone(&self.quality_escalations)),
4568            ..AlgorithmBuilder::default()
4569        };
4570        apply_sqp_options(&self.options, &mut builder.sqp);
4571        apply_qp_subproblem_options(&self.options, &mut builder.sqp_qp);
4572        builder
4573    }
4574
4575    /// Refuse an explicitly set `ma57_pivtolmax` that sits below
4576    /// `ma57_pivtol`, at either option prefix.
4577    ///
4578    /// Upstream's `Ma57TSolverInterface::InitializeImpl` asserts
4579    /// `pivtolmax >= pivtol` and raises `OPTION_INVALID`, but only when
4580    /// the user set `ma57_pivtolmax` explicitly; left unset, the
4581    /// registered default is lifted to `ma57_pivtol` instead. Both
4582    /// halves are mirrored — the lifting in
4583    /// `pounce_hsl::ma57::Options::from_options_list`, the refusal here.
4584    ///
4585    /// Checked at **both** prefixes because the restoration sub-IPM
4586    /// configures its own MA57 backend from `"resto."`-scoped options
4587    /// (gh#825), so `resto.ma57_pivtolmax` can contradict
4588    /// `resto.ma57_pivtol` without the un-prefixed pair being wrong.
4589    ///
4590    /// Deliberately **not** gated on the `ma57` cargo feature or on
4591    /// `linear_solver` resolving to MA57. It is a consistency check on
4592    /// two numbers the user wrote, needs no HSL to perform, and a
4593    /// verdict that changed with a build flag would be worse than a
4594    /// consistent one — it would also be untestable in CI, which cannot
4595    /// link CoinHSL. Only an *explicitly set* `ma57_pivtolmax` can
4596    /// trigger it, so an options file that never mentions the option is
4597    /// unaffected.
4598    fn ma57_pivtol_bracket_refusal(&self) -> Option<String> {
4599        for prefix in ["", "resto."] {
4600            // `(_, true)` is the explicitly-set arm; an unset option
4601            // reports the registry default with `false` and is the
4602            // branch upstream lifts rather than refuses.
4603            let Ok((pivtolmax, true)) = self.options.get_numeric_value("ma57_pivtolmax", prefix)
4604            else {
4605                continue;
4606            };
4607            let pivtol = self
4608                .options
4609                .get_numeric_value("ma57_pivtol", prefix)
4610                .map(|(v, _)| v)
4611                .unwrap_or(1e-8);
4612            if pivtolmax < pivtol {
4613                return Some(format!(
4614                    "pounce: {prefix}ma57_pivtolmax ({pivtolmax:e}) is below \
4615                     {prefix}ma57_pivtol ({pivtol:e}). ma57_pivtolmax is the ceiling MA57 \
4616                     may raise the pivot tolerance to when it escalates for accuracy, so it \
4617                     cannot sit below the tolerance it starts from. Raise \
4618                     {prefix}ma57_pivtolmax to at least {pivtol:e}, or lower \
4619                     {prefix}ma57_pivtol."
4620                ));
4621            }
4622        }
4623        None
4624    }
4625
4626    /// Build a linear-solver factory from the application's current options,
4627    /// for the paths that do not go through `optimize_constrained`'s own
4628    /// factory plumbing — the active-set SQP driver and the post-convergence
4629    /// crossover.
4630    ///
4631    /// This used to ignore its `choice` argument and return
4632    /// `FeralSolverInterface::new()`: a default-configured FERAL, whatever the
4633    /// caller asked for. Three things were silently dropped on every SQP
4634    /// solve. `linear_solver=ma57` ran FERAL while the banner said
4635    /// `MA57 (HSL)`, so an MA57-vs-FERAL comparison on this path measured
4636    /// nothing — the same defect as gh#825, one path over. Every `feral_*`
4637    /// option (`feral_refine`, `feral_ordering`, `feral_scaling`,
4638    /// `feral_increase_quality`, …) was accepted and discarded. And
4639    /// `set_external_ordering` — whose whole purpose is to inject an ordering
4640    /// a generic algorithm cannot derive — reached the IPM and not this arm.
4641    ///
4642    /// Reads the same two snapshots and calls the same constructor the IPM
4643    /// path does, so there is one answer to "what does `linear_solver` mean"
4644    /// rather than one per algorithm.
4645    fn make_backend_factory(&self) -> LinearBackendFactory {
4646        // `RefineCarveOut::None`: this arm does not refine the unreduced system
4647        // itself, so the backend loop is the only refinement in the stack and
4648        // the interior-point carve-out's premise is false here. See
4649        // `feral_config_from_options_scoped` for the measurement.
4650        let mut feral_cfg = feral_config_from_options_scoped(&self.options, RefineCarveOut::None);
4651        // Same override, and for the same reason, as the IPM path: the
4652        // external permutation carries a vector, which no string option can
4653        // express, so it arrives through the side-channel field instead.
4654        if let Some(perm) = &self.external_ordering {
4655            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
4656        }
4657        let ma57_cfg = ma57_config_from_options(&self.options, "");
4658        default_backend_factory_with_sink(
4659            feral_cfg,
4660            ma57_cfg,
4661            Arc::clone(&self.linsol_summary_sink),
4662        )
4663    }
4664
4665    /// Phase 3.5 auto-fallback driver.
4666    ///
4667    /// Runs the standard solve (no wrapper) first. If it ends in a
4668    /// trigger-class status (`Restoration_Failed`, `Infeasible_Problem_Detected`,
4669    /// `Solved_To_Acceptable_Level`, `Maximum_Iterations_Exceeded`, or
4670    /// `Not_Enough_Degrees_Of_Freedom`), retries transparently with
4671    /// the ℓ₁ wrapper enabled. Promotes the retry's status only if
4672    /// it returns `Solve_Succeeded`; otherwise returns the original
4673    /// status.
4674    ///
4675    /// Caveat: the user TNLP's `finalize_solution` runs once per
4676    /// attempt. When the retry doesn't promote, the user's captured
4677    /// fields hold the retry's iterate (the ℓ₁-best least-infeasible
4678    /// point) even though the returned status is the original's.
4679    /// Documented on the option's help text; tightening this is a
4680    /// Phase-4 follow-up.
4681    fn run_with_l1_fallback(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
4682        // First attempt: the standard IPM solve, no ℓ₁ wrapper. Only
4683        // reached for `m > 0`, so `optimize_constrained` is exact.
4684        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4685        if !is_l1_fallback_trigger(first_status) {
4686            return first_status;
4687        }
4688        // gh#987 item 6: the plain attempt's iterations are part of what this
4689        // call spent, and the retry's `optimize_constrained` resets them.
4690        let first_attempt = self.statistics.borrow().clone();
4691        // Trigger fired. Flip the wrapper option for the retry and
4692        // restore it after — keeps the user's option-table view of the
4693        // session exactly as they left it.
4694        let prev = self
4695            .options
4696            .get_string_value("l1_exact_penalty_barrier", "")
4697            .ok();
4698        let _ = self
4699            .options
4700            .set_string_value("l1_exact_penalty_barrier", "yes", true, false);
4701        let retry_status = self
4702            .run_l1_penalty_outer_loop(Rc::clone(&tnlp))
4703            .unwrap_or(ApplicationReturnStatus::InternalError);
4704        let _ = self.options.set_string_value(
4705            "l1_exact_penalty_barrier",
4706            prev.as_ref().map(|(v, _)| v.as_str()).unwrap_or("no"),
4707            true,
4708            false,
4709        );
4710        // Fold the plain attempt in ahead of the retry's passes. A retry that
4711        // never ran a pass (wrapper construction declined) leaves the plain
4712        // attempt's own statistics standing untouched.
4713        {
4714            let mut st = self.statistics.borrow_mut();
4715            if !st.passes.is_empty() {
4716                let mut head = MultiPassTotals::default();
4717                head.push_pass(&first_attempt, None, first_status);
4718                let shift = head.rows.len();
4719                let mut passes = head.passes;
4720                passes.extend(st.passes.iter().cloned().map(|mut p| {
4721                    p.first_row += shift;
4722                    p
4723                }));
4724                let mut rows = head.rows;
4725                rows.append(&mut st.iterations);
4726                st.iterations = rows;
4727                st.iteration_count += first_attempt.iteration_count;
4728                st.num_obj_evals += first_attempt.num_obj_evals;
4729                st.num_constr_evals += first_attempt.num_constr_evals;
4730                st.num_obj_grad_evals += first_attempt.num_obj_grad_evals;
4731                st.num_constr_jac_evals += first_attempt.num_constr_jac_evals;
4732                st.num_hess_evals += first_attempt.num_hess_evals;
4733                st.restoration_calls += first_attempt.restoration_calls;
4734                st.restoration_inner_iters += first_attempt.restoration_inner_iters;
4735                st.restoration_outer_iters += first_attempt.restoration_outer_iters;
4736                st.passes = passes;
4737            }
4738        }
4739        if matches!(retry_status, ApplicationReturnStatus::SolveSucceeded) {
4740            retry_status
4741        } else {
4742            first_status
4743        }
4744    }
4745
4746    /// μ-strategy auto-fallback driver (pounce#138).
4747    ///
4748    /// Runs the standard solve first. If it stalls short of optimal in a
4749    /// way a μ-strategy flip can plausibly fix — `Solved_To_Acceptable_Level`
4750    /// or `Maximum_Iterations_Exceeded`, the two signatures seen on the
4751    /// princetonlib instances where the dual infeasibility parks above
4752    /// `tol` while constraint violation and complementarity are already
4753    /// deeply converged — it flips `mu_strategy` (adaptive↔monotone) and
4754    /// solves once more. The retry's status is promoted only if it returns
4755    /// `Solve_Succeeded`; otherwise the original status is returned.
4756    ///
4757    /// (maxcut/price stall at acceptable-level under adaptive; fermat2_vareps
4758    /// stalls at `max_iter` — hence both triggers. flosp2tm is μ-independent
4759    /// and correctly does not promote.)
4760    ///
4761    /// The flip direction is taken from the strategy the option table
4762    /// actually resolves to (`effective_mu_strategy_is_adaptive`):
4763    /// `adaptive` → `monotone`, otherwise → `adaptive`. Absence is not
4764    /// the same as `monotone` — under a limited-memory Hessian an unset
4765    /// `mu_strategy` resolves to `adaptive` (gh#746), and flipping the
4766    /// *registered* default there would re-run the strategy that just
4767    /// stalled. The option table is restored to the resolved view
4768    /// afterward.
4769    ///
4770    /// Caveat (shared with the ℓ₁ fallback): the user TNLP's
4771    /// `finalize_solution` runs once per attempt, so when the retry
4772    /// doesn't promote the captured fields hold the retry's iterate.
4773    fn run_with_mu_strategy_fallback(
4774        &mut self,
4775        tnlp: Rc<RefCell<dyn TNLP>>,
4776    ) -> ApplicationReturnStatus {
4777        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4778        // Which statuses are worth a second solve depends on who asked
4779        // for the retry (pounce#748).
4780        //
4781        // An explicit `mu_strategy_fallback=yes` keeps the historical
4782        // pair: the caller opted in and can afford the second solve.
4783        //
4784        // The *default*-on retry takes `Maximum_Iterations_Exceeded`
4785        // unconditionally, and `Solved_To_Acceptable_Level` only when
4786        // the caller left the convergence configuration alone
4787        // (gh #757). pounce#748 refused the latter status outright, for
4788        // three reasons; two of them are properties of a *caller-
4789        // modified* configuration, not of the status. It launders
4790        // downgrades the caller induced deliberately -- a tight
4791        // `kkt_fidelity_tol`, a certificate veto, `least_square_init_
4792        // primal` -- so the signal the option exists to produce never
4793        // reaches them. And because the retry returns the other run's
4794        // *point*, not just its status, it can hand back a different
4795        // local solution: on `autocorr_bern55-06` with the
4796        // dual-divergence guard on it swaps -2304.0000278 for
4797        // -2320.0000298 (crates/pounce-cli/tests/
4798        // issue_250_dual_guard_never_worse.rs). Both cases -- and all
4799        // five test targets the wide trigger broke -- arm a
4800        // non-default option from `TERMINATION_POLICY_OPTIONS`, so
4801        // deferring to that set preserves every one of them while
4802        // leaving a stock-options stall retryable. The third reason,
4803        // cost, stands and is the price: one extra solve on a run that
4804        // reached only the acceptable tolerance, paid to try for the
4805        // certificate. `cho_parmest` is the motivating case -- monotone
4806        // parks `inf_du` on a ~1e-6 evaluation-noise floor and misses
4807        // `tol` by 5%, taking six null steps of 1e-12 at `mu_min`,
4808        // while adaptive certifies it in 20 iterations.
4809        //
4810        // `dirichlet120`, the case that motivated turning the retry on,
4811        // stalls at `Maximum_Iterations_Exceeded`, so it is recovered
4812        // either way.
4813        let retry_worthy = match first_status {
4814            ApplicationReturnStatus::MaximumIterationsExceeded => true,
4815            ApplicationReturnStatus::SolvedToAcceptableLevel => {
4816                self.mu_strategy_fallback_was_set() || !self.caller_set_termination_policy()
4817            }
4818            _ => false,
4819        };
4820        if !retry_worthy {
4821            return first_status;
4822        }
4823        // gh#857: decline the flip when the solve that just failed escalated
4824        // the factorization and an escalation-off re-solve is enabled.
4825        //
4826        // The mu flip is a *blind* second opinion: it changes the barrier
4827        // schedule and hopes. A `feral_increase_quality` escalation is a
4828        // *measured* fact about the run that just failed -- FERAL reroutes
4829        // which pivots are taken and never steps back down, so every
4830        // iteration after the first escalation, restoration sub-solves
4831        // included, ran on a trajectory the defaults do not describe. Flipping
4832        // `mu_strategy` while leaving that in place is not a controlled
4833        // experiment: it varies the knob that is not implicated and holds the
4834        // one that is.
4835        //
4836        // It is not free either. On `square_flowsheet_resto`'s lbfgs leg the
4837        // flip escalates 25 times all over again, burns a second full
4838        // 3000-iteration budget, and ends no better than the first -- after
4839        // which rung 4 of the second-opinion ladder converges the model in 178
4840        // with the escalation off. That is 6178 real iterations to reach an
4841        // answer that 3178 reach without the flip, and the flip contributes
4842        // nothing to it. Measured both ways: `mu_strategy=adaptive` alone
4843        // still gives 3000 with 25 escalations, and `feral_increase_quality=no`
4844        // gives 178 under *either* mu strategy.
4845        //
4846        // Why decline rather than fold the escalation off into this retry: the
4847        // backend factory is minted from an options snapshot taken by the
4848        // caller *before* `solve()`, so writing `feral_increase_quality` here
4849        // is too late to reach the retry's linear solver. `mu_strategy` is read
4850        // per-solve from the option table and is not; that asymmetry is why
4851        // this layer can only choose whether to spend the solve, not what to
4852        // spend it on.
4853        //
4854        // Restricted to `Maximum_Iterations_Exceeded`, which is exactly the
4855        // status rung 4 opens on. A `Solved_To_Acceptable_Level` exit opens no
4856        // escalation rung, so declining there would drop a retry with nothing
4857        // in its place. Gated on `feral_increase_quality_retry`, so setting
4858        // that option to `no` restores the historical behaviour on both sides
4859        // at once: no rung 4, and no decline here.
4860        //
4861        // The one place the stand-down is not paired with the rung is the
4862        // multi-start paths (`solve_nlp_batch`, the CLI's `minima` search),
4863        // which deliberately do not drive the ladder -- a failed start there is
4864        // routine and extra solves per start multiply. Those paths lose the
4865        // flip on an escalating budget exit and gain nothing back, which is the
4866        // one behaviour change here that is not a strict improvement. It is the
4867        // same trade they already take on every other rung, and for the same
4868        // reason: an escalating capped start is one of many, and doubling its
4869        // cost to re-run the trajectory the escalation governs is the worse end
4870        // of it.
4871        if matches!(
4872            first_status,
4873            ApplicationReturnStatus::MaximumIterationsExceeded
4874        ) && self.quality_escalations.get() >= 1
4875            && self
4876                .options
4877                .get_bool_value("feral_increase_quality_retry", "")
4878                .map(|(v, _found)| v)
4879                .unwrap_or(true)
4880            && self
4881                .options
4882                .get_bool_value("feral_increase_quality", "")
4883                .map(|(v, _found)| v)
4884                .unwrap_or(true)
4885        {
4886            return first_status;
4887        }
4888        // Flip the strategy for one retry. The parser maps "adaptive" →
4889        // Adaptive and every other value (incl. unset) → Monotone, so the
4890        // opposite of an explicit "adaptive" is "monotone" and the
4891        // opposite of anything else is "adaptive".
4892        let prev = self.options.get_string_value("mu_strategy", "").ok();
4893        let was_adaptive = self.effective_mu_strategy_is_adaptive();
4894        let flipped = if was_adaptive { "monotone" } else { "adaptive" };
4895        // Unwind cover only: the normal-path restore below writes the
4896        // resolved value back as caller-set, deliberately, and the scope must
4897        // not change that. A panic in the retry used to leave the flipped
4898        // strategy in the option table of an application `ffi_guard` keeps.
4899        let mut scope = RetryOptionScope::enter(self, &["mu_strategy"], true);
4900        let _ = scope
4901            .options
4902            .set_string_value("mu_strategy", flipped, true, false);
4903        // Floor the *answer*, not just the status (pounce#870).
4904        //
4905        // The promote-only-on-`Solve_Succeeded` rule below has always floored
4906        // the status. It did not floor the point, and the point is what the
4907        // caller consumes: `optimize_constrained` calls the user TNLP's
4908        // `finalize_solution` once per attempt, so a retry that fails to
4909        // promote still overwrites the answer with its own iterate, and the
4910        // statistics with its own residuals. The result is a status describing
4911        // one attempt attached to a point from another.
4912        //
4913        // Measured on a random corpus of 1200 nonconvex models, 20 of them
4914        // (1.7%) returned a materially worse point under an unchanged status,
4915        // the worst flipping sign: a `Maximum_Iterations_Exceeded` exit went
4916        // from -2.38e7 to +7.89e7, and a `Solved_To_Acceptable_Level` one from
4917        // -3.83e7 to +3.41e5 while its reported `final_kkt_error` rose to
4918        // 2.85e-4 — 285x the `acceptable_tol` its own status names, so the
4919        // report contradicted itself. The known example on record understated
4920        // it by three orders: `autocorr_bern55-06` swapping -2304.0000278 for
4921        // -2320.0000298 is the same defect at 0.07%.
4922        //
4923        // This is the floor idiom the rest of the codebase already uses for a
4924        // bet it might lose — `honour_neg_curv_floor` (gh#797),
4925        // `honour_decline_floor` (gh#534), `honour_best_acceptable_after_dual_
4926        // guard` — applied to the one bet that was only half-floored.
4927        //
4928        // Not extended to `run_with_l1_fallback`, which carries the same
4929        // caveat in its doc comment but is NOT the same call: its retry
4930        // deliberately reports the l1-best least-infeasible point, which the
4931        // option help calls informative in its own right. Changing that needs
4932        // its own measurement.
4933        let solution_floor = scope.last_finalize.borrow().clone();
4934        let certificate_floor = SolutionCertificate::of(&scope.statistics.borrow());
4935        let trace_floor = *scope.last_iter_stats.borrow();
4936        // gh#1042 C1: the first attempt's verdict and cost, recorded before
4937        // the re-solve overwrites the statistics. A promoted re-solve reports
4938        // its own `iteration_count` and `restoration_calls` only, and without
4939        // this nothing says the first attempt got worse.
4940        let mut record = {
4941            let st = scope.statistics.borrow();
4942            pounce_nlp::MuStrategyFallbackRecord {
4943                base_status: first_status.upstream_name().to_string(),
4944                base_iteration_count: st.iteration_count,
4945                base_restoration_calls: st.restoration_calls,
4946                base_objective: st.final_objective,
4947                retry_mu_strategy: flipped.to_string(),
4948                ..Default::default()
4949            }
4950        };
4951        *scope.mu_strategy_fallback_record.borrow_mut() = Some(record.clone());
4952        let retry_status = scope.optimize_constrained(Rc::clone(&tnlp));
4953        record.retry_status = retry_status.upstream_name().to_string();
4954        record.retry_iteration_count = scope.statistics.borrow().iteration_count;
4955        record.promoted = matches!(retry_status, ApplicationReturnStatus::SolveSucceeded);
4956        *scope.mu_strategy_fallback_record.borrow_mut() = Some(record.clone());
4957        // Restore the user's original option-table view.
4958        let _ = scope.options.set_string_value(
4959            "mu_strategy",
4960            prev.as_ref()
4961                .filter(|(_, found)| *found)
4962                .map(|(v, _)| v.as_str())
4963                .unwrap_or(if was_adaptive { "adaptive" } else { "monotone" }),
4964            true,
4965            false,
4966        );
4967        drop(scope);
4968        self.statistics.borrow_mut().mu_strategy_fallback = Some(record);
4969        if matches!(retry_status, ApplicationReturnStatus::SolveSucceeded) {
4970            return retry_status;
4971        }
4972        // The bet lost. Put the first attempt's answer back, so the point and
4973        // the statistics describe the same solve the returned status does.
4974        //
4975        // `finalize_solution` therefore runs once more than the number of
4976        // attempts on this path. That is deliberate, and is the cheaper of the
4977        // two corrections: withholding the retry's `finalize_solution` until it
4978        // is known to promote would deprive a caller that watches the callback
4979        // of the retry's progress, and buys nothing, since the retry's payload
4980        // is discarded either way.
4981        if let Some(floor) = solution_floor {
4982            tracing::debug!(target: "pounce::algorithm",
4983                "[POUNCE] the mu_strategy_fallback retry did not promote \
4984                 ({:?} is not Solve_Succeeded); restoring the first attempt's \
4985                 solution and statistics alongside its status (pounce#870).",
4986                retry_status);
4987            self.restore_floor(&floor, &tnlp);
4988            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
4989            // Third sink: the per-iteration trace. Consumers accumulate that
4990            // themselves from `intermediate_callback` — the CasADi plugin
4991            // pushes into its own vectors and clears once per `nlpsol` call —
4992            // so POUNCE cannot rewind it, and both attempts concatenate into
4993            // one trace. Restoring the certificate without touching the trace
4994            // leaves the reported numbers describing attempt 1 while the trace
4995            // ends on the retry, which breaks the invariant
4996            // `casadi/test_parity.py` states outright: "The final numbers and
4997            // the end of the trace are the same quantities, and must not come
4998            // from two different places."
4999            //
5000            // Re-emitting the winning attempt's final row restores it. It is
5001            // the trace analogue of `FinalizeSnapshot::replay` above, and it
5002            // makes the property hold by construction rather than by hoping a
5003            // consumer resets on an attempt boundary — nothing in the callback
5004            // contract marks one, and gh#634 is what happens when a consumer
5005            // has to guess the scope of a trace.
5006            //
5007            // The row is a real iterate that was already sent once, not a
5008            // synthesized one, so a trace still contains only points the solver
5009            // actually visited.
5010            if let Some(stats) = trace_floor {
5011                let _ = tnlp.borrow_mut().intermediate_callback(
5012                    stats,
5013                    &TnlpIpoptData::default(),
5014                    &TnlpIpoptCq::default(),
5015                );
5016            }
5017        }
5018        first_status
5019    }
5020
5021    /// Is the gh#884 biactive dual-divergence retry enabled? Default
5022    /// `yes`; `dual_divergence_retry=no` is the kill switch, and
5023    /// restores the pre-gh#884 behaviour outright (no detector cost, no
5024    /// second solve, and the base attempt's verdict returned unchanged).
5025    fn is_dual_divergence_retry_enabled(&self) -> bool {
5026        self.options
5027            .get_bool_value("dual_divergence_retry", "")
5028            .map(|(v, _found)| v)
5029            .unwrap_or(true)
5030    }
5031
5032    /// gh#884: throw the iterate away and solve again from scratch with
5033    /// `perturb_always_cd` on, when the base solve settled its primal
5034    /// while its multipliers ran away.
5035    ///
5036    /// # The defect
5037    ///
5038    /// On an MPCC lowered through an exact complementarity product
5039    /// `G·H = 0`, a pair that is **biactive** at the solution — both
5040    /// `G` and `H` zero — leaves that row's gradient
5041    /// `H∇G + G∇H` identically zero. The row is still there, so its
5042    /// multiplier is *arbitrary* rather than nonexistent, and the IPM
5043    /// drives it to infinity while the primal iterate sits on the
5044    /// answer. Because the convergence verdict is reached on an
5045    /// `s_d`-normalised aggregate and `s_d` grows with the mean
5046    /// multiplier magnitude, the aggregate reads clean: MacMPEC's
5047    /// `qpec_small` under `ncp_eq`/`prod_eq` reported
5048    /// `Solved_To_Acceptable_Level` at an *unscaled* dual infeasibility
5049    /// of `7.9e+04`.
5050    ///
5051    /// # Why a retry rather than a gate
5052    ///
5053    /// Four other shapes of fix were measured and rejected — a Hessian
5054    /// sparsity hypothesis, engaging `delta_c` *in flight*, flipping
5055    /// `perturb_always_cd` on globally, and putting a dual ceiling on
5056    /// the acceptable-level gate. `dev-notes/mpcc-biactive-dual-
5057    /// divergence.md` records all four with numbers. The short version:
5058    /// by the time the runaway is visible this iterate is unrecoverable,
5059    /// so the only action left is to *stop using it*; and the remedy
5060    /// that works — `perturb_always_cd=yes` — is measured to return a
5061    /// wrong answer reported as success on `ralph1`
5062    /// (`Solve_Succeeded` at `f = -2.71e-5`, below `f* = 0`), so it
5063    /// cannot be turned on for everyone.
5064    ///
5065    /// **The detector is therefore the entire safety barrier**, and the
5066    /// promotion gate below is the second one. `ralph1` is exactly the
5067    /// model the detector must not fire on, and
5068    /// `IpoptAlgorithm`'s scale-relative step floor is what keeps it
5069    /// from doing so: `qpec_small` settles to `4.3e-8` while `ralph1`
5070    /// bottoms out at `7.2e-3`, five orders apart.
5071    ///
5072    /// # The gate
5073    ///
5074    /// The retry's verdict replaces the base one only when **all** of:
5075    ///
5076    /// 1. the base attempt saw the signature (a converged primal, a step
5077    ///    at zero, and an unscaled `‖∇L‖∞` far above `dual_inf_tol`, all
5078    ///    at one iterate — see `IpoptAlgorithm::dual_divergence_signature`);
5079    /// 2. the base status is `Solved_To_Acceptable_Level` or
5080    ///    `Restoration_Failed` — the two verdicts the vanishing-gradient
5081    ///    row produces directly. Generic exhaustion exits are excluded;
5082    ///    `deb7` under L-BFGS is why, and the reason is in the code
5083    ///    below;
5084    /// 3. the retry returns `Solve_Succeeded`;
5085    /// 4. the retry's claimed success is **real in the model's own
5086    ///    units** — unscaled KKT error at or below `tol`-scale, which is
5087    ///    the property the base attempt failed and the whole point of
5088    ///    the issue;
5089    /// 5. the retry's unscaled KKT error is *strictly better* than the
5090    ///    base attempt's.
5091    ///
5092    /// Otherwise the base attempt's status, point and statistics are all
5093    /// put back, by the same three-sink floor
5094    /// [`Self::run_with_mu_strategy_fallback`] uses and for the same
5095    /// reason (pounce#870): a status describing one attempt attached to
5096    /// a point from another is worse than either.
5097    fn run_with_dual_divergence_retry(
5098        &mut self,
5099        tnlp: Rc<RefCell<dyn TNLP>>,
5100    ) -> ApplicationReturnStatus {
5101        let first_status = self.dispatch_standard_solve(Rc::clone(&tnlp));
5102        if !self.dual_divergence_signature.get() {
5103            return first_status;
5104        }
5105        // Which base verdicts this remedy is *for*.
5106        //
5107        // Two, and the narrowing was bought with a measurement. The
5108        // detector is a statement about the iterate; it is not a
5109        // statement that `perturb_always_cd` will help. `deb7` under
5110        // L-BFGS is the corpus case that separates the two: the
5111        // signature is real there — iteration 346, scale-relative step
5112        // `6.5e-6`, `inf_pr` `3.0e-12`, unscaled `inf_du` `9.2e5`,
5113        // which is an order *above* the gh#884 reproducer's `7.9e4`, so
5114        // no dual floor excludes it, and the step conjunct separates the
5115        // two only by fitting the default onto one fixture and spending
5116        // the margin that holds `ralph1` out — and the retry still does
5117        // not work: 3000 iterations to
5118        // `Maximum_Iterations_Exceeded` at an unscaled KKT error of
5119        // `6.7e1` against the base attempt's `9.9e1`. Pure cost, 4x the
5120        // base trajectory, on a fixture whose verdict does not move.
5121        //
5122        // The exclusion is by *status*, so it is only as complete as the
5123        // status is stable, and on this very fixture it is not. `deb7`
5124        // reaches `Error_In_Step_Computation` at default options and is
5125        // out; under `limited_memory_ls_failure_restarts=1` (gh#818's
5126        // rung, off by default) it reaches `Restoration_Failed` instead
5127        // and is therefore *in*. It used to pay exactly the cost above
5128        // there — 6.1 s to 25.2 s wall clock for the same
5129        // `Restoration_Failed` verdict and a declined retry, which is
5130        // gh#887. That is the price of scoping by status rather than by
5131        // model, and it is why the second gate below scopes by the
5132        // *answer* instead: `deb7` now declines before spending
5133        // anything. The status scope is kept because it is cheap and
5134        // reads on the verdict a caller sees, but it is not what is
5135        // being relied on.
5136        //
5137        // What separates them is the *status*, and it separates them
5138        // for a reason rather than by luck:
5139        //
5140        //  * `Solved_To_Acceptable_Level` is gh#884 verbatim — the
5141        //    runaway laundered itself through `s_d` into a success.
5142        //  * `Restoration_Failed` is the same defect one step earlier:
5143        //    the rows whose gradients vanished drive the solve into
5144        //    restoration, and restoration cannot repair a row that has
5145        //    no gradient. It is where the `qpec_small` TNLP fixture
5146        //    lands (unscaled KKT `3.3e11`).
5147        //  * `Error_In_Step_Computation` and
5148        //    `Maximum_Iterations_Exceeded` are generic exhaustion
5149        //    exits. Every hard model reaches them, for every reason.
5150        //    Retrying *those* is not "repair the runaway", it is "try
5151        //    again harder" — which is what `mu_strategy_fallback` and
5152        //    the second-opinion ladder already are, and `deb7` is what
5153        //    that costs.
5154        //
5155        // `Solve_Succeeded` is excluded because it is already the best
5156        // verdict available and its certificate has already been
5157        // checked in the model's own units; there is nothing to buy.
5158        //
5159        // Worst-case cost is therefore one extra solve under the
5160        // caller's own `max_iter` — the same contract
5161        // `run_with_mu_strategy_fallback` already has.
5162        //
5163        // Deliberately **not** deferred to `TERMINATION_POLICY_OPTIONS`
5164        // the way the μ flip's acceptable-level trigger is (gh#757).
5165        // That deferral exists because the μ flip returns a different
5166        // *local solution*, so laundering a caller's deliberate
5167        // downgrade loses a signal they asked for. This retry cannot:
5168        // conjunct 4 requires the promoted answer to satisfy the KKT
5169        // conditions in the model's own units, which a downgrade the
5170        // caller induced on purpose does not. And the gh#884 reproducer
5171        // sets `tol=1e-8` explicitly, so deferring would decline the
5172        // retry on the one case the issue is about.
5173        let retry_worthy = matches!(
5174            first_status,
5175            ApplicationReturnStatus::SolvedToAcceptableLevel
5176                | ApplicationReturnStatus::RestorationFailed
5177        );
5178        if !retry_worthy {
5179            return first_status;
5180        }
5181        let base_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
5182        // The runaway has to be the *whole* residual of the answer being
5183        // reported.
5184        //
5185        // The detector is a statement about an *iterate*, and the iterate
5186        // it fires on need not be the one the solve ends at. A run can
5187        // pass through a settled point with a diverged multiplier, work
5188        // its way back down, and report something ordinary — and then
5189        // there is nothing left here for `perturb_always_cd` to repair,
5190        // whatever the trajectory did in the middle. This is what makes
5191        // "one extra solve" a cost the caller only pays on a run that
5192        // still *exhibits* the defect (gh#887).
5193        //
5194        // The test is `runaway_is_the_whole_residual`, which reads only
5195        // the reported answer and only as a ratio within it; its doc
5196        // comment carries the rule and the measured populations.
5197        let (base_viol, base_compl) = {
5198            let st = self.statistics.borrow();
5199            (st.final_unscaled_constr_viol, st.final_unscaled_compl)
5200        };
5201        let base_dual_inf = self.statistics.borrow().final_unscaled_dual_inf;
5202        if !runaway_is_the_whole_residual(
5203            base_dual_inf,
5204            base_viol,
5205            base_compl,
5206            self.options
5207                .get_numeric_value("dual_divergence_retry_du_floor", "")
5208                .map(|(v, _)| v)
5209                .unwrap_or(DUAL_DIV_RETRY_DU_FLOOR),
5210        ) {
5211            tracing::debug!(target: "pounce::algorithm",
5212                "[POUNCE] gh#884: the signature fired mid-trajectory, but the \
5213                 answer being reported is not a converged point with a runaway \
5214                 multiplier — unscaled dual {:.3e} against viol {:.3e} and \
5215                 complementarity {:.3e}. Nothing here for perturb_always_cd to \
5216                 repair, so no retry (gh#887).",
5217                base_dual_inf, base_viol, base_compl);
5218            return first_status;
5219        }
5220        // Floor all three sinks — solution payload, certificate, and the
5221        // last trace row — exactly as the μ fallback does (pounce#870).
5222        let solution_floor = self.last_finalize.borrow().clone();
5223        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
5224        let trace_floor = *self.last_iter_stats.borrow();
5225        tracing::debug!(target: "pounce::algorithm",
5226            "[POUNCE] gh#884: the primal settled while the multipliers ran away \
5227             (base {:?}, unscaled KKT {:.3e}); re-solving from scratch with \
5228             perturb_always_cd=yes.",
5229            first_status, base_unscaled_kkt);
5230        let prev = self.options.get_string_value("perturb_always_cd", "").ok();
5231        // Unwind cover only, as for the μ-strategy fallback: the restore
5232        // below is the normal path and is left exactly as it was.
5233        let mut scope = RetryOptionScope::enter(self, &["perturb_always_cd"], true);
5234        let _ = scope
5235            .options
5236            .set_string_value("perturb_always_cd", "yes", true, false);
5237        let retry_status = scope.dispatch_standard_solve(Rc::clone(&tnlp));
5238        // Restore the caller's option-table view. Absence is restored as
5239        // absence would be seen: the registered default is `no`.
5240        let _ = scope.options.set_string_value(
5241            "perturb_always_cd",
5242            prev.as_ref()
5243                .filter(|(_, found)| *found)
5244                .map(|(v, _)| v.as_str())
5245                .unwrap_or("no"),
5246            true,
5247            false,
5248        );
5249        drop(scope);
5250        let retry_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
5251        let retry_viol = self.statistics.borrow().final_unscaled_constr_viol;
5252        // Conjuncts 3, 4 and 5. Conjunct 4 is the one that distinguishes
5253        // this gate from every other promote-on-`Solve_Succeeded` retry
5254        // in this file: the base attempt's defect *was* a status that its
5255        // own unscaled residual contradicts, so promoting on the status
5256        // alone would reproduce the bug one attempt later.
5257        let accept_tol = self.dual_divergence_retry_accept_tol();
5258        let claimed_success_is_real = (retry_unscaled_kkt <= accept_tol
5259            && retry_viol <= accept_tol)
5260            || retry_certificate_dominates(
5261                base_unscaled_kkt,
5262                retry_unscaled_kkt,
5263                retry_viol,
5264                accept_tol,
5265            );
5266        // Conjuncts 6 and 7 — see `retry_answer_is_admissible`. Everything
5267        // above this line ranks the two attempts on their *certificates*;
5268        // this ranks them as *answers*, which is what a caller receives.
5269        // Without it a better multiplier is allowed to buy a worse point:
5270        // measured, `-13.0057 -> -1.2072` on a random QPEC, and
5271        // `+1.82e-09 -> -6.61e-05` on `scholtes4`, whose `f*` is exactly 0.
5272        let retry_obj = self.statistics.borrow().final_objective;
5273        // `obj_scaling_factor < 0` is how a maximization is posed, and
5274        // `final_objective` is the user's signed objective, so the
5275        // comparison direction has to follow it (R2).
5276        let sense = if self
5277            .options
5278            .get_numeric_value("obj_scaling_factor", "")
5279            .map(|(v, _)| v)
5280            .unwrap_or(1.0)
5281            < 0.0
5282        {
5283            -1.0
5284        } else {
5285            1.0
5286        };
5287        let answer_is_admissible = retry_answer_is_admissible(
5288            certificate_floor.objective,
5289            certificate_floor.unscaled_constr_viol,
5290            retry_obj,
5291            retry_viol,
5292            self.dual_divergence_retry_accept_tol(),
5293            sense,
5294        );
5295        let promote = matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
5296            && claimed_success_is_real
5297            && retry_unscaled_kkt < base_unscaled_kkt
5298            && answer_is_admissible;
5299        // Say on the console which of the two answers shipped.
5300        //
5301        // The per-attempt end summary cannot: `emit_end_summary` runs
5302        // inside `optimize_constrained`, once per attempt, and the
5303        // promotion is decided after the last of them. So a summary that
5304        // reported the promotion would report `false` on the very run that
5305        // promotes, contradicting the JSON report written from the same
5306        // statistics. The summary reports the *signature*, which is true
5307        // when it prints; this line reports the *outcome*, printed once,
5308        // where it is known.
5309        //
5310        // Gated on `print_level >= 1`, matching `emit_end_summary` — the
5311        // block this line follows.
5312        let console_output = match self.options.get_integer_value("print_level", "") {
5313            Ok((v, true)) => v >= 1,
5314            _ => true,
5315        };
5316        if console_output {
5317            println!();
5318            if promote {
5319                println!(
5320                    "gh#884 dual-divergence retry: promoted — unscaled KKT error \
5321                     {base_unscaled_kkt:.4e} -> {retry_unscaled_kkt:.4e}."
5322                );
5323            } else if !answer_is_admissible {
5324                // A distinct line, because this decline looks like a
5325                // contradiction otherwise: the retry converged, its
5326                // certificate is clean, and it was still refused. Say
5327                // which of the two rules refused it and on what numbers,
5328                // so the reader is not left comparing KKT errors that
5329                // had nothing to do with it.
5330                println!(
5331                    "gh#884 dual-divergence retry: declined on the ANSWER, not the \
5332                     certificate — the retry converged (unscaled KKT error \
5333                     {retry_unscaled_kkt:.4e} against the base attempt's \
5334                     {base_unscaled_kkt:.4e}) but its objective {retry_obj:.8e} at \
5335                     constraint violation {retry_viol:.4e} is not admissible next to \
5336                     the base attempt's {:.8e} at {:.4e}; the base attempt's answer \
5337                     is the one reported.",
5338                    certificate_floor.objective, certificate_floor.unscaled_constr_viol
5339                );
5340            } else {
5341                println!(
5342                    "gh#884 dual-divergence retry: declined ({retry_status:?}, \
5343                     unscaled KKT error {retry_unscaled_kkt:.4e} against the base \
5344                     attempt's {base_unscaled_kkt:.4e}); the base attempt's answer \
5345                     is the one reported."
5346                );
5347            }
5348        }
5349        if promote {
5350            self.dual_divergence_retry_promoted.set(true);
5351            self.statistics.borrow_mut().dual_divergence_retry_promoted = true;
5352            tracing::debug!(target: "pounce::algorithm",
5353                "[POUNCE] gh#884: the retry promoted — unscaled KKT {:.3e} \
5354                 (base {:.3e}).",
5355                retry_unscaled_kkt, base_unscaled_kkt);
5356            return retry_status;
5357        }
5358        if let Some(floor) = solution_floor {
5359            tracing::debug!(target: "pounce::algorithm",
5360                "[POUNCE] gh#884: the retry did not promote ({:?}, unscaled KKT \
5361                 {:.3e} vs base {:.3e}); restoring the first attempt's solution \
5362                 and statistics alongside its status.",
5363                retry_status, retry_unscaled_kkt, base_unscaled_kkt);
5364            self.restore_floor(&floor, &tnlp);
5365            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5366            // The signature belongs to the attempt whose numbers are now
5367            // reported, and `certificate_floor` does not carry it.
5368            self.statistics.borrow_mut().dual_divergence_signature = true;
5369            if let Some(stats) = trace_floor {
5370                let _ = tnlp.borrow_mut().intermediate_callback(
5371                    stats,
5372                    &TnlpIpoptData::default(),
5373                    &TnlpIpoptCq::default(),
5374                );
5375            }
5376        }
5377        first_status
5378    }
5379
5380    /// Is the gh#983 solve-quality audit enabled? Default `yes`;
5381    /// `solve_quality_audit=no` restores the pre-gh#983 behaviour (no
5382    /// re-scale retry, no `warnings`).
5383    fn is_solve_quality_audit_enabled(&self) -> bool {
5384        self.options
5385            .get_bool_value("solve_quality_audit", "")
5386            .map(|(v, _found)| v)
5387            .unwrap_or(true)
5388    }
5389
5390    /// gh#983 items 2 and 3: audit a success verdict against the *model's
5391    /// own* scale, re-solve once when the scaling is what is wrong, and say
5392    /// so in `statistics.warnings` when it is not fixed.
5393    ///
5394    /// The strict gate judges a scaled aggregate. Gradient-based scaling
5395    /// measures the objective gradient once, at the starting point, and
5396    /// freezes the factor; it also only ever scales *down*. Two failures
5397    /// follow, one on each side, and neither is visible to a gate that reads
5398    /// the scaled space:
5399    ///
5400    /// * **Frozen at a huge-gradient start** (LJ7 from a start whose gradient
5401    ///   is `3e8`): the factor is `3e-7`, the scaled test passes at a point
5402    ///   whose unscaled stationarity residual is `2.9e-2`, and no amount of
5403    ///   continued iteration under that factor improves it
5404    ///   (`obj_scale_certificate_threshold` already tries, and its budget is
5405    ///   spent). The fix is the one the issue names: re-evaluate the scaling
5406    ///   *at the returned point*, where the gradient is small, and solve
5407    ///   again from there.
5408    /// * **Small user objective** (profit in M$/L, gradient `1e-5`): nothing
5409    ///   scales up, so the absolute complementarity floor `~mu` is a
5410    ///   `2.5e-4` fraction of the objective gradient and the answer sits
5411    ///   `4.7e-4` (relative) off the optimum on an active bound. The retry
5412    ///   multiplies the objective by `1/max|grad f|` and solves again from
5413    ///   the returned point.
5414    ///
5415    /// Both retries are *bets that are tested*, floored exactly like the
5416    /// gh#884 and mu-strategy retries: the retry is promoted only when it
5417    /// returns a clean verdict, its unscaled KKT error is no worse, its
5418    /// complementarity (small-objective case) or unscaled KKT error (frozen
5419    /// case) is strictly better, and its answer is admissible next to the
5420    /// base attempt's. Otherwise the base attempt's status, point and
5421    /// statistics are restored and a structured warning is attached.
5422    fn audit_solve_quality(
5423        &mut self,
5424        tnlp: Rc<RefCell<dyn TNLP>>,
5425        first_status: ApplicationReturnStatus,
5426    ) -> ApplicationReturnStatus {
5427        if !self.is_solve_quality_audit_enabled()
5428            || !matches!(
5429                first_status,
5430                ApplicationReturnStatus::SolveSucceeded
5431                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5432            )
5433        {
5434            return first_status;
5435        }
5436        let num = |name: &str, default: Number| -> Number {
5437            self.options
5438                .get_numeric_value(name, "")
5439                .ok()
5440                .and_then(|(v, f)| f.then_some(v))
5441                .unwrap_or(default)
5442        };
5443        let acceptable_tol = num("acceptable_tol", 1e-6);
5444        let masked_threshold = num("obj_scale_certificate_threshold", 1e-4);
5445        // `equilibration-based` is registered but pounce runs it as
5446        // gradient-based (see `algorithm_builder_from_options`), so it gets the
5447        // gradient-based audit.
5448        let gradient_based = self
5449            .options
5450            .get_string_value("nlp_scaling_method", "")
5451            .ok()
5452            .and_then(|(v, f)| f.then_some(v))
5453            .map(|v| v == "gradient-based" || v == "equilibration-based")
5454            .unwrap_or(true);
5455        let base = self.statistics.borrow().clone();
5456        // gh#983 review item 2: measure the objective gradient at the point
5457        // being returned, so the audit asks what re-evaluating the scaling
5458        // *there* would do instead of keying on the start alone.
5459        let final_grad_max = self
5460            .last_finalize
5461            .borrow()
5462            .as_ref()
5463            .and_then(|f| {
5464                let mut g = vec![0.0; f.x.len()];
5465                tnlp.borrow_mut()
5466                    .eval_grad_f(&f.x, true, &mut g)
5467                    .then(|| g.iter().fold(0.0_f64, |m, v| m.max(v.abs())))
5468            })
5469            .unwrap_or(Number::NAN);
5470        let rescaled_obj_scale = if final_grad_max.is_finite() {
5471            pounce_nlp::orig_ipopt_nlp::gradient_obj_scale(
5472                final_grad_max,
5473                num("nlp_scaling_max_gradient", 100.0),
5474                num("nlp_scaling_min_value", 1e-8),
5475                num("nlp_scaling_obj_target_gradient", 0.0),
5476            )
5477        } else {
5478            Number::NAN
5479        };
5480        let input = ScaleAuditInput {
5481            tol: num("tol", 1e-8),
5482            obj_scale: base.final_obj_scaling_factor,
5483            rescaled_obj_scale,
5484            start_grad_max: base.start_obj_grad_max,
5485            final_grad_max,
5486            unscaled_kkt: base.final_unscaled_kkt_error,
5487            unscaled_compl: base.final_unscaled_compl,
5488            acceptable_tol,
5489            masked_threshold,
5490            warm_start: self
5491                .options
5492                .get_bool_value("warm_start_init_point", "")
5493                .map(|(v, _)| v)
5494                .unwrap_or(false),
5495        };
5496        let grad_scale = input.grad_scale();
5497        let trigger = scale_audit_trigger(input);
5498        let mut status = first_status;
5499        match trigger {
5500            Some(ScaleAudit::SmallObjective) => {
5501                self.statistics
5502                    .borrow_mut()
5503                    .warnings
5504                    .push(scale_audit_warning(
5505                        ScaleAudit::SmallObjective,
5506                        &base,
5507                        grad_scale,
5508                        acceptable_tol,
5509                        "",
5510                    ));
5511            }
5512            Some(kind) if gradient_based => {
5513                status = self.run_scale_retry(tnlp, first_status, kind, grad_scale);
5514            }
5515            Some(kind) => {
5516                // The caller owns the scaling (`none` / `user-scaling`): not ours
5517                // to override, but the verdict still deserves its caveat.
5518                self.statistics
5519                    .borrow_mut()
5520                    .warnings
5521                    .push(scale_audit_warning(
5522                        kind,
5523                        &base,
5524                        grad_scale,
5525                        acceptable_tol,
5526                        "was not attempted: nlp_scaling_method is not gradient-based",
5527                    ));
5528            }
5529            None => {}
5530        }
5531        status
5532    }
5533
5534    /// gh#983 review items 1 and 3: the verdict-level half of the audit, run
5535    /// **once**, on the run whose point is being returned -- after every
5536    /// retry and fallback has decided.
5537    ///
5538    /// * The item-5 downgrade (a strict verdict on a run that saw the gh#884
5539    ///   signature and still carries an unscaled dual infeasibility above
5540    ///   `max(acceptable_tol, 1e-3)`) used to run inside each attempt, so it
5541    ///   could turn a base `Solve_Succeeded` into the acceptable level *before*
5542    ///   the gh#884 retry decided, reopening that retry for a case it was
5543    ///   deliberately not widened to; and it read the cumulative signature, so
5544    ///   a promoted mu-fallback run that never showed it was downgraded for its
5545    ///   discarded sibling. It now reads
5546    ///   `returned_run_dual_divergence_signature`, which the certificate floor
5547    ///   saves and restores with the rest of the run's tally.
5548    /// * The model-scale caveats ([`quality_warnings`]) are attached here, and
5549    ///   deduplicated by code, so a code appears at most once.
5550    fn finalize_quality_verdict(
5551        &mut self,
5552        status: ApplicationReturnStatus,
5553    ) -> ApplicationReturnStatus {
5554        if !self.is_solve_quality_audit_enabled() {
5555            return status;
5556        }
5557        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5558        let mut status = status;
5559        if matches!(status, ApplicationReturnStatus::SolveSucceeded) {
5560            let (sig, du, du_scale) = {
5561                let st = self.statistics.borrow();
5562                (
5563                    st.returned_run_dual_divergence_signature,
5564                    st.final_unscaled_dual_inf,
5565                    st.final_unscaled_dual_scale,
5566                )
5567            };
5568            // gh#983 item 5. `1e-3` is `UNSCALED_DUAL_WARN`; the measured
5569            // population behind it is in that constant's doc. A residual at
5570            // the rounding floor of its own terms is not evidence of a miss
5571            // (gh#1000, II.22): see `UNSCALED_DUAL_ROUNDOFF_ULPS`.
5572            if sig
5573                && du.is_finite()
5574                && du > acceptable_tol.max(UNSCALED_DUAL_WARN)
5575                && !unscaled_dual_inf_is_roundoff(du, du_scale)
5576            {
5577                status = ApplicationReturnStatus::SolvedToAcceptableLevel;
5578                push_warning_once(
5579                    &mut self.statistics.borrow_mut().warnings,
5580                    format!(
5581                        "unscaled_dual_inf_above_acceptable: the run saw a settled primal with a \
5582                         runaway multiplier (gh#884) and the returned point's unscaled dual \
5583                         infeasibility is {du:.2e}, above {:.0e}; the status is downgraded from \
5584                         Solve_Succeeded to Solved_To_Acceptable_Level",
5585                        acceptable_tol.max(UNSCALED_DUAL_WARN)
5586                    ),
5587                );
5588            }
5589        }
5590        let st = self.statistics.borrow().clone();
5591        let extra = quality_warnings(
5592            status,
5593            st.final_unscaled_dual_inf,
5594            st.final_unscaled_dual_scale,
5595            self.options
5596                .get_numeric_value("dual_inf_tol", "")
5597                .map(|(v, _)| v)
5598                .unwrap_or(1.0),
5599            acceptable_tol,
5600            self.options
5601                .get_numeric_value("bound_relax_factor", "")
5602                .is_ok_and(|(v, _)| v == 0.0),
5603        );
5604        let mut sm = self.statistics.borrow_mut();
5605        for w in extra {
5606            push_warning_once(&mut sm.warnings, w);
5607        }
5608        status
5609    }
5610
5611    /// The variable box `tnlp` declares, `(x_L, x_U)` in its own (full-x)
5612    /// space -- the space a `finalize_solution` payload is in. `None` if the
5613    /// TNLP declines to say.
5614    fn declared_x_box(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> Option<(Vec<Number>, Vec<Number>)> {
5615        let mut t = tnlp.borrow_mut();
5616        let info = t.get_nlp_info()?;
5617        let (n, m) = (info.n.max(0) as usize, info.m.max(0) as usize);
5618        let (mut x_l, mut x_u) = (vec![0.0; n], vec![0.0; n]);
5619        let (mut g_l, mut g_u) = (vec![0.0; m], vec![0.0; m]);
5620        t.get_bounds_info(BoundsInfo {
5621            x_l: &mut x_l,
5622            x_u: &mut x_u,
5623            g_l: &mut g_l,
5624            g_u: &mut g_u,
5625        })
5626        .then_some((x_l, x_u))
5627    }
5628
5629    /// The re-solve half of [`Self::audit_solve_quality`].
5630    fn run_scale_retry(
5631        &mut self,
5632        tnlp: Rc<RefCell<dyn TNLP>>,
5633        first_status: ApplicationReturnStatus,
5634        kind: ScaleAudit,
5635        grad_scale: Number,
5636    ) -> ApplicationReturnStatus {
5637        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5638        let solution_floor = self.last_finalize.borrow().clone();
5639        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
5640        let trace_floor = *self.last_iter_stats.borrow();
5641        let base = self.statistics.borrow().clone();
5642        let Some(seed) = solution_floor.as_ref().map(|f| f.x.clone()) else {
5643            return first_status;
5644        };
5645        // Budget the re-solve: an iteration cap tied to the base solve
5646        // (`SCALE_AUDIT_RETRY_ITER_FACTOR`), and only the time the caller's
5647        // limits have left. Every solve builds a fresh deadline, so without
5648        // this the re-solve got a second full `max_cpu_time` / `max_wall_time`
5649        // after the run had already succeeded. Restored below, absence as
5650        // absence.
5651        let prev_iter = self.options.get_integer_value("max_iter", "").ok();
5652        let prev_cpu = self.options.get_numeric_value("max_cpu_time", "").ok();
5653        let prev_wall = self.options.get_numeric_value("max_wall_time", "").ok();
5654        let cpu_left = prev_cpu.map(|(v, _)| v - base.total_cpu_time_secs);
5655        let wall_left = prev_wall.map(|(v, _)| v - base.total_wallclock_time_secs);
5656        if cpu_left.is_some_and(|t| t <= 0.0) || wall_left.is_some_and(|t| t <= 0.0) {
5657            return first_status;
5658        }
5659        let retry_iter = (SCALE_AUDIT_RETRY_ITER_FACTOR * base.iteration_count)
5660            .max(SCALE_AUDIT_RETRY_MIN_ITER)
5661            .min(prev_iter.map_or(Index::MAX, |(v, _)| v));
5662        let seeded: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(
5663            pounce_nlp::seeded_tnlp::SeededTnlp::new(Rc::clone(&tnlp), seed),
5664        ));
5665        // gh#983 review item 7: remember whether the caller *named* the
5666        // factor, so the restore puts back absence as absence. Writing the
5667        // default back with `found = true` left `obj_scaling_factor` reading as
5668        // user-set after the audit, which every "did the caller name it" test
5669        // downstream (`TERMINATION_POLICY_OPTIONS`, the gh#884 sense) then
5670        // misread.
5671        let prev_user = self
5672            .options
5673            .get_numeric_value("obj_scaling_factor", "")
5674            .ok()
5675            .and_then(|(v, f)| f.then_some(v));
5676        let prev_user_factor = prev_user.unwrap_or(1.0);
5677        let caller_named_relax = self
5678            .options
5679            .get_numeric_value("bound_relax_factor", "")
5680            .is_ok_and(|(_, found)| found);
5681        // Everything below until the scope drops is this re-solve's own
5682        // configuration; the scope puts every entry back, and clears the box
5683        // flag, however the re-solve exits.
5684        let mut scope = RetryOptionScope::enter(
5685            self,
5686            &[
5687                "obj_scaling_factor",
5688                "max_iter",
5689                "max_cpu_time",
5690                "max_wall_time",
5691            ],
5692            false,
5693        );
5694        if let ScaleAudit::Upscale(k) = kind {
5695            let _ = scope.options.set_numeric_value(
5696                "obj_scaling_factor",
5697                prev_user_factor * k,
5698                true,
5699                false,
5700            );
5701        }
5702        let _ = scope
5703            .options
5704            .set_integer_value("max_iter", retry_iter, true, false);
5705        // Solve the re-solve on the caller's own variable box: the rows are
5706        // widened by `bound_relax_factor` exactly as in the base attempt, the
5707        // box is not -- unless the caller named a widening.
5708        //
5709        // The re-solve exists to drive complementarity down (`Upscale`) or the
5710        // unscaled residual (`Rescale`), and on a bound-active variable that
5711        // is the same motion as driving the point onto its bound: `s · z = mu`
5712        // with `z` multiplied by the objective factor, so the slack to the
5713        // *widened* bound shrinks by that factor and the point lands at
5714        // `x_U + bound_relax_factor · max(1, |x_U|)` -- outside the box the
5715        // caller wrote. The base attempt, less converged, usually sat inside
5716        // it. So every promoted re-solve on a bound-active model shipped a
5717        // point outside its declared bounds: measured with `pounce verify`,
5718        // `ex1_320` `1.0e-8` across thousands of controls, `trainf` `7.0e-8`,
5719        // `reading1` `9.9e-9`, against `0` from the base attempt.
5720        //
5721        // The improvement itself is real, not bought with that slack: solved
5722        // with the declared box the re-solve reaches the same objective
5723        // (`reading1` `-1.604802802e-1` against `-1.604802843e-1` widened, the
5724        // base attempt's `-1.604578481e-1`) with the box held exactly. So the
5725        // box widening is dropped for this one solve rather than the re-solve
5726        // refused: it starts from a point that already satisfies the box, and
5727        // `bound_push` moves the seed off any bound it sits on.
5728        //
5729        // Why the box and not `bound_relax_factor=0`: that also un-widens the
5730        // inequality rows, which makes the re-solve a strictly tighter model
5731        // than the base attempt, and its objective then reads *worse* than
5732        // the base's by the row widening's worth -- measured on
5733        // `masked_certificate_fuzz` case 12, `-3.453863914e7` against
5734        // `-3.453863947e7`, with both points inside their box. The rows are
5735        // what the base attempt's `final_unscaled_constr_viol` and rule 2 of
5736        // `retry_answer_is_admissible` already compare like with like; the box
5737        // is the one thing neither did.
5738        //
5739        // A caller who named the factor defined the model that way and keeps
5740        // it; for that case the declared-box conjunct of the promotion gate
5741        // below is what holds the line.
5742        scope.retry_keeps_declared_box.set(!caller_named_relax);
5743        if let Some(t) = cpu_left {
5744            let _ = scope
5745                .options
5746                .set_numeric_value("max_cpu_time", t, true, false);
5747        }
5748        if let Some(t) = wall_left {
5749            let _ = scope
5750                .options
5751                .set_numeric_value("max_wall_time", t, true, false);
5752        }
5753        tracing::debug!(target: "pounce::algorithm",
5754            "[POUNCE] gh#983: {:?} verdict audited ({:?}); re-solving from the \
5755             returned point (max_iter {retry_iter}).", first_status, kind);
5756        // One IPM solve, without the mu-strategy fallback: the re-solve is
5757        // already a second opinion on a run that succeeded, and when it hit
5758        // its cap the flip spent the same budget again (`meyer3` 768 + 768,
5759        // `brainpc3` 120 + 120, `brainpc9` timing out in the second leg).
5760        // No promoted re-solve in the release sweep needed the flip except
5761        // `robot_b` past the cap, which keeps its `Solve_Succeeded` base.
5762        if match scope.options.get_integer_value("print_level", "") {
5763            Ok((v, true)) => v >= 1,
5764            _ => true,
5765        } {
5766            println!();
5767            println!(
5768                "gh#983 scale audit: re-solving from the returned point ({kind:?}); the \
5769                 summary below is a candidate's, and the line after it says whether it \
5770                 replaced the answer above."
5771            );
5772        }
5773        let retry_status = scope.optimize_constrained(Rc::clone(&seeded));
5774        drop(scope);
5775        let retry = self.statistics.borrow().clone();
5776        let sense = if prev_user_factor < 0.0 { -1.0 } else { 1.0 };
5777        let clean = match first_status {
5778            ApplicationReturnStatus::SolveSucceeded => {
5779                matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
5780            }
5781            _ => matches!(
5782                retry_status,
5783                ApplicationReturnStatus::SolveSucceeded
5784                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5785            ),
5786        };
5787        let better = match kind {
5788            ScaleAudit::Rescale => retry.final_unscaled_kkt_error < base.final_unscaled_kkt_error,
5789            ScaleAudit::Upscale(_) | ScaleAudit::SmallObjective => {
5790                retry.final_unscaled_compl < 0.1 * base.final_unscaled_compl
5791                    && retry.final_unscaled_kkt_error <= base.final_unscaled_kkt_error
5792            }
5793        };
5794        let admissible = retry_answer_is_admissible(
5795            certificate_floor.objective,
5796            certificate_floor.unscaled_constr_viol,
5797            retry.final_objective,
5798            retry.final_unscaled_constr_viol,
5799            acceptable_tol,
5800            sense,
5801        );
5802        // Measured on the two `finalize_solution` payloads -- the points a
5803        // caller would actually receive -- against the box the user TNLP
5804        // declares.
5805        let (base_box_rel, retry_box_rel) = match self.declared_x_box(&tnlp) {
5806            Some((x_l, x_u)) => {
5807                let (lo, up) = (self.nlp_lower_bound_inf(), self.nlp_upper_bound_inf());
5808                let rel = |x: &[Number]| declared_box_relative_violation(x, &x_l, &x_u, lo, up);
5809                (
5810                    solution_floor.as_ref().map_or(Number::NAN, |f| rel(&f.x)),
5811                    self.last_finalize
5812                        .borrow()
5813                        .as_ref()
5814                        .map_or(Number::NAN, |f| rel(&f.x)),
5815                )
5816            }
5817            None => (Number::NAN, Number::NAN),
5818        };
5819        let keeps_box = retry_keeps_declared_box(base_box_rel, retry_box_rel);
5820        let promote = clean && better && admissible && keeps_box;
5821        let console_output = match self.options.get_integer_value("print_level", "") {
5822            Ok((v, true)) => v >= 1,
5823            _ => true,
5824        };
5825        if console_output {
5826            println!();
5827            if clean && better && admissible && !keeps_box {
5828                println!(
5829                    "gh#983 scale audit: declined (the re-solve's point is {:.4e} outside the \
5830                     declared variable bounds, the base attempt's {:.4e}); the base attempt's \
5831                     answer is the one reported.",
5832                    retry.final_declared_box_viol, certificate_floor.declared_box_viol
5833                );
5834            } else if promote {
5835                println!(
5836                    "gh#983 scale audit: promoted -- unscaled KKT error {:.4e} -> {:.4e}, \
5837                     unscaled complementarity {:.4e} -> {:.4e}.",
5838                    base.final_unscaled_kkt_error,
5839                    retry.final_unscaled_kkt_error,
5840                    base.final_unscaled_compl,
5841                    retry.final_unscaled_compl
5842                );
5843            } else {
5844                println!(
5845                    "gh#983 scale audit: declined ({retry_status:?}, unscaled KKT error \
5846                     {:.4e} against the base attempt's {:.4e}); the base attempt's answer \
5847                     is the one reported.",
5848                    retry.final_unscaled_kkt_error, base.final_unscaled_kkt_error
5849                );
5850            }
5851            if !promote {
5852                // The re-solve's own end summary printed above this line, with
5853                // *its* objective and bound violation, before the verdict was
5854                // known (`emit_end_summary` runs inside each attempt). Say
5855                // which block that was and restate the numbers that ship, so
5856                // the console cannot be read as reporting the discarded point.
5857                println!(
5858                    "gh#983 scale audit: the summary block above is the discarded re-solve's; \
5859                     the reported answer is the base attempt's (objective {:.16e}, variable \
5860                     bound violation {:.16e}).",
5861                    certificate_floor.objective, certificate_floor.declared_box_viol
5862                );
5863            }
5864        }
5865        if promote {
5866            return retry_status;
5867        }
5868        if let Some(floor) = solution_floor {
5869            self.restore_floor(&floor, &tnlp);
5870            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5871            self.statistics.borrow_mut().dual_divergence_signature |=
5872                retry.dual_divergence_signature;
5873            if let Some(stats) = trace_floor {
5874                let _ = tnlp.borrow_mut().intermediate_callback(
5875                    stats,
5876                    &TnlpIpoptData::default(),
5877                    &TnlpIpoptCq::default(),
5878                );
5879            }
5880        }
5881        let detail = if keeps_box {
5882            format!(
5883                "was declined: the re-solve returned {retry_status:?} with unscaled KKT error {:.2e}",
5884                retry.final_unscaled_kkt_error
5885            )
5886        } else {
5887            format!(
5888                "was declined: the re-solve returned {retry_status:?} at a point {:.2e} outside \
5889                 the declared variable bounds",
5890                retry.final_declared_box_viol
5891            )
5892        };
5893        self.statistics
5894            .borrow_mut()
5895            .warnings
5896            .push(scale_audit_warning(
5897                kind,
5898                &base,
5899                grad_scale,
5900                acceptable_tol,
5901                &detail,
5902            ));
5903        first_status
5904    }
5905
5906    /// The tolerance conjunct 4 of the dual-divergence promotion gate
5907    /// tests the retry's *unscaled* residuals against.
5908    ///
5909    /// `acceptable_tol`-scale rather than `tol`-scale on purpose: the
5910    /// unscaled residual is the one quantity nothing in the solve is
5911    /// driven against, so holding it to `tol` would decline honest
5912    /// retries on badly scaled models for a reason that has nothing to
5913    /// do with gh#884. `qpec_small`'s honest retry reaches `9.96e-8`,
5914    /// four orders inside it.
5915    fn dual_divergence_retry_accept_tol(&self) -> Number {
5916        self.options
5917            .get_numeric_value("acceptable_tol", "")
5918            .ok()
5919            .and_then(|(v, f)| f.then_some(v))
5920            .unwrap_or(1e-6)
5921    }
5922
5923    /// Phase-3 ℓ₁-exact penalty-barrier outer loop.
5924    ///
5925    /// Builds an [`L1PenaltyBarrierTnlp`] wrapper around the user
5926    /// TNLP, runs the constrained IPM at the current ρ, escalates ρ
5927    /// per Byrd-Nocedal-Waltz steering, and terminates on any of:
5928    ///   - slack sum collapses (`Σ(p+n) ≤ l1_slack_tol`)
5929    ///   - inner solve returns non-Optimal (escalation won't fix
5930    ///     numerical / restoration failure at this ρ)
5931    ///   - ρ already at `l1_penalty_max`
5932    ///   - `l1_penalty_max_outer_iter` reached
5933    ///
5934    /// After the loop, if the inner status is `SolveSucceeded` or
5935    /// `SolvedToAcceptableLevel` but slacks didn't collapse, override
5936    /// to `Infeasible_Problem_Detected` — the returned point is the
5937    /// ℓ₁-best least-infeasible iterate, which is informative even
5938    /// though the original constraints are not satisfied.
5939    ///
5940    /// Returns `Some(status)` if the wrapper ran the solve, `None` if
5941    /// wrapper construction failed (caller should fall through to the
5942    /// standard dispatch path).
5943    fn run_l1_penalty_outer_loop(
5944        &mut self,
5945        tnlp: Rc<RefCell<dyn TNLP>>,
5946    ) -> Option<ApplicationReturnStatus> {
5947        let rho_init = self.l1_penalty_init();
5948        let rho_max = self.l1_penalty_max().max(rho_init);
5949        let factor = self.l1_penalty_increase_factor().max(1.0);
5950        let tau = self.l1_steering_factor();
5951        let slack_tol = self.l1_slack_tol();
5952        let max_outer = self.l1_penalty_max_outer_iter().max(1);
5953
5954        let mut wrapper = pounce_l1penalty::L1PenaltyBarrierTnlp::new(Rc::clone(&tnlp), rho_init)?;
5955        if wrapper.m_eq() == 0 {
5956            // Nothing to slack — let the standard dispatch path handle
5957            // this TNLP unmodified.
5958            return None;
5959        }
5960        wrapper.set_defer_inner_finalize(true);
5961        let wrapper_rc = Rc::new(RefCell::new(wrapper));
5962
5963        let mut rho = rho_init;
5964        let mut last_status = ApplicationReturnStatus::InternalError;
5965        // gh#987 item 6: every pass resets the statistics, so without this the
5966        // report described only the last ρ — `iter_count` 26 for a solve that
5967        // ran 18 + 22 + 22 + 26 iterations. Accumulated here, applied once
5968        // after the loop.
5969        let mut totals = MultiPassTotals::default();
5970        for _outer in 0..max_outer {
5971            wrapper_rc.borrow_mut().set_rho(rho);
5972            let dyn_tnlp: Rc<RefCell<dyn TNLP>> = wrapper_rc.clone();
5973            last_status = self.optimize_constrained(dyn_tnlp);
5974            totals.push_pass(&self.statistics.borrow(), Some(rho), last_status);
5975
5976            let w = wrapper_rc.borrow();
5977            if !w.has_solution() {
5978                // Inner solve aborted before producing an iterate.
5979                drop(w);
5980                break;
5981            }
5982            let slack_sum = w.last_slack_sum();
5983            let y_eq_inf = w.last_y_eq_inf_norm();
5984            let x_here: Vec<Number> = w.last_x_trunc().to_vec();
5985            drop(w);
5986            totals.set_slack_sum(slack_sum);
5987
5988            // Termination decisions.
5989            let inner_ok = matches!(
5990                last_status,
5991                ApplicationReturnStatus::SolveSucceeded
5992                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5993            );
5994            if !inner_ok {
5995                break;
5996            }
5997            // Stop escalating ρ once the **user's** constraints are
5998            // satisfied to the tolerance the caller asked for — not once
5999            // `Σ(p + n)` falls under `l1_slack_tol`, which is a different
6000            // quantity judged by a different number (gh#794 P1). The
6001            // slack sum stays the BNW steering signal below, which is
6002            // the job it is right for. One extra `eval_g` per outer
6003            // iteration buys the difference between stopping at the
6004            // penalty solution and stopping at the model's own.
6005            let feasible_here = {
6006                let m_inner = tnlp
6007                    .borrow_mut()
6008                    .get_nlp_info()
6009                    .map(|i| i.m.max(0) as usize)
6010                    .unwrap_or(0);
6011                let mut g_here = vec![0.0; m_inner];
6012                let evaluated =
6013                    m_inner == 0 || tnlp.borrow_mut().eval_g(&x_here, true, &mut g_here);
6014                evaluated
6015                    .then(|| {
6016                        original_space_feasibility(
6017                            &tnlp,
6018                            &x_here,
6019                            &g_here,
6020                            self.nlp_lower_bound_inf(),
6021                            self.nlp_upper_bound_inf(),
6022                            self.user_tol(),
6023                            self.user_acceptable_tol(),
6024                            self.user_constr_viol_tol(),
6025                            self.user_acceptable_constr_viol_tol(),
6026                            self.user_primal_noise_floor_kappa(),
6027                        )
6028                    })
6029                    .flatten()
6030                    .map(|f| {
6031                        totals.set_violation(f.max_violation);
6032                        f.negligible_at_tol
6033                    })
6034            };
6035            match feasible_here {
6036                Some(true) => break,
6037                Some(false) => {}
6038                // Unmeasurable model: fall back to the historical
6039                // slack-sum test rather than looping to the cap.
6040                None if slack_sum.is_finite() && slack_sum <= slack_tol => break,
6041                None => {}
6042            }
6043            if rho >= rho_max {
6044                break;
6045            }
6046            // BNW steering: ρ_new = max(ρ·factor, τ·‖y_eq‖∞ + ε)
6047            let geom = rho * factor;
6048            let steer = tau * y_eq_inf + 1.0e-12;
6049            rho = geom.max(steer).min(rho_max);
6050        }
6051
6052        // gh#987 item 6: total iterations and the per-pass summary.
6053        totals.apply(&mut self.statistics.borrow_mut());
6054
6055        // Forward to the user's inner.finalize_solution exactly once.
6056        let w = wrapper_rc.borrow();
6057        if w.has_solution() {
6058            let x_trunc: Vec<Number> = w.last_x_trunc().to_vec();
6059            let lambda: Vec<Number> = w.last_lambda().to_vec();
6060            let z_l: Vec<Number> = w.last_z_l_trunc().to_vec();
6061            let z_u: Vec<Number> = w.last_z_u_trunc().to_vec();
6062            let solver_status = w.last_status().unwrap_or(SolverReturn::InternalError);
6063            let slack_sum = w.last_slack_sum();
6064            drop(w);
6065
6066            // Recompute f(x*) and c(x*) on the inner. Both are needed
6067            // before the status is decided, because the status now turns
6068            // on the *original-space* feasibility at this point.
6069            let f_inner = tnlp
6070                .borrow_mut()
6071                .eval_f(&x_trunc, true)
6072                .unwrap_or(Number::NAN);
6073            let m = tnlp
6074                .borrow_mut()
6075                .get_nlp_info()
6076                .map(|i| i.m as usize)
6077                .unwrap_or(0);
6078            // The success flag decides whether `g_inner` is a measurement
6079            // or a zero-filled buffer. Dropping it would let a TNLP whose
6080            // final `eval_g` fails fabricate feasibility: every row would
6081            // read `0`, `original_space_feasibility` would return a
6082            // violation of zero, and that would flow into both the exit
6083            // status and the reported residuals. Gate it exactly as the
6084            // ρ-escalation measurement above does, so an evaluation
6085            // failure produces `None` and follows the documented
6086            // `l1_slack_tol` fallback instead (gh#794 review).
6087            let mut g_inner = vec![0.0; m];
6088            let g_evaluated = m == 0 || tnlp.borrow_mut().eval_g(&x_trunc, false, &mut g_inner);
6089
6090            // gh#794 P1. Everything below used to argue from `Σ(p + n)`,
6091            // the sum of the augmented slacks, judged against
6092            // `l1_slack_tol`. That is not the user's constraint
6093            // violation and it is not judged by the user's tolerance:
6094            //
6095            //   * the violation of equality row `i` is `|p_i − n_i|`,
6096            //     not `p_i + n_i`, and at the barrier's interior both
6097            //     slacks stay positive where their difference is zero,
6098            //     so the sum is an upper bound that is loose in one
6099            //     direction; and
6100            //   * `l1_slack_tol` defaults to `1e-6`, four orders looser
6101            //     than a `tol = 1e-8` solve asked for, so a violation
6102            //     that the solver's own strict gate would refuse on the
6103            //     unwrapped problem read as "the constraints are
6104            //     satisfied".
6105            //
6106            // Measured, not argued: the MPCC benchmark's `ralph1`
6107            // (`benchmarks/mpcc/`) returned `Solve_Succeeded` at a point
6108            // violating its one equality row by `2.5e-07`, with the
6109            // reported `final_constr_viol` — the *augmented* residual —
6110            // at `9.6e-15`, so no field in the result disclosed it. The
6111            // objective came back `5.0e-04` below the true optimum,
6112            // which is reachable only off the feasible set.
6113            //
6114            // So: measure the user's own rows at the returned point, and
6115            // judge them by the tolerances the caller set. The slack sum
6116            // keeps its other job unchanged — it is the BNW steering
6117            // signal for ρ escalation inside the loop above, which is
6118            // what it is the right quantity for.
6119            let feas = g_evaluated
6120                .then(|| {
6121                    original_space_feasibility(
6122                        &tnlp,
6123                        &x_trunc,
6124                        &g_inner,
6125                        self.nlp_lower_bound_inf(),
6126                        self.nlp_upper_bound_inf(),
6127                        self.user_tol(),
6128                        self.user_acceptable_tol(),
6129                        self.user_constr_viol_tol(),
6130                        self.user_acceptable_constr_viol_tol(),
6131                        self.user_primal_noise_floor_kappa(),
6132                    )
6133                })
6134                .flatten();
6135
6136            // The reported constraint violation must be the user's, not
6137            // the augmented problem's. Without this the KKT block of a
6138            // successful ℓ₁ solve describes a problem the caller never
6139            // posed. The aggregate errors take a `max` rather than a
6140            // rewrite: the NLP error's primal term enters undivided, so
6141            // the aggregate is never below the constraint violation, and
6142            // the other two components are unaffected by the wrapper.
6143            //
6144            // `f.max_violation` is measured on the inner TNLP's own rows
6145            // and bounds, so it is in the model's **original units**. That
6146            // decides which field family may carry it. `SolveStatistics`
6147            // documents `final_*` as the max-norms in the internally
6148            // scaled NLP space and `final_unscaled_*` as the same
6149            // residuals with the scaling divided back out — equal only
6150            // when no scaling is active — and `docs/src/python.md` states
6151            // the same contract to Python callers. Writing an
6152            // original-units number into `final_constr_viol` would break
6153            // it on any run with `nlp_scaling_method` engaged (gh#794
6154            // review).
6155            //
6156            // So the unscaled family always takes the measurement, and
6157            // the scaled family mirrors it exactly when per-row scaling
6158            // did not engage — the case in which the contract requires
6159            // the two to agree anyway. Under active row scaling the
6160            // scaled fields keep what the inner solve reported; the
6161            // converted number is not available here, because the
6162            // augmented problem's row-scale factors belong to an NLP that
6163            // `optimize_constrained` has already dropped. The status
6164            // decision below does not read these fields — it reads
6165            // `feas` directly — so an active-scaling run is judged on the
6166            // user's rows either way.
6167            // gh#987 (remaining item b): `final_declared_constr_viol` is the
6168            // violation of the model AS THE USER DECLARED IT. The inner
6169            // solve's value describes the wrapper's augmented rows, where
6170            // the elastic slacks absorb any violation, so it read ~1e-12
6171            // even at an infeasible point. Overwrite it with the measurement
6172            // on the user's own rows and box (original units, the same
6173            // quantity the non-l1 path reports); `NaN` when the model could
6174            // not be evaluated, never the augmented number.
6175            self.statistics.borrow_mut().final_declared_constr_viol =
6176                feas.as_ref().map_or(Number::NAN, |f| f.max_violation);
6177            if let Some(f) = feas.as_ref() {
6178                let scaled_may_mirror = self.row_scaling_active.get() == Some(false);
6179                let mut stats = self.statistics.borrow_mut();
6180                stats.final_unscaled_constr_viol = f.max_violation;
6181                stats.final_unscaled_kkt_error =
6182                    stats.final_unscaled_kkt_error.max(f.max_violation);
6183                if scaled_may_mirror {
6184                    stats.final_constr_viol = f.max_violation;
6185                    stats.final_kkt_error = stats.final_kkt_error.max(f.max_violation);
6186                    stats.final_kkt_error_above_noise =
6187                        stats.final_kkt_error_above_noise.max(f.max_violation);
6188                }
6189            }
6190
6191            let inner_claimed_success = matches!(
6192                last_status,
6193                ApplicationReturnStatus::SolveSucceeded
6194                    | ApplicationReturnStatus::SolvedToAcceptableLevel
6195            );
6196
6197            // Downgrade, not upgrade: a solve that reached the strict
6198            // standard on the user's own rows keeps whatever status the
6199            // inner gave it, and nothing here can turn a failure into a
6200            // success.
6201            let downgrade_to_acceptable = inner_claimed_success
6202                && feas
6203                    .as_ref()
6204                    .is_some_and(|f| !f.negligible_at_tol && f.negligible_at_acceptable);
6205
6206            let infeasible_certificate = inner_claimed_success
6207                && match feas.as_ref() {
6208                    // Measured: the point does not satisfy the user's
6209                    // constraints even to `acceptable_tol`.
6210                    Some(f) => !f.negligible_at_acceptable,
6211                    // Unmeasurable model — fall back to the historical
6212                    // slack-sum argument rather than to silence.
6213                    None => slack_sum.is_finite() && slack_sum > slack_tol,
6214                };
6215
6216            if let Some(f) = feas.as_ref()
6217                && inner_claimed_success
6218                && !f.negligible_at_tol
6219            {
6220                tracing::info!(
6221                    target: "pounce::application",
6222                    "l1 penalty-barrier: the inner solve converged the augmented NLP, \
6223                     but the returned point violates the model's own constraints by \
6224                     {:.3e}, which does not meet tol; reporting {} rather than success \
6225                     (gh#794)",
6226                    f.max_violation,
6227                    if f.negligible_at_acceptable {
6228                        "Solved_To_Acceptable_Level"
6229                    } else {
6230                        "an infeasibility verdict"
6231                    },
6232                );
6233            }
6234            // …unless the model's own starting point satisfies every
6235            // constraint, which disproves the certificate outright (gh #379).
6236            // Same gate as the IPM and SQP paths; see
6237            // `withdraw_infeasibility_if_refuted`.
6238            let refuted = infeasible_certificate
6239                && withdraw_infeasibility_if_refuted(
6240                    &tnlp,
6241                    SolverReturn::LocalInfeasibility,
6242                    self.nlp_lower_bound_inf(),
6243                    self.nlp_upper_bound_inf(),
6244                    self.user_tol(),
6245                ) != SolverReturn::LocalInfeasibility;
6246            let final_solver_status = match (infeasible_certificate, refuted) {
6247                (true, false) => SolverReturn::LocalInfeasibility,
6248                // The point is not feasible, so `Solve_Succeeded` would be
6249                // just as wrong as `Infeasible_Problem_Detected`. Report the
6250                // breakdown.
6251                (true, true) => SolverReturn::ErrorInStepComputation,
6252                (false, _) if downgrade_to_acceptable => SolverReturn::StopAtAcceptablePoint,
6253                (false, _) => solver_status,
6254            };
6255            let final_app_status = match (infeasible_certificate, refuted) {
6256                (true, false) => ApplicationReturnStatus::InfeasibleProblemDetected,
6257                (true, true) => ApplicationReturnStatus::ErrorInStepComputation,
6258                (false, _) if downgrade_to_acceptable => {
6259                    ApplicationReturnStatus::SolvedToAcceptableLevel
6260                }
6261                (false, _) => last_status,
6262            };
6263
6264            tnlp.borrow_mut().finalize_solution(
6265                Solution {
6266                    status: final_solver_status,
6267                    x: &x_trunc,
6268                    z_l: &z_l,
6269                    z_u: &z_u,
6270                    g: &g_inner,
6271                    lambda: &lambda,
6272                    obj_value: f_inner,
6273                },
6274                &TnlpIpoptData::default(),
6275                &TnlpIpoptCq::default(),
6276            );
6277            return Some(final_app_status);
6278        }
6279        // No solution captured at all — pass the inner status through.
6280        Some(last_status)
6281    }
6282
6283    /// Constrained-NLP path: build adapter → OrigIpoptNlp → algorithm
6284    /// bundle, run `optimize`, populate statistics, and call
6285    /// `finalize_solution` on the user's TNLP.
6286    /// Whether an over-determined model (more equality rows than free
6287    /// variables) is *provably* infeasible by linear bound propagation.
6288    ///
6289    /// Consulted only on the `NotEnoughDegreesOfFreedom` failure path, where
6290    /// the solve never runs and therefore can never itself discover the
6291    /// infeasibility (gh#387). Builds a throwaway presolve wrapper with only
6292    /// Phase 1 (bound tightening) enabled and asks it for a certified proof —
6293    /// this inherits the certification safety net wholesale: the crossing must
6294    /// exceed the solver's own acceptance margin at the crossed pair's scale,
6295    /// and a concrete witness point satisfying every constraint withdraws the
6296    /// verdict. A `false` here costs nothing but keeping the DOF error.
6297    ///
6298    /// The witness gate runs under [`pounce_presolve::WitnessRule`]'s
6299    /// `DeclaredRowRelative` form, which is admissible only because the solve
6300    /// cannot run on this path (gh#391) — see the comment on the probe below.
6301    ///
6302    /// Deliberately independent of the `presolve` master switch: this is not a
6303    /// model transformation (the wrapper is dropped without solving through
6304    /// it), it is a last check before reporting a structural error for a
6305    /// problem whose verdict is already decided.
6306    fn overdetermined_model_certified_infeasible(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> bool {
6307        let mut opts = pounce_presolve::PresolveOptions::from_options_list(&self.options)
6308            .unwrap_or_else(|_| pounce_presolve::PresolveOptions::defaults());
6309        opts.enabled = true;
6310        opts.bound_tightening = true;
6311        // Certification needs Phase 1 only; every transformative or
6312        // diagnostic phase is dead weight on a wrapper that is never
6313        // solved through.
6314        opts.auxiliary = false;
6315        opts.fbbt = false;
6316        opts.redundant_constraint_removal = false;
6317        opts.licq_check = false;
6318        opts.warm_z_bounds = false;
6319        // The one place the witness rule is raised off the solver's own
6320        // acceptance test (gh#391). It is sound *here specifically* because the
6321        // gate has already established the solve cannot run: the alternative to
6322        // the proof is the structural 5xx error, never `Solve_Succeeded`, so
6323        // the #380 "two routes, two answers" contradiction the clamp exists to
6324        // prevent has no second route to contradict. See `WitnessRule` for the
6325        // full argument and the homogeneous-row fallback.
6326        let mut probe =
6327            pounce_presolve::PresolveTnlp::new(Rc::clone(tnlp), opts).probing_without_a_solve();
6328        if probe.get_nlp_info().is_none() {
6329            return false;
6330        }
6331        probe.certified_infeasible().is_some()
6332    }
6333
6334    fn optimize_constrained(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
6335        let t_start = Instant::now();
6336
6337        // Invalidate the row-scaling record before anything can read it.
6338        //
6339        // It is written near the end of this function, from the NLP the
6340        // solve actually built, so a solve that bails before that point
6341        // leaves whatever the *previous* one recorded. The ℓ₁ outer loop
6342        // calls this repeatedly and reads the flag after each call, so a
6343        // stale `Some(false)` would let it mirror an original-units
6344        // violation into the scaled family — the exact contract this flag
6345        // exists to protect (gh#794 review round 2). Clearing it here
6346        // makes the failure mode fail-closed: "not recorded" reads as
6347        // "cannot mirror", never as "scaling was off".
6348        self.row_scaling_active.set(None);
6349        // gh#983 review item 1: the structured warnings describe the run whose
6350        // point is returned, so each attempt starts with none. They used to
6351        // accumulate on the application for its lifetime, and a promoted
6352        // gh#884 retry (`Solve_Succeeded` at `du = 1.6e-7`) carried the
6353        // discarded base attempt's `large_dual_scale ... 1.43e9`. A declined
6354        // retry restores the floored attempt's own list via
6355        // `SolutionCertificate`.
6356        self.statistics.borrow_mut().warnings.clear();
6357        self.statistics
6358            .borrow_mut()
6359            .returned_run_dual_divergence_signature = false;
6360
6361        // `print_user_options yes` — dump the OptionsList before the
6362        // solve. Mirrors `IpoptApplication::call_optimize` (upstream
6363        // calls `Jnlst().Printf(.., "%s", options_->PrintUserOptions())`).
6364        let print_opts = self
6365            .options
6366            .get_bool_value("print_user_options", "")
6367            .ok()
6368            .and_then(|(v, f)| f.then_some(v))
6369            .unwrap_or(false);
6370        if print_opts {
6371            print!(
6372                "\nList of user-set options:\n\n{}",
6373                self.options.print_user_options()
6374            );
6375        }
6376
6377        // `print_options_documentation yes` — dump the full registry
6378        // (every option with type, default, valid range/strings, and
6379        // long description) before the solve. Honors
6380        // `print_options_mode` (`text` / `latex` / `doxygen`; only
6381        // `text` is implemented today, the others fall through with a
6382        // one-line note) and `print_advanced_options`. Mirrors
6383        // upstream `IpoptApplication::call_optimize`'s
6384        // `print_options_documentation` branch and `Common/IpRegOptions.cpp`
6385        // `OutputOptionDocumentation`.
6386        let print_doc = self
6387            .options
6388            .get_bool_value("print_options_documentation", "")
6389            .ok()
6390            .and_then(|(v, f)| f.then_some(v))
6391            .unwrap_or(false);
6392        if print_doc {
6393            let mode = self
6394                .options
6395                .get_string_value("print_options_mode", "")
6396                .ok()
6397                .map(|(v, _)| PrintOptionsMode::from_tag(&v))
6398                .unwrap_or(PrintOptionsMode::Text);
6399            let advanced = self
6400                .options
6401                .get_bool_value("print_advanced_options", "")
6402                .ok()
6403                .map(|(v, _)| v)
6404                .unwrap_or(false);
6405            print!(
6406                "\n# Pounce options registry\n\n{}",
6407                self.reg_options.print_options_documentation(mode, advanced)
6408            );
6409        }
6410
6411        // Mint a fresh `TimingStatistics` for this solve — shared (via
6412        // `Rc`) with the data and the NLP below so every `eval_*` and
6413        // every iterate-phase records into the same accumulator. The
6414        // application keeps its own `Rc` so callers can read totals out
6415        // via [`Self::timing_stats`].
6416        let timing = Rc::new(TimingStatistics::new());
6417        *self.timing.borrow_mut() = Rc::clone(&timing);
6418        // gh#606: same lifetime as the timings — a solve that bails out
6419        // before the initializer runs must not report the previous
6420        // solve's warm-start verdict.
6421        *self.warm_start_diag.borrow_mut() = None;
6422        // Gate the *detailed* per-subsystem timers on `timing_statistics`
6423        // (default "no"), matching upstream Ipopt. Without this, every
6424        // timed `eval_*` / phase section pays two `getrusage` syscalls per
6425        // start/end even when statistics are off — 16-20% of busy CPU on
6426        // fast-objective NLPs (issue #190). `print_timing_statistics=yes`
6427        // implies `timing_statistics=yes` (per its option help), so either
6428        // one enables the detailed timers. `overall_alg` is started
6429        // unconditionally below: it feeds the `max_cpu_time` check and is
6430        // reported regardless of the option.
6431        //
6432        // Each name is read as a literal rather than looped over an
6433        // array: the registered-but-unread scan
6434        // (`tests/no_silent_options.rs`) keys on the option name as it
6435        // appears at the accessor, so a loop variable reads as "no key
6436        // here" and hid `timing_statistics` among the silent options
6437        // when it has been wired since #190 (#677, #551).
6438        let read_yes = |key: &str| -> bool {
6439            self.options
6440                .get_bool_value(key, "")
6441                .ok()
6442                .and_then(|(v, f)| f.then_some(v))
6443                .unwrap_or(false)
6444        };
6445        let timing_enabled = read_yes("timing_statistics") || read_yes("print_timing_statistics");
6446        timing.set_detailed_enabled(timing_enabled);
6447        timing.overall_alg.start();
6448
6449        // Reset the linear-solver summary sink so back-to-back solves
6450        // don't bleed factor counters / extremal pivots into each
6451        // other. Surviving the lock failure with a debug-assert keeps
6452        // a poisoned mutex from sinking a release build that doesn't
6453        // even consume the summary.
6454        for sink in [&self.linsol_summary_sink, &self.resto_linsol_summary_sink] {
6455            match sink.lock() {
6456                Ok(mut guard) => {
6457                    *guard = LinearSolverSummary::default();
6458                }
6459                _ => {
6460                    debug_assert!(false, "linsol summary sink mutex poisoned");
6461                }
6462            }
6463        }
6464        // Same reasoning for the quality-escalation tally (gh#857): the
6465        // number belongs to this solve, not to whatever ran before it.
6466        self.quality_escalations.set(0);
6467        // And for the published partition: back-to-back solves on one
6468        // application can differ in which variables are fixed, so last
6469        // solve's labels must not describe this solve's KKT. Cleared here and
6470        // written again below only if this solve resolves one.
6471        if let Ok(mut g) = self.kkt_blocks_published.lock() {
6472            *g = None;
6473        }
6474
6475        // Build adapter + Nlp. Honor `fixed_variable_treatment` (default
6476        // `make_parameter`; pounce additionally implements `relax_bounds`,
6477        // which the adapter also auto-selects as a fallback when
6478        // `make_parameter` would leave `n_x_var < n_c` — mirrors upstream
6479        // `IpTNLPAdapter.cpp:623-633`).
6480        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
6481        let adapter = match TNLPAdapter::new_with_options(
6482            Rc::clone(&tnlp),
6483            lo_inf,
6484            up_inf,
6485            fixed_treatment,
6486        ) {
6487            Ok(a) => Rc::new(RefCell::new(a)),
6488            Err(_) => {
6489                timing.overall_alg.end();
6490                return ApplicationReturnStatus::InvalidProblemDefinition;
6491            }
6492        };
6493        // Carry the user's constant `obj_scaling_factor` (default 1.0;
6494        // negative ⇒ maximize) into the NLP. Until pounce#128's
6495        // follow-up this option was registered but never read, so it
6496        // was silently a no-op — maximization diverged because the
6497        // algorithm minimized the unscaled objective.
6498        let obj_scaling_factor = self
6499            .options
6500            .get_numeric_value("obj_scaling_factor", "")
6501            .ok()
6502            .and_then(|(v, f)| f.then_some(v))
6503            .unwrap_or(1.0);
6504        let mut orig_nlp = match OrigIpoptNlp::new(
6505            Rc::clone(&adapter),
6506            Rc::new(ConstObjScaling(obj_scaling_factor)),
6507        ) {
6508            Ok(n) => n,
6509            Err(_) => {
6510                timing.overall_alg.end();
6511                return ApplicationReturnStatus::InternalError;
6512            }
6513        };
6514        orig_nlp.set_timing_stats(Rc::clone(&timing));
6515        // Q6: decide which derivatives may be reused across iterates,
6516        // before anything is evaluated (gh #588).
6517        self.install_constant_derivative_hints(&mut orig_nlp);
6518
6519        // Mirror upstream `OrigIpoptNLP::InitializeStructures` (IpOrigIpoptNLP.cpp:299):
6520        // bail out with NotEnoughDegreesOfFreedom when there are fewer free
6521        // variables than equality constraints. Without this gate, square /
6522        // over-determined systems push the algorithm into restoration on
6523        // iter 0 and exit Restoration_Failed instead of the cleaner DOF code.
6524        let n_x_var = orig_nlp.x_space().dim();
6525        let n_c = orig_nlp.c_space().dim();
6526        if n_x_var > 0 && n_x_var < n_c {
6527            timing.overall_alg.end();
6528            // An over-determined system can still be *provably* infeasible —
6529            // `x == 0.2` with `x == 0.8` is about as provable as infeasibility
6530            // gets — and for such a model the structural DOF error is the
6531            // strictly weaker answer: it reports "cannot attempt this" for a
6532            // problem whose verdict is already decided (gh#387). The DOF gate
6533            // fires before any iteration runs, so nothing downstream will ever
6534            // get the chance to detect the infeasibility; check for a
6535            // bound-propagation proof here, on the rare failure path only.
6536            // The probe reuses presolve's full certification pipeline
6537            // (crossing margin + witness refutation), so a model the solver
6538            // would accept as feasible at its own tolerance is never upgraded
6539            // to "proved infeasible" — those still report the DOF error.
6540            if self.overdetermined_model_certified_infeasible(&tnlp) {
6541                use pounce_common::journalist::JournalCategory;
6542                self.journalist.print(
6543                    JournalLevel::J_SUMMARY,
6544                    JournalCategory::J_MAIN,
6545                    "\nEXIT: Problem has too few degrees of freedom, and bound \
6546                     propagation proves its constraints inconsistent.\n\
6547                     No feasible point exists; the solve was not run.\n",
6548                );
6549                return ApplicationReturnStatus::InfeasibleProblemDetected;
6550            }
6551            return ApplicationReturnStatus::NotEnoughDegreesOfFreedom;
6552        }
6553
6554        // Relax `x_L / x_U / d_L / d_U` by `bound_relax_factor` (default
6555        // 1e-8), capped by `constr_viol_tol` (default 1e-4). Matches
6556        // `OrigIpoptNLP::InitializeStructures` lines 343-358.
6557        let bound_relax_factor = self
6558            .options
6559            .get_numeric_value("bound_relax_factor", "")
6560            .ok()
6561            .and_then(|(v, f)| f.then_some(v))
6562            .unwrap_or(1e-8);
6563        let constr_viol_tol = self
6564            .options
6565            .get_numeric_value("constr_viol_tol", "")
6566            .ok()
6567            .and_then(|(v, f)| f.then_some(v))
6568            .unwrap_or(1e-4);
6569        if self.retry_keeps_declared_box.get() {
6570            orig_nlp.relax_bounds_keeping_box(bound_relax_factor, constr_viol_tol);
6571        } else {
6572            orig_nlp.relax_bounds(bound_relax_factor, constr_viol_tol);
6573        }
6574
6575        // `honor_original_bounds` (default `no`, matching upstream):
6576        // project the reported point back into the un-relaxed box. Must
6577        // follow `relax_bounds`, which snapshots the bounds to project
6578        // onto. Registered but never read before, so a user asking for
6579        // it still got a bound-pinned solution sitting up to
6580        // `min(bound_relax_factor·max(1,|b|), constr_viol_tol)` outside
6581        // its own bounds (gh#483 follow-up).
6582        let honor_original_bounds = self
6583            .options
6584            .get_bool_value("honor_original_bounds", "")
6585            .ok()
6586            .and_then(|(v, f)| f.then_some(v))
6587            .unwrap_or(false);
6588        orig_nlp.set_honor_original_bounds(honor_original_bounds);
6589
6590        // Apply automatic NLP scaling per `nlp_scaling_method` option
6591        // (port of `OrigIpoptNLP::InitializeStructures` →
6592        // `NLPScalingObject::DetermineScaling`). Default is
6593        // `gradient-based` to match upstream Ipopt 3.14.
6594        let scaling_method = self
6595            .options
6596            .get_string_value("nlp_scaling_method", "")
6597            .ok()
6598            .and_then(|(v, f)| f.then_some(v))
6599            .unwrap_or_else(|| "gradient-based".to_string());
6600        let scaling_method = match scaling_method.as_str() {
6601            "none" => ScalingMethod::None,
6602            "gradient-based" => ScalingMethod::GradientBased,
6603            // `curvature-based` computes the factors from the model's
6604            // quadratic coefficients and hands them back through
6605            // `TNLP::get_scaling_parameters` (gh #703), so from the
6606            // engine's side it *is* user scaling — the only difference is
6607            // who filled the vectors in.
6608            "user-scaling" | "curvature-based" => ScalingMethod::UserScaling,
6609            // `equilibration-based` is registered upstream but not yet
6610            // implemented in pounce; fall back to gradient-based (the
6611            // upstream default) to keep behavior predictable.
6612            _ => ScalingMethod::GradientBased,
6613        };
6614        let max_gradient = self
6615            .options
6616            .get_numeric_value("nlp_scaling_max_gradient", "")
6617            .ok()
6618            .and_then(|(v, f)| f.then_some(v))
6619            .unwrap_or(100.0);
6620        let min_value = self
6621            .options
6622            .get_numeric_value("nlp_scaling_min_value", "")
6623            .ok()
6624            .and_then(|(v, f)| f.then_some(v))
6625            .unwrap_or(1e-8);
6626        let obj_target_gradient = self
6627            .options
6628            .get_numeric_value("nlp_scaling_obj_target_gradient", "")
6629            .ok()
6630            .and_then(|(v, f)| f.then_some(v))
6631            .unwrap_or(0.0);
6632        let constr_target_gradient = self
6633            .options
6634            .get_numeric_value("nlp_scaling_constr_target_gradient", "")
6635            .ok()
6636            .and_then(|(v, f)| f.then_some(v))
6637            .unwrap_or(0.0);
6638        orig_nlp.determine_scaling_from_starting_point(
6639            scaling_method,
6640            max_gradient,
6641            min_value,
6642            obj_target_gradient,
6643            constr_target_gradient,
6644        );
6645
6646        let nlp_handle: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
6647
6648        // Build the algorithm strategy bundle. Read coarse knobs from
6649        // the OptionsList where we have them; fall through to defaults
6650        // otherwise. The full upstream parsing surface (mu_strategy,
6651        // hessian_approximation, line_search_method, ...) is wired by
6652        // `AlgBuilder::RegisterOptions` in upstream — that registry
6653        // hookup lands as a follow-up; default builder is correct for
6654        // HS71-class problems.
6655        let mut builder = self.algorithm_builder_from_options();
6656
6657        // The objective element's support for the partitioned Hessian.
6658        // Every constraint element reads its support off a Jacobian row;
6659        // only the objective has none declared, so without this the
6660        // updater falls back to the first `∇f`'s nonzeros — a
6661        // value-derived pattern. See
6662        // `TNLPAdapter::objective_nonlinear_vars`.
6663        if matches!(
6664            builder.hessian_approximation,
6665            HessianApproxChoice::Partitioned | HessianApproxChoice::FiniteDifference
6666        ) {
6667            builder.objective_nonlinear_vars = adapter.borrow().objective_nonlinear_vars();
6668        }
6669        // gh#989 item 5: the declared Lagrangian Hessian structure splits the
6670        // partitioned elements into the independent blocks they really are.
6671        if matches!(
6672            builder.hessian_approximation,
6673            HessianApproxChoice::Partitioned
6674        ) {
6675            let declared = !matches!(
6676                self.options.get_string_value("partitioned_structure", ""),
6677                Ok((ref v, true)) if v == "jacobian"
6678            );
6679            if declared {
6680                builder.hessian_declared_pattern = adapter.borrow().lagrangian_hessian_pattern();
6681            }
6682        }
6683
6684        // Which variables the limited-memory Hessian should span (gh#624).
6685        // Upstream's precedence: a TNLP that implements
6686        // `get_number_of_nonlinear_variables` wins, and
6687        // `num_linear_variables` is only the contiguous-prefix fallback.
6688        // Exact-Hessian solves never consult either.
6689        if matches!(
6690            builder.hessian_approximation,
6691            HessianApproxChoice::LimitedMemory | HessianApproxChoice::FiniteDifference
6692        ) {
6693            let num_linear_variables = self
6694                .options
6695                .get_integer_value("num_linear_variables", "")
6696                .ok()
6697                .and_then(|(v, f)| f.then_some(v))
6698                .unwrap_or(0);
6699            match adapter
6700                .borrow()
6701                .quasi_newton_nonlinear_vars(num_linear_variables)
6702            {
6703                Ok(mask) => builder.limited_memory_nonlinear_vars = mask,
6704                Err(e) => {
6705                    use pounce_common::journalist::JournalCategory;
6706                    self.journalist.print(
6707                        JournalLevel::J_ERROR,
6708                        JournalCategory::J_MAIN,
6709                        &format!("\nEXIT: Invalid nonlinear-variable list: {}\n", e.message),
6710                    );
6711                    timing.overall_alg.end();
6712                    return ApplicationReturnStatus::InvalidProblemDefinition;
6713                }
6714            }
6715        }
6716
6717        // Linear-solver backend. The default factory is option-aware
6718        // — it reads the `feral_*` extension options off the same
6719        // `OptionsList` that drove the IPM-level builder above so
6720        // per-problem `.opt` files can flip backend knobs without
6721        // rebuilding pounce.
6722        let mut feral_cfg = feral_config_from_options(&self.options);
6723        // Block-triangular / Schur KKT partition (pounce#180 item 2). Configure
6724        // the Schur block solvers from the *base* feral cfg: a full-KKT external
6725        // ordering (item 1) is sized for the whole system and cannot apply to
6726        // the A_FF sub-block, so the Schur path keeps the default sub-block
6727        // ordering. `build_with_backend` honors this only on the IPM + feral +
6728        // exact-Hessian path and falls back to the standard solver otherwise.
6729        if let Some(indices) = &self.kkt_schur_block {
6730            builder.set_kkt_schur(indices.clone(), feral_cfg.clone());
6731            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6732        }
6733        // Block-parallel KKT partition (structured-KKT Phase 5b), explicit or
6734        // detected (`kkt_block_detect`).
6735        let detect = matches!(
6736            self.options.get_string_value("kkt_block_detect", ""),
6737            Ok((ref v, true)) if v.eq_ignore_ascii_case("yes")
6738        );
6739        // A model-space declaration (§45) is mapped to KKT indices here, where
6740        // the NLP layout — which variables survived fixing, how constraints
6741        // split into equalities and inequalities — is known.
6742        {
6743            let a = adapter.borrow();
6744            let cls = a.classification();
6745            self.x_elimination = Some((cls.x_not_fixed_map.clone(), cls.n_full_x as usize));
6746        }
6747        let mapped = self.model_blocks.as_ref().and_then(|(v, c)| {
6748            let cls = adapter.borrow().classification().clone();
6749            match map_block_structure_to_kkt(&cls, v, c) {
6750                Ok(l) => Some(l),
6751                Err(e) => {
6752                    tracing::warn!(
6753                        target: "pounce::kkt",
6754                        error = %e,
6755                        "declared block structure does not fit this problem; using the standard solver"
6756                    );
6757                    None
6758                }
6759            }
6760        });
6761        if let Some(labels) = mapped
6762            .or_else(|| self.kkt_blocks.clone())
6763            .or(detect.then(Vec::new))
6764        {
6765            builder.set_kkt_blocks(labels.clone(), feral_cfg.clone());
6766            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6767            // And to the restoration sub-IPM, whose builder was minted before
6768            // this mapping existed. Its reduced system is this one, so the
6769            // same labels apply; see `kkt_blocks_published`. Off with
6770            // `kkt_block_restoration no`, which is how restoration's own
6771            // contribution is measured.
6772            let resto_blocks = !matches!(
6773                self.options.get_string_value("kkt_block_restoration", ""),
6774                Ok((ref v, _)) if v.eq_ignore_ascii_case("no")
6775            );
6776            if resto_blocks {
6777                if let Ok(mut g) = self.kkt_blocks_published.lock() {
6778                    *g = Some((labels, feral_cfg.clone()));
6779                }
6780            }
6781        }
6782        // A caller-supplied KKT permutation (pounce#180 item 1) overrides
6783        // the string-option / env ordering: `OrderingMethod::External`
6784        // can't be expressed through the OptionsList (it carries a
6785        // vector), so it is injected here from the side-channel field.
6786        // Only applies to the workspace-default FERAL backend below; a
6787        // custom `linear_backend_factory` owns its own config.
6788        if let Some(perm) = &self.external_ordering {
6789            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
6790        }
6791        // MA57's knobs come off the same `OptionsList`, at the main-IPM
6792        // prefix. The restoration sub-IPM reads them again under
6793        // `"resto."` when its caller mints the inner backend factory —
6794        // see `ma57_config_from_options`.
6795        let ma57_cfg = ma57_config_from_options(&self.options, "");
6796        // gh#987 item 3: publish the unperturbed trials' inertia next to the
6797        // backend's own per-factorization record.
6798        builder.inertia_sink = Some(Arc::clone(&self.linsol_summary_sink));
6799        let factory = self.linear_backend_factory.take().unwrap_or_else(|| {
6800            default_backend_factory_with_sink(
6801                feral_cfg,
6802                ma57_cfg,
6803                Arc::clone(&self.linsol_summary_sink),
6804            )
6805        });
6806        let bundle = builder.build_with_backend(factory);
6807
6808        // Wire the data / cq pair around the NLP. Install the shared
6809        // `TimingStatistics` so the algorithm's iterate phases
6810        // (output, convergence, hessian, μ, search-direction,
6811        // line-search, accept) all record into the same accumulator
6812        // the application exposes via `timing_stats()`.
6813        let data: crate::ipopt_data::IpoptDataHandle = Rc::new(RefCell::new(AlgIpoptData::new()));
6814        data.borrow_mut().timing = Rc::clone(&timing);
6815        // Install a shared wall/CPU-time deadline (pounce#242) so the time
6816        // budget is honored at the granularity of the expensive inner
6817        // steps — the main loop's KKT factorization / line search and the
6818        // restoration inner IPM — instead of only between outer iterations.
6819        // The `Deadline` starts its clock now (right after `overall_alg`),
6820        // and the restoration sub-solve reuses this same instance, so the
6821        // caller's budget bounds the whole solve rather than each nested
6822        // level independently. The convergence check treats it as
6823        // authoritative when present (see `conv_check::opt_error`).
6824        data.borrow_mut().deadline = Some(pounce_common::timing::Deadline::new(
6825            builder.conv_check.max_wall_time,
6826            builder.conv_check.max_cpu_time,
6827        ));
6828        let cq: crate::ipopt_cq::IpoptCqHandle = Rc::new(RefCell::new(
6829            IpoptCalculatedQuantities::new(Rc::clone(&data), Rc::clone(&nlp_handle)),
6830        ));
6831        // Correction size for very small slacks (default mach_eps^{3/4});
6832        // drives the safe-slack bound-adjustment mechanism.
6833        if let Ok((v, true)) = self.options.get_numeric_value("slack_move", "") {
6834            cq.borrow_mut().slack_move = v;
6835        }
6836        // `kappa_d` — weight of the linear damping term added to the
6837        // barrier objective/gradient to handle one-sided bounds
6838        // (`IpIpoptCalculatedQuantities.cpp`). Registered (default 1e-5)
6839        // but previously never read, so a user override was silently
6840        // ignored (#191). Routed through the builder for parity with the
6841        // other numeric knobs; the default matches the registered
6842        // default, so only explicit overrides change behavior.
6843        cq.borrow_mut().kappa_d = builder.kappa_d;
6844        // `s_max` — cap on the average multiplier magnitude in the
6845        // `(s_d, s_c)` scaling of the KKT error test. Same shape as
6846        // `kappa_d`: registered (default 100) and previously never read,
6847        // so an override was silently ignored (#551 / #677).
6848        cq.borrow_mut().s_max = builder.s_max;
6849
6850        // Seed `data.curr` with a zero-valued iterate of the correct
6851        // dimensions. The `IterateInitializer` consumes these as its
6852        // template (it overwrites `x`, `s`, multipliers in place); we
6853        // just need the dim metadata.
6854        {
6855            let nlp_borrow = nlp_handle.borrow();
6856            let n_x = nlp_borrow.n();
6857            let n_s = nlp_borrow.m_ineq();
6858            let n_yc = nlp_borrow.m_eq();
6859            let n_yd = nlp_borrow.m_ineq();
6860            let n_zl = nlp_borrow.x_l().dim();
6861            let n_zu = nlp_borrow.x_u().dim();
6862            let n_vl = nlp_borrow.d_l().dim();
6863            let n_vu = nlp_borrow.d_u().dim();
6864            drop(nlp_borrow);
6865            let iv = IteratesVector::new(
6866                Rc::new(DenseVectorSpace::new(n_x).make_new_dense()),
6867                Rc::new(DenseVectorSpace::new(n_s).make_new_dense()),
6868                Rc::new(DenseVectorSpace::new(n_yc).make_new_dense()),
6869                Rc::new(DenseVectorSpace::new(n_yd).make_new_dense()),
6870                Rc::new(DenseVectorSpace::new(n_zl).make_new_dense()),
6871                Rc::new(DenseVectorSpace::new(n_zu).make_new_dense()),
6872                Rc::new(DenseVectorSpace::new(n_vl).make_new_dense()),
6873                Rc::new(DenseVectorSpace::new(n_vu).make_new_dense()),
6874            );
6875            data.borrow_mut().set_curr(iv);
6876        }
6877
6878        // Full primal-dual warm restart (debugger `resolve`): if a
6879        // captured iterate is queued, install it onto `data.curr` over
6880        // the placeholder so the `WarmStartIterateInitializer`'s
6881        // re-optimize branch (x already initialized) keeps it and only
6882        // clamps multipliers / sets target_mu — no cold re-seed from the
6883        // NLP. Skipped (with a warning) if the dimensions don't line up,
6884        // e.g. an option changed the problem structure between solves.
6885        if let Some(snap) = self.warm_start_iterate.take() {
6886            let dims_match = {
6887                let borrow = data.borrow();
6888                borrow
6889                    .curr
6890                    .as_ref()
6891                    .map(|c| iterates_dims(c) == iterates_dims(snap.iterates()))
6892                    .unwrap_or(false)
6893            };
6894            if dims_match {
6895                data.borrow_mut().set_curr(snap.iterates().clone());
6896                data.borrow_mut().curr_mu = snap.mu();
6897            } else {
6898                tracing::warn!(
6899                    target: "pounce::warm_start",
6900                    "debugger warm-restart iterate dimensions differ from the fresh \
6901                     solve; ignoring the captured iterate and seeding normally"
6902                );
6903            }
6904        }
6905
6906        let max_iter = self
6907            .options
6908            .get_integer_value("max_iter", "")
6909            .ok()
6910            .and_then(|(v, f)| f.then_some(v))
6911            .unwrap_or(3000);
6912        let tol = self
6913            .options
6914            .get_numeric_value("tol", "")
6915            .ok()
6916            .and_then(|(v, f)| f.then_some(v))
6917            .unwrap_or(1e-8);
6918        data.borrow_mut().tol = tol;
6919
6920        let mut alg = IpoptAlgorithm::new(data, cq, bundle)
6921            .with_nlp(Rc::clone(&nlp_handle))
6922            .with_tnlp(Rc::clone(&tnlp));
6923        alg.last_iter_stats_sink = Some(Rc::clone(&self.last_iter_stats));
6924        alg.live_iterate_fixed_var_duals = self.reports_fixed_var_duals();
6925        // Mint a fresh restoration factory per inner solve if a
6926        // provider is configured (pounce#10 Phase 3). Falls back to
6927        // the legacy one-shot `restoration_factory` slot when no
6928        // provider is set, preserving single-shot caller behavior.
6929        if let Some(provider) = self.restoration_factory_provider.as_mut() {
6930            self.restoration_factory = Some(provider());
6931        }
6932        if let Some(factory) = self.restoration_factory.as_mut() {
6933            alg = alg.with_restoration(factory());
6934        }
6935        if let Some(diag) = self.diagnostics.as_ref() {
6936            alg = alg.with_diagnostics(Rc::clone(diag));
6937        }
6938        // Move the interactive debugger hook (if any) into the main
6939        // algorithm. Taken — not cloned — so it drives exactly this
6940        // solve; a subsequent solve must reinstall it.
6941        if let Some(hook) = self.debug_hook.take() {
6942            alg = alg.with_debug_hook(hook);
6943        }
6944        alg.max_iter = max_iter;
6945        // `kappa_sigma` — factor bounding how far the bound multipliers
6946        // may deviate from their primal estimates; the clamp runs after
6947        // every accepted step (`IpIpoptAlg.cpp`, Eqn. (16)). Registered
6948        // (default 1e10) but previously never read, so a user override —
6949        // including the documented `< 1` "disable the correction" — was
6950        // silently ignored (#191). Routed through the builder; the struct
6951        // default matches the registered default, so default runs are
6952        // unchanged.
6953        alg.kappa_sigma = builder.kappa_sigma;
6954        // `recalc_y` (#677) — see the read site above for why the
6955        // limited-memory path defaults it on.
6956        // `linear_system_scaling=slack-based` (#677) — the only scaling
6957        // choice whose factors depend on the iterate, so the main loop
6958        // has to refresh them. See `IpoptAlgorithm::push_slack_scaling`.
6959        alg.slack_based_scaling = matches!(
6960            builder.linear_system_scaling,
6961            crate::alg_builder::LinearSystemScalingChoice::SlackBased
6962        );
6963        alg.recalc_y = builder.recalc_y;
6964        alg.recalc_y_feas_tol = builder.recalc_y_feas_tol;
6965        // `start_with_resto` — the outer loop is what acts on it. It was
6966        // previously copied only into the restoration sub-solver's own
6967        // builder, which has no first outer iteration to force, so
6968        // setting the option did nothing at all.
6969        alg.start_with_resto = builder.resto.start_with_resto;
6970        // Tiny-step and divergence guards (#191): registered but
6971        // previously never read. Struct defaults match the registered
6972        // defaults, so default runs are unchanged.
6973        alg.tiny_step_tol = builder.tiny_step_tol;
6974        alg.tiny_step_y_tol = builder.tiny_step_y_tol;
6975        alg.diverging_iterates_tol = builder.diverging_iterates_tol;
6976        alg.dual_diverging_streak = builder.dual_diverging_streak.max(0) as usize;
6977        alg.dual_divergence_retry_step_tol = builder.dual_divergence_retry_step_tol;
6978        alg.dual_divergence_retry_du_floor = builder.dual_divergence_retry_du_floor;
6979        alg.resto_decline_deferrals = builder.resto_decline_deferrals.max(0) as usize;
6980        alg.resto_decline_progress_ratio = builder.resto_decline_progress_ratio;
6981        alg.neg_curv_escapes = builder.neg_curv_escapes.max(0) as usize;
6982        alg.lbfgs_ls_failure_restarts = builder.limited_memory_ls_failure_restarts.max(0) as usize;
6983        alg.kkt_fidelity_tol = builder.kkt_fidelity_tol;
6984        // Honor `print_level == 0`: silence the algorithm's direct-to-stdout
6985        // output — the per-iteration table and, new in #206, the
6986        // problem-statistics and end-of-run summary blocks the engine now
6987        // emits itself. Default (unset) or any positive level shows them; the
6988        // CLI's JSON mode forces print_level 0, so structured output stays
6989        // clean. (The Phase-7 journalist surface respects print_level already;
6990        // this is the legacy direct-print site that needs the same gate.)
6991        let console_output = match self.options.get_integer_value("print_level", "") {
6992            Ok((v, true)) => v >= 1,
6993            _ => true,
6994        };
6995        if !console_output {
6996            alg.print_iter_output = false;
6997            // The nested restoration IPM is built inside the restoration
6998            // driver, not by `IpoptAlgorithm::new`, so it never sees this
6999            // gate unless we forward it.
7000            if let Some(resto) = alg.restoration.as_mut() {
7001                resto.set_print_iter_output(false);
7002            }
7003        }
7004
7005        // Problem statistics, Ipopt-style, emitted before the iteration table
7006        // from the engine's own reduced problem (#206). Built from the same
7007        // collect_stats inputs the CLI used, so the block is byte-identical;
7008        // emitting it here means every frontend (CLI, Python, C) and every
7009        // algorithm (IPM, SQP) gets it.
7010        self.emit_problem_stats(&tnlp, console_output);
7011
7012        // Per-iteration history (pounce#71): when requested, capture the
7013        // `pounce::iteration` events emitted during the solve into an
7014        // `IterRecord` trajectory via the observability collector layer.
7015        // This replaces the old in-loop `iter_history` accumulation; it
7016        // requires the collector to be installed in the active
7017        // subscriber (the CLI / Python / C frontends install it via
7018        // `pounce_observability::init_subscriber`; tests call
7019        // `init_for_tests`). The collector scopes out restoration
7020        // sub-solve iterations via the `restoration` span, so the
7021        // trajectory matches the previous behavior (outer iters only).
7022        let iter_capture = self
7023            .record_iter_history
7024            .then(pounce_observability::IterCaptureGuard::start);
7025
7026        let handover_cells = self.install_handover(&mut alg, &nlp_handle);
7027        let solver_status = alg.optimize();
7028        self.finish_handover(&nlp_handle, handover_cells);
7029        // Keep the initializer's feasibility diagnostics reachable
7030        // after the algorithm goes out of scope (gh#605).
7031        self.least_square_init_report = alg.least_square_init_report();
7032
7033        let captured_iters = iter_capture.map(|g| g.finish()).unwrap_or_default();
7034        // Propagate to any enclosing capture (e.g. `with_iter_capture`
7035        // wrapped around a solve with iteration history enabled), whose
7036        // buffer this inner guard would otherwise leave empty.
7037        pounce_observability::extend_active_capture(&captured_iters);
7038        // Close the overall-algorithm timer on the success path. The
7039        // early-return arms above end it themselves before bailing out;
7040        // this one matches upstream `IpoptApplication::call_optimize`
7041        // (which calls `EndCpuTime()` on overall_alg right after
7042        // `Optimize` returns, regardless of solver_status).
7043        timing.overall_alg.end();
7044
7045        // gh#612: opt-in crossover. Runs here — after the algorithm is done
7046        // but BEFORE the statistics drain, the status gates, the
7047        // `on_converged` hook and `finalize_via_orig_nlp` — so that when it
7048        // accepts, every one of those describes the point actually returned.
7049        // Placing it later would mean reporting residuals for an iterate the
7050        // user is not given, and would hide the exact active set from the
7051        // post-optimal sensitivity hook, which is the first of the three
7052        // consumers this exists for.
7053        self.maybe_crossover(&mut alg, &nlp_handle, solver_status);
7054
7055        // Drain counters / iter count off the algorithm.
7056        {
7057            let mut stats = self.statistics.borrow_mut();
7058            {
7059                let d = alg.data.borrow();
7060                stats.iteration_count = d.iter_count;
7061                // Converged barrier parameter μ — threaded forward into a
7062                // warm-started corrector's `mu_init` / `warm_start_target_mu`
7063                // for predictor–corrector path following (pounce#86).
7064                stats.final_mu = d.curr_mu;
7065            }
7066            // gh#606: the warm-start initializer's verdict on what the
7067            // caller supplied. Lifted off the (solve-local) data handle
7068            // so it outlives the solve; `None` on a cold start.
7069            *self.warm_start_diag.borrow_mut() = alg.data.borrow().warm_start_diagnostics.clone();
7070            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
7071            // Restoration-phase audit counters (pounce#12). Zero on
7072            // problems where restoration never fires; populated by
7073            // `IpoptAlgorithm::invoke_restoration`.
7074            // Finite-difference Hessian census (gh#823 review). `None` on
7075            // every other updater, which leaves the `-1` sentinel in
7076            // place and says "this mode did not run" rather than "it ran
7077            // and found nothing".
7078            if let Some(fd) = alg.bundle.hess.fd_hessian_stats() {
7079                use crate::hess::fd_hessian::FdPatternSource;
7080                stats.fd_hessian_pattern_used = match fd.pattern_used {
7081                    Some(FdPatternSource::Declared) => 0,
7082                    Some(FdPatternSource::Jacobian) => 1,
7083                    None => -1,
7084                };
7085                stats.fd_hessian_nnz = fd.nnz as Index;
7086                stats.fd_hessian_n = fd.n as Index;
7087                stats.fd_hessian_groups = fd.groups as Index;
7088                stats.fd_hessian_rho_max = fd.rho_max as Index;
7089                stats.fd_hessian_coloring_fell_back = fd.coloring_fell_back;
7090                stats.fd_hessian_objective_clique_widened = fd.objective_clique_widened;
7091            }
7092            stats.restoration_calls = alg.resto_calls;
7093            stats.restoration_inner_iters = alg.resto_inner_iters;
7094            stats.restoration_outer_iters = alg.resto_outer_iters;
7095            stats.restoration_wall_secs = alg.resto_wall_secs;
7096            // gh#857. Read off the shared cell rather than the algorithm's
7097            // own `PdFullSpaceSolver`, so restoration sub-solves — which
7098            // run their own solver instance — are included.
7099            stats.quality_escalations = self.quality_escalations.get() as Index;
7100            // gh#1042: which `Restoration_Failed` this is, for the ladder.
7101            stats.unreleased_handback_exit = alg.unreleased_handback_exit();
7102            // gh#884. Read off the algorithm that just ran, so
7103            // `run_with_dual_divergence_retry` — which sits above this
7104            // call — can see what it observed.
7105            self.dual_divergence_signature
7106                .set(self.dual_divergence_signature.get() || alg.dual_divergence_signature());
7107            stats.dual_divergence_signature = self.dual_divergence_signature.get();
7108            stats.returned_run_dual_divergence_signature = alg.dual_divergence_signature();
7109            stats.dual_divergence_retry_promoted = self.dual_divergence_retry_promoted.get();
7110            stats.mu_strategy_fallback = self.mu_strategy_fallback_record.borrow().clone();
7111            stats.derivative_check = self.derivative_check.borrow().clone();
7112            let (rs, ra) = self.obj_scale_refused.get();
7113            self.obj_scale_refused.set((
7114                rs || alg.obj_scale_certificate_refused(),
7115                ra || alg.obj_scale_acceptable_refused(),
7116            ));
7117            stats.obj_scale_certificate_refused = self.obj_scale_refused.get().0;
7118            stats.obj_scale_acceptable_refused = self.obj_scale_refused.get().1;
7119            stats.iterations = captured_iters;
7120            // A refused starting point does not produce a valid iterate.
7121            // Leave final objective/residual fields at their NaN defaults.
7122            // Capture the final *scaled* objective at the algorithm's
7123            // (compressed `x_var`-space) iterate via the NLP: the
7124            // algorithm-side `eval_f` returns `f * obj_scale_factor`.
7125            // `final_objective` is seeded with it only as a best-effort
7126            // fallback; the success path below overwrites it with the
7127            // true unscaled objective from `finalize_via_orig_nlp`
7128            // (which evaluates the user TNLP directly).
7129            if solver_status != SolverReturn::InvalidProblemDefinition {
7130                let curr_x = alg.data.borrow().curr.as_ref().map(|c| c.x.clone());
7131                if let Some(x) = curr_x {
7132                    if let Ok(f) = try_eval_curr_f(&nlp_handle, &x) {
7133                        stats.final_objective = f;
7134                        stats.final_scaled_objective = f;
7135                    }
7136                }
7137                // Final residuals straight off the cq cache. These mirror
7138                // the values upstream prints in its end-of-run summary
7139                // ("Dual infeasibility / Constraint violation /
7140                // Complementarity / Overall NLP error").
7141                let cq = alg.cq.borrow();
7142                stats.final_dual_inf = cq.curr_dual_infeasibility_max();
7143                // Stays on the *internal* measure deliberately: the summary's
7144                // "Overall NLP error" is `curr_nlp_error`, and it is built from
7145                // this same `max(||c||, ||d - s||)`. Switching the violation line
7146                // alone to the original-NLP measure
7147                // (`curr_unscaled_nlp_constraint_violation_max`, now used by the
7148                // `inf_pr` column) would leave the block self-inconsistent —
7149                // an error larger than the max of its own components. Making
7150                // them agree means deciding whether *convergence* should be
7151                // judged on the original NLP, which is a behaviour change for
7152                // every model, not a reporting fix. See pounce#476.
7153                //
7154                // NOTE (gh #528): "Overall NLP error" is no longer the number
7155                // the strict gate tests. That gate judges
7156                // `curr_nlp_error_above_primal_noise` — the same aggregate with
7157                // each row's residual counted only above what it can represent
7158                // in floating point — so on a model whose constraint values run
7159                // to `~1e8` the summary can report an error above `tol` beside
7160                // `EXIT: Optimal Solution Found`. The gap is exactly the part
7161                // of the residual that is quantisation noise, and it is bounded
7162                // by `constr_viol_tol`, which is still tested here on the full
7163                // unfloored residual. Reporting is deliberately left on the raw
7164                // value: it is the honest measurement, and at these magnitudes
7165                // the default `bound_relax_factor = 1e-8` has already moved
7166                // every bound by orders of magnitude more than the floor
7167                // forgives, so the raw number was never an exact statement
7168                // about the original NLP either.
7169                stats.final_constr_viol = cq.curr_primal_infeasibility_max();
7170                // How far outside the model AS DECLARED the returned point
7171                // sits. The line above is the internal slack measure the
7172                // convergence test reads, on the `bound_relax_factor`-widened
7173                // model this arm genuinely solves; the widening stays here
7174                // because a feasible-iterate log-barrier needs `x` strictly
7175                // inside its bounds (the convex arm's does not -- see
7176                // `qp_extract::BoundRelax`). The two can differ by orders and
7177                // nothing used to say so: on netlib `wood1p` this reports
7178                // `1.71e-14` at a point `7.96e-09` outside the declared rows
7179                // and `9.84e-09` outside the declared box. Reported on
7180                // every solve (see gh#987 below).
7181                //
7182                // gh#987: computed on every solve, not only a widened one.
7183                // `final_constr_viol` is documented as the internal scaled
7184                // residual, so under row scaling with `bound_relax_factor=0`
7185                // the user-unit violation was reported nowhere (the field read
7186                // NaN). Without a widening the declared and live models
7187                // coincide, but the *units* do not, and this is the one field
7188                // that is always in the caller's.
7189                stats.final_declared_constr_viol = cq.curr_declared_primal_violation_max();
7190                // The box half of the same measurement, unconditionally: this
7191                // one is a *summary line* (Ipopt's `Variable bound
7192                // violation`), not an extra warning, so it has to carry a real
7193                // number on every solve rather than only on a widened one. At
7194                // `bound_relax_factor = 0` the honest number is `0` and the
7195                // accessor returns it by measurement, not by assumption.
7196                stats.final_declared_box_viol = cq.curr_declared_box_violation_max();
7197                // Infinity-norm complementarity, max over all four bound
7198                // blocks (s_xl·z_l, s_xu·z_u, s_sl·v_l, s_su·v_u). The
7199                // empty-bound blocks return `0` from amax(), so the max is
7200                // safe even when only one side has bounds.
7201                let compl = cq
7202                    .curr_compl_x_l()
7203                    .amax()
7204                    .max(cq.curr_compl_x_u().amax())
7205                    .max(cq.curr_compl_s_l().amax())
7206                    .max(cq.curr_compl_s_u().amax());
7207                stats.final_compl = compl;
7208                stats.final_kkt_error = cq.curr_nlp_error();
7209                // The aggregate the strict gate tested (gh #528). Reported
7210                // alongside the raw one so a summary can account for the gap
7211                // between them; equal to it on every `O(1)` model, and on any
7212                // run with `primal_noise_floor_kappa = 0`.
7213                stats.final_kkt_error_above_noise = cq
7214                    .curr_nlp_error_above_primal_noise(builder.conv_check.primal_noise_floor_kappa);
7215                // Unscaled (user-space) counterparts — divide the nlp_scaling
7216                // back out so a consumer can verify the certificate in its own
7217                // units (pounce#173). Identical to the scaled fields when no
7218                // scaling is active.
7219                stats.final_unscaled_dual_inf = cq.curr_unscaled_dual_infeasibility_max();
7220                stats.final_unscaled_dual_scale = cq.curr_unscaled_dual_infeasibility_scale_max();
7221                stats.final_obj_scaling_factor = cq.computed_obj_scaling_factor();
7222                stats.final_total_obj_scaling_factor = cq.obj_scaling_factor().abs();
7223                stats.start_obj_grad_max = cq.start_obj_gradient_max();
7224                stats.final_unscaled_constr_viol = cq.curr_unscaled_primal_infeasibility_max();
7225                // Record whether per-row scaling actually engaged, so a
7226                // wrapper that measures the user's rows in the model's own
7227                // units knows which field family may carry that number.
7228                // `curr_unscaled_primal_infeasibility_max` treats both
7229                // vectors absent as "scaled == unscaled"; the ℓ₁ outer loop
7230                // relies on the same equivalence (gh#794 review).
7231                {
7232                    let nlp_ref = nlp_handle.borrow();
7233                    self.row_scaling_active.set(Some(
7234                        nlp_ref.c_scale_vec().is_some() || nlp_ref.d_scale_vec().is_some(),
7235                    ));
7236                }
7237                stats.final_unscaled_compl = cq.curr_unscaled_complementarity_max();
7238                stats.final_unscaled_kkt_error = cq.curr_unscaled_nlp_error();
7239
7240                // Report an accepted crossover in the frame it solved in
7241                // (#646). Everything above measures against the bounds the
7242                // interior iteration ran against, which `bound_relax_factor`
7243                // widened by `δ` before the solve. That is the right frame
7244                // for an interior iterate — it never touches a bound — but a
7245                // crossed-over point sits *exactly* on the constraints of the
7246                // problem as declared, i.e. `δ` inside the relaxed ones, so
7247                // the four `s·z` blocks above read `|multiplier| · δ`. For a
7248                // unit multiplier and the default `δ = 1e-8` that is `1e-8`,
7249                // which is `tol`: a strictly better point printed an `Overall
7250                // NLP error` above tolerance, and the opt-in
7251                // `kkt_fidelity_tol` gate below downgraded it.
7252                //
7253                // Only complementarity moves. Stationarity involves no
7254                // bounds, and the crossed-over point is *interior* to the
7255                // relaxed box, so its violation is zero under either reading.
7256                //
7257                // The substitution is confined to reporting. Crossover runs
7258                // after the status is decided, and it only ever installs a
7259                // point the never-regress gate accepted on the declared-bound
7260                // residuals, so this cannot dress up a worse iterate — the
7261                // measurement it replaces is the artifact.
7262                // The same holds for a point the in-solve handover installed
7263                // (gh#1054) while it is still the iterate being reported —
7264                // `curr_from_crossover` is cleared if the interior method
7265                // moved on from it.
7266                let declared_compl = self
7267                    .crossover_report
7268                    .as_ref()
7269                    .filter(|r| r.accepted())
7270                    .or_else(|| {
7271                        self.handover_report
7272                            .as_ref()
7273                            .filter(|_| alg.data.borrow().curr_from_crossover)
7274                            .and_then(|h| h.last.as_ref())
7275                            .filter(|r| r.accepted())
7276                    })
7277                    .map(|r| r.compl_after)
7278                    .filter(|c| c.is_finite());
7279                if let Some(compl_declared) = declared_compl {
7280                    stats.final_compl = compl_declared;
7281                    stats.final_kkt_error =
7282                        cq.curr_nlp_error_with_complementarity(compl_declared, 0.0);
7283                    stats.final_kkt_error_above_noise = cq.curr_nlp_error_with_complementarity(
7284                        compl_declared,
7285                        builder.conv_check.primal_noise_floor_kappa,
7286                    );
7287                    // Same unscaling as `curr_unscaled_complementarity_max`:
7288                    // the slack's row factor and the multiplier's cancel in
7289                    // the product, leaving the objective factor. Magnitude —
7290                    // `obj_scaling_factor` is signed, `-1` being the
7291                    // documented way to pose a maximization.
7292                    let df = cq.obj_scaling_factor().abs();
7293                    stats.final_unscaled_compl = if df == 0.0 || df == 1.0 {
7294                        compl_declared
7295                    } else {
7296                        compl_declared / df
7297                    };
7298                    stats.final_unscaled_kkt_error = stats
7299                        .final_unscaled_dual_inf
7300                        .max(stats.final_unscaled_constr_viol)
7301                        .max(stats.final_unscaled_compl);
7302                }
7303            }
7304        }
7305
7306        // Never report `Infeasible_Problem_Detected` while holding a point that
7307        // satisfies every constraint. The gates that produce this verdict argue
7308        // from a stalled feasibility sub-problem, and gh #379 is what that looks
7309        // like when the argument is wrong — a model whose own starting point is
7310        // exactly feasible, reported infeasible. See
7311        // `withdraw_infeasibility_if_refuted`.
7312        let solver_status =
7313            withdraw_infeasibility_if_refuted(&tnlp, solver_status, lo_inf, up_inf, tol);
7314
7315        // Map SolverReturn → ApplicationReturnStatus per
7316        // MAIN_LOOP.md's exception table, then apply the opt-in
7317        // status-fidelity gate (pounce#173).
7318        let app_status = self.apply_kkt_fidelity_gate(solver_return_to_app_status(solver_status));
7319        // gh#986 item 5: `mehrotra_algorithm=yes` runs with no line search
7320        // (every trial step is accepted), which is sound on LP / convex QP and
7321        // not on a general NLP — there an unglobalized step can walk the
7322        // iterate into an infeasible region that restoration then cannot
7323        // leave. (A *feasible* iterate is no longer sent to restoration by the
7324        // probing guard: it is recentred, gh#986 item 5, so this no longer
7325        // fires on the guard's own account.) Say so when it happens.
7326        if app_status == ApplicationReturnStatus::RestorationFailed
7327            && matches!(
7328                self.options.get_string_value("mehrotra_algorithm", ""),
7329                Ok((ref v, true)) if v == "yes"
7330            )
7331        {
7332            tracing::warn!(
7333                target: "pounce::algorithm",
7334                "pounce: restoration failed under mehrotra_algorithm=yes. That option \
7335                 disables the line search and is intended for LPs and convex QPs; on a \
7336                 general NLP every trial step is accepted, so the iterate can leave the \
7337                 region restoration can repair, and a successful run may stop at a \
7338                 different local solution than the default algorithm finds. Retry with \
7339                 the default (mehrotra_algorithm=no)."
7340            );
7341        }
7342
7343        // On convergence, fire the user-supplied callback (post-optimal
7344        // sensitivity hook, pounce#16) before flowing back through
7345        // `finalize_via_orig_nlp`. Borrowed handles into the converged
7346        // KKT state stay alive for the duration of the closure.
7347        if matches!(
7348            app_status,
7349            ApplicationReturnStatus::SolveSucceeded
7350                | ApplicationReturnStatus::SolvedToAcceptableLevel
7351        ) {
7352            if let Some(cb) = self.on_converged.as_mut() {
7353                // `data.w` is one iterate behind here: the main loop checks
7354                // convergence before it updates the Hessian, so it still holds
7355                // `W(w_k)` from the final Newton step while every other block
7356                // the hook factors (Jacobians, slacks, multipliers, `Σ`) is
7357                // read at the converged point `w*`. Re-evaluate it so the
7358                // sensitivity matrix is the KKT Jacobian at `w*` rather than a
7359                // hybrid of two iterates. Updaters with no `W` to re-evaluate
7360                // (the quasi-Newton ones) answer `None` and keep theirs.
7361                // See `set_on_converged_refreshes_hessian`.
7362                if self.on_converged_refreshes_hessian
7363                    && let Some(w) = alg.bundle.hess.hessian_at_current(&alg.data, &alg.cq)
7364                {
7365                    alg.data.borrow_mut().w = Some(w);
7366                }
7367                if let Some(sd) = alg.search_dir.as_mut() {
7368                    let pd = sd.pd_solver_rc();
7369                    // Tag the firing before it runs, so the hook can file what
7370                    // it keeps under the id `finalize_via_orig_nlp` then
7371                    // stamps on this attempt's payload.
7372                    let id = self.on_converged_fired.get() + 1;
7373                    self.on_converged_fired.set(id);
7374                    alg.data.borrow_mut().on_converged_id = Some(id);
7375                    cb(&alg.data, &alg.cq, &nlp_handle, pd);
7376                }
7377            }
7378        }
7379
7380        // Finalize: forward the final iterate to the user's TNLP. The
7381        // returned objective is evaluated on the *user* TNLP at the
7382        // unscaled iterate, so it overrides the scaled best-effort
7383        // value stashed in `final_objective` above (the algorithm-side
7384        // `eval_f` returns `f * obj_scale_factor`).
7385        if solver_status != SolverReturn::InvalidProblemDefinition {
7386            match finalize_via_orig_nlp(
7387                &nlp_handle,
7388                &alg,
7389                solver_status,
7390                app_status,
7391                &tnlp,
7392                &self.last_finalize,
7393                self.reports_fixed_var_duals(),
7394            ) {
7395                Ok(f_unscaled) => {
7396                    self.statistics.borrow_mut().final_objective = f_unscaled;
7397                }
7398                Err(()) => {}
7399            }
7400        }
7401
7402        // End-of-solve timing report. Gated on `print_timing_statistics`
7403        // (default "no"); mirrors upstream's
7404        // `IpoptApplication::call_optimize` →
7405        // `IpTimingStatistics::PrintAllValues` call site. The report
7406        // goes to stdout (for parity with the banner / iter-row output
7407        // path) and is also fanned out to the journalist so an
7408        // `output_file` attached via `Initialize` picks it up.
7409        let print_timing = self
7410            .options
7411            .get_bool_value("print_timing_statistics", "")
7412            .ok()
7413            .and_then(|(v, f)| f.then_some(v))
7414            .unwrap_or(false);
7415        if print_timing {
7416            let report = timing.report();
7417            print!("{}", report);
7418            use pounce_common::journalist::{JournalCategory, JournalLevel};
7419            self.journalist.print(
7420                JournalLevel::J_SUMMARY,
7421                JournalCategory::J_TIMING_STATISTICS,
7422                &report,
7423            );
7424        }
7425
7426        // End-of-run summary, Ipopt-style, emitted last (after any timing
7427        // report) from the engine's own statistics (#206). Drains the eval
7428        // tallies into SolveStatistics (read AFTER finalize so the final
7429        // solution evaluation is included) and prints the summary, gated on
7430        // the same print_level as the rest of the console.
7431        self.emit_end_summary(app_status, &nlp_handle, console_output);
7432
7433        app_status
7434    }
7435
7436    /// Build an [`AlgorithmBuilder`] populated from the app's
7437    /// [`OptionsList`]. Public so callers wiring the restoration
7438    /// factory can hand the *inner* IPM a builder that mirrors the
7439    /// outer's `mu_strategy`/`mu_oracle`/line-search choices —
7440    /// matching upstream `IpAlgBuilder::BuildRestoIpoptAlgorithm`,
7441    /// which reads the same `mu_strategy` option with prefix `"resto."
7442    /// + prefix` and falls back to the outer setting.
7443    pub fn algorithm_builder_from_options(&self) -> AlgorithmBuilder {
7444        let mut builder = AlgorithmBuilder::new();
7445        // gh#857: share this application's escalation tally. Every
7446        // frontend builds the restoration provider's inner builder from
7447        // this method, so restoration escalations aggregate here too.
7448        builder.quality_escalation_counter = Some(Rc::clone(&self.quality_escalations));
7449        // Structured-KKT Phase 5b: the same reasoning, one solve later. The
7450        // partition this solve resolves is not known yet — it is derived from
7451        // a KKT layout that does not exist until `optimize` builds it — so the
7452        // builder takes the cell rather than the labels, and reads it when
7453        // restoration actually runs. Block-path factorizations record into the
7454        // restoration sink, so `linear_solver.restoration` reports them where
7455        // the rest of restoration's linear algebra is reported.
7456        if let Ok((v, _)) = self.options.get_integer_value("kkt_block_min_size", "") {
7457            builder.kkt_block_min_size = v.max(0) as usize;
7458        }
7459        builder.set_kkt_blocks_cell(Arc::clone(&self.kkt_blocks_published));
7460        builder.set_kkt_schur_summary_sink(Arc::clone(&self.resto_linsol_summary_sink));
7461
7462        // `mehrotra_algorithm` is parsed first so its cascading
7463        // defaults (mu_strategy=adaptive, mu_oracle=probing) can be
7464        // overridden by an explicit user setting of those keys
7465        // below. Mirrors `IpAlgBuilder.cpp:Mehrotra`.
7466        // `fast_step_computation` — skip the search-direction residual
7467        // check and allow an inexact linear solve. `PdSearchDirCalc` has
7468        // consumed this flag since it landed, hard-coded to `false`; the
7469        // option's read site was simply missing, so setting it did
7470        // nothing at all (gh#483 follow-up, #191 round 2).
7471        if let Ok((v, true)) = self.options.get_string_value("fast_step_computation", "") {
7472            builder.fast_step_computation = v.eq_ignore_ascii_case("yes");
7473        }
7474
7475        let mut mehrotra_on = false;
7476        if let Ok((v, found)) = self.options.get_string_value("mehrotra_algorithm", "") {
7477            if found && v == "yes" {
7478                mehrotra_on = true;
7479                builder.mehrotra_algorithm = true;
7480                builder.mu_strategy = MuStrategyChoice::Adaptive;
7481                builder.mu_oracle = crate::mu::adaptive::MuOracleKind::Probing;
7482                // `accept_every_trial_step` short-circuits the alpha
7483                // loop / filter — Mehrotra steps would otherwise be
7484                // rejected by the filter on LP-shaped problems because
7485                // the barrier objective is non-monotone along the
7486                // corrector. Mirrors upstream `IpAlgBuilder.cpp:Mehrotra`.
7487                builder.line_search.accept_every_trial_step = true;
7488                // Aggressive iterate-push defaults (`SetNumericValueIfUnset`
7489                // in upstream). The explicit user parses below will
7490                // overwrite these if the user set them explicitly.
7491                builder.init.bound_push = 10.0;
7492                builder.init.bound_frac = 0.2;
7493                builder.init.slack_bound_push = 10.0;
7494                builder.init.slack_bound_frac = 0.2;
7495                builder.init.bound_mult_init_val = 10.0;
7496                builder.init.constr_mult_init_max = 0.0;
7497                // `alpha_for_y=bound-mult` — Mehrotra wants the
7498                // equality multipliers to advance with the dual
7499                // alpha so they stay in step with z/v. Mirrors
7500                // upstream `IpIpoptAlg.cpp:InitializeImpl`.
7501                builder.line_search.alpha_for_y =
7502                    crate::line_search::backtracking::AlphaForY::BoundMult;
7503                // `adaptive_mu_globalization=never-monotone-mode` —
7504                // upstream `IpIpoptAlg.cpp:148-154` enforces this:
7505                // Mehrotra disables the globalization switch entirely
7506                // (no fallback to monotone mode when convergence
7507                // stalls). Required for the unsafeguarded Mehrotra
7508                // path to function.
7509                builder.mu.adaptive_mu_globalization =
7510                    crate::mu::adaptive::AdaptiveMuGlobalization::NeverMonotoneMode;
7511                // `least_square_init_primal=yes` — upstream
7512                // `IpIpoptAlg.cpp:182` enables this for the Mehrotra
7513                // cascade. Replaces the user's starting `x` with the
7514                // min-norm primal that satisfies the linearized
7515                // equality+inequality constraints. Critical on
7516                // LP-shaped problems where the user's starting point
7517                // can be wildly infeasible (e.g. nuffield2_trap).
7518                builder.init.least_square_init_primal = true;
7519            }
7520        }
7521
7522        if let Ok((v, found)) = self.options.get_string_value("mu_strategy", "") {
7523            if found {
7524                let parsed = match v.as_str() {
7525                    "adaptive" => MuStrategyChoice::Adaptive,
7526                    _ => MuStrategyChoice::Monotone,
7527                };
7528                if mehrotra_on && matches!(parsed, MuStrategyChoice::Monotone) {
7529                    // Upstream Ipopt refuses this combination: Mehrotra
7530                    // needs an affine step every iter, which only the
7531                    // adaptive path computes. Keep adaptive and warn.
7532                    tracing::warn!(target: "pounce::algorithm",
7533                        "pounce: mehrotra_algorithm=yes requires \
7534                         mu_strategy=adaptive; ignoring \
7535                         mu_strategy=monotone."
7536                    );
7537                } else {
7538                    builder.mu_strategy = parsed;
7539                }
7540            }
7541        }
7542        if let Ok((v, found)) = self.options.get_string_value("mu_oracle", "") {
7543            if found {
7544                builder.mu_oracle = match v.as_str() {
7545                    "loqo" => crate::mu::adaptive::MuOracleKind::Loqo,
7546                    "probing" => crate::mu::adaptive::MuOracleKind::Probing,
7547                    _ => crate::mu::adaptive::MuOracleKind::QualityFunction,
7548                };
7549            }
7550        }
7551        if let Ok((v, found)) = self
7552            .options
7553            .get_string_value("adaptive_mu_globalization", "")
7554        {
7555            if found {
7556                use crate::mu::adaptive::AdaptiveMuGlobalization;
7557                builder.mu.adaptive_mu_globalization = match v.as_str() {
7558                    "kkt-error" => AdaptiveMuGlobalization::KktError,
7559                    "never-monotone-mode" => AdaptiveMuGlobalization::NeverMonotoneMode,
7560                    _ => AdaptiveMuGlobalization::ObjConstrFilter,
7561                };
7562            }
7563        }
7564        if let Ok((v, found)) = self.options.get_string_value("hessian_approximation", "") {
7565            if found {
7566                builder.hessian_approximation = match v.as_str() {
7567                    "limited-memory" => HessianApproxChoice::LimitedMemory,
7568                    "partitioned" => HessianApproxChoice::Partitioned,
7569                    "finite-difference" => HessianApproxChoice::FiniteDifference,
7570                    _ => HessianApproxChoice::Exact,
7571                };
7572            }
7573        }
7574        // **Upstream changes the `mu_strategy` default for a
7575        // limited-memory Hessian.** `IpAlgBuilder.cpp:1059`:
7576        //
7577        //     if( !options.GetStringValue("mu_strategy", smuupdate, prefix) )
7578        //     {
7579        //        // Change default for quasi-Newton option (then we use adaptive)
7580        //        ... if( hessian_approximation == LIMITED_MEMORY )
7581        //               smuupdate = "adaptive";
7582        //     }
7583        //
7584        // and again at `:920` for the restoration-phase algorithm.
7585        // Registered default is `monotone`; the quasi-Newton path takes
7586        // `adaptive` unless the caller says otherwise. pounce read the
7587        // registered default unconditionally, so every L-BFGS solve ran
7588        // a barrier schedule Ipopt does not use on that path — a
7589        // trajectory divergence on the arm the Python frontend and the
7590        // CasADi plugin select automatically (gh#746).
7591        //
7592        // The restoration sub-IPM inherits this: `run_inner_resto`
7593        // clones the configured `inner_alg_builder`, so the flag set
7594        // here is what the resto algorithm gets, matching `:920`.
7595        //
7596        // Only when unset — an explicit `mu_strategy` still wins, and
7597        // `mehrotra_algorithm` (parsed above) has already forced
7598        // adaptive on its own terms.
7599        if builder.hessian_approximation == HessianApproxChoice::LimitedMemory
7600            && !self.mu_strategy_was_set()
7601        {
7602            builder.mu_strategy = MuStrategyChoice::Adaptive;
7603        }
7604        // Limited-memory quasi-Newton update formula. Registered upstream
7605        // (`limited_memory_update_type`, IpLimMemQuasiNewtonUpdater.cpp) but
7606        // until now read nowhere on the IPM path — the updater was hard-wired
7607        // to Powell-damped BFGS. SR1 is honored too (the updater and the
7608        // low-rank/inertia path already handle its indefinite models).
7609        // Partitioned quasi-Newton knobs. `partitioned_update_type`
7610        // defaults to SR1 rather than BFGS — see
7611        // `crates::hess::partitioned_quasi_newton` for why damping is
7612        // the wrong choice on a per-constraint element.
7613        if let Ok((v, found)) = self.options.get_string_value("partitioned_update_type", "") {
7614            if found {
7615                builder.partitioned_update_type = match v.as_str() {
7616                    "bfgs" => UpdateType::Bfgs,
7617                    _ => UpdateType::Sr1,
7618                };
7619                builder.partitioned_update_type_was_set = true;
7620            }
7621        }
7622        if let Ok((v, found)) = self
7623            .options
7624            .get_integer_value("partitioned_max_element", "")
7625        {
7626            if found && v > 0 {
7627                builder.partitioned_max_element = v as usize;
7628            }
7629        }
7630        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_pattern", "") {
7631            if found {
7632                builder.fd_hessian_pattern = match v.as_str() {
7633                    "jacobian" => crate::hess::fd_hessian::FdPatternSource::Jacobian,
7634                    _ => crate::hess::fd_hessian::FdPatternSource::Declared,
7635                };
7636            }
7637        }
7638        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_coloring", "") {
7639            if found {
7640                builder.fd_hessian_coloring = match v.as_str() {
7641                    "cpr" => crate::hess::fd_hessian::FdColoring::Cpr,
7642                    _ => crate::hess::fd_hessian::FdColoring::Star,
7643                };
7644            }
7645        }
7646        if let Ok((v, found)) = self.options.get_numeric_value("fd_hessian_reuse_tol", "") {
7647            if found && v >= 0.0 {
7648                builder.fd_hessian_reuse_tol = v;
7649            }
7650        }
7651        if let Ok((v, found)) = self.options.get_string_value("partitioned_elements", "") {
7652            if found {
7653                builder.partitioned_elements = match v.as_str() {
7654                    "blocks" => crate::hess::partitioned_quasi_newton::ElementMode::PrimalBlock,
7655                    _ => crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
7656                };
7657            }
7658        }
7659        if let Ok((v, found)) = self.options.get_integer_value("partitioned_block_size", "") {
7660            if found && v > 0 {
7661                builder.partitioned_block_size = v as usize;
7662            }
7663        }
7664        if let Ok((v, found)) = self
7665            .options
7666            .get_numeric_value("partitioned_curvature_cap", "")
7667        {
7668            if found && v > 0.0 {
7669                builder.partitioned_curvature_cap = v;
7670            }
7671        }
7672        if let Ok((v, found)) = self
7673            .options
7674            .get_string_value("limited_memory_update_type", "")
7675        {
7676            if found {
7677                builder.limited_memory_update_type = match v.as_str() {
7678                    "sr1" => UpdateType::Sr1,
7679                    _ => UpdateType::Bfgs,
7680                };
7681            }
7682        }
7683        // Limited-memory history length (`limited_memory_max_history`).
7684        if let Ok((v, found)) = self
7685            .options
7686            .get_integer_value("limited_memory_max_history", "")
7687        {
7688            if found && v >= 0 {
7689                builder.limited_memory_max_history = v as Index;
7690            }
7691        }
7692        // `limited_memory_initialization` — which formula picks the
7693        // initial Hessian scalar σ. Registered since the option port with
7694        // upstream's `scalar1` default and read nowhere until #677, so
7695        // the updater's own `Scalar2` default was the only value any
7696        // solve ever used: setting the option did nothing, and it warned
7697        // nothing. Same miss as gh#483 / #191 round 2 (which wired
7698        // `limited_memory_init_val_max`/`_min`) — this is the third
7699        // argument to that same `initial_hessian_scalar` call.
7700        //
7701        // The effective default now follows the registry (`scalar1`),
7702        // matching Ipopt. σ_scalar2/σ_scalar1 = (yᵀy·sᵀs)/(sᵀy)² ≥ 1 and
7703        // is unbounded as the curvature pair degrades, so on an
7704        // ill-conditioned problem `scalar2` inflates `B0 = σI` until it
7705        // swamps the rank-2 corrections and the step collapses.
7706        if let Ok((v, found)) = self
7707            .options
7708            .get_string_value("limited_memory_initialization", "")
7709        {
7710            if found {
7711                use crate::hess::lim_mem_quasi_newton::InitialApprox;
7712                // Every registered value is named explicitly. #551 §3
7713                // held this option back precisely because wiring only
7714                // the values that mapped would leave the rest falling
7715                // back silently — a new no-op created by the fix — so a
7716                // catch-all standing in for a real value is the one
7717                // shape to avoid here. `OptionsList` rejects any
7718                // unregistered value before this runs (`options_list.rs`
7719                // `OPTION_INVALID`), so the final arm is unreachable
7720                // rather than a fallback.
7721                builder.limited_memory_initialization = match v.as_str() {
7722                    "scalar1" => InitialApprox::Scalar1,
7723                    "scalar2" => InitialApprox::Scalar2,
7724                    "scalar3" => InitialApprox::Scalar3,
7725                    "scalar4" => InitialApprox::Scalar4,
7726                    "constant" => InitialApprox::Constant,
7727                    "history-max" => InitialApprox::HistoryMax,
7728                    _ => InitialApprox::Scalar2,
7729                };
7730            }
7731        }
7732        // `recalc_y` / `recalc_y_feas_tol` — least-square re-estimation
7733        // of the equality multipliers once feasible (#677).
7734        //
7735        // Upstream registers `recalc_y` as `no`, but its own option text
7736        // ends "If a limited memory quasi-Newton option is chosen, this
7737        // is used by default", so upstream's effective default is
7738        // conditional on the Hessian approximation.
7739        //
7740        // **pounce does not follow that, and the discrepancy is
7741        // deliberate.** Auto-enabling it for the limited-memory path was
7742        // implemented and measured against the fixture corpus first: it
7743        // moved 16 of 57 fixtures on the L-BFGS leg and took **7 from
7744        // solved to not solved, with nothing moving the other way** —
7745        // `airport` 56 it → `SearchDirectionBecomesTooSmall` at 541,
7746        // `pooling_rt2stp` 413 it → the same at 1775, all three `jit1`
7747        // variants, `linear_eq_collapsed_box`, and `hs13_bigstart` to
7748        // the iteration cap. The signature is consistent: re-estimating
7749        // `y` on every feasible iteration overwrites Newton multipliers
7750        // that were converging, the dual never settles, and the step
7751        // vanishes short of the certificate.
7752        //
7753        // So the feature is available and off by default. That still
7754        // closes the gap that mattered — until #677 the option was
7755        // refused outright as unimplemented, so an L-BFGS user could not
7756        // reach Ipopt's behaviour at all. They can now, by asking.
7757        //
7758        // Why it is worth having: a quasi-Newton model's dual step is
7759        // computed from an approximate `W`, so L-BFGS can settle a
7760        // feasible primal and still not drive `inf_du` to tolerance —
7761        // the failure a 59,939-variable CasADi model hit, oscillating
7762        // `inf_du` between 3.6e-3 and 1.8e+01 for 300 iterations with
7763        // the objective already settled. On that shape it is the fix;
7764        // on a corpus of small well-conditioned models it is a
7765        // pessimisation. Matching upstream's conditional default needs
7766        // to explain the 7 regressions first.
7767        if let Ok((v, true)) = self.options.get_string_value("recalc_y", "") {
7768            builder.recalc_y = v == "yes";
7769        }
7770        if let Ok((v, true)) = self.options.get_numeric_value("recalc_y_feas_tol", "") {
7771            builder.recalc_y_feas_tol = v;
7772        }
7773        // `limited_memory_init_val` — σ before any curvature pair exists,
7774        // and every iteration under `constant`. Also unread until #677;
7775        // the empty-history branch hard-coded the same `1.0`.
7776        if let Ok((v, true)) = self
7777            .options
7778            .get_numeric_value("limited_memory_init_val", "")
7779        {
7780            builder.limited_memory_init_val = v;
7781        }
7782        // `limited_memory_max_skipping` (#686) — registered and unread,
7783        // and the feature behind it did not exist either: the updater
7784        // counted nothing and never discarded its history.
7785        if let Ok((v, true)) = self
7786            .options
7787            .get_integer_value("limited_memory_max_skipping", "")
7788        {
7789            if v >= 0 {
7790                builder.limited_memory_max_skipping = v as Index;
7791            }
7792        }
7793        if let Ok((v, found)) = self.options.get_string_value("line_search_method", "") {
7794            if found {
7795                builder.line_search_method = match v.as_str() {
7796                    // Unreachable from a real solve since gh#981:
7797                    // `cg-penalty` is refused by
7798                    // `unimplemented_options::UNIMPLEMENTED_VALUES`
7799                    // before the builder is configured, because the
7800                    // variant assembles the plain penalty acceptor.
7801                    "cg-penalty" => LineSearchChoice::CgPenalty,
7802                    "penalty" => LineSearchChoice::Penalty,
7803                    _ => LineSearchChoice::Filter,
7804                };
7805            }
7806        }
7807        // `accept_every_trial_step` — direct user override. Parsed
7808        // after the Mehrotra cascade so an explicit `no` still wins.
7809        if let Ok((v, found)) = self.options.get_string_value("accept_every_trial_step", "") {
7810            if found {
7811                builder.line_search.accept_every_trial_step = v == "yes";
7812            }
7813        }
7814        // `alpha_for_y` — direct user override. Parsed after the
7815        // Mehrotra cascade so an explicit value still wins.
7816        if let Ok((v, found)) = self.options.get_string_value("alpha_for_y", "") {
7817            if found {
7818                use crate::line_search::backtracking::AlphaForY;
7819                builder.line_search.alpha_for_y = match v.as_str() {
7820                    "primal" => AlphaForY::Primal,
7821                    "bound-mult" | "bound_mult" => AlphaForY::BoundMult,
7822                    "full" => AlphaForY::Full,
7823                    "min" => AlphaForY::Min,
7824                    "max" => AlphaForY::Max,
7825                    "primal-and-full" | "dual-and-full" => AlphaForY::Primal,
7826                    _ => AlphaForY::Primal,
7827                };
7828            }
7829        }
7830        // `nlp_scaling_method` is consumed NLP-side in
7831        // `OrigIpoptNlp::determine_scaling_from_starting_point` (see the
7832        // `determine_scaling_from_starting_point` call earlier in this
7833        // method); there is no algorithm-side scaling strategy to wire.
7834        // `limited_memory_init_val_max` / `_min` — the clamp on the
7835        // initial Hessian scalar. `LimMemQuasiNewtonUpdater` consumes
7836        // both in `initial_hessian_scalar`; only the read sites were
7837        // missing, so setting either did nothing (gh#483, #191 round 2).
7838        if let Ok((v, true)) = self
7839            .options
7840            .get_numeric_value("limited_memory_init_val_max", "")
7841        {
7842            builder.limited_memory_init_val_max = v;
7843        }
7844        if let Ok((v, true)) = self
7845            .options
7846            .get_numeric_value("limited_memory_init_val_min", "")
7847        {
7848            builder.limited_memory_init_val_min = v;
7849        }
7850
7851        // Unlike the other options here, we always honor the registry
7852        // value (not just when the user set it explicitly): the option
7853        // registry default is "ma57" but `AlgorithmBuilder::default`
7854        // has `linear_solver: Feral`, so gating on `found` would
7855        // silently route default runs through Feral while the banner
7856        // (and ipopt-compatible behavior) advertises MA57.
7857        //
7858        // Record the **effective** backend, not the requested one. MA57 lives
7859        // behind the optional `ma57` cargo feature (HSL is licensed and needs a
7860        // Fortran toolchain); without it `default_backend_factory` silently
7861        // substitutes FERAL. Storing `Ma57` here therefore made
7862        // `builder.linear_solver` disagree with the backend actually built, and
7863        // consumers acted on the lie: the Schur KKT gate in
7864        // `alg_builder::build_with_backend` tests `== Feral`, so on the
7865        // pure-Rust default build — where the registry default (then upstream's
7866        // "ma57") resolved to FERAL anyway — `set_kkt_schur_block()` silently
7867        // never engaged for ANY user. Resolving here keeps the field truthful
7868        // for every consumer.
7869        //
7870        // The `_ =>` arm is now only reachable for `feral`: every other name
7871        // is refused up front by `unimplemented_linear_solver`. It used to
7872        // swallow `mumps`, `pardiso`, `ma97`, … and run FERAL instead.
7873        if let Ok((v, _found)) = self.options.get_string_value("linear_solver", "") {
7874            let requested = if v.eq_ignore_ascii_case("ma57") {
7875                LinearSolverChoice::Ma57
7876            } else {
7877                LinearSolverChoice::Feral
7878            };
7879            builder.linear_solver =
7880                if matches!(requested, LinearSolverChoice::Ma57) && !cfg!(feature = "ma57") {
7881                    LinearSolverChoice::Feral
7882                } else {
7883                    requested
7884                };
7885        }
7886
7887        // `linear_system_scaling` — symmetric scaling of the augmented
7888        // KKT matrix before factorization. Port of
7889        // `IpTSymLinearSolver.cpp:RegisterOptions` plumbing. Default
7890        // "none"; "ruiz" invokes the Ruiz-2001 symmetric ∞-norm
7891        // equilibration in `RuizTSymScalingMethod`. "mc19" and
7892        // "slack-based" are accepted by the registry but not yet
7893        // implemented at this layer; they fall back to no scaling
7894        // with a one-line notice.
7895        //
7896        // `slack-based` is implemented as of #677. It used to reach the
7897        // no-scaling fallback through the catch-all arm, which meant it
7898        // fell back **silently** — the comment above promised a notice
7899        // that only `mc19` actually emitted. It is not a hypothetical
7900        // value: it is what Ipopt's own recommended configuration for
7901        // large collocation NLPs uses, so the users most likely to set
7902        // it were the least likely to be told it did nothing. The
7903        // catch-all is left for genuinely unreachable input —
7904        // `OptionsList` rejects anything the registry does not list.
7905        if let Ok((v, found)) = self.options.get_string_value("linear_system_scaling", "") {
7906            if found {
7907                builder.linear_system_scaling = match v.as_str() {
7908                    "ruiz" => crate::alg_builder::LinearSystemScalingChoice::Ruiz,
7909                    "mc19" => crate::alg_builder::LinearSystemScalingChoice::Mc19,
7910                    "slack-based" => crate::alg_builder::LinearSystemScalingChoice::SlackBased,
7911                    _ => crate::alg_builder::LinearSystemScalingChoice::None,
7912                };
7913            }
7914        }
7915        if let Ok((v, found)) = self.options.get_bool_value("linear_scaling_on_demand", "") {
7916            if found {
7917                builder.linear_scaling_on_demand = v;
7918            }
7919        }
7920
7921        // Convergence tolerances (port of `IpOptErrorConvCheck.cpp`'s
7922        // `RegisterOptions` consumers). Defaults already match upstream
7923        // — only override when the user set the key explicitly.
7924        let read_num = |key: &str| -> Option<f64> {
7925            self.options
7926                .get_numeric_value(key, "")
7927                .ok()
7928                .and_then(|(v, f)| f.then_some(v))
7929        };
7930        let read_int = |key: &str| -> Option<i32> {
7931            self.options
7932                .get_integer_value(key, "")
7933                .ok()
7934                .and_then(|(v, f)| f.then_some(v))
7935        };
7936        if let Some(v) = read_num("tol") {
7937            builder.conv_check.tol = v;
7938        }
7939        if let Some(v) = read_num("obj_scale_certificate_threshold") {
7940            builder.conv_check.obj_scale_certificate_threshold = v;
7941        }
7942        if let Some(v) = read_num("primal_noise_floor_kappa") {
7943            builder.conv_check.primal_noise_floor_kappa = v;
7944        }
7945        if let Some(v) = read_num("acceptable_progress_kappa") {
7946            builder.conv_check.acceptable_progress_kappa = v;
7947        }
7948        if let Some(v) = read_num("dual_inf_scale_kappa") {
7949            builder.conv_check.dual_inf_scale_kappa = v;
7950        }
7951        if let Some(v) = read_num("kkt_fidelity_tol") {
7952            builder.kkt_fidelity_tol = v;
7953        }
7954        if let Some(v) = read_num("dual_inf_tol") {
7955            builder.conv_check.dual_inf_tol = v;
7956            // gh#983 item 1: a caller who names `dual_inf_tol` has asked for
7957            // that absolute standard. The scale-relative floor (gh#532) is a
7958            // default for a caller who has not, and it let `1e-6` certify a
7959            // point with `‖∇L‖∞ = 0.144` because the multipliers were 3.5e9
7960            // (a failed constraint qualification, which is not a reason to
7961            // loosen the test). Naming `dual_inf_scale_kappa` as well opts the
7962            // floor back in.
7963            //
7964            // gh#983 review: a value equal to the registered default is read
7965            // as "not named". Front ends that echo every default (option
7966            // files copied from Ipopt's documentation, wrappers that pass the
7967            // full table) would otherwise lose the gh#532 floor without asking
7968            // for anything. That is safe because the floor with the default
7969            // tolerance IS the default behaviour; a caller who wants the
7970            // absolute standard at `1` names `dual_inf_scale_kappa 0`, which
7971            // the option help documents.
7972            let default_tol = crate::alg_builder::ConvCheckOptions::default().dual_inf_tol;
7973            if read_num("dual_inf_scale_kappa").is_none() && v != default_tol {
7974                builder.conv_check.dual_inf_scale_kappa = 0.0;
7975            }
7976        }
7977        if let Some(v) = read_num("constr_viol_tol") {
7978            builder.conv_check.constr_viol_tol = v;
7979        }
7980        if let Some(v) = read_num("compl_inf_tol") {
7981            builder.conv_check.compl_inf_tol = v;
7982        }
7983        if let Some(v) = read_int("max_iter") {
7984            builder.conv_check.max_iter = v;
7985        }
7986        if let Some(v) = read_num("max_cpu_time") {
7987            builder.conv_check.max_cpu_time = v;
7988        }
7989        if let Some(v) = read_num("max_wall_time") {
7990            builder.conv_check.max_wall_time = v;
7991        }
7992        if let Some(v) = read_num("acceptable_tol") {
7993            builder.conv_check.acceptable_tol = v;
7994        }
7995        if let Some(v) = read_num("acceptable_dual_inf_tol") {
7996            builder.conv_check.acceptable_dual_inf_tol = v;
7997        }
7998        if let Some(v) = read_num("acceptable_constr_viol_tol") {
7999            builder.conv_check.acceptable_constr_viol_tol = v;
8000        }
8001        if let Some(v) = read_num("acceptable_compl_inf_tol") {
8002            builder.conv_check.acceptable_compl_inf_tol = v;
8003        }
8004        if let Some(v) = read_num("acceptable_obj_change_tol") {
8005            builder.conv_check.acceptable_obj_change_tol = v;
8006        }
8007        if let Some(v) = read_int("acceptable_iter") {
8008            builder.conv_check.acceptable_iter = v;
8009        }
8010        if let Some(v) = read_num("infeas_stationarity_tol") {
8011            builder.conv_check.infeas_stationarity_tol = v;
8012        }
8013        if let Some(v) = read_num("infeas_viol_kappa") {
8014            builder.conv_check.infeas_viol_kappa = v;
8015        }
8016        if let Some(v) = read_int("infeas_max_streak") {
8017            builder.conv_check.infeas_max_streak = v;
8018        }
8019
8020        // Bound-multiplier / barrier damping constants (#191). Both were
8021        // registered but never read, so user overrides were silently
8022        // dropped; the algorithm ran with the hard-coded struct defaults.
8023        // Defaults equal the registered defaults, so this changes nothing
8024        // for a run that doesn't set them.
8025        if let Some(v) = read_num("kappa_sigma") {
8026            builder.kappa_sigma = v;
8027        }
8028        if let Some(v) = read_num("kappa_d") {
8029            builder.kappa_d = v;
8030        }
8031        // `s_max` — the cap in the `(s_d, s_c)` scaling of the KKT error
8032        // test (#551 / #677). `IpoptCalculatedQuantities` carried it as a
8033        // hard-coded 100 (the registered default) and nothing read the
8034        // option; a run that does not set it is unaffected.
8035        if let Some(v) = read_num("s_max") {
8036            builder.s_max = v;
8037        }
8038        if let Some(v) = read_num("tiny_step_tol") {
8039            builder.tiny_step_tol = v;
8040        }
8041        if let Some(v) = read_num("tiny_step_y_tol") {
8042            builder.tiny_step_y_tol = v;
8043        }
8044        if let Some(v) = read_num("diverging_iterates_tol") {
8045            builder.diverging_iterates_tol = v;
8046        }
8047        if let Some(v) = read_int("dual_diverging_streak") {
8048            builder.dual_diverging_streak = v;
8049        }
8050        if let Some(v) = read_num("dual_divergence_retry_step_tol") {
8051            builder.dual_divergence_retry_step_tol = v;
8052        }
8053        if let Some(v) = read_num("dual_divergence_retry_du_floor") {
8054            builder.dual_divergence_retry_du_floor = v;
8055        }
8056        if let Some(v) = read_int("resto_decline_deferrals") {
8057            builder.resto_decline_deferrals = v;
8058        }
8059        if let Some(v) = read_num("resto_decline_progress_ratio") {
8060            builder.resto_decline_progress_ratio = v;
8061        }
8062        if let Some(v) = read_int("neg_curv_escapes") {
8063            builder.neg_curv_escapes = v;
8064        }
8065        if let Some(v) = read_int("limited_memory_ls_failure_restarts") {
8066            builder.limited_memory_ls_failure_restarts = v;
8067        }
8068
8069        // Barrier-parameter (μ) options — consumers in
8070        // `IpMonotoneMuUpdate.cpp` / `IpAdaptiveMuUpdate.cpp`. Both
8071        // updaters share the same option names; the builder forwards
8072        // each into whichever strategy is assembled.
8073        if let Some(v) = read_num("mu_init") {
8074            builder.mu.mu_init = v;
8075        }
8076        if let Some(v) = read_num("mu_max") {
8077            builder.mu.mu_max = v;
8078        }
8079        if let Some(v) = read_num("mu_max_fact") {
8080            builder.mu.mu_max_fact = v;
8081        }
8082        if let Some(v) = read_num("mu_min") {
8083            builder.mu.mu_min = v;
8084        }
8085        if let Some(v) = read_num("mu_target") {
8086            builder.mu.mu_target = v;
8087        }
8088        if let Some(v) = read_num("mu_linear_decrease_factor") {
8089            builder.mu.mu_linear_decrease_factor = v;
8090        }
8091        if let Some(v) = read_num("mu_superlinear_decrease_power") {
8092            builder.mu.mu_superlinear_decrease_power = v;
8093        }
8094        if let Ok((v, found)) = self
8095            .options
8096            .get_string_value("mu_allow_fast_monotone_decrease", "")
8097        {
8098            if found {
8099                builder.mu.mu_allow_fast_monotone_decrease = v == "yes";
8100            }
8101        }
8102        if let Some(v) = read_num("barrier_tol_factor") {
8103            builder.mu.barrier_tol_factor = v;
8104        }
8105        // `tau_min` — floor on the fraction-to-the-boundary parameter
8106        // (#551 / #677). Both `MonotoneMuUpdate` and `AdaptiveMuUpdate`
8107        // carried the field with upstream's 0.99 default and nothing
8108        // read the option, so an override was silently dropped. The
8109        // default equals the registered default, so this changes
8110        // nothing for a run that does not set it.
8111        if let Some(v) = read_num("tau_min") {
8112            builder.mu.tau_min = v;
8113        }
8114        if let Some(v) = read_num("sigma_max") {
8115            builder.mu.sigma_max = v;
8116        }
8117        if let Some(v) = read_num("sigma_min") {
8118            builder.mu.sigma_min = v;
8119        }
8120
8121        // Quality-function oracle knobs — consumers in
8122        // `IpQualityFunctionMuOracle.cpp:RegisterOptions`. Forwarded
8123        // to the oracle on every free-mode call.
8124        if let Ok((v, found)) = self
8125            .options
8126            .get_string_value("quality_function_norm_type", "")
8127        {
8128            if found {
8129                use crate::mu::oracle::quality_function::NormType;
8130                builder.mu.quality_function_norm_type = match v.as_str() {
8131                    "1-norm" => NormType::OneNorm,
8132                    "2-norm" => NormType::TwoNorm,
8133                    "max-norm" => NormType::MaxNorm,
8134                    _ => NormType::TwoNormSquared,
8135                };
8136            }
8137        }
8138        if let Ok((v, found)) = self
8139            .options
8140            .get_string_value("quality_function_centrality", "")
8141        {
8142            if found {
8143                use crate::mu::oracle::quality_function::CentralityType;
8144                builder.mu.quality_function_centrality = match v.as_str() {
8145                    "log" => CentralityType::LogCenter,
8146                    "reciprocal" => CentralityType::ReciprocalCenter,
8147                    "cubed-reciprocal" => CentralityType::CubedReciprocalCenter,
8148                    _ => CentralityType::None,
8149                };
8150            }
8151        }
8152        if let Ok((v, found)) = self
8153            .options
8154            .get_string_value("quality_function_balancing_term", "")
8155        {
8156            if found {
8157                use crate::mu::oracle::quality_function::BalancingTermType;
8158                builder.mu.quality_function_balancing_term = match v.as_str() {
8159                    "cubic" => BalancingTermType::CubicTerm,
8160                    _ => BalancingTermType::None,
8161                };
8162            }
8163        }
8164        if let Some(v) = read_int("quality_function_max_section_steps") {
8165            builder.mu.quality_function_max_section_steps = v;
8166        }
8167        if let Some(v) = read_num("quality_function_section_sigma_tol") {
8168            builder.mu.quality_function_section_sigma_tol = v;
8169        }
8170        if let Some(v) = read_num("quality_function_section_qf_tol") {
8171            builder.mu.quality_function_section_qf_tol = v;
8172        }
8173
8174        // `probing_iterate_quality_factor` — pounce-specific guard
8175        // (pounce#58) on the probing μ-oracle's input iterate. When
8176        // `curr_avrg_compl / curr_mu` exceeds this factor, the
8177        // μ-update layer signals restoration via
8178        // `IpoptData::request_resto` instead of letting probing
8179        // return `σ · mu_curr` ≫ previous μ. Default 1e4; set to ≤ 0
8180        // to disable. No upstream Ipopt counterpart.
8181        if let Some(v) = read_num("probing_iterate_quality_factor") {
8182            builder.mu.probing_iterate_quality_factor = v;
8183        }
8184
8185        // Adaptive-μ extras — consumers in
8186        // `IpAdaptiveMuUpdate.cpp:RegisterOptions`. Only active when
8187        // `mu_strategy=adaptive`.
8188        if let Some(v) = read_num("adaptive_mu_safeguard_factor") {
8189            builder.mu.adaptive_mu_safeguard_factor = v;
8190        }
8191        if let Some(v) = read_num("adaptive_mu_monotone_init_factor") {
8192            builder.mu.adaptive_mu_monotone_init_factor = v;
8193        }
8194        if let Ok((v, found)) = self
8195            .options
8196            .get_bool_value("adaptive_mu_restore_previous_iterate", "")
8197        {
8198            if found {
8199                builder.mu.adaptive_mu_restore_previous_iterate = v;
8200            }
8201        }
8202        if let Some(v) = read_int("adaptive_mu_max_free_returns") {
8203            builder.mu.adaptive_mu_max_free_returns = v;
8204        }
8205        if let Some(v) = read_num("adaptive_mu_budget_pin_fraction") {
8206            builder.mu.adaptive_mu_budget_pin_fraction = v;
8207        }
8208        if let Some(v) = read_int("adaptive_mu_kkterror_red_iters") {
8209            if v >= 0 {
8210                builder.mu.adaptive_mu_kkterror_red_iters = v as usize;
8211            }
8212        }
8213        if let Some(v) = read_num("adaptive_mu_kkterror_red_fact") {
8214            builder.mu.adaptive_mu_kkterror_red_fact = v;
8215        }
8216        // `filter_margin_fact` / `filter_max_margin` (#551) — the margin
8217        // an entry must clear in the `obj-constr-filter` globalization
8218        // test. `AdaptiveMuUpdate` computes
8219        // `filter_margin_fact * min(filter_max_margin, err)` and has
8220        // always done so; only these two read sites were missing, so
8221        // setting either did nothing. Defaults equal the registered
8222        // defaults (1e-5 / 1.0), so an unset run is unchanged.
8223        if let Some(v) = read_num("filter_margin_fact") {
8224            builder.mu.filter_margin_fact = v;
8225        }
8226        if let Some(v) = read_num("filter_max_margin") {
8227            builder.mu.filter_max_margin = v;
8228        }
8229        if let Ok((v, found)) = self
8230            .options
8231            .get_string_value("adaptive_mu_kkt_norm_type", "")
8232        {
8233            if found {
8234                use crate::mu::adaptive::AdaptiveMuKktNorm;
8235                builder.mu.adaptive_mu_kkt_norm_type = match v.as_str() {
8236                    "1-norm" => AdaptiveMuKktNorm::OneNorm,
8237                    "2-norm" => AdaptiveMuKktNorm::TwoNorm,
8238                    "max-norm" => AdaptiveMuKktNorm::MaxNorm,
8239                    _ => AdaptiveMuKktNorm::TwoNormSquared,
8240                };
8241            }
8242        }
8243
8244        // Watchdog options — consumers in
8245        // `IpBacktrackingLineSearch.cpp:RegisterOptions`. Baked into
8246        // the `BacktrackingLineSearch` at build time.
8247        if let Some(v) = read_int("watchdog_shortened_iter_trigger") {
8248            builder.line_search.watchdog_shortened_iter_trigger = v;
8249        }
8250        if let Some(v) = read_int("watchdog_trial_iter_max") {
8251            builder.line_search.watchdog_trial_iter_max = v;
8252        }
8253        if let Some(v) = read_num("soft_resto_pderror_reduction_factor") {
8254            builder.line_search.soft_resto_pderror_reduction_factor = v;
8255        }
8256        if let Some(v) = read_int("max_soft_resto_iters") {
8257            builder.line_search.max_soft_resto_iters = v;
8258        }
8259        // `alpha_red_factor` (#678) and `accept_after_max_steps` (#551)
8260        // — both consumed by the α-loop in `BacktrackingLineSearch`,
8261        // both registered without a read site until those issues.
8262        // `alpha_red_factor`'s default (0.5) equals the registered one,
8263        // and `accept_after_max_steps` defaults to `-1`, which disables
8264        // the escape hatch, so neither moves a solve that leaves them
8265        // alone.
8266        if let Some(v) = read_num("alpha_red_factor") {
8267            builder.line_search.alpha_red_factor = v;
8268        }
8269        if let Some(v) = read_num("alpha_red_factor_min") {
8270            builder.line_search.alpha_red_factor_min = Some(v);
8271        }
8272        if let Some(v) = read_int("accept_after_max_steps") {
8273            builder.line_search.accept_after_max_steps = v;
8274        }
8275
8276        // Filter switching / Armijo / margin constants (#191). Consumed
8277        // by `FilterLsAcceptor` (only on the `Filter` line-search path);
8278        // registered but never read, so overrides were silently dropped.
8279        // Defaults equal the registered defaults.
8280        if let Some(v) = read_num("eta_phi") {
8281            builder.line_search.eta_phi = v;
8282        }
8283        // `delta` (#551) — the switching rule's multiplier on the
8284        // constraint violation (Eqn. (19)); `FilterLsAcceptor` has
8285        // always used it as `delta_armijo`, only the read site was
8286        // missing. Default 1.0 equals the registered default.
8287        if let Some(v) = read_num("delta") {
8288            builder.line_search.delta = v;
8289        }
8290        if let Some(v) = read_num("theta_min_fact") {
8291            builder.line_search.theta_min_fact = v;
8292        }
8293        if let Some(v) = read_num("theta_max_row_scale_kappa") {
8294            builder.line_search.theta_max_row_scale_kappa = v;
8295        }
8296        if let Some(v) = read_int("theta_max_adaptive_trigger") {
8297            builder.line_search.theta_max_adaptive_trigger = v.max(0) as u32;
8298        }
8299        if let Some(v) = read_num("theta_max_adaptive_factor") {
8300            builder.line_search.theta_max_adaptive_factor = v;
8301        }
8302        if let Some(v) = read_int("theta_max_adaptive_max_raises") {
8303            builder.line_search.theta_max_adaptive_max_raises = v.max(0) as u32;
8304        }
8305        if let Some(v) = read_num("theta_max_fact") {
8306            builder.line_search.theta_max_fact = v;
8307        }
8308        if let Some(v) = read_num("gamma_phi") {
8309            builder.line_search.gamma_phi = v;
8310        }
8311        if let Some(v) = read_num("gamma_theta") {
8312            builder.line_search.gamma_theta = v;
8313        }
8314        if let Some(v) = read_num("s_phi") {
8315            builder.line_search.s_phi = v;
8316        }
8317        if let Some(v) = read_num("s_theta") {
8318            builder.line_search.s_theta = v;
8319        }
8320        if let Some(v) = read_num("alpha_min_frac") {
8321            builder.line_search.alpha_min_frac = v;
8322        }
8323        if let Some(v) = read_num("obj_max_inc") {
8324            builder.line_search.obj_max_inc = v;
8325        }
8326        if let Some(v) = read_int("max_filter_resets") {
8327            builder.line_search.max_filter_resets = v;
8328        }
8329        if let Some(v) = read_int("filter_reset_trigger") {
8330            builder.line_search.filter_reset_trigger = v;
8331        }
8332        // `filter_theta_roundoff_retry` (gh#945).
8333        if let Ok((v, true)) = self
8334            .options
8335            .get_bool_value("filter_theta_roundoff_retry", "")
8336        {
8337            builder.line_search.filter_theta_roundoff_retry = v;
8338        }
8339        // `objective_noise_wolfe` (gh#1016).
8340        if let Ok((v, true)) = self.options.get_bool_value("objective_noise_wolfe", "") {
8341            builder.line_search.objective_noise_wolfe = v;
8342        }
8343        // Penalty line-search constants (#551), consumed by
8344        // `PenaltyLsAcceptor` (only on the `line_search_method=penalty`
8345        // / `cg-penalty` paths). The acceptor implements ν and the
8346        // Armijo test on the penalty merit function already; these four
8347        // were registered with no read site, so tuning the penalty
8348        // update did nothing. Defaults equal the registered defaults.
8349        if let Some(v) = read_num("nu_init") {
8350            builder.line_search.nu_init = v;
8351        }
8352        if let Some(v) = read_num("nu_inc") {
8353            builder.line_search.nu_inc = v;
8354        }
8355        if let Some(v) = read_num("rho") {
8356            builder.line_search.rho = v;
8357        }
8358        if let Some(v) = read_num("eta_penalty") {
8359            builder.line_search.eta_penalty = v;
8360        }
8361
8362        // Second-order-correction constants (#191), consumed by
8363        // `BacktrackingLineSearch`. `max_soc = 0` disables SOC.
8364        if let Some(v) = read_int("max_soc") {
8365            builder.line_search.max_soc = v;
8366        }
8367        if let Some(v) = read_num("kappa_soc") {
8368            builder.line_search.kappa_soc = v;
8369        }
8370        if let Some(v) = read_int("soc_method") {
8371            builder.line_search.soc_method = v;
8372        }
8373
8374        // Inertia-correction / Jacobian-regularization constants (#191),
8375        // consumed by `PdPerturbationHandler`. Registered but never read.
8376        if let Some(v) = read_num("max_hessian_perturbation") {
8377            builder.perturbation.max_hessian_perturbation = v;
8378        }
8379        if let Some(v) = read_num("min_hessian_perturbation") {
8380            builder.perturbation.min_hessian_perturbation = v;
8381        }
8382        if let Some(v) = read_num("perturb_inc_fact_first") {
8383            builder.perturbation.perturb_inc_fact_first = v;
8384        }
8385        if let Some(v) = read_num("perturb_inc_fact") {
8386            builder.perturbation.perturb_inc_fact = v;
8387        }
8388        if let Some(v) = read_num("perturb_dec_fact") {
8389            builder.perturbation.perturb_dec_fact = v;
8390        }
8391        if let Some(v) = read_num("first_hessian_perturbation") {
8392            builder.perturbation.first_hessian_perturbation = v;
8393        }
8394        if let Some(v) = read_num("jacobian_regularization_value") {
8395            builder.perturbation.jacobian_regularization_value = v;
8396        }
8397        if let Some(v) = read_num("jacobian_regularization_exponent") {
8398            builder.perturbation.jacobian_regularization_exponent = v;
8399        }
8400        if let Ok((v, true)) = self.options.get_bool_value("perturb_always_cd", "") {
8401            builder.perturbation.perturb_always_cd = v;
8402        }
8403        if let Some(v) = read_int("perturb_delta_c_max_rungs") {
8404            builder.perturbation.perturb_delta_c_max_rungs = v;
8405        }
8406
8407        // Iterative-refinement constants (#191), consumed by
8408        // `PdFullSpaceSolver`. Registered but never read.
8409        if let Some(v) = read_int("min_refinement_steps") {
8410            builder.refinement.min_refinement_steps = v;
8411        }
8412        if let Some(v) = read_int("max_refinement_steps") {
8413            builder.refinement.max_refinement_steps = v;
8414        }
8415        if let Some(v) = read_num("residual_ratio_max") {
8416            builder.refinement.residual_ratio_max = v;
8417        }
8418        if let Some(v) = read_num("residual_ratio_singular") {
8419            builder.refinement.residual_ratio_singular = v;
8420        }
8421        if let Some(v) = read_num("residual_improvement_factor") {
8422            builder.refinement.residual_improvement_factor = v;
8423        }
8424
8425        // Inertia-free curvature test (#551 / #677), also consumed by
8426        // `PdFullSpaceSolver`. `neg_curv_test_tol` had a field that only
8427        // ever held its 0.0 default, and `neg_curv_test_reg` had none at
8428        // all; both are now read, and the curvature test they configure
8429        // is implemented in `PdFullSpaceSolver::solve_once`. At the
8430        // registered default (`0.0`) the heuristic is off and the
8431        // inertia check runs as before.
8432        if let Some(v) = read_num("neg_curv_test_tol") {
8433            builder.refinement.neg_curv_test_tol = v;
8434        }
8435        if let Ok((v, true)) = self.options.get_bool_value("neg_curv_test_reg", "") {
8436            builder.refinement.neg_curv_test_reg = v;
8437        }
8438
8439        // Restoration-phase constants (#191). Carried on the outer builder
8440        // and copied into the `RestoAlgorithmBuilder` when the restoration
8441        // factory is minted (the frontends pass this builder in). The
8442        // restoration builder was never options-configured, so these were
8443        // registered but never read. Defaults equal the registered
8444        // defaults.
8445        if let Some(v) = read_num("bound_mult_reset_threshold") {
8446            builder.resto.bound_mult_reset_threshold = v;
8447        }
8448        if let Some(v) = read_num("constr_mult_reset_threshold") {
8449            builder.resto.constr_mult_reset_threshold = v;
8450        }
8451        if let Some(v) = read_num("resto_penalty_parameter") {
8452            builder.resto.resto_penalty_parameter = v;
8453        }
8454        if let Some(v) = read_num("resto_proximity_weight") {
8455            builder.resto.resto_proximity_weight = v;
8456        }
8457        // `required_infeasibility_reduction` (#439) — the κ_resto guard the
8458        // restoration sub-solve exits on. Registered since #191 but the
8459        // value was hardcoded at the callsite, so setting it was a silent
8460        // no-op.
8461        if let Some(v) = read_num("required_infeasibility_reduction") {
8462            builder.resto.required_infeasibility_reduction = v;
8463        }
8464        // gh#483 / #191 round 2: three restoration switches whose fields
8465        // `RestoAlgorithmBuilder` has consumed all along — the read site
8466        // was the only missing piece, so setting them did nothing.
8467        let read_yes = |key: &str| -> Option<bool> {
8468            match self.options.get_string_value(key, "") {
8469                Ok((v, true)) => Some(v.eq_ignore_ascii_case("yes")),
8470                _ => None,
8471            }
8472        };
8473        if let Some(v) = read_yes("evaluate_orig_obj_at_resto_trial") {
8474            builder.resto.evaluate_orig_obj_at_resto_trial = v;
8475        }
8476        if let Some(v) = read_yes("expect_infeasible_problem") {
8477            builder.resto.expect_infeasible_problem = v;
8478        }
8479        if let Some(v) = read_yes("start_with_resto") {
8480            builder.resto.start_with_resto = v;
8481        }
8482        // `max_resto_iter` (#551 / #677) — the cap on *successive*
8483        // restoration iterations. `RestoConvCheckAdapter` has enforced a cap
8484        // all along (returning `MaxIterExceeded` at the limit); the number
8485        // it enforced was a hard-coded constant in `resto_inner_solver.rs`,
8486        // so setting the option did nothing. The consumer's field is
8487        // `maximum_resto_iters`, not the option name — grepping for
8488        // `max_resto_iter` found only the registry (#551 caution 2).
8489        //
8490        // DEFAULT MISMATCH, LEFT AS IT IS ON PURPOSE: the registry declares
8491        // upstream's 3000000, pounce's effective cap is 3000
8492        // (`RestoOptions::default`). `read_int` fires only when the user set
8493        // the key, so an unset `max_resto_iter` still means 3000 and this
8494        // wiring is trajectory-neutral. Adopting upstream's number would let
8495        // restorations pounce currently truncates run on, which is a
8496        // trajectory change and needs its own measurement.
8497        if let Some(v) = read_int("max_resto_iter") {
8498            builder.resto.max_resto_iter = v;
8499        }
8500
8501        // Iteration-output options — consumed by `OrigIterationOutput`.
8502        if let Some(v) = read_int("print_frequency_iter") {
8503            builder.output.print_frequency_iter = v;
8504        }
8505        if let Some(v) = read_num("print_frequency_time") {
8506            builder.output.print_frequency_time = v;
8507        }
8508        if let Ok((v, found)) = self.options.get_bool_value("print_info_string", "") {
8509            if found {
8510                builder.output.print_info_string = v;
8511            }
8512        }
8513        if let Ok((v, found)) = self.options.get_string_value("inf_pr_output", "") {
8514            if found {
8515                builder.output.inf_pr_output_internal = v == "internal";
8516            }
8517        }
8518
8519        // Warm-start options — consumed by `WarmStartIterateInitializer`
8520        // (port of `IpWarmStartIterateInitializer.cpp:RegisterOptions`).
8521        // `warm_start_init_point` is the toggle that picks between the
8522        // default (cold) and warm-start initializers; the remaining
8523        // knobs are baked onto the chosen initializer at build time.
8524        if let Ok((v, found)) = self.options.get_bool_value("warm_start_init_point", "") {
8525            if found {
8526                builder.warm_start_init_point = v;
8527            }
8528        }
8529        if let Some(v) = read_num("warm_start_bound_push") {
8530            builder.warm.bound_push = v;
8531        }
8532        if let Some(v) = read_num("warm_start_bound_frac") {
8533            builder.warm.bound_frac = v;
8534        }
8535        if let Some(v) = read_num("warm_start_slack_bound_push") {
8536            builder.warm.slack_bound_push = v;
8537        }
8538        if let Some(v) = read_num("warm_start_slack_bound_frac") {
8539            builder.warm.slack_bound_frac = v;
8540        }
8541        if let Some(v) = read_num("warm_start_mult_bound_push") {
8542            builder.warm.mult_bound_push = v;
8543        }
8544        if let Some(v) = read_num("warm_start_mult_init_max") {
8545            builder.warm.mult_init_max = v;
8546        }
8547        if let Some(v) = read_num("warm_start_target_mu") {
8548            builder.warm.target_mu = v;
8549        }
8550        // gh#606: residual-adaptive recentering. `warm_start_entire_iterate`
8551        // and `warm_start_same_structure` used to be parsed here into
8552        // fields nothing read; they are refused by
8553        // `unimplemented_options` instead (they name the
8554        // `GetWarmStartIterate` TNLP surface pounce does not expose).
8555        if let Ok((v, found)) = self.options.get_string_value("warm_start_recentering", "") {
8556            if found {
8557                builder.warm.recentering = if v.eq_ignore_ascii_case("none") {
8558                    crate::alg_builder::WarmStartRecentering::None
8559                } else {
8560                    crate::alg_builder::WarmStartRecentering::Residual
8561                };
8562            }
8563        }
8564
8565        // `DefaultIterateInitializer` knobs — parsed after the Mehrotra
8566        // cascade so explicit user values win
8567        // (mirrors upstream's `SetNumericValueIfUnset` semantics).
8568        if let Some(v) = read_num("bound_push") {
8569            builder.init.bound_push = v;
8570        }
8571        if let Some(v) = read_num("bound_frac") {
8572            builder.init.bound_frac = v;
8573        }
8574        if let Some(v) = read_num("slack_bound_push") {
8575            builder.init.slack_bound_push = v;
8576        }
8577        if let Some(v) = read_num("slack_bound_frac") {
8578            builder.init.slack_bound_frac = v;
8579        }
8580        if let Some(v) = read_num("constr_mult_init_max") {
8581            builder.init.constr_mult_init_max = v;
8582        }
8583        if let Some(v) = read_num("bound_mult_init_val") {
8584            builder.init.bound_mult_init_val = v;
8585        }
8586        if let Ok((v, found)) = self.options.get_string_value("bound_mult_init_method", "") {
8587            if found {
8588                builder.init.bound_mult_init_method = v;
8589            }
8590        }
8591        if let Ok((v, found)) = self
8592            .options
8593            .get_string_value("least_square_init_primal", "")
8594        {
8595            if found {
8596                builder.init.least_square_init_primal = v == "yes";
8597            }
8598        }
8599        builder
8600    }
8601}
8602
8603/// Map the integer `print_level` / `file_print_level` option to the
8604/// matching [`JournalLevel`] variant. Mirrors upstream's
8605/// `static_cast<EJournalLevel>(int_value)` with clamping.
8606/// The eight block dimensions of an iterate, in canonical order
8607/// (x, s, y_c, y_d, z_l, z_u, v_l, v_u). Used to guard the debugger's
8608/// warm-restart install against a structural mismatch between solves.
8609fn iterates_dims(c: &IteratesVector) -> [i32; 8] {
8610    [
8611        c.x.dim(),
8612        c.s.dim(),
8613        c.y_c.dim(),
8614        c.y_d.dim(),
8615        c.z_l.dim(),
8616        c.z_u.dim(),
8617        c.v_l.dim(),
8618        c.v_u.dim(),
8619    ]
8620}
8621
8622fn journal_level_from_int(v: i32) -> JournalLevel {
8623    match v.clamp(0, 12) {
8624        0 => JournalLevel::J_NONE,
8625        1 => JournalLevel::J_ERROR,
8626        2 => JournalLevel::J_STRONGWARNING,
8627        3 => JournalLevel::J_SUMMARY,
8628        4 => JournalLevel::J_WARNING,
8629        5 => JournalLevel::J_ITERSUMMARY,
8630        6 => JournalLevel::J_DETAILED,
8631        7 => JournalLevel::J_MOREDETAILED,
8632        8 => JournalLevel::J_VECTOR,
8633        9 => JournalLevel::J_MOREVECTOR,
8634        10 => JournalLevel::J_MATRIX,
8635        11 => JournalLevel::J_MOREMATRIX,
8636        _ => JournalLevel::J_ALL,
8637    }
8638}
8639
8640/// MA57 backend knobs snapshotted off an `OptionsList`, ready to be
8641/// handed to a backend factory.
8642///
8643/// The type exists — rather than passing `pounce_hsl::Ma57Options`
8644/// directly — so that the factory signature is the same shape whether or
8645/// not the `ma57` cargo feature is on. `pounce-py`, `pounce-cinterface`
8646/// and `pounce-restoration` all call [`default_backend_factory`] and none
8647/// of them can name a `pounce-hsl` type; without the feature this struct
8648/// carries nothing and costs nothing.
8649///
8650/// Build it with [`ma57_config_from_options`]. It is the MA57 half of
8651/// what [`feral_config_from_options`] does for FERAL, and the asymmetry
8652/// between the two was the root cause of gh#825: FERAL's knobs were
8653/// threaded into the factory and MA57's were not, so the factory had
8654/// nothing to give MA57 and called `Ma57SolverInterface::new()` — which
8655/// hard-codes the defaults. Every `ma57_*` option was registered,
8656/// documented, accepted, and then silently discarded.
8657#[derive(Debug, Clone, Default)]
8658pub struct Ma57Config {
8659    #[cfg(feature = "ma57")]
8660    opts: pounce_hsl::Ma57Options,
8661}
8662
8663impl Ma57Config {
8664    /// The wrapped MA57 settings.
8665    #[cfg(feature = "ma57")]
8666    pub fn options(&self) -> &pounce_hsl::Ma57Options {
8667        &self.opts
8668    }
8669}
8670
8671/// Read the `ma57_*` options off `options` under `prefix`, for handing
8672/// to [`default_backend_factory`] / [`default_backend_factory_with_sink`].
8673///
8674/// `prefix` is `""` for the main IPM and `"resto."` for the restoration
8675/// sub-IPM, mirroring upstream's
8676/// `Ma57TSolverInterface::InitializeImpl(options, prefix)`. The
8677/// restoration sub-IPM builds its own backend through its own
8678/// `InnerBackendFactoryFactory` (see
8679/// `pounce_restoration::resto_inner_solver`), so the two really are
8680/// separately configurable — before gh#825 neither was.
8681///
8682/// Without the `ma57` cargo feature this returns an empty config and
8683/// does not touch `options`; nothing downstream can consume MA57
8684/// settings in that build.
8685pub fn ma57_config_from_options(
8686    options: &pounce_common::options_list::OptionsList,
8687    prefix: &str,
8688) -> Ma57Config {
8689    #[cfg(feature = "ma57")]
8690    {
8691        Ma57Config {
8692            opts: pounce_hsl::Ma57Options::from_options_list(options, prefix),
8693        }
8694    }
8695    #[cfg(not(feature = "ma57"))]
8696    {
8697        let _ = (options, prefix);
8698        Ma57Config::default()
8699    }
8700}
8701
8702/// Construct the MA57 backend for a factory, or fall back to FERAL when
8703/// the `ma57` cargo feature is off.
8704///
8705/// Factored out of the two factories below so there is exactly one place
8706/// that decides how an MA57 backend is built from a [`Ma57Config`]. Both
8707/// factories used to inline `Ma57SolverInterface::new()`, and the
8708/// duplication is half of why gh#825 was easy to miss.
8709fn make_ma57_backend(
8710    ma57_cfg: &Ma57Config,
8711    feral_fallback: impl FnOnce() -> Box<dyn SparseSymLinearSolverInterface>,
8712) -> Box<dyn SparseSymLinearSolverInterface> {
8713    #[cfg(feature = "ma57")]
8714    {
8715        let _ = feral_fallback;
8716        Box::new(pounce_hsl::Ma57SolverInterface::with_options(
8717            *ma57_cfg.options(),
8718        ))
8719    }
8720    #[cfg(not(feature = "ma57"))]
8721    {
8722        // ma57 feature not compiled in — fall back to FERAL.
8723        let _ = ma57_cfg;
8724        feral_fallback()
8725    }
8726}
8727
8728/// Default symmetric linear-solver factory, parameterized by the
8729/// pounce-extension FERAL knobs and the `ma57_*` knobs read off the
8730/// application's `OptionsList`.
8731///
8732/// FERAL (pure-Rust) is the shipping default. The HSL MA57 backend is
8733/// available when the `ma57` cargo feature is enabled; without it,
8734/// requesting `linear_solver = ma57` falls back to FERAL with a
8735/// warning printed by the journalist (see [`AlgorithmBuilder`]).
8736///
8737/// Both configs are snapshots, not live views: take them with
8738/// [`feral_config_from_options`] and [`ma57_config_from_options`] at the
8739/// point the application's options are fully populated. The factory is
8740/// called more than once per solve (the main KKT solver and, under
8741/// limited memory, the Hessian-free bypass solver), so each call gets a
8742/// fresh backend built from the same snapshot.
8743pub fn default_backend_factory(
8744    feral_cfg: pounce_feral::FeralConfig,
8745    ma57_cfg: Ma57Config,
8746) -> LinearBackendFactory {
8747    Box::new(
8748        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8749            match choice {
8750                LinearSolverChoice::Feral => Box::new(
8751                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone()),
8752                ),
8753                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8754                    Box::new(pounce_feral::FeralSolverInterface::with_config(
8755                        feral_cfg.clone(),
8756                    ))
8757                }),
8758            }
8759        },
8760    )
8761}
8762
8763/// Turn a model-space block declaration into the KKT-space labels the block
8764/// solver takes (structured-KKT Phase 5b's mapper, plan §63.6).
8765///
8766/// The KKT is laid out `[x | slacks | equality duals | inequality duals]`, so
8767/// each part inherits a label from what it belongs to:
8768///
8769/// * an `x` column takes its variable's label — skipping variables fixed out
8770///   by `fixed_variable_treatment`, which are not in the KKT at all;
8771/// * a slack and its inequality dual take their constraint's label;
8772/// * an equality dual takes its constraint's label.
8773///
8774/// `var_blocks` / `con_blocks` are in the model's own indexing (`n_full_x`,
8775/// `n_full_g`); negative means shared. Returns the label per KKT index, or an
8776/// error naming the mismatch — the caller then falls back rather than
8777/// mislabel, because a label that is off by one row silently declares a
8778/// structure the matrix does not have.
8779pub fn map_block_structure_to_kkt(
8780    cls: &pounce_nlp::tnlp_adapter::BoundClassification,
8781    var_blocks: &[i32],
8782    con_blocks: &[i32],
8783) -> Result<Vec<i32>, String> {
8784    if var_blocks.len() != cls.n_full_x as usize {
8785        return Err(format!(
8786            "block structure has {} variable labels, the problem has {} variables",
8787            var_blocks.len(),
8788            cls.n_full_x
8789        ));
8790    }
8791    if con_blocks.len() != cls.n_full_g as usize {
8792        return Err(format!(
8793            "block structure has {} constraint labels, the problem has {} constraints",
8794            con_blocks.len(),
8795            cls.n_full_g
8796        ));
8797    }
8798    let n_x = cls.x_not_fixed_map.len();
8799    let n_c = cls.c_map.len();
8800    let n_d = cls.d_map.len();
8801    let mut labels = Vec::with_capacity(n_x + 2 * n_d + n_c);
8802    for &full in &cls.x_not_fixed_map {
8803        labels.push(var_blocks[full as usize]);
8804    }
8805    for &full in &cls.d_map {
8806        labels.push(con_blocks[full as usize]); // slack
8807    }
8808    for &full in &cls.c_map {
8809        labels.push(con_blocks[full as usize]); // equality dual
8810    }
8811    for &full in &cls.d_map {
8812        labels.push(con_blocks[full as usize]); // inequality dual
8813    }
8814    Ok(labels)
8815}
8816
8817/// Sink-aware variant of [`default_backend_factory`]. Identical
8818/// dispatch, but the FERAL backend is constructed with a
8819/// `LinearSolverSummary` sink so [`IpoptApplication`] can read out
8820/// aggregate post-mortem stats (factor counts, fill ratio, extremal
8821/// pivots, final inertia) after the solve returns. MA57 ignores the
8822/// sink — the HSL backend doesn't carry the same instrumentation yet.
8823pub fn default_backend_factory_with_sink(
8824    feral_cfg: pounce_feral::FeralConfig,
8825    ma57_cfg: Ma57Config,
8826    sink: Arc<Mutex<LinearSolverSummary>>,
8827) -> LinearBackendFactory {
8828    Box::new(
8829        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8830            match choice {
8831                LinearSolverChoice::Feral => Box::new(
8832                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8833                        .with_summary_sink(Arc::clone(&sink)),
8834                ),
8835                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8836                    Box::new(
8837                        pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8838                            .with_summary_sink(Arc::clone(&sink)),
8839                    )
8840                }),
8841            }
8842        },
8843    )
8844}
8845
8846/// Read the `feral_*` extension options off `options`, falling
8847/// back to the env-var defaults baked into [`pounce_feral::FeralConfig::from_env`]
8848/// for any knob the caller did not set explicitly. The returned
8849/// config is what every default-factory invocation (main IPM and
8850/// restoration sub-IPM) consumes.
8851pub fn feral_config_from_options(
8852    options: &pounce_common::options_list::OptionsList,
8853) -> pounce_feral::FeralConfig {
8854    feral_config_from_options_scoped(options, RefineCarveOut::InteriorPoint)
8855}
8856
8857/// Whether [`feral_config_from_options_scoped`] applies the interior-point
8858/// arm's limited-memory `feral_refine` carve-out.
8859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8860pub enum RefineCarveOut {
8861    /// Apply it: under `hessian_approximation=limited-memory`, force
8862    /// `refine = false` unless the user said otherwise. This is the shipped
8863    /// interior-point behaviour and what [`feral_config_from_options`] does.
8864    InteriorPoint,
8865    /// Skip it. For arms that do not refine the unreduced system themselves,
8866    /// where the backend loop is the only refinement in the stack.
8867    None,
8868}
8869
8870/// [`feral_config_from_options`] with the limited-memory `refine` carve-out
8871/// made explicit.
8872///
8873/// The carve-out is interior-point-specific in both of its premises, and
8874/// neither holds on the active-set SQP arm. It is justified by
8875/// `PdFullSpaceSolver::compute_residuals` already refining the *unreduced*
8876/// Newton system — the SQP arm has no such host loop, so
8877/// `pounce_qp::factor::LinearSolver` relies on the backend's own refinement
8878/// ("refinement is *implicit* in this layer", that module's docs) and turning
8879/// it off removes refinement from the stack entirely. And it keys off
8880/// `hessian_approximation`, which is not that arm's Hessian selector at all:
8881/// `sqp_hessian` is.
8882///
8883/// Measured, and this is why the parameter exists rather than the SQP path
8884/// just calling the plain function: inheriting the carve-out moved 10 of 97
8885/// fixtures on the sweep's L-BFGS leg under `algorithm=active-set-sqp`, while
8886/// the exact leg did not move at all. Some of that movement looked like a win
8887/// (`mu_fallback_point_floor` MaximumIterationsExceeded/200 ->
8888/// SolveSucceeded/8), but it was a win bought by disabling refinement for a
8889/// reason that does not apply here, and it came with `hs13_bigstart` landing
8890/// on a different point (objective 1 -> 1.0018) and `eigena2` and
8891/// `mpcc_scholtes4_biactive` likewise. Turning refinement off on this arm may
8892/// well be worth measuring on its own merits; it should not arrive as a side
8893/// effect of honouring `linear_solver`.
8894pub fn feral_config_from_options_scoped(
8895    options: &pounce_common::options_list::OptionsList,
8896    carve_out: RefineCarveOut,
8897) -> pounce_feral::FeralConfig {
8898    let mut cfg = pounce_feral::FeralConfig::from_env();
8899    // Tri-state: the `(_, true)` arm only fires when the user set the
8900    // option explicitly. Leaving it unset keeps `cfg.cascade_break` at
8901    // `None`, which inherits FERAL's `NumericParams::default()` (CB on
8902    // as of FERAL Phase B / pounce#55). `Some(false)` explicitly
8903    // disarms (reproduces pre-Phase-B behaviour, surfaces FERAL's
8904    // `DelayBudgetExceeded` on non-root cascade victims).
8905    if let Ok((v, true)) = options.get_bool_value("feral_cascade_break", "") {
8906        cfg.cascade_break = Some(v);
8907    }
8908    if let Ok((v, true)) = options.get_bool_value("feral_fma", "") {
8909        cfg.fma = v;
8910    }
8911    // Not tri-state, and deliberately not: on the limited-memory path
8912    // the IPM's default is the opposite of the library's (gh#710,
8913    // gh#698 obs 5). `FeralConfig` ships `refine = true` because a
8914    // caller that only refines its own system needs the backend loop.
8915    //
8916    // Scoped to limited-memory, because that is where the win was
8917    // measured and where it comes from. Under L-BFGS the Hessian-free
8918    // bypass batches the low-rank SMW correction into one multi-RHS
8919    // back-solve, and the backend loop refines per right-hand side, so
8920    // its cost scales with the memory depth — while what it polishes is
8921    // the *condensed* system, which is not where Waechter-Biegler 3.10
8922    // puts refinement. Turning it off takes `laptime` under
8923    // limited-memory from 1397 s to 394 s.
8924    //
8925    // The same switch is a net loss on the exact path, so it is not
8926    // applied there. It costs `NARX_CFy` 230 iterations (400 -> 630,
8927    // 173 s -> 250 s) to buy back 34 on `laptime` (380 -> 346). And the
8928    // exact path has no rung left to stand in for it: the
8929    // `increase_quality` escalation that once argued for dropping the
8930    // backend loop here proved inert and was itself removed, so with
8931    // `refine` off the host loop in `PdFullSpaceSolver` is the only
8932    // refinement in the stack — and it stops the moment it crosses
8933    // `residual_ratio_max` (1e-10), three orders looser than the ~1e-16
8934    // the backend-refined solves reach.
8935    //
8936    // Tightening that threshold instead is not the fix, and was measured
8937    // rather than assumed: it is chaotic on this corpus, flipping `deb7`
8938    // to `Error_In_Step_Computation` at 1e-12 and swinging
8939    // `pooling_rt2stp` between 107 and 199 iterations across 1e-11 to
8940    // 1e-13. Forcing extra passes via `min_refinement_steps` behaves the
8941    // same way (both fixtures break at 2). Restoring the backend loop is
8942    // trajectory-neutral next to either (`deb7` 146 -> 147,
8943    // `pooling_rt2stp` 107 -> 109).
8944    //
8945    // Ordered env-then-registry-then-option so `POUNCE_FERAL_REFINE`
8946    // still reaches this path and an explicit `feral_refine` still beats
8947    // both.
8948    //
8949    // gh#909: the registry read below takes the value and IGNORES the
8950    // found flag, which is the whole point. Reading it as `Ok((v, true))`
8951    // — the tri-state shape every other option in this function uses —
8952    // consults the user's setting and never the *registered default*, so
8953    // an unset option left `cfg.refine` at `FeralConfig::default()`'s
8954    // `true` while `pounce --print-options` reported the registry's.
8955    // Registered `no`, ran `yes`: the gh#677 shape, one option family
8956    // over. It is fixed by making the registry authoritative here rather
8957    // than by changing what runs — see below for why — so the registered
8958    // default moved to `yes` in the same commit and this read is what
8959    // keeps the two from drifting apart again.
8960    //
8961    // The scoping stays. There is no single default that is right on both
8962    // paths, and this is a two-sided trade of the same shape as
8963    // `feral_increase_quality` above: the option is the lever, and the
8964    // default is a choice rather than a fact. Measured on `e5f5830b`,
8965    // one binary, `feral_refine=no` against the default:
8966    //
8967    //   fixture corpus, exact leg: 10 legs move, NO status flips, and
8968    //     the net is favourable -- `issue_508_infeasible_gap_1em4`
8969    //     441 -> 245, `square_flowsheet_resto` 54 -> 47 (tot 185 -> 176),
8970    //     `issue_508_infeasible_gap_1em2` 114 -> 112, `deb7` 147 -> 146,
8971    //     `pooling_rt2stp` 109 -> 107, against one loss
8972    //     (`mu_fallback_point_floor` 31 -> 32).
8973    //   fixture corpus, lbfgs leg: identical, refine is already off there.
8974    //   `NARX_CFy` (Mittelmann): 400 -> 630 iterations, 208.7 s -> 254.2 s.
8975    //   `eigena2` final dual infeasibility: 3.43e-10 -> 5.20e-09, both
8976    //     inside `tol`, and see `issue_540_eigena2_superlinear_tail.rs`.
8977    //   AC-OPF (PGLib), gh#909: 10-18% faster, iteration counts
8978    //     unchanged, solution identical to ~13 significant figures.
8979    //
8980    // So the corpus and the AC-OPF benchmarks both prefer `no` and
8981    // `NARX_CFy` pays 57% more iterations for it. Nothing here separates
8982    // those, which is why the default is scoped rather than flipped.
8983    let limited_memory = carve_out == RefineCarveOut::InteriorPoint
8984        && matches!(
8985            options.get_string_value("hessian_approximation", ""),
8986            Ok((ref s, true)) if s == "limited-memory"
8987        );
8988    if std::env::var_os("POUNCE_FERAL_REFINE").is_none() {
8989        // Deliberately `_`, not `true`: see above.
8990        if let Ok((v, _)) = options.get_bool_value("feral_refine", "") {
8991            cfg.refine = v;
8992        }
8993        if limited_memory {
8994            cfg.refine = false;
8995        }
8996    }
8997    // An explicit setting beats both the carve-out and the environment.
8998    if let Ok((v, true)) = options.get_bool_value("feral_refine", "") {
8999        cfg.refine = v;
9000    }
9001    // gh #850: `feral_increase_quality` exists because this rung is a genuine
9002    // two-sided trade, and the option is the lever — the default is left ON,
9003    // which is the 0.11 behaviour.
9004    //
9005    // Ipopt's `IncreaseQuality` contract assumes a *monotone* escalation: MA57
9006    // raises `pivtol` toward `pivtolmax`, strictly more conservative each time,
9007    // so keeping it raised for the rest of the solve can only make the
9008    // factorization safer. FERAL's ladder changes which pivots are taken, which
9009    // is lateral in trajectory terms, and it persists the same way. So it
9010    // reroutes solves, and the reroute goes both ways:
9011    //
9012    //   it COSTS two whole solves, both `square_flowsheet_resto`:
9013    //     exact  Optimal/99  -> RestorationFailed/131 (a second-opinion rung
9014    //                          rescues it, at 185 iterations total)
9015    //     lbfgs  Optimal/178 -> 3000 iterations at the cap, rescued by nothing
9016    //   it BUYS accuracy where nothing else does:
9017    //     `watchdog_trial_is_not_a_divergence_verdict`'s 12-variable model ends
9018    //     `SolvedToAcceptableLevel` at obj 3.7e-6 with the rung and at obj 3.42
9019    //     against `f* = 0` without it — a wrong-ish answer under a
9020    //     success-shaped status, which is worse than an honest failure.
9021    //   and it buys iterations on five more fixture-legs (15-25%).
9022    //
9023    // There is no scoping that separates those. Measured with a process-global
9024    // firing cap on `square_flowsheet_resto`: the rung fires twice, once in the
9025    // main solve at iteration 25 and once inside restoration at `76r`, and
9026    // allowing only the first still loses the leg — so declining it just for
9027    // the restoration sub-solve would not help. Nor does a count separate them:
9028    // `deb7` and `square_flowsheet_resto` each fire it exactly twice on their
9029    // exact legs, one gaining 16% of its iterations and the other losing its
9030    // verdict.
9031    //
9032    // So the default stands, and the losing direction now recovers itself:
9033    // `feral_increase_quality_retry` (gh#857) re-solves once with this off when
9034    // a solve that actually escalated ends `Restoration_Failed` or
9035    // `Maximum_Iterations_Exceeded`.
9036    //
9037    // It is a re-solve rather than a *revertible* escalation because the
9038    // revertible one was tried. jkitchin/feral#192 landed as `reset_quality`,
9039    // was plumbed here and instrumented (376 escalations, 376 matching resets
9040    // on one solve), and recovers neither leg at either re-baselining boundary
9041    // -- the harm is the destination, not the duration. See
9042    // `dev-notes/second-opinion-promotions-in-the-sweep.md`.
9043    if let Ok((v, true)) = options.get_bool_value("feral_increase_quality", "") {
9044        cfg.increase_quality = v;
9045    }
9046    // Only consulted when `refine` is on; see `FeralConfig::refine_max_steps`
9047    // (gh#710). Registered as an integer option with lower bound 0, so the
9048    // cast cannot go negative.
9049    if let Ok((v, true)) = options.get_integer_value("feral_refine_steps", "") {
9050        cfg.refine_max_steps = v.max(0) as usize;
9051    }
9052    // Also only consulted when `refine` is on. Registered with lower bound
9053    // 0, and 0 disables the pre-check; see `FeralConfig::refine_target`.
9054    if let Ok((v, true)) = options.get_numeric_value("feral_refine_target", "") {
9055        cfg.refine_target = v.max(0.0);
9056    }
9057    // Explicit static-pivoting opt-in (feral#8 cascade breaker, pounce#254).
9058    // Same tri-state discipline: unset leaves `cfg.static_pivoting` at
9059    // whatever `from_env` resolved (`None` → inherit feral's delayed-pivot
9060    // default), so the default numeric path is unchanged.
9061    if let Ok((v, true)) = options.get_bool_value("feral_static_pivoting", "") {
9062        cfg.static_pivoting = Some(v);
9063    }
9064    if let Ok((v, true)) = options.get_numeric_value("feral_singular_pivot_floor", "") {
9065        cfg.singular_pivot_floor = v;
9066    }
9067    // Explicitly set pins an absolute floor for every dimension (`0`
9068    // disables the trigger); left unset, `None` keeps the dimension-aware
9069    // `n * eps` default (pounce gh#592).
9070    if let Ok((v, true)) = options.get_numeric_value("feral_inertia_pivot_floor", "") {
9071        cfg.inertia_pivot_floor = Some(v);
9072    }
9073    // Number option (not integer): the gate is a u64 and Index is i32, too
9074    // narrow for large flop counts or the u64::MAX reject-all sentinel. The
9075    // lower bound (0.0) rules out negatives; `as u64` then saturates a very
9076    // large finite value to u64::MAX (reject all tree-level parallelism).
9077    if let Ok((v, true)) = options.get_numeric_value("feral_min_par_flops", "") {
9078        cfg.min_par_flops = Some(v as u64);
9079    }
9080    if let Ok((v, true)) = options.get_numeric_value("feral_pivtol", "") {
9081        cfg.pivtol = v;
9082    }
9083    // Only override on explicit set so `from_env` (which itself
9084    // defaults to OrderingMethod::Auto) keeps governing unset cases.
9085    // Unrecognized tags are silently ignored — the registered enum
9086    // restricts inputs at the OptionsList layer.
9087    if let Ok((v, true)) = options.get_string_value("feral_ordering", "") {
9088        if let Some(m) = pounce_feral::parse_ordering_method(&v) {
9089            cfg.ordering = m;
9090        }
9091    }
9092    if let Ok((v, true)) = options.get_string_value("feral_ordering_preprocess", "") {
9093        if let Some(p) = pounce_feral::parse_ordering_preprocess(&v) {
9094            cfg.ordering_preprocess = p;
9095        }
9096    }
9097    // Same explicit-set discipline as `feral_ordering`: `from_env`
9098    // defaults to ScalingStrategy::Auto (FERAL's current default), so
9099    // leaving the option unset preserves existing behaviour exactly.
9100    if let Ok((v, true)) = options.get_string_value("feral_scaling", "") {
9101        if let Some(s) = pounce_feral::parse_scaling_strategy(&v) {
9102            cfg.scaling = s;
9103        }
9104    }
9105    cfg
9106}
9107
9108/// Withdraw a numerical infeasibility verdict the model's own starting point
9109/// disproves.
9110///
9111/// Applied at every site in this file that can return
9112/// `Infeasible_Problem_Detected` from a *numerical* argument — the IPM path's
9113/// restoration / cycle gates, the SQP path's infeasible-subproblem exit, and the
9114/// ℓ₁ wrapper's uncollapsed-slack certificate. Deliberately one gate rather than
9115/// three: the two preceding safeguards in this area (gh #376, gh #380) were each
9116/// added to one path and not its twin, and a hole survived both times.
9117///
9118/// Not applied to a presolve *certificate*
9119/// (`TNLP::presolve_infeasibility_proof`), which carries its own, tighter
9120/// refutation
9121/// (`pounce_presolve::witness_refutes_infeasibility`) and is a proof rather than
9122/// a numerical inference.
9123///
9124/// The replacement is `Error_In_Step_Computation`, the status this codebase
9125/// already uses for "the solve broke down and we are **not** claiming
9126/// infeasibility" — see the `cycle_exit` fallback in
9127/// [`crate::ipopt_alg::IpoptAlgorithm::invoke_restoration`], which picks between
9128/// exactly these two on exactly this question. It maps to AMPL 500, an honest
9129/// failure the caller can see, instead of AMPL 200, a wrong answer they cannot.
9130///
9131/// gh #379.
9132fn withdraw_infeasibility_if_refuted(
9133    tnlp: &Rc<RefCell<dyn TNLP>>,
9134    solver_status: SolverReturn,
9135    lo_inf: Number,
9136    up_inf: Number,
9137    tol: Number,
9138) -> SolverReturn {
9139    if solver_status != SolverReturn::LocalInfeasibility {
9140        return solver_status;
9141    }
9142    // A presolve proof is not a numerical inference; it does its own refutation.
9143    if tnlp.borrow().presolve_infeasibility_proof().is_some() {
9144        return solver_status;
9145    }
9146    match crate::infeasibility_refutation::starting_point_refutes_infeasibility(
9147        tnlp, lo_inf, up_inf, tol,
9148    ) {
9149        Some(w) => {
9150            tracing::debug!(
9151                target: "pounce::application",
9152                "[PN_INFEAS_REFUTED] the model's starting point satisfies every constraint \
9153                 (max violation {:.3e}) — withdrawing Infeasible_Problem_Detected",
9154                w.max_violation
9155            );
9156            SolverReturn::ErrorInStepComputation
9157        }
9158        None => solver_status,
9159    }
9160}
9161
9162/// How well a point satisfies the **user's own** rows and bounds.
9163///
9164/// Computed from `g = c(x)` and the inner TNLP's declared bounds, in the
9165/// user's units, with no reference to whatever problem the algorithm
9166/// actually iterated on. That distinction is the whole reason this
9167/// exists: on the ℓ₁ path the IPM converges the *augmented* NLP
9168/// `c(x) − p + n = target`, whose equality rows the slacks satisfy to
9169/// machine precision by construction, and reporting that residual as
9170/// the solve's constraint violation says nothing about `c(x) − target`
9171/// (gh#794 finding P1).
9172struct OriginalSpaceFeasibility {
9173    /// Largest absolute violation of any row or bound, in the user's units.
9174    max_violation: Number,
9175    /// Every row and bound negligible at `tol`, judged scale-relative.
9176    negligible_at_tol: bool,
9177    /// The same at `acceptable_tol`.
9178    negligible_at_acceptable: bool,
9179}
9180
9181/// Measure [`OriginalSpaceFeasibility`] at `x`, given `g = c(x)`.
9182///
9183/// `is_negligible` rather than `!is_significant`, deliberately, and for
9184/// the reason that function's own documentation gives: the question here
9185/// is "did the solve converge well enough to call this point feasible",
9186/// which must never demand more precision than the solver promised, so
9187/// the threshold is clamped at `tol` from below (`tol · max(|scale|, 1)`).
9188/// The refutation path next door asks the opposite question — "is this
9189/// residual real at this row's scale" — and correctly uses the pure
9190/// relative form.
9191///
9192/// Returns `None` when the model cannot be measured (bounds unreadable, a
9193/// non-finite value). `None` means "not measured", never "feasible": the
9194/// caller keeps whatever verdict it already had.
9195fn original_space_feasibility(
9196    tnlp: &Rc<RefCell<dyn TNLP>>,
9197    x: &[Number],
9198    g: &[Number],
9199    lower_bound_inf: Number,
9200    upper_bound_inf: Number,
9201    tol: Number,
9202    acceptable_tol: Number,
9203    constr_viol_tol: Number,
9204    acceptable_constr_viol_tol: Number,
9205    noise_floor_kappa: Number,
9206) -> Option<OriginalSpaceFeasibility> {
9207    use pounce_common::tolerance::is_negligible;
9208
9209    let info = tnlp.borrow_mut().get_nlp_info()?;
9210    let n = info.n.max(0) as usize;
9211    let m = info.m.max(0) as usize;
9212    if x.len() < n || g.len() < m {
9213        return None;
9214    }
9215
9216    let mut x_l = vec![0.0; n];
9217    let mut x_u = vec![0.0; n];
9218    let mut g_l = vec![0.0; m];
9219    let mut g_u = vec![0.0; m];
9220    if !tnlp.borrow_mut().get_bounds_info(BoundsInfo {
9221        x_l: &mut x_l,
9222        x_u: &mut x_u,
9223        g_l: &mut g_l,
9224        g_u: &mut g_u,
9225    }) {
9226        return None;
9227    }
9228
9229    let mut max_violation: Number = 0.0;
9230    let mut ok_tol = true;
9231    let mut ok_acceptable = true;
9232
9233    // Only *finite, present* bounds inform a row's magnitude: letting the
9234    // `±1e19` sentinel set the scale would make every row look satisfied,
9235    // the same trap `infeasibility_refutation` documents.
9236    let present = |b: Number, is_lower: bool| -> Option<Number> {
9237        let absent = if is_lower {
9238            b <= lower_bound_inf
9239        } else {
9240            b >= upper_bound_inf
9241        };
9242        (b.is_finite() && !absent).then_some(b)
9243    };
9244
9245    // Accumulates into `max_violation` / `ok_tol` / `ok_acceptable`; a
9246    // non-positive `viol` means the side is satisfied and contributes
9247    // nothing. Returns nothing — every caller is a statement.
9248    let mut judge = |viol: Number, scale: Number| {
9249        if viol <= 0.0 {
9250            return;
9251        }
9252        max_violation = max_violation.max(viol);
9253        // The scale-relative test alone is not a feasibility standard, and
9254        // on a large-magnitude row it is not even close to one: it accepts
9255        // anything up to `tol · |row|`, which on a row near `1e10` is `1e2`
9256        // at the default `tol`. An adversary probe on this branch built a
9257        // model infeasible by exactly `50` with its row at `1e10` and got
9258        // `Solve_Succeeded` — a *worse* verdict than this branch's own
9259        // parent, which refused the same point (the old `Σ(p+n)` argument
9260        // was crude but absolute). So the wrapper has to judge feasibility
9261        // the way the rest of the solver does.
9262        //
9263        // `OptErrorConvCheck::primal_component_passes` is that standard:
9264        // an absolute `constr_viol <= constr_viol_tol`, with scale-awareness
9265        // supplied by an abstention when every row sits at its own
9266        // floating-point noise floor (gh#528/gh#590) rather than by
9267        // multiplying the tolerance by the row's magnitude. That
9268        // abstention "cannot fabricate a success on a genuinely infeasible
9269        // model: such a model's violation is pinned at its infeasibility
9270        // gap, orders above `eps ·` the row's own magnitude" — which is
9271        // exactly the property `is_negligible` lacks and the probe
9272        // exploited (`50` is `~2e7 ×` this row's floor).
9273        //
9274        // The strict gate's `primal_resolvable` cannot be reused verbatim:
9275        // it is computed by the CQ on the *augmented* NLP, whose rows the
9276        // slacks satisfy to machine precision, so it would abstain always
9277        // and accept everything. The floor is therefore recomputed here on
9278        // the user's own row, from the same `kappa · eps · magnitude` the
9279        // option documents. `primal_noise_floor_kappa = 0` opts out, as it
9280        // does for the strict gate.
9281        //
9282        // Both arms are conjoined rather than substituted: the relative
9283        // test still catches a violation that is small in absolute terms
9284        // but large for its row, which is the gh#794 P1 case itself
9285        // (`ralph1` at `2.5e-7` under a `2.5e-11` tol).
9286        let noise = noise_floor_kappa * Number::EPSILON * scale.abs();
9287        let absolute_ok = |bound: Number| viol <= bound || viol <= noise;
9288        ok_tol &= is_negligible(viol, scale, tol) && absolute_ok(constr_viol_tol);
9289        ok_acceptable &=
9290            is_negligible(viol, scale, acceptable_tol) && absolute_ok(acceptable_constr_viol_tol);
9291    };
9292
9293    for i in 0..m {
9294        let v = g[i];
9295        if !v.is_finite() {
9296            return None;
9297        }
9298        let lo = present(g_l[i], true);
9299        let hi = present(g_u[i], false);
9300        let scale = v
9301            .abs()
9302            .max(lo.map_or(0.0, Number::abs))
9303            .max(hi.map_or(0.0, Number::abs));
9304        judge(lo.map_or(0.0, |b| b - v), scale);
9305        judge(hi.map_or(0.0, |b| v - b), scale);
9306    }
9307    for j in 0..n {
9308        let v = x[j];
9309        if !v.is_finite() {
9310            return None;
9311        }
9312        let lo = present(x_l[j], true);
9313        let hi = present(x_u[j], false);
9314        let scale = v
9315            .abs()
9316            .max(lo.map_or(0.0, Number::abs))
9317            .max(hi.map_or(0.0, Number::abs));
9318        judge(lo.map_or(0.0, |b| b - v), scale);
9319        judge(hi.map_or(0.0, |b| v - b), scale);
9320    }
9321
9322    Some(OriginalSpaceFeasibility {
9323        max_violation,
9324        negligible_at_tol: ok_tol,
9325        negligible_at_acceptable: ok_acceptable,
9326    })
9327}
9328
9329/// Map upstream `SolverReturn` codes to `ApplicationReturnStatus`.
9330/// Mirrors the table in
9331/// `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception → SolverReturn
9332/// map") and the corresponding switch in
9333/// `IpIpoptApplication.cpp:call_optimize`.
9334fn solver_return_to_app_status(s: SolverReturn) -> ApplicationReturnStatus {
9335    match s {
9336        SolverReturn::Success => ApplicationReturnStatus::SolveSucceeded,
9337        SolverReturn::StopAtAcceptablePoint => ApplicationReturnStatus::SolvedToAcceptableLevel,
9338        SolverReturn::FeasiblePointFound => ApplicationReturnStatus::FeasiblePointFound,
9339        SolverReturn::MaxiterExceeded => ApplicationReturnStatus::MaximumIterationsExceeded,
9340        SolverReturn::CpuTimeExceeded => ApplicationReturnStatus::MaximumCpuTimeExceeded,
9341        SolverReturn::WallTimeExceeded => ApplicationReturnStatus::MaximumWallTimeExceeded,
9342        SolverReturn::StopAtTinyStep => ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
9343        SolverReturn::LocalInfeasibility => ApplicationReturnStatus::InfeasibleProblemDetected,
9344        SolverReturn::UserRequestedStop => ApplicationReturnStatus::UserRequestedStop,
9345        SolverReturn::DivergingIterates => ApplicationReturnStatus::DivergingIterates,
9346        SolverReturn::RestorationFailure => ApplicationReturnStatus::RestorationFailed,
9347        SolverReturn::ErrorInStepComputation => ApplicationReturnStatus::ErrorInStepComputation,
9348        SolverReturn::InvalidNumberDetected => ApplicationReturnStatus::InvalidNumberDetected,
9349        SolverReturn::TooFewDegreesOfFreedom => ApplicationReturnStatus::NotEnoughDegreesOfFreedom,
9350        SolverReturn::InvalidProblemDefinition => ApplicationReturnStatus::InvalidProblemDefinition,
9351        SolverReturn::InvalidOption => ApplicationReturnStatus::InvalidOption,
9352        SolverReturn::OutOfMemory => ApplicationReturnStatus::InsufficientMemory,
9353        SolverReturn::InternalError | SolverReturn::Unassigned => {
9354            ApplicationReturnStatus::InternalError
9355        }
9356    }
9357}
9358
9359/// Best-effort evaluation of the objective at the algorithm's final
9360/// `x`. Returns the *scaled* objective (`f * obj_scale_factor`); used
9361/// to populate `SolveStatistics::final_scaled_objective`.
9362fn try_eval_curr_f(
9363    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9364    x: &Rc<dyn pounce_linalg::Vector>,
9365) -> Result<Number, ()> {
9366    let mut nlp_mut = nlp.borrow_mut();
9367    Ok(nlp_mut.eval_f(&**x))
9368}
9369
9370/// Trigger predicate for the Phase-3.5 ℓ₁ auto-fallback path. Returns
9371/// `true` when a status warrants a retry through the wrapper. Mirrors
9372/// ripopt#23's trigger set, extended per the audit's Refinement B
9373/// (pounce-side `Not_Enough_Degrees_Of_Freedom` is added because
9374/// pounce's DOF early-exit blocks NE-suffix problems that ripopt's
9375/// equivalent would let pass to the wrapper).
9376fn is_l1_fallback_trigger(status: ApplicationReturnStatus) -> bool {
9377    matches!(
9378        status,
9379        ApplicationReturnStatus::RestorationFailed
9380            | ApplicationReturnStatus::InfeasibleProblemDetected
9381            | ApplicationReturnStatus::SolvedToAcceptableLevel
9382            | ApplicationReturnStatus::MaximumIterationsExceeded
9383            | ApplicationReturnStatus::NotEnoughDegreesOfFreedom
9384    )
9385}
9386
9387/// Forward the final iterate back to the user's `TNLP::finalize_solution`.
9388/// We pull `x` (compressed in `x_var`-space) off the algorithm's
9389/// `data.curr`, lift it back to full TNLP indexing, and pass empty
9390/// multipliers for now (the algorithm's `y_c`, `y_d`, `z_l`, `z_u` are
9391/// in compressed split form — re-assembling them into the user's
9392/// `lambda` / `z_l` / `z_u` is mechanical but lives behind a
9393/// `OrigIpoptNlp::finalize_solution_*` accessor that's still being
9394/// fleshed out). On success returns the unscaled objective evaluated
9395/// on the user TNLP at the final iterate; returns `Err` if the final
9396/// iterate is missing.
9397/// Read a `dyn Vector`'s entries. Empty for a non-dense backing; POUNCE is
9398/// dense-only, so that is defensive rather than a supported case.
9399/// `constr_viol_tol`, `dual_inf_tol` and `compl_inf_tol`, as the user set
9400/// them (unscaled).
9401struct UserTolerances {
9402    constr_viol: Number,
9403    dual_inf: Number,
9404    compl_inf: Number,
9405}
9406
9407/// Whether a crossed-over point meets the user's tolerances in user units on
9408/// the model as declared (gh#1054).
9409///
9410/// Crossover's own acceptance reads the SQP's residuals, which live in the
9411/// scaled space. That is the right space for the never-regress comparison
9412/// against the interior iterate, and the wrong one for "is this a solution of
9413/// the user's problem": gradient-based scaling sized a row at a start point
9414/// with `x₀ = 1e4`, and at `x = (2, 0)` a violation of `1` read `3.3e-7` —
9415/// under every scaled tolerance, so `hs13_bigstart` came back
9416/// `Solve_Succeeded` at an infeasible point with every printed residual `0`.
9417/// The interior-point verdict is gated in user units (pounce#173); a point
9418/// that replaces it is held to the same gate. Stationarity and
9419/// complementarity unscale by `|df|`, as the calculated quantities do.
9420fn meets_user_tolerances(
9421    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9422    res: &crate::sqp::SqpResult,
9423    report: &crate::crossover::CrossoverReport,
9424    tols: &UserTolerances,
9425) -> bool {
9426    let adapter = crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(nlp_handle));
9427    let (rows, bx) = adapter.declared_violation(&res.x);
9428    let df = adapter.obj_scale();
9429    let dual = res.final_stationarity / df;
9430    let compl = report.compl_after / df;
9431    let ok = rows <= tols.constr_viol
9432        && bx.unwrap_or(0.0) <= tols.constr_viol
9433        && dual <= tols.dual_inf
9434        && (compl.is_nan() || compl <= tols.compl_inf);
9435    if !ok {
9436        tracing::debug!(
9437            target: "pounce::crossover",
9438            "crossed-over point fails the user tolerances: rows {rows:.2e}, box {bx:?}, \
9439             dual {dual:.2e}, compl {compl:.2e}"
9440        );
9441    }
9442    ok
9443}
9444
9445/// The converged-or-not interior iterate `curr` as a crossover seed, in the
9446/// algorithm's compressed / scaled space. The SQP adapter presents that same
9447/// space, so nothing is translated beyond repacking the bound duals:
9448/// `λ_x = z_l − z_u`.
9449fn crossover_seed(
9450    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9451    curr: &crate::iterates_vector::IteratesVector,
9452) -> crate::crossover::CrossoverSeed {
9453    crate::crossover::CrossoverSeed {
9454        x: dense_values(&*curr.x),
9455        lambda_g: {
9456            let mut v = dense_values(&*curr.y_c);
9457            v.extend(dense_values(&*curr.y_d));
9458            v
9459        },
9460        lambda_x: crate::sqp::ipopt_adapter::pack_bound_multipliers(
9461            nlp_handle,
9462            &dense_values(&*curr.z_l),
9463            &dense_values(&*curr.z_u),
9464        ),
9465    }
9466}
9467
9468/// An accepted crossover result as an interior-point iterate.
9469///
9470/// All eight components have to move together: leaving `s`, `v_l` or `v_u`
9471/// describing the interior point while `x` and the duals describe the
9472/// crossed-over one would make the calculated quantities read off an iterate
9473/// that never existed, and the residuals reported to the user would be
9474/// neither point's. The slack relations are the barrier problem's own —
9475/// `s = d(x)` and `v_l − v_u = −y_d`. `None` (with a warning) when the result
9476/// does not fit the iterate's vectors.
9477fn crossover_iterate(
9478    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9479    curr: &crate::iterates_vector::IteratesVector,
9480    res: &crate::sqp::SqpResult,
9481) -> Option<crate::iterates_vector::IteratesVector> {
9482    let (m_c, m_d) = {
9483        let b = nlp_handle.borrow();
9484        (b.m_eq() as usize, b.m_ineq() as usize)
9485    };
9486    let y_c = &res.lambda_g[..m_c];
9487    let y_d = &res.lambda_g[m_c..];
9488    // `s = d(x)`: the adapter's combined constraint vector is `[c ; d]`,
9489    // so the inequality block is its tail.
9490    let mut adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(nlp_handle));
9491    let c_all = crate::sqp::SqpProblemSpec::eval_c(&mut adapter, &res.x);
9492    let s_new = &c_all[m_c..];
9493    debug_assert_eq!(s_new.len(), m_d);
9494    let (z_l, z_u) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp_handle, &res.lambda_x);
9495    let (v_l, v_u) = crate::sqp::ipopt_adapter::split_slack_multipliers(nlp_handle, y_d);
9496
9497    let mut out = curr.deep_copy();
9498    let ok = set_dense(&mut *out.x, &res.x)
9499        && set_dense(&mut *out.s, s_new)
9500        && set_dense(&mut *out.y_c, y_c)
9501        && set_dense(&mut *out.y_d, y_d)
9502        && set_dense(&mut *out.z_l, &z_l)
9503        && set_dense(&mut *out.z_u, &z_u)
9504        && set_dense(&mut *out.v_l, &v_l)
9505        && set_dense(&mut *out.v_u, &v_u);
9506    if !ok {
9507        // A non-dense backing or a length mismatch. POUNCE is dense-only,
9508        // so this is defensive — but a partially-written iterate is worse
9509        // than no crossover at all, so bail without touching `curr`.
9510        tracing::warn!(
9511            target: "pounce::crossover",
9512            "crossover result did not fit the iterate; keeping the interior point"
9513        );
9514        return None;
9515    }
9516    Some(out.freeze())
9517}
9518
9519fn dense_values(v: &dyn pounce_linalg::Vector) -> Vec<Number> {
9520    v.as_any()
9521        .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
9522        .map(|d| d.expanded_values())
9523        .unwrap_or_default()
9524}
9525
9526/// Overwrite a `dyn Vector`'s entries. Returns false — writing nothing —
9527/// when the backing is not dense or the lengths disagree, so a caller
9528/// updating several components together can abandon the whole update rather
9529/// than leave a half-written iterate.
9530fn set_dense(v: &mut dyn pounce_linalg::Vector, vals: &[Number]) -> bool {
9531    match v
9532        .as_any_mut()
9533        .downcast_mut::<pounce_linalg::dense_vector::DenseVector>()
9534    {
9535        Some(d) if pounce_linalg::Vector::dim(d) as usize == vals.len() => {
9536            d.set_values(vals);
9537            true
9538        }
9539        _ => false,
9540    }
9541}
9542
9543/// An owned copy of a [`Solution`] payload already delivered to the user's
9544/// TNLP, enough to deliver it again.
9545///
9546/// Exists because a losing second-opinion retry has to be undoable. The status
9547/// a retry earns is already floored — `run_with_mu_strategy_fallback` returns
9548/// `first_status` unless the retry promotes — but the *point* was not, and the
9549/// user consumes the point. See that function for what went wrong without this.
9550#[derive(Debug, Clone)]
9551struct FinalizeSnapshot {
9552    status: SolverReturn,
9553    x: Vec<Number>,
9554    z_l: Vec<Number>,
9555    z_u: Vec<Number>,
9556    g: Vec<Number>,
9557    lambda: Vec<Number>,
9558    obj_value: Number,
9559    /// The `on_converged` firing of the attempt that produced this payload,
9560    /// `None` if the hook did not fire for it. Travels with the payload, so a
9561    /// floor replay brings the matching firing back with the answer.
9562    on_converged_id: Option<u64>,
9563}
9564
9565/// The option-table overrides (and the box flag) one retry applies for its
9566/// own solve, put back when the scope ends -- on **every** exit, unwinding
9567/// included.
9568///
9569/// The retries used to restore by hand after `optimize_constrained`
9570/// returned, so a panic inside it left the overrides in place. That is not
9571/// hypothetical for an embedder: `pounce-cinterface`'s `ffi_guard` catches the
9572/// panic and keeps the `IpoptApplication`, so the next `IpoptSolve` on that
9573/// handle ran with the scale audit's `max_iter` (`3x` the base solve's),
9574/// `obj_scaling_factor` multiplied by `k`, a CPU / wall budget shrunk to what
9575/// the audited run had left -- and, since gh#983's declared-box fix, the
9576/// variable box un-widened.
9577///
9578/// Derefs to the application, so the retry runs *through* the scope:
9579/// `scope.optimize_constrained(..)`. Each entry is restored with
9580/// [`OptionsList::restore_entry`], i.e. exactly as it stood, absence as
9581/// absence.
9582///
9583/// `on_unwind_only` is for the two retries (μ-strategy fallback, gh#884)
9584/// whose normal-path restore is deliberately *not* "as it stood" -- both
9585/// write the resolved value back with `found = true` -- and whose behaviour
9586/// on that path this guard must not change: there it only covers the unwind.
9587struct RetryOptionScope<'a> {
9588    app: &'a mut IpoptApplication,
9589    saved: Vec<(
9590        &'static str,
9591        pounce_common::options_list::OptionEntrySnapshot,
9592    )>,
9593    on_unwind_only: bool,
9594}
9595
9596impl<'a> RetryOptionScope<'a> {
9597    fn enter(app: &'a mut IpoptApplication, tags: &[&'static str], on_unwind_only: bool) -> Self {
9598        let saved = tags
9599            .iter()
9600            .map(|&t| (t, app.options.snapshot_entry(t)))
9601            .collect();
9602        Self {
9603            app,
9604            saved,
9605            on_unwind_only,
9606        }
9607    }
9608}
9609
9610impl std::ops::Deref for RetryOptionScope<'_> {
9611    type Target = IpoptApplication;
9612    fn deref(&self) -> &IpoptApplication {
9613        self.app
9614    }
9615}
9616
9617impl std::ops::DerefMut for RetryOptionScope<'_> {
9618    fn deref_mut(&mut self) -> &mut IpoptApplication {
9619        self.app
9620    }
9621}
9622
9623impl Drop for RetryOptionScope<'_> {
9624    fn drop(&mut self) {
9625        if self.on_unwind_only && !std::thread::panicking() {
9626            return;
9627        }
9628        for (tag, snap) in self.saved.drain(..) {
9629            self.app.options.restore_entry(tag, snap);
9630        }
9631        self.app.retry_keeps_declared_box.set(false);
9632    }
9633}
9634
9635/// The `final_*` half of [`SolveStatistics`] — the numbers that describe the
9636/// answer and the certificate attached to it.
9637///
9638/// Deliberately **not** the whole struct. `SolveStatistics` mixes two kinds of
9639/// number and they float back differently when a second-opinion retry loses:
9640///
9641/// * the `final_*` fields describe *the point being reported*, so they have to
9642///   agree with the status reported beside them. A `Solved_To_Acceptable_Level`
9643///   carrying a `final_kkt_error` two orders above `acceptable_tol` is
9644///   self-contradictory, and that is pounce#870.
9645/// * the wall clock (`total_wallclock_time_secs`) and the cumulative
9646///   dual-divergence flags describe *what the invocation did*: both attempts
9647///   really ran, so rewinding them would under-report the work actually
9648///   spent.
9649///
9650/// Everything else a solve report reads beside the final residuals describes
9651/// the *run that produced the returned point* (gh#983 item 5): the iteration
9652/// count and rows, the evaluation counts, the restoration tallies and
9653/// `quality_escalations`. Before that fix `deb7` at `max_iter=100` reported the
9654/// declined retry's 100 iterations beside the first attempt's objective and
9655/// point, and `eigenb2` (limited memory) 86 objective evaluations beside the
9656/// first attempt's 47 iterations and 159 evaluations. The first attempt's own
9657/// counts (`deb7`: 84 outer + 32 restoration = 116) are the ones that belong
9658/// with its point. The console's per-attempt summaries still show each
9659/// attempt's own tally.
9660///
9661/// So the certificate and the run it came from are floored together; only the
9662/// wall clock is the invocation's.
9663#[derive(Debug, Clone)]
9664struct SolutionCertificate {
9665    objective: Number,
9666    scaled_objective: Number,
9667    dual_inf: Number,
9668    constr_viol: Number,
9669    compl: Number,
9670    kkt_error: Number,
9671    unscaled_dual_inf: Number,
9672    unscaled_constr_viol: Number,
9673    unscaled_compl: Number,
9674    unscaled_kkt_error: Number,
9675    kkt_error_above_noise: Number,
9676    mu: Number,
9677    /// How far the attempt's point sits outside the model as declared --
9678    /// rows and box. Both are read off the statistics beside the residuals
9679    /// above, and both describe the *point*; leaving them out meant a
9680    /// declined retry's measurement was reported beside the base attempt's
9681    /// point (`Variable bound violation` and `final_declared_box_viol` naming
9682    /// the discarded re-solve's `9.9e-9` next to a point that sits inside
9683    /// its box).
9684    declared_constr_viol: Number,
9685    declared_box_viol: Number,
9686    /// gh#983 item 5: the iteration count and per-iteration rows of the
9687    /// attempt being floored. A solve report reads both from the statistics,
9688    /// so restoring the certificate without them left a report whose
9689    /// numbers describe the returned point and whose iteration table
9690    /// describes the declined retry.
9691    iteration_count: Index,
9692    iterations: Vec<pounce_nlp::solve_statistics::IterRecord>,
9693    /// The per-run evaluation and restoration tallies of the attempt, for the
9694    /// same reason as the iteration table: they are read off the statistics
9695    /// beside the final residuals, and a declined retry used to leave its own
9696    /// (`eigenb2` limited-memory: 86 objective evaluations reported beside the
9697    /// base attempt's 47 iterations and 159 evaluations).
9698    evals: [Index; 5],
9699    restoration: (Index, Index, Index, Number),
9700    quality_escalations: Index,
9701    /// gh#983: the scale the stationarity residual is judged against, the
9702    /// objective scale the run ended with, and the warnings raised about the
9703    /// attempt. All three describe the *point being reported*.
9704    unscaled_dual_scale: Number,
9705    obj_scaling_factor: Number,
9706    total_obj_scaling_factor: Number,
9707    start_obj_grad_max: Number,
9708    warnings: Vec<String>,
9709    /// gh#983 review item 3: the detector's verdict on this run alone.
9710    returned_run_signature: bool,
9711}
9712
9713impl SolutionCertificate {
9714    fn of(s: &pounce_nlp::solve_statistics::SolveStatistics) -> Self {
9715        Self {
9716            objective: s.final_objective,
9717            scaled_objective: s.final_scaled_objective,
9718            dual_inf: s.final_dual_inf,
9719            constr_viol: s.final_constr_viol,
9720            compl: s.final_compl,
9721            kkt_error: s.final_kkt_error,
9722            unscaled_dual_inf: s.final_unscaled_dual_inf,
9723            unscaled_constr_viol: s.final_unscaled_constr_viol,
9724            unscaled_compl: s.final_unscaled_compl,
9725            unscaled_kkt_error: s.final_unscaled_kkt_error,
9726            kkt_error_above_noise: s.final_kkt_error_above_noise,
9727            mu: s.final_mu,
9728            declared_constr_viol: s.final_declared_constr_viol,
9729            declared_box_viol: s.final_declared_box_viol,
9730            iteration_count: s.iteration_count,
9731            iterations: s.iterations.clone(),
9732            evals: [
9733                s.num_obj_evals,
9734                s.num_constr_evals,
9735                s.num_obj_grad_evals,
9736                s.num_constr_jac_evals,
9737                s.num_hess_evals,
9738            ],
9739            restoration: (
9740                s.restoration_calls,
9741                s.restoration_inner_iters,
9742                s.restoration_outer_iters,
9743                s.restoration_wall_secs,
9744            ),
9745            quality_escalations: s.quality_escalations,
9746            unscaled_dual_scale: s.final_unscaled_dual_scale,
9747            obj_scaling_factor: s.final_obj_scaling_factor,
9748            total_obj_scaling_factor: s.final_total_obj_scaling_factor,
9749            start_obj_grad_max: s.start_obj_grad_max,
9750            warnings: s.warnings.clone(),
9751            returned_run_signature: s.returned_run_dual_divergence_signature,
9752        }
9753    }
9754
9755    fn restore_into(&self, s: &mut pounce_nlp::solve_statistics::SolveStatistics) {
9756        s.final_objective = self.objective;
9757        s.final_scaled_objective = self.scaled_objective;
9758        s.final_dual_inf = self.dual_inf;
9759        s.final_constr_viol = self.constr_viol;
9760        s.final_compl = self.compl;
9761        s.final_kkt_error = self.kkt_error;
9762        s.final_unscaled_dual_inf = self.unscaled_dual_inf;
9763        s.final_unscaled_constr_viol = self.unscaled_constr_viol;
9764        s.final_unscaled_compl = self.unscaled_compl;
9765        s.final_unscaled_kkt_error = self.unscaled_kkt_error;
9766        s.final_kkt_error_above_noise = self.kkt_error_above_noise;
9767        s.final_mu = self.mu;
9768        s.final_declared_constr_viol = self.declared_constr_viol;
9769        s.final_declared_box_viol = self.declared_box_viol;
9770        s.iteration_count = self.iteration_count;
9771        s.iterations = self.iterations.clone();
9772        s.num_obj_evals = self.evals[0];
9773        s.num_constr_evals = self.evals[1];
9774        s.num_obj_grad_evals = self.evals[2];
9775        s.num_constr_jac_evals = self.evals[3];
9776        s.num_hess_evals = self.evals[4];
9777        s.restoration_calls = self.restoration.0;
9778        s.restoration_inner_iters = self.restoration.1;
9779        s.restoration_outer_iters = self.restoration.2;
9780        s.restoration_wall_secs = self.restoration.3;
9781        s.quality_escalations = self.quality_escalations;
9782        s.final_unscaled_dual_scale = self.unscaled_dual_scale;
9783        s.final_obj_scaling_factor = self.obj_scaling_factor;
9784        s.final_total_obj_scaling_factor = self.total_obj_scaling_factor;
9785        s.start_obj_grad_max = self.start_obj_grad_max;
9786        s.warnings = self.warnings.clone();
9787        s.returned_run_dual_divergence_signature = self.returned_run_signature;
9788    }
9789}
9790
9791impl FinalizeSnapshot {
9792    /// Re-deliver this payload to `tnlp`, overwriting whatever a later attempt
9793    /// captured there.
9794    fn replay(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
9795        tnlp.borrow_mut().finalize_solution(
9796            Solution {
9797                status: self.status,
9798                x: &self.x,
9799                z_l: &self.z_l,
9800                z_u: &self.z_u,
9801                g: &self.g,
9802                lambda: &self.lambda,
9803                obj_value: self.obj_value,
9804            },
9805            &TnlpIpoptData::default(),
9806            &TnlpIpoptCq::default(),
9807        );
9808    }
9809}
9810
9811fn finalize_via_orig_nlp(
9812    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9813    alg: &IpoptAlgorithm,
9814    solver_status: SolverReturn,
9815    _app_status: ApplicationReturnStatus,
9816    tnlp: &Rc<RefCell<dyn TNLP>>,
9817    sink: &RefCell<Option<FinalizeSnapshot>>,
9818    fixed_var_duals: bool,
9819) -> Result<Number, ()> {
9820    let curr = alg.data.borrow().curr.clone().ok_or(())?;
9821    // Lift compressed x_var → full-x (length `info.n`) so the user
9822    // TNLP receives the same shape it provided. With `make_parameter`
9823    // the fixed components are spliced back in by the IpoptNlp.
9824    let nlp_borrow = nlp.borrow();
9825    // `finalize_solution_x`, not `lift_x_to_full`: the reported point also
9826    // owes the user the `honor_original_bounds` projection. `f` and `g`
9827    // below are then evaluated at the point actually reported, so x/f/g
9828    // agree with each other.
9829    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&*curr.x);
9830    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
9831    let n = info.n as usize;
9832    let m = info.m as usize;
9833    debug_assert_eq!(x_vec.len(), n);
9834    // Lift algorithm-side multipliers back into user-space (pounce#11).
9835    // Use the `finalize_solution_*` family (not the `pack_*` family): the
9836    // final solution duals must be reported in the user's *unscaled-
9837    // Lagrangian* convention `∇f + λ·∇g + z = 0`, which divides out the
9838    // `obj_scale_factor` the algorithm threads through `eval_h`. The `pack_*`
9839    // family deliberately omits that division because it feeds the scaled
9840    // `eval_h`; calling it here left every dual scaled by `obj_scale_factor`
9841    // whenever gradient-based scaling triggered (pounce#11 F1).
9842    // Backends without overrides return empty; fall back to zero stubs so the
9843    // user sees a length-consistent vector.
9844    let mut z_l = nlp_borrow.finalize_solution_z_l(&*curr.z_l);
9845    if z_l.is_empty() {
9846        z_l = vec![0.0; n];
9847    }
9848    let mut z_u = nlp_borrow.finalize_solution_z_u(&*curr.z_u);
9849    if z_u.is_empty() {
9850        z_u = vec![0.0; n];
9851    }
9852    let mut lambda = nlp_borrow.finalize_solution_lambda(&*curr.y_c, &*curr.y_d);
9853    if lambda.is_empty() {
9854        lambda = vec![0.0; m];
9855    }
9856    if fixed_var_duals {
9857        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
9858    }
9859    drop(nlp_borrow);
9860    // Compute g(x) via the user TNLP so the final residual is
9861    // populated for the user.
9862    let mut g_final = vec![0.0; m];
9863    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
9864    let f_final = tnlp
9865        .borrow_mut()
9866        .eval_f(&x_vec, true)
9867        .unwrap_or(Number::NAN);
9868    let snap = FinalizeSnapshot {
9869        status: solver_status,
9870        x: x_vec,
9871        z_l,
9872        z_u,
9873        g: g_final,
9874        lambda,
9875        obj_value: f_final,
9876        on_converged_id: alg.data.borrow().on_converged_id,
9877    };
9878    snap.replay(tnlp);
9879    *sink.borrow_mut() = Some(snap);
9880    Ok(f_final)
9881}
9882
9883/// Bind SQP suboptions registered in `upstream_options.rs`
9884/// (`sqp_globalization`, `sqp_hessian`, `sqp_max_iter`, `sqp_tol`,
9885/// `sqp_constr_viol_tol`, `sqp_dual_inf_tol`, `sqp_l1_penalty`,
9886/// `sqp_bt_reduction`, `sqp_bt_min_alpha`, `sqp_print_level`,
9887/// `sqp_lbfgs_max_history`) onto
9888/// `opts`. Used by [`IpoptApplication::algorithm_builder_snapshot`]
9889/// before constructing an SQP algorithm.
9890fn apply_sqp_options(options: &OptionsList, opts: &mut crate::sqp::SqpOptions) {
9891    use crate::sqp::{SqpGlobalization, SqpHessianSource};
9892
9893    if let Ok((s, true)) = options.get_string_value("sqp_globalization", "") {
9894        opts.globalization = match s.as_str() {
9895            "filter" => SqpGlobalization::Filter,
9896            "l1-elastic" => SqpGlobalization::L1Elastic,
9897            _ => opts.globalization,
9898        };
9899    }
9900    // `hessian_approximation` is the upstream Ipopt option a frontend sets
9901    // when the caller supplies no second derivatives -- `pounce.minimize` does
9902    // it automatically, and warns that it is doing so. It was only ever read
9903    // on the IPM path, so an SQP solve ignored it and fell back to the
9904    // `Exact` default, asking the NLP for a Lagrangian Hessian that was never
9905    // provided. A zero Hessian turns the QP subproblem into an LP, which is
9906    // unbounded whenever the objective gradient has a component in the null
9907    // space of the active constraints -- so the solve died with
9908    // `Internal_Error` on problems the IPM handles without complaint:
9909    //
9910    //     min (x0-3)^2 + (x1-2)^2  s.t.  4 - x0 - x1 >= 0
9911    //
9912    // (IPM: x = [2.5, 1.5]. Active-set SQP before this: Internal_Error, or
9913    // with variable bounds, a run to the box corner along the null-space
9914    // direction.)
9915    //
9916    // The quasi-Newton source picked here is the *dense Powell-damped BFGS*,
9917    // not the limited-memory one, even though the requesting option is spelled
9918    // `limited-memory`. On this active-set-SQP path L-BFGS buys nothing: its
9919    // `as_triplet` materializes a full dense `n×n` Hessian for the QP
9920    // subproblem exactly as `DampedBfgs` does (the matrix-free product
9921    // interface that would make L-BFGS cheaper is not implemented yet), and it
9922    // is markedly less robust -- it stalls with
9923    // `Search_Direction_Becomes_Too_Small` (or reports the QP subproblem
9924    // `unbounded`) on easy, well-conditioned convex QPs whenever a general
9925    // inequality is active at the optimum, returning `success=False` with a
9926    // wrong `x` (issue #358). `DampedBfgs` solves those. So the automatic
9927    // approximation the facade injects when no analytic Hessian is available
9928    // maps to the robust dense update; a caller who genuinely wants
9929    // limited-memory storage can still request it explicitly with
9930    // `sqp_hessian = "lbfgs"` below (read after this, so it wins).
9931    //
9932    // ...up to `sqp_dense_hessian_max_n` variables (gh#1054). Above that the
9933    // dense update is not a robust choice but an impossible one -- `n²`
9934    // storage, and every QP factorization dense -- so `QuasiNewtonAuto`
9935    // resolves per solve, from the model's `n`, to L-BFGS in the lifted
9936    // low-rank form that keeps the QP sparse. The paragraph above still
9937    // governs every model at or below the ceiling.
9938    //
9939    // Read this before `sqp_hessian` so an explicit setting still wins.
9940    if let Ok((s, true)) = options.get_string_value("hessian_approximation", "") {
9941        if s == "limited-memory" {
9942            opts.hessian = SqpHessianSource::QuasiNewtonAuto;
9943        }
9944    }
9945    if let Ok((s, true)) = options.get_string_value("sqp_hessian", "") {
9946        opts.hessian = match s.as_str() {
9947            "exact" => SqpHessianSource::Exact,
9948            "damped-bfgs" => SqpHessianSource::DampedBfgs,
9949            "lbfgs" => SqpHessianSource::Lbfgs,
9950            _ => opts.hessian,
9951        };
9952    }
9953    if let Ok((v, true)) = options.get_integer_value("sqp_max_iter", "") {
9954        if v >= 0 {
9955            opts.max_iter = v as u32;
9956        }
9957    }
9958    if let Ok((v, true)) = options.get_numeric_value("sqp_tol", "") {
9959        opts.tol = v;
9960    }
9961    if let Ok((v, true)) = options.get_numeric_value("sqp_constr_viol_tol", "") {
9962        opts.constr_viol_tol = v;
9963    }
9964    if let Ok((v, true)) = options.get_numeric_value("sqp_dual_inf_tol", "") {
9965        opts.dual_inf_tol = v;
9966    }
9967    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty", "") {
9968        opts.l1_penalty = v;
9969    }
9970    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_safety", "") {
9971        opts.l1_penalty_safety = v;
9972    }
9973    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_max", "") {
9974        opts.l1_penalty_max = v;
9975    }
9976    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_reduction", "") {
9977        opts.bt_reduction = v;
9978    }
9979    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_min_alpha", "") {
9980        opts.bt_min_alpha = v;
9981    }
9982    if let Ok((v, true)) = options.get_integer_value("sqp_print_level", "") {
9983        opts.print_level = v.clamp(0, u8::MAX as i32) as u8;
9984    }
9985    if let Ok((v, true)) = options.get_integer_value("sqp_lbfgs_max_history", "") {
9986        if v >= 1 {
9987            opts.lbfgs_max_history = v as u32;
9988        }
9989    }
9990    // An explicit `sqp_qp_use_schur_updates` is the caller's choice and goes
9991    // to the QP options as given (`apply_qp_subproblem_options`); only an
9992    // unset one is left to the size rule.
9993    if let Ok((_, true)) = options.get_string_value("sqp_qp_use_schur_updates", "") {
9994        opts.qp_schur_min_dim = None;
9995    }
9996    if let Ok((v, true)) = options.get_integer_value("sqp_dense_hessian_max_n", "") {
9997        opts.dense_hessian_max_n = usize::try_from(v).unwrap_or(0);
9998    }
9999}
10000
10001/// Populate the active-set SQP **QP-subproblem** options
10002/// ([`pounce_qp::QpOptions`]) from the `sqp_qp_*` option family.
10003///
10004/// Sister to [`apply_sqp_options`], which handles the SQP *outer-loop*
10005/// options ([`crate::sqp::SqpOptions`]); this one feeds the inner QP
10006/// solver that `SqpAlgorithm` delegates each subproblem to. Consulted
10007/// only on the `ActiveSetSqp` path. Each knob is forwarded only when
10008/// the user explicitly set it, so the `pounce_qp` defaults stand
10009/// otherwise.
10010///
10011/// The reading itself is [`pounce_qp::ActiveSetOverrides`], shared with
10012/// `pounce_convex`'s direct active-set driver, which overlays the same
10013/// eight names onto the same `QpOptions` type. This function had its own
10014/// copy until then, and the two had drifted: this one silently ignored a
10015/// `sqp_qp_max_iter` of 0 and an unknown `sqp_qp_anti_cycling` value where
10016/// the other rejected them. Neither divergence was reachable — the
10017/// registry bounds `sqp_qp_max_iter` at 1 and restricts `anti_cycling` to
10018/// three values — but two readers of one option family is how a
10019/// reachable one starts.
10020fn apply_qp_subproblem_options(options: &OptionsList, opts: &mut pounce_qp::QpOptions) {
10021    match pounce_qp::ActiveSetOverrides::try_from_options_list(options) {
10022        Ok(overrides) => overrides.apply(opts),
10023        // Unreachable from here: this runs after `initialize()`, so every
10024        // value present has already been validated against the registered
10025        // bound that the reader re-checks. Say so out loud anyway rather
10026        // than solving with a configuration the user did not ask for —
10027        // silently dropping the whole family is exactly the failure mode
10028        // `tests/no_silent_options.rs` exists to prevent.
10029        Err(error) => tracing::error!(
10030            target: "pounce::options",
10031            %error,
10032            "sqp_qp_* options were rejected after the registry accepted them; \
10033             the QP subproblem is running on pounce-qp defaults"
10034        ),
10035    }
10036}
10037
10038/// The TNLP's own starting point as an SQP warm start, in algorithm space,
10039/// through the projections the IPM's warm initializer reads
10040/// (`prepare_warm_start`, `get_starting_x/y/z`). `None` when the NLP
10041/// declines. An unseeded bound multiplier (NaN, gh#622) counts as zero: the
10042/// SQP has no `bound_mult_init_val` of its own to resolve it to.
10043fn sqp_tnlp_warm_start(nlp_rc: &Rc<RefCell<dyn IpoptNlp>>) -> Option<crate::sqp::SqpIterates> {
10044    use pounce_linalg::dense_vector::DenseVectorSpace;
10045    let dense = |v: &dyn pounce_linalg::Vector| -> Vec<Number> {
10046        v.as_any()
10047            .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
10048            .map(|d| d.expanded_values().to_vec())
10049            .unwrap_or_default()
10050    };
10051    let (z_l, z_u, x, lambda_g) = {
10052        let mut nlp = nlp_rc.borrow_mut();
10053        if !nlp.prepare_warm_start() {
10054            return None;
10055        }
10056        let (n, m_eq, m_ineq) = (nlp.n(), nlp.m_eq(), nlp.m_ineq());
10057        let (n_xl, n_xu) = (nlp.x_l().dim(), nlp.x_u().dim());
10058        let (n_dl, n_du) = (nlp.d_l().dim(), nlp.d_u().dim());
10059        let mut x = DenseVectorSpace::new(n).make_new_dense();
10060        let mut y_c = DenseVectorSpace::new(m_eq).make_new_dense();
10061        let mut y_d = DenseVectorSpace::new(m_ineq).make_new_dense();
10062        let mut z_l = DenseVectorSpace::new(n_xl).make_new_dense();
10063        let mut z_u = DenseVectorSpace::new(n_xu).make_new_dense();
10064        let mut v_l = DenseVectorSpace::new(n_dl).make_new_dense();
10065        let mut v_u = DenseVectorSpace::new(n_du).make_new_dense();
10066        let ok = nlp.get_starting_x(&mut x)
10067            && nlp.get_starting_y(&mut y_c, &mut y_d)
10068            && nlp.get_starting_z(&mut z_l, &mut z_u, &mut v_l, &mut v_u);
10069        nlp.finish_warm_start();
10070        if !ok {
10071            return None;
10072        }
10073        let finite = |v: Vec<Number>| -> Vec<Number> {
10074            v.into_iter()
10075                .map(|a| if a.is_finite() { a } else { 0.0 })
10076                .collect()
10077        };
10078        let mut lambda_g = finite(dense(&y_c));
10079        lambda_g.extend(finite(dense(&y_d)));
10080        (
10081            finite(dense(&z_l)),
10082            finite(dense(&z_u)),
10083            dense(&x),
10084            lambda_g,
10085        )
10086    };
10087    let lambda_x = crate::sqp::ipopt_adapter::pack_bound_multipliers(nlp_rc, &z_l, &z_u);
10088    Some(crate::sqp::SqpIterates {
10089        x,
10090        lambda_g,
10091        lambda_x,
10092        working: None,
10093    })
10094}
10095
10096/// Map a staged SQP warm start from the caller's space into the algorithm's:
10097/// the exact inverse of what [`finalize_via_sqp`] / [`sqp_user_iterate`] do on
10098/// the way out, so that the multipliers a solve reports, fed back unchanged,
10099/// are the iterate the next solve starts from.
10100///
10101/// | field | user space (what callers stage) | algorithm space |
10102/// |---|---|---|
10103/// | `x` | full `n`, model units | fixed columns dropped, `x̃ = d ⊙ x` |
10104/// | `lambda_x` | full `n`, `z_L − z_U` | fixed dropped, `· obj_scal ⊘ d` |
10105/// | `lambda_g` | `m`, in `g` order | `[y_c; y_d]`, `y = λ · obj_scal / {c,d}_scale` |
10106/// | `working.constraints` | `m`, in `g` order | `[c; d]` order |
10107///
10108/// (`working.bounds` goes from full `n` to the reduced columns in the
10109/// caller, which also knows which elimination an already-reduced set came
10110/// from.)
10111///
10112/// `d` is the per-variable factor of a `ScalingTnlp` below the NLP (gh#486;
10113/// `z̃ = z ⊘ d`, its `get_starting_point` rule) and `obj_scal` includes the
10114/// sign of a maximize. The `λ` rule is `OrigIpoptNlp::initialize_starting_point`'s,
10115/// the IPM's inbound half of the same inverse.
10116///
10117/// Every frontend stages user space — the C API and `pounce-py` pass the
10118/// caller's `x` / `mult_g` / `z_L − z_U` through untouched. Before this they
10119/// went in as-is: on a model whose equality is not the first row, the two
10120/// constraint multipliers landed on each other's rows, and any
10121/// `obj_scaling_factor` ≠ 1 left them off by that factor.
10122///
10123/// An `x` / `lambda_x` already of the reduced length (a problem with fixed
10124/// variables) is taken as user-unit values of the surviving columns, in
10125/// order; any other length is left alone for the dimension check to reject.
10126fn sqp_warm_start_to_algorithm(nlp: &dyn IpoptNlp, w: &mut crate::sqp::SqpIterates) {
10127    let n_alg = nlp.n() as usize;
10128    let n_full = nlp.n_full_x() as usize;
10129    let m_full = nlp.n_full_g() as usize;
10130    let m_eq = nlp.m_eq() as usize;
10131    let obj_scal = nlp.obj_scaling_factor();
10132    let d = nlp.variable_scaling();
10133    // Algorithm column -> (user column, its x-scaling factor).
10134    let cols: Vec<(usize, Number)> = (0..n_alg)
10135        .map(|k| {
10136            let j = nlp.var_x_to_full_x(k as Index) as usize;
10137            let dj = d.as_ref().and_then(|d| d.get(j).copied()).unwrap_or(1.0);
10138            (j, dj)
10139        })
10140        .collect();
10141    let to_alg = |v: &[Number], f: &dyn Fn(Number, Number) -> Number| -> Option<Vec<Number>> {
10142        if v.len() == n_full {
10143            Some(cols.iter().map(|&(j, dj)| f(v[j], dj)).collect())
10144        } else if v.len() == n_alg {
10145            Some(cols.iter().zip(v).map(|(&(_, dj), &x)| f(x, dj)).collect())
10146        } else {
10147            None
10148        }
10149    };
10150    if let Some(x) = to_alg(&w.x, &|x, dj| x * dj) {
10151        w.x = x;
10152    }
10153    if let Some(lx) = to_alg(&w.lambda_x, &|z, dj| z * obj_scal / dj) {
10154        w.lambda_x = lx;
10155    }
10156    if w.lambda_g.len() == m_full {
10157        let cs = nlp.c_scale_vec();
10158        let ds = nlp.d_scale_vec();
10159        let mut y = vec![0.0; m_full];
10160        for (i, &lam) in w.lambda_g.iter().enumerate() {
10161            let i = i as Index;
10162            if let Some(k) = nlp.full_g_to_c_block(i) {
10163                let k = k as usize;
10164                let s = cs.as_ref().map_or(1.0, |v| v[k]);
10165                y[k] = lam / s * obj_scal;
10166            } else if let Some(k) = nlp.full_g_to_d_block(i) {
10167                let k = k as usize;
10168                let s = ds.as_ref().map_or(1.0, |v| v[k]);
10169                y[m_eq + k] = lam / s * obj_scal;
10170            }
10171        }
10172        w.lambda_g = y;
10173    }
10174    if let Some(ws) = w.working.as_mut() {
10175        ws.constraints = working_set_rows_to_algorithm(nlp, std::mem::take(&mut ws.constraints));
10176    }
10177}
10178
10179/// Algorithm row `k` of the `[c; d]` constraint vector → user `g` row, or
10180/// `None` when the NLP's row count does not describe a full split.
10181fn algorithm_rows_to_user(nlp: &dyn IpoptNlp) -> Option<Vec<usize>> {
10182    let m_full = nlp.n_full_g() as usize;
10183    let m_eq = nlp.m_eq() as usize;
10184    let m_alg = m_eq + nlp.m_ineq() as usize;
10185    if m_full != m_alg {
10186        return None;
10187    }
10188    let mut map = vec![usize::MAX; m_alg];
10189    for i in 0..m_full {
10190        let k = if let Some(k) = nlp.full_g_to_c_block(i as Index) {
10191            k as usize
10192        } else if let Some(k) = nlp.full_g_to_d_block(i as Index) {
10193            m_eq + k as usize
10194        } else {
10195            return None;
10196        };
10197        if k >= m_alg || map[k] != usize::MAX {
10198            return None;
10199        }
10200        map[k] = i;
10201    }
10202    Some(map)
10203}
10204
10205/// Constraint statuses of a working set, algorithm `[c; d]` order → user
10206/// `g` order. The SQP stacks equalities first, so on a model whose first
10207/// row is an inequality the statuses published positionally landed on the
10208/// wrong rows (`[Equality, AtUpper]` for `g = [ineq, eq]`). A vector of
10209/// any other length is returned unchanged for the dimension check to judge.
10210fn working_set_rows_to_user(
10211    nlp: &dyn IpoptNlp,
10212    rows: Vec<pounce_qp::ConsStatus>,
10213) -> Vec<pounce_qp::ConsStatus> {
10214    match algorithm_rows_to_user(nlp) {
10215        Some(map) if map.len() == rows.len() => {
10216            let mut user = vec![pounce_qp::ConsStatus::Inactive; rows.len()];
10217            for (k, &i) in map.iter().enumerate() {
10218                user[i] = rows[k];
10219            }
10220            user
10221        }
10222        _ => rows,
10223    }
10224}
10225
10226/// Inverse of [`working_set_rows_to_user`]: user `g` order → `[c; d]`.
10227fn working_set_rows_to_algorithm(
10228    nlp: &dyn IpoptNlp,
10229    rows: Vec<pounce_qp::ConsStatus>,
10230) -> Vec<pounce_qp::ConsStatus> {
10231    match algorithm_rows_to_user(nlp) {
10232        Some(map) if map.len() == rows.len() => map.iter().map(|&i| rows[i]).collect(),
10233        _ => rows,
10234    }
10235}
10236
10237/// The SQP iterate in the user's index spaces, for the live-inspector window
10238/// (gh#1015). Same conversions as [`finalize_via_sqp`] — `λ_x` is packed
10239/// signed (`z_L − z_U`) and is split by sign — minus the user-callback
10240/// evaluations: `g` comes from the loop's own `[c; d]` values.
10241fn sqp_user_iterate(
10242    nlp: &Rc<RefCell<dyn IpoptNlp>>,
10243    x: &[Number],
10244    lambda_g: &[Number],
10245    lambda_x: &[Number],
10246    c_vals: &[Number],
10247    grad_lag_x: &[Number],
10248    fixed_var_duals: bool,
10249) -> crate::intermediate::UserIterate {
10250    use pounce_linalg::dense_vector::DenseVectorSpace;
10251
10252    // `finalize_solution_z_*` read the compressed x_l / x_u spaces (one
10253    // entry per finite bound, via `x_l_map`), not one entry per variable;
10254    // `split_bound_multipliers` does that split, as crossover does.
10255    let (zl, zu) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, lambda_x);
10256    let nlp = nlp.borrow();
10257    let n_alg = nlp.n() as usize;
10258    let m_eq = nlp.m_eq() as usize;
10259    let m_ineq = nlp.m_ineq() as usize;
10260    let n_user = nlp.n_full_x() as usize;
10261    let m_user = nlp.n_full_g() as usize;
10262
10263    let x_space = DenseVectorSpace::new(n_alg as Index);
10264    let c_space = DenseVectorSpace::new(m_eq as Index);
10265    let d_space = DenseVectorSpace::new(m_ineq as Index);
10266    let dv = |space: &Rc<DenseVectorSpace>, v: &[Number]| {
10267        let mut d = space.make_new_dense();
10268        if !v.is_empty() {
10269            d.set_values(v);
10270        }
10271        d
10272    };
10273
10274    let x_full = nlp.finalize_solution_x(&dv(&x_space, x));
10275    let mut z_l = nlp.finalize_solution_z_l(&dv(&DenseVectorSpace::new(zl.len() as Index), &zl));
10276    if z_l.is_empty() {
10277        z_l = vec![0.0; n_user];
10278    }
10279    let mut z_u = nlp.finalize_solution_z_u(&dv(&DenseVectorSpace::new(zu.len() as Index), &zu));
10280    if z_u.is_empty() {
10281        z_u = vec![0.0; n_user];
10282    }
10283    let (y_c, y_d) = lambda_g.split_at(m_eq.min(lambda_g.len()));
10284    let mut lambda = nlp.finalize_solution_lambda(&dv(&c_space, y_c), &dv(&d_space, y_d));
10285    if lambda.is_empty() {
10286        lambda = vec![0.0; m_user];
10287    }
10288    if fixed_var_duals {
10289        nlp.complete_fixed_var_bound_multipliers(&x_full, &lambda, &mut z_l, &mut z_u);
10290    }
10291    // Everything here is in the space of the TNLP the NLP wraps, which
10292    // under per-variable `user-scaling` is a `ScalingTnlp` seeing
10293    // `x̃ = d ⊙ x`; that wrapper undoes the substitution on the iterate's
10294    // way through its `intermediate_callback`, by its `finalize_solution`'s
10295    // rule (`x = x̃ ⊘ d`, `z = d ⊙ z̃`).
10296    let (c, d) = c_vals.split_at(m_eq.min(c_vals.len()));
10297    let g = nlp.pack_g_for_user(&dv(&c_space, c), &dv(&d_space, d));
10298    // The SQP iterates against the same live bounds (widened only when
10299    // `bound_relax_factor` is set by name on this arm).
10300    let (x_l_alg, x_u_alg) = crate::intermediate::algorithm_x_bounds(&*nlp, &x_full);
10301    crate::intermediate::UserIterate {
10302        x: x_full,
10303        z_l,
10304        z_u,
10305        g,
10306        lambda,
10307        scaling: Some(crate::intermediate::iterate_scaling(&*nlp)),
10308        x_l_alg,
10309        x_u_alg,
10310        grad_lag_x: crate::intermediate::user_grad_lag(&*nlp, grad_lag_x),
10311    }
10312}
10313
10314/// SQP-side analog of [`finalize_via_orig_nlp`]. Hands the SQP
10315/// solution iterate to the user TNLP via the standard
10316/// `finalize_solution` callback. Multiplier lifting goes through
10317/// the same OrigIpoptNlp hooks so the user sees the same shape
10318/// regardless of which algorithm produced the iterate.
10319///
10320/// Returns the user-space objective value on success.
10321fn finalize_via_sqp(
10322    nlp: &Rc<RefCell<dyn IpoptNlp>>,
10323    res: &crate::sqp::SqpResult,
10324    solver_status: pounce_nlp::SolverReturn,
10325    tnlp: &Rc<RefCell<dyn TNLP>>,
10326    sink: &RefCell<Option<FinalizeSnapshot>>,
10327    fixed_var_duals: bool,
10328) -> Result<Number, ()> {
10329    use pounce_linalg::dense_vector::DenseVectorSpace;
10330
10331    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
10332    let n = info.n as usize;
10333    let m = info.m as usize;
10334
10335    // Wrap SQP slices in DenseVectors so we can pass them through
10336    // the OrigIpoptNlp lift_x_to_full / pack_*_for_user hooks.
10337    let nlp_borrow = nlp.borrow();
10338    let n_alg = nlp_borrow.n() as usize;
10339    let m_eq = nlp_borrow.m_eq() as usize;
10340    let m_ineq = nlp_borrow.m_ineq() as usize;
10341    debug_assert_eq!(res.x.len(), n_alg);
10342    debug_assert_eq!(res.lambda_g.len(), m_eq + m_ineq);
10343    debug_assert_eq!(res.lambda_x.len(), n_alg);
10344
10345    let x_space = DenseVectorSpace::new(n_alg as Index);
10346    let c_space = DenseVectorSpace::new(m_eq as Index);
10347    let d_space = DenseVectorSpace::new(m_ineq as Index);
10348
10349    let mut x_dv = x_space.make_new_dense();
10350    x_dv.set_values(&res.x);
10351    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&x_dv);
10352    debug_assert_eq!(x_vec.len(), n);
10353
10354    // λ_x is packed signed (z_l − z_u), one entry per variable. Split it
10355    // into the compressed x_l / x_u spaces `finalize_solution_z_*` read
10356    // (one entry per finite bound): splitting per variable put each
10357    // multiplier on the wrong variable whenever an unbounded one came
10358    // first, as crossover's `split_bound_multipliers` call already avoids.
10359    let (zl_vals, zu_vals) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, &res.lambda_x);
10360    let mut z_l_compressed = DenseVectorSpace::new(zl_vals.len() as Index).make_new_dense();
10361    let mut z_u_compressed = DenseVectorSpace::new(zu_vals.len() as Index).make_new_dense();
10362    if !zl_vals.is_empty() {
10363        z_l_compressed.set_values(&zl_vals);
10364    }
10365    if !zu_vals.is_empty() {
10366        z_u_compressed.set_values(&zu_vals);
10367    }
10368    // `finalize_solution_*` (not `pack_*`): report unscaled-Lagrangian duals,
10369    // dividing out `obj_scale_factor` — see `finalize_via_orig_nlp` (F1).
10370    let mut z_l = nlp_borrow.finalize_solution_z_l(&z_l_compressed);
10371    if z_l.is_empty() {
10372        z_l = vec![0.0; n];
10373    }
10374    let mut z_u = nlp_borrow.finalize_solution_z_u(&z_u_compressed);
10375    if z_u.is_empty() {
10376        z_u = vec![0.0; n];
10377    }
10378
10379    // λ_g is [y_c; y_d]; split into the c/d blocks for lift.
10380    let mut y_c_dv = c_space.make_new_dense();
10381    let mut y_d_dv = d_space.make_new_dense();
10382    if m_eq > 0 {
10383        y_c_dv.set_values(&res.lambda_g[..m_eq]);
10384    }
10385    if m_ineq > 0 {
10386        y_d_dv.set_values(&res.lambda_g[m_eq..]);
10387    }
10388    let mut lambda = nlp_borrow.finalize_solution_lambda(&y_c_dv, &y_d_dv);
10389    if lambda.is_empty() {
10390        lambda = vec![0.0; m];
10391    }
10392    if fixed_var_duals {
10393        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
10394    }
10395    drop(nlp_borrow);
10396
10397    let mut g_final = vec![0.0; m];
10398    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
10399    let f_final = tnlp
10400        .borrow_mut()
10401        .eval_f(&x_vec, true)
10402        .unwrap_or(Number::NAN);
10403    let snap = FinalizeSnapshot {
10404        status: solver_status,
10405        x: x_vec,
10406        z_l,
10407        z_u,
10408        g: g_final,
10409        lambda,
10410        obj_value: f_final,
10411        // The SQP arm has no `on_converged` firing.
10412        on_converged_id: None,
10413    };
10414    snap.replay(tnlp);
10415    *sink.borrow_mut() = Some(snap);
10416    Ok(f_final)
10417}
10418
10419/// Whether `options` resolve to the adaptive μ strategy, by the rules
10420/// `IpoptApplication::algorithm_builder_from_options` applies:
10421/// `mehrotra_algorithm=yes` forces adaptive; otherwise an explicit
10422/// `mu_strategy` wins; otherwise a limited-memory Hessian takes upstream's
10423/// quasi-Newton default, adaptive (gh#746), and anything else the registered
10424/// `monotone`.
10425///
10426/// Anything that asks "would this solve already run adaptive?" must ask this,
10427/// not read the raw `mu_strategy` string: under L-BFGS the string is unset and
10428/// the solve is adaptive. The second-opinion ladder read the string, so its
10429/// `mu_strategy=adaptive` rung re-ran a limited-memory base solve
10430/// byte-for-byte (`deb7`, 1610 iterations and `f = 99.636943584` both times).
10431pub fn mu_strategy_resolves_to_adaptive(options: &OptionsList) -> bool {
10432    if matches!(
10433        options.get_string_value("mehrotra_algorithm", ""),
10434        Ok((ref v, true)) if v == "yes"
10435    ) {
10436        return true;
10437    }
10438    if let Ok((v, true)) = options.get_string_value("mu_strategy", "") {
10439        return v == "adaptive";
10440    }
10441    matches!(
10442        options.get_string_value("hessian_approximation", ""),
10443        Ok((ref v, true)) if v == "limited-memory"
10444    )
10445}
10446
10447#[cfg(test)]
10448mod block_structure_tests {
10449    use super::map_block_structure_to_kkt;
10450    use pounce_nlp::tnlp_adapter::BoundClassification;
10451
10452    /// Three variables (the middle one fixed out) and four constraints: two
10453    /// equalities (rows 0 and 3) and two inequalities (rows 1 and 2).
10454    fn classification() -> BoundClassification {
10455        BoundClassification {
10456            n_full_x: 3,
10457            n_full_g: 4,
10458            n_x_fixed: 1,
10459            x_not_fixed_map: vec![0, 2],
10460            x_fixed_map: vec![1],
10461            x_fixed_vals: vec![0.0],
10462            full_to_var: vec![0, -1, 1],
10463            x_l_map: vec![],
10464            x_u_map: vec![],
10465            n_c: 2,
10466            c_map: vec![0, 3],
10467            n_d: 2,
10468            d_map: vec![1, 2],
10469            d_l_map: vec![],
10470            d_u_map: vec![],
10471            full_to_c: vec![0, -1, -1, 1],
10472            full_to_d: vec![-1, 0, 1, -1],
10473        }
10474    }
10475
10476    /// The KKT is `[x | slacks | equality duals | inequality duals]`, so a
10477    /// declaration in the model's terms lands as: the surviving variables'
10478    /// labels, then each inequality's label twice (slack and dual) around the
10479    /// equalities' labels. A variable fixed out of the problem contributes
10480    /// nothing — reading its label anyway would shift every later one.
10481    #[test]
10482    fn model_labels_map_onto_the_kkt_layout() {
10483        let cls = classification();
10484        let var_blocks = vec![7, 99, -1]; // x0 -> block 7, x1 fixed, x2 shared
10485        let con_blocks = vec![5, 6, -1, 8]; // eq 5, ineq 6, ineq shared, eq 8
10486        let labels = map_block_structure_to_kkt(&cls, &var_blocks, &con_blocks).unwrap();
10487        assert_eq!(
10488            labels,
10489            vec![
10490                7, -1, // x: the two unfixed variables
10491                6, -1, // slacks, in d order (rows 1 and 2)
10492                5, 8, // equality duals, in c order (rows 0 and 3)
10493                6, -1, // inequality duals, same order as their slacks
10494            ]
10495        );
10496    }
10497
10498    /// A length that does not match the problem is refused rather than
10499    /// truncated: a structure off by one row declares blocks the matrix does
10500    /// not have, and the solver would only notice as a wrong answer or a
10501    /// rejected partition.
10502    #[test]
10503    fn a_mismatched_declaration_is_refused() {
10504        let cls = classification();
10505        assert!(map_block_structure_to_kkt(&cls, &[1, 2], &[1, 2, 3, 4]).is_err());
10506        assert!(map_block_structure_to_kkt(&cls, &[1, 2, 3], &[1, 2, 3]).is_err());
10507    }
10508}
10509
10510#[cfg(test)]
10511mod tests {
10512    use super::*;
10513
10514    /// pounce#748 — the flipped default is conditional on the caller not
10515    /// having named a `mu_strategy`. All four combinations, because the
10516    /// point of the condition is that an explicit strategy suppresses the
10517    /// automatic retry while an explicit `mu_strategy_fallback` does not.
10518    #[test]
10519    fn mu_strategy_fallback_default_defers_to_an_explicit_strategy() {
10520        // Nothing set: the retry is on.
10521        let app = IpoptApplication::new();
10522        assert!(app.is_mu_strategy_fallback_enabled());
10523
10524        // Caller named a strategy: the automatic retry stands down.
10525        let mut app = IpoptApplication::new();
10526        app.options_mut()
10527            .set_string_value("mu_strategy", "monotone", true, false)
10528            .unwrap();
10529        assert!(!app.is_mu_strategy_fallback_enabled());
10530
10531        // ... unless they also asked for the retry explicitly.
10532        app.options_mut()
10533            .set_string_value("mu_strategy_fallback", "yes", true, false)
10534            .unwrap();
10535        assert!(app.is_mu_strategy_fallback_enabled());
10536
10537        // An explicit "no" is honoured with no strategy set.
10538        let mut app = IpoptApplication::new();
10539        app.options_mut()
10540            .set_string_value("mu_strategy_fallback", "no", true, false)
10541            .unwrap();
10542        assert!(!app.is_mu_strategy_fallback_enabled());
10543    }
10544
10545    /// gh#990: a `mu_strategy` a POUNCE frontend pinned (the Python
10546    /// no-`hessian` path's `monotone`) is not the caller naming a strategy,
10547    /// so the default-on stall retry stays on; an explicit `no` still wins.
10548    #[test]
10549    fn a_pounce_chosen_mu_strategy_keeps_the_fallback_on() {
10550        let mut app = IpoptApplication::new();
10551        app.options_mut()
10552            .set_string_value("hessian_approximation", "limited-memory", true, false)
10553            .unwrap();
10554        app.options_mut()
10555            .set_string_value("mu_strategy", "monotone", true, false)
10556            .unwrap();
10557        assert!(!app.is_mu_strategy_fallback_enabled());
10558        app.mark_mu_strategy_pounce_chosen();
10559        assert!(app.is_mu_strategy_fallback_enabled());
10560        // The pin still decides the schedule: no limited-memory -> adaptive.
10561        assert!(!app.effective_mu_strategy_is_adaptive());
10562        app.options_mut()
10563            .set_string_value("mu_strategy_fallback", "no", true, false)
10564            .unwrap();
10565        assert!(!app.is_mu_strategy_fallback_enabled());
10566    }
10567
10568    use pounce_nlp::tnlp::{
10569        BoundsInfo, IndexStyle, IpoptCq, IpoptData, NlpInfo, ScalingRequest, Solution,
10570        SparsityRequest, StartingPoint,
10571    };
10572
10573    struct Hs071Stub;
10574    impl TNLP for Hs071Stub {
10575        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10576            // HS071 dimensions: n=4, m=2, dense Jacobian (8 nz),
10577            // dense lower-triangular Hessian (10 nz).
10578            Some(NlpInfo {
10579                n: 4,
10580                m: 2,
10581                nnz_jac_g: 8,
10582                nnz_h_lag: 10,
10583                index_style: IndexStyle::C,
10584            })
10585        }
10586        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10587            b.x_l.copy_from_slice(&[1.0; 4]);
10588            b.x_u.copy_from_slice(&[5.0; 4]);
10589            b.g_l.copy_from_slice(&[25.0, 40.0]);
10590            b.g_u.copy_from_slice(&[2.0e19, 40.0]);
10591            true
10592        }
10593        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10594            sp.x.copy_from_slice(&[1.0, 5.0, 5.0, 1.0]);
10595            true
10596        }
10597        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
10598            Some(x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2])
10599        }
10600        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10601            grad.fill(0.0);
10602            true
10603        }
10604        fn eval_g(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10605            g.fill(0.0);
10606            true
10607        }
10608        fn eval_jac_g(
10609            &mut self,
10610            _x: Option<&[Number]>,
10611            _new_x: bool,
10612            mode: SparsityRequest<'_>,
10613        ) -> bool {
10614            if let SparsityRequest::Structure { irow, jcol } = mode {
10615                irow.copy_from_slice(&[0, 0, 0, 0, 1, 1, 1, 1]);
10616                jcol.copy_from_slice(&[0, 1, 2, 3, 0, 1, 2, 3]);
10617            }
10618            true
10619        }
10620        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
10621    }
10622
10623    #[test]
10624    fn application_default_does_not_select_sqp() {
10625        let mut app = IpoptApplication::new();
10626        app.initialize().unwrap();
10627        assert!(!app.is_sqp_algorithm_selected());
10628    }
10629
10630    /// gh#1061: `algorithm=active-set-sqp` starts from the interior point at
10631    /// `n + m ≥ AUTO_HANDOVER_MIN_DIM` — and only there, only when the user
10632    /// asked for the active-set SQP, and never when they set
10633    /// `ipm_sqp_handover` themselves.
10634    #[test]
10635    fn active_set_sqp_hands_over_from_the_interior_point_at_size() {
10636        let big = (AUTO_HANDOVER_MIN_DIM - 1000, 1000);
10637        let small = (AUTO_HANDOVER_MIN_DIM - 1000, 999);
10638        let with = |opts: &str| {
10639            let mut app = IpoptApplication::new();
10640            app.initialize().unwrap();
10641            app.initialize_with_options_str(opts).unwrap();
10642            app
10643        };
10644        let sqp = with("algorithm active-set-sqp\n");
10645        assert!(sqp.sqp_auto_handover(big.0, big.1));
10646        assert!(!sqp.sqp_auto_handover(small.0, small.1));
10647        assert!(with("solver_selection qp-active-set\n").sqp_auto_handover(big.0, big.1));
10648        let ipm = with("");
10649        assert!(
10650            !ipm.sqp_auto_handover(big.0, big.1),
10651            "the IPM is not rerouted"
10652        );
10653        for set in ["no", "yes"] {
10654            let app = with(&format!(
10655                "algorithm active-set-sqp\nipm_sqp_handover {set}\n"
10656            ));
10657            assert!(
10658                !app.sqp_auto_handover(big.0, big.1),
10659                "ipm_sqp_handover={set} was set, so the user decides"
10660            );
10661        }
10662    }
10663
10664    #[test]
10665    fn application_routes_to_sqp_when_algorithm_option_set() {
10666        let mut app = IpoptApplication::new();
10667        app.initialize().unwrap();
10668        app.initialize_with_options_str("algorithm active-set-sqp\n")
10669            .unwrap();
10670        assert!(app.is_sqp_algorithm_selected());
10671    }
10672
10673    #[test]
10674    fn feral_min_par_flops_option_reaches_config() {
10675        let mut app = IpoptApplication::new();
10676        app.initialize().unwrap();
10677        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10678        // which leaves it None (inherit feral's built-in default) when the
10679        // POUNCE_FERAL_MIN_PAR_FLOPS env var is also absent.
10680        assert_eq!(
10681            feral_config_from_options(app.options()).min_par_flops,
10682            None,
10683            "unset feral_min_par_flops should not force an override"
10684        );
10685        // Explicit set is mapped through, cast to u64. `0` is the "dispatch
10686        // on every eligible tree" setting and must survive the cast.
10687        app.initialize_with_options_str("feral_min_par_flops 0\n")
10688            .unwrap();
10689        assert_eq!(
10690            feral_config_from_options(app.options()).min_par_flops,
10691            Some(0)
10692        );
10693        // A large finite value passes through intact (5e8 > i32::MAX, which
10694        // is why this is a number option, not an integer one).
10695        app.initialize_with_options_str("feral_min_par_flops 5e8\n")
10696            .unwrap();
10697        assert_eq!(
10698            feral_config_from_options(app.options()).min_par_flops,
10699            Some(500_000_000)
10700        );
10701    }
10702
10703    #[test]
10704    fn feral_refine_steps_option_reaches_config() {
10705        let mut app = IpoptApplication::new();
10706        app.initialize().unwrap();
10707        // Unset: falls through to FeralConfig::from_env, which resolves to
10708        // feral's own DEFAULT_REFINE_MAX_STEPS. The bump to feral 0.17.0 is
10709        // deliberately behaviour-preserving here — the cap that gh#710 wants
10710        // to measure (1) is not yet the default.
10711        assert_eq!(
10712            feral_config_from_options(app.options()).refine_max_steps,
10713            pounce_feral::FeralConfig::default().refine_max_steps,
10714            "unset feral_refine_steps must keep feral's own default"
10715        );
10716        // The setting gh#710 exists to evaluate.
10717        app.initialize_with_options_str("feral_refine_steps 1\n")
10718            .unwrap();
10719        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 1);
10720        // `0` is a legal cap (zero corrections, refined entry point still
10721        // taken) and must not be read as "unset".
10722        app.initialize_with_options_str("feral_refine_steps 0\n")
10723            .unwrap();
10724        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 0);
10725    }
10726
10727    #[test]
10728    fn feral_static_pivoting_option_reaches_config() {
10729        let mut app = IpoptApplication::new();
10730        app.initialize().unwrap();
10731        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10732        // which leaves it None (inherit feral's delayed-pivot default) when
10733        // the POUNCE_FERAL_STATIC_PIVOTING env var is also absent — so the
10734        // default numeric path is unchanged.
10735        assert_eq!(
10736            feral_config_from_options(app.options()).static_pivoting,
10737            None,
10738            "unset feral_static_pivoting must not force a numeric override"
10739        );
10740        // Explicit `yes` maps to Some(true): every supernode factors with
10741        // delayed pivoting disabled (feral#8 cascade breaker).
10742        app.initialize_with_options_str("feral_static_pivoting yes\n")
10743            .unwrap();
10744        assert_eq!(
10745            feral_config_from_options(app.options()).static_pivoting,
10746            Some(true)
10747        );
10748        // Explicit `no` maps to Some(false): keep delayed pivoting on
10749        // (distinct from unset, which merely inherits the default).
10750        app.initialize_with_options_str("feral_static_pivoting no\n")
10751            .unwrap();
10752        assert_eq!(
10753            feral_config_from_options(app.options()).static_pivoting,
10754            Some(false)
10755        );
10756    }
10757
10758    /// Convex equality NLP fixture for end-to-end SQP testing
10759    /// through `IpoptApplication`:
10760    ///
10761    ///     min ½(x₁² + x₂²) − x₁ − 2x₂  s.t.  x₁ + x₂ = 1
10762    ///
10763    /// Closed form: x* = (0, 1), obj = -1.5, λ_g = 1.
10764    struct ConvexEqTnlp {
10765        finalize_called: std::rc::Rc<std::cell::RefCell<Option<(Vec<Number>, Number)>>>,
10766    }
10767    impl TNLP for ConvexEqTnlp {
10768        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10769            Some(NlpInfo {
10770                n: 2,
10771                m: 1,
10772                nnz_jac_g: 2,
10773                nnz_h_lag: 2,
10774                index_style: IndexStyle::C,
10775            })
10776        }
10777        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10778            b.x_l.copy_from_slice(&[-2.0e19; 2]);
10779            b.x_u.copy_from_slice(&[2.0e19; 2]);
10780            b.g_l.copy_from_slice(&[1.0]);
10781            b.g_u.copy_from_slice(&[1.0]);
10782            true
10783        }
10784        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10785            sp.x.copy_from_slice(&[0.0, 0.0]);
10786            true
10787        }
10788        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
10789            Some(0.5 * (x[0] * x[0] + x[1] * x[1]) - x[0] - 2.0 * x[1])
10790        }
10791        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10792            grad[0] = x[0] - 1.0;
10793            grad[1] = x[1] - 2.0;
10794            true
10795        }
10796        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10797            g[0] = x[0] + x[1];
10798            true
10799        }
10800        fn eval_jac_g(
10801            &mut self,
10802            _x: Option<&[Number]>,
10803            _new_x: bool,
10804            mode: SparsityRequest<'_>,
10805        ) -> bool {
10806            match mode {
10807                SparsityRequest::Structure { irow, jcol } => {
10808                    irow.copy_from_slice(&[0, 0]);
10809                    jcol.copy_from_slice(&[0, 1]);
10810                }
10811                SparsityRequest::Values { values, .. } => {
10812                    values.copy_from_slice(&[1.0, 1.0]);
10813                }
10814            }
10815            true
10816        }
10817        fn eval_h(
10818            &mut self,
10819            _x: Option<&[Number]>,
10820            _new_x: bool,
10821            _obj_factor: Number,
10822            _lambda: Option<&[Number]>,
10823            _new_lambda: bool,
10824            mode: SparsityRequest<'_>,
10825        ) -> bool {
10826            match mode {
10827                SparsityRequest::Structure { irow, jcol } => {
10828                    irow.copy_from_slice(&[0, 1]);
10829                    jcol.copy_from_slice(&[0, 1]);
10830                }
10831                SparsityRequest::Values { values, .. } => {
10832                    values.copy_from_slice(&[1.0, 1.0]);
10833                }
10834            }
10835            true
10836        }
10837        fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
10838            *self.finalize_called.borrow_mut() = Some((sol.x.to_vec(), sol.obj_value));
10839        }
10840    }
10841
10842    /// A TNLP that solves normally once, then declines to supply bounds.
10843    ///
10844    /// The second `optimize_constrained` therefore bails long before the
10845    /// statistics block that records `row_scaling_active`, which is the
10846    /// path the fail-closed reset exists for.
10847    struct DescribesItselfOnce {
10848        /// Flipped by the test between the two solves. A call counter
10849        /// would not work: these hooks are called more than once per
10850        /// solve, so it would trip inside the first one.
10851        refuse: std::rc::Rc<std::cell::Cell<bool>>,
10852        inner: ExactQuadratic,
10853    }
10854    impl TNLP for DescribesItselfOnce {
10855        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10856            self.inner.get_nlp_info()
10857        }
10858        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10859            // Declining here is a documented TNLP outcome and unwinds
10860            // cleanly; declining `get_nlp_info` mid-flight panics instead,
10861            // which would test the panic path rather than the reset.
10862            if self.refuse.get() {
10863                return false;
10864            }
10865            self.inner.get_bounds_info(b)
10866        }
10867        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10868            self.inner.get_starting_point(sp)
10869        }
10870        fn eval_f(&mut self, x: &[Number], n: bool) -> Option<Number> {
10871            self.inner.eval_f(x, n)
10872        }
10873        fn eval_grad_f(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10874            self.inner.eval_grad_f(x, n, g)
10875        }
10876        fn eval_g(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10877            self.inner.eval_g(x, n, g)
10878        }
10879        fn eval_jac_g(&mut self, x: Option<&[Number]>, n: bool, mode: SparsityRequest<'_>) -> bool {
10880            self.inner.eval_jac_g(x, n, mode)
10881        }
10882        fn eval_h(
10883            &mut self,
10884            x: Option<&[Number]>,
10885            n: bool,
10886            o: Number,
10887            l: Option<&[Number]>,
10888            nl: bool,
10889            mode: SparsityRequest<'_>,
10890        ) -> bool {
10891            self.inner.eval_h(x, n, o, l, nl, mode)
10892        }
10893        fn finalize_solution(&mut self, s: Solution<'_>, d: &IpoptData, c: &IpoptCq) {
10894            self.inner.finalize_solution(s, d, c)
10895        }
10896    }
10897
10898    /// gh#794 review round 2: `row_scaling_active` must be fail-closed.
10899    ///
10900    /// It is written near the end of `optimize_constrained`, from the NLP
10901    /// that solve built. A solve that bails before that point used to
10902    /// leave the *previous* solve's value in place — and the ℓ₁ outer
10903    /// loop calls `optimize_constrained` repeatedly and reads the flag
10904    /// after each call, so a stale `Some(false)` would let it mirror an
10905    /// original-units violation into the scaled family. That is exactly
10906    /// the units contract the flag was added to protect.
10907    ///
10908    /// The two solves here are the shape that matters: the first records
10909    /// a verdict, the second never gets far enough to record one.
10910    /// Removing the reset at the top of `optimize_constrained` makes this
10911    /// fail with `Some(false)` where `None` is required — checked, not
10912    /// assumed.
10913    #[test]
10914    fn row_scaling_active_is_cleared_when_a_later_solve_bails_early() {
10915        let mut app = IpoptApplication::new();
10916        app.initialize().unwrap();
10917
10918        // Solve 1: reaches the statistics block and records a verdict.
10919        // `ExactQuadratic` supplies `eval_h`, so the solve stays on the
10920        // exact-Hessian NLP path that writes this flag; a fixture without
10921        // one lands on L-BFGS instead.
10922        let refuse = std::rc::Rc::new(std::cell::Cell::new(false));
10923        let first = std::rc::Rc::new(std::cell::RefCell::new(DescribesItselfOnce {
10924            refuse: std::rc::Rc::clone(&refuse),
10925            inner: ExactQuadratic,
10926        }));
10927        let _ = app
10928            .optimize_tnlp(std::rc::Rc::clone(&first) as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
10929        assert!(
10930            app.row_scaling_active.get().is_some(),
10931            "the first solve did not record a row-scaling verdict, so this \
10932             test cannot show the second one clearing it",
10933        );
10934
10935        // Solve 2, same application: bails before recording anything.
10936        refuse.set(true);
10937        let _ = app.optimize_tnlp(first as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
10938
10939        assert_eq!(
10940            app.row_scaling_active.get(),
10941            None,
10942            "a solve that bailed before recording row scaling left the \
10943             previous solve's verdict in place; the ℓ₁ outer loop would \
10944             read it as fact and mirror an original-units violation into \
10945             the scaled family (gh#794 review round 2)",
10946        );
10947    }
10948
10949    #[test]
10950    fn application_sqp_path_solves_convex_eq_nlp_and_finalizes() {
10951        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
10952        let tnlp = std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
10953            finalize_called: std::rc::Rc::clone(&finalize_slot),
10954        }));
10955
10956        let mut app = IpoptApplication::new();
10957        app.initialize().unwrap();
10958        app.initialize_with_options_str("algorithm active-set-sqp\n")
10959            .unwrap();
10960        let status = app.optimize_tnlp(tnlp);
10961        assert_eq!(status, ApplicationReturnStatus::SolveSucceeded);
10962
10963        // The TNLP's finalize_solution must have been invoked.
10964        let recv = finalize_slot.borrow().clone();
10965        let (x_recv, obj_recv) = recv.expect("finalize_solution was not called");
10966        assert_eq!(x_recv.len(), 2);
10967        assert!((x_recv[0] - 0.0).abs() < 1e-6, "x[0] = {}", x_recv[0]);
10968        assert!((x_recv[1] - 1.0).abs() < 1e-6, "x[1] = {}", x_recv[1]);
10969        assert!(
10970            (obj_recv - (-1.5)).abs() < 1e-6,
10971            "obj = {} but expected -1.5",
10972            obj_recv
10973        );
10974    }
10975
10976    #[test]
10977    fn application_routes_to_sqp_case_insensitively() {
10978        let mut app = IpoptApplication::new();
10979        app.initialize().unwrap();
10980        app.initialize_with_options_str("algorithm Active-Set-SQP\n")
10981            .unwrap();
10982        // get_string_value may return the value as-stored (no
10983        // normalization); the dispatch must handle case
10984        // insensitively per the c11 design choice.
10985        assert!(app.is_sqp_algorithm_selected());
10986    }
10987
10988    #[test]
10989    fn application_constructs_and_loads_options() {
10990        let mut app = IpoptApplication::new();
10991        app.initialize().unwrap();
10992        // ipopt.opt-style file: an integer-typed option registered by
10993        // the Interfaces layer.
10994        app.initialize_with_options_str("print_level 5\nfile_print_level 7\n")
10995            .unwrap();
10996        let (level, found) = app.options().get_integer_value("print_level", "").unwrap();
10997        assert!(found);
10998        assert_eq!(level, 5);
10999    }
11000
11001    #[test]
11002    fn application_sqp_suboptions_propagate_to_builder() {
11003        // All SQP suboptions are read by algorithm_builder_snapshot
11004        // and baked into the builder's `sqp` field.
11005        let mut app = IpoptApplication::new();
11006        app.initialize().unwrap();
11007        app.initialize_with_options_str(
11008            "algorithm active-set-sqp\n\
11009             sqp_globalization l1-elastic\n\
11010             sqp_hessian lbfgs\n\
11011             sqp_max_iter 17\n\
11012             sqp_tol 1e-7\n\
11013             sqp_constr_viol_tol 1e-5\n\
11014             sqp_dual_inf_tol 1e-3\n\
11015             sqp_l1_penalty 2.5\n\
11016             sqp_bt_reduction 0.25\n\
11017             sqp_bt_min_alpha 1e-10\n\
11018             sqp_print_level 2\n\
11019             sqp_lbfgs_max_history 12\n",
11020        )
11021        .unwrap();
11022        let snap = app.algorithm_builder_snapshot();
11023        assert_eq!(
11024            snap.sqp.globalization,
11025            crate::sqp::SqpGlobalization::L1Elastic
11026        );
11027        assert_eq!(snap.sqp.hessian, crate::sqp::SqpHessianSource::Lbfgs);
11028        assert_eq!(snap.sqp.max_iter, 17);
11029        assert!((snap.sqp.tol - 1e-7).abs() < 1e-18);
11030        assert!((snap.sqp.constr_viol_tol - 1e-5).abs() < 1e-18);
11031        assert!((snap.sqp.dual_inf_tol - 1e-3).abs() < 1e-18);
11032        assert!((snap.sqp.l1_penalty - 2.5).abs() < 1e-18);
11033        assert!((snap.sqp.bt_reduction - 0.25).abs() < 1e-18);
11034        assert!((snap.sqp.bt_min_alpha - 1e-10).abs() < 1e-18);
11035        assert_eq!(snap.sqp.print_level, 2);
11036        assert_eq!(snap.sqp.lbfgs_max_history, 12);
11037    }
11038
11039    /// Every `sqp_qp_*` key that [`apply_qp_subproblem_options`] reads must
11040    /// actually be *registered*, and must reach `pounce_qp::QpOptions`.
11041    ///
11042    /// The whole family was readable-but-unregistered (gh #360): the options
11043    /// registry rejected each one with OPTION_INVALID, so the reader was
11044    /// unreachable and the documented knobs were unusable. This is the guard
11045    /// that class of omission needs — it fails both if a key stops being
11046    /// registered and if a newly-read key is never registered at all.
11047    #[test]
11048    fn issue_1054_schur_updates_follow_size_unless_set() {
11049        let mut app = IpoptApplication::new();
11050        app.initialize().unwrap();
11051        app.initialize_with_options_str("algorithm active-set-sqp\n")
11052            .unwrap();
11053        assert_eq!(
11054            app.algorithm_builder_snapshot().sqp.qp_schur_min_dim,
11055            Some(crate::sqp::options::DEFAULT_QP_SCHUR_MIN_DIM)
11056        );
11057        for v in ["yes", "no"] {
11058            let mut app = IpoptApplication::new();
11059            app.initialize().unwrap();
11060            app.initialize_with_options_str(&format!(
11061                "algorithm active-set-sqp\nsqp_qp_use_schur_updates {v}\n"
11062            ))
11063            .unwrap();
11064            let snap = app.algorithm_builder_snapshot();
11065            assert_eq!(snap.sqp.qp_schur_min_dim, None, "{v}: explicit wins");
11066            assert_eq!(snap.sqp_qp.use_schur_updates, v == "yes");
11067        }
11068    }
11069
11070    #[test]
11071    fn application_sqp_qp_subproblem_options_are_registered_and_propagate() {
11072        use pounce_qp::AntiCyclingChoice;
11073
11074        // Source of truth: the keys `apply_qp_subproblem_options` reads.
11075        // Kept in step with that function by the round-trip assertions below.
11076        let mut app = IpoptApplication::new();
11077        app.initialize().unwrap();
11078        app.initialize_with_options_str(
11079            "algorithm active-set-sqp\n\
11080             sqp_qp_max_iter 37\n\
11081             sqp_qp_feas_tol 1e-7\n\
11082             sqp_qp_opt_tol 2e-7\n\
11083             sqp_qp_elastic_gamma 1e4\n\
11084             sqp_qp_anti_cycling bland\n\
11085             sqp_qp_use_schur_updates yes\n\
11086             sqp_qp_max_schur_updates_before_refactor 12\n\
11087             sqp_qp_use_homotopy yes\n\
11088             sqp_qp_certify_second_order yes\n",
11089        )
11090        .expect("every sqp_qp_* option must be registered (gh #360)");
11091
11092        let qp = &app.algorithm_builder_snapshot().sqp_qp;
11093        assert_eq!(qp.max_iter, 37);
11094        assert!((qp.feas_tol - 1e-7).abs() < 1e-20);
11095        assert!((qp.opt_tol - 2e-7).abs() < 1e-20);
11096        assert!((qp.elastic_gamma - 1e4).abs() < 1e-9);
11097        assert_eq!(qp.anti_cycling, AntiCyclingChoice::Bland);
11098        // The Schur update path was implemented but reachable only through
11099        // `SqpAlgorithm::with_qp_options`, so no CLI/library user could turn
11100        // it on — the same unreachable-knob defect gh #360 fixed for the rest
11101        // of this family.
11102        assert!(qp.use_schur_updates);
11103        assert_eq!(qp.max_schur_updates_before_refactor, 12);
11104        assert!(qp.use_homotopy);
11105        // gh #848. Off by default on this path (see
11106        // `QpOptions::sqp_subproblem`), so the value that proves the wire is
11107        // live is `yes` — asserting the default would pass on a reader that
11108        // never ran.
11109        assert!(qp.certify_second_order);
11110
11111        // Untouched options must keep the SQP subproblem base, not be
11112        // overwritten with zeros by the "explicitly set" gate. That base is
11113        // `QpOptions::default()` in every field but one; the exception is
11114        // asserted below.
11115        let mut app = IpoptApplication::new();
11116        app.initialize().unwrap();
11117        app.initialize_with_options_str("algorithm active-set-sqp\n")
11118            .unwrap();
11119        let defaults = pounce_qp::QpOptions::default();
11120        let qp = &app.algorithm_builder_snapshot().sqp_qp;
11121        assert_eq!(qp.max_iter, defaults.max_iter);
11122        assert!((qp.feas_tol - defaults.feas_tol).abs() < 1e-20);
11123        assert!((qp.opt_tol - defaults.opt_tol).abs() < 1e-20);
11124        assert_eq!(qp.anti_cycling, defaults.anti_cycling);
11125        // Off in the base QP options: the SQP driver turns it on per solve
11126        // from `n + m >= 500` (gh#1054; measured on Maros-Meszaros, see the
11127        // option text). Do not move that threshold without re-running the
11128        // comparison.
11129        assert!(!qp.use_schur_updates);
11130        assert_eq!(
11131            qp.max_schur_updates_before_refactor,
11132            defaults.max_schur_updates_before_refactor
11133        );
11134        // Off by default *on the SQP path*, and deliberately different from
11135        // `QpOptions::default()` — which is what a standalone `solve_qp`
11136        // gets, and where it is on. gh #848 / gh #856.
11137        assert!(!qp.certify_second_order);
11138        assert!(pounce_qp::QpOptions::default().certify_second_order);
11139    }
11140
11141    /// The other direction of the gh #360 guard: every **registered**
11142    /// `sqp_qp_*` option must be one `apply_qp_subproblem_options` actually
11143    /// reads.
11144    ///
11145    /// The sister test above checks read-keys-are-registered. It cannot catch
11146    /// the inverse, and the inverse happened: `sqp_qp_use_homotopy` was
11147    /// registered with the homotopy work and never wired into the reader, so
11148    /// setting it on the SQP path silently did nothing while the option's own
11149    /// documentation described what it would do. A registered knob that no
11150    /// code reads is worse than a missing one — it validates, it accepts a
11151    /// value, and it lies.
11152    ///
11153    /// Adding a new `sqp_qp_*` option therefore fails here until it is both
11154    /// read by `apply_qp_subproblem_options` and asserted in the round-trip
11155    /// test above.
11156    #[test]
11157    fn application_every_registered_sqp_qp_option_is_read_by_the_subproblem_reader() {
11158        let mut app = IpoptApplication::new();
11159        app.initialize().unwrap();
11160
11161        let mut registered: Vec<String> = app
11162            .registered_options()
11163            .registered_options_in_order()
11164            .iter()
11165            .map(|o| o.name.clone())
11166            .filter(|n| n.starts_with("sqp_qp_"))
11167            .collect();
11168        registered.sort();
11169
11170        // Kept in step by hand with the `options.get_*_value("sqp_qp_…")`
11171        // calls in `apply_qp_subproblem_options`, and cross-checked by the
11172        // round-trip assertions in the sister test.
11173        let mut read_by_the_reader = vec![
11174            "sqp_qp_anti_cycling".to_string(),
11175            "sqp_qp_certify_second_order".to_string(),
11176            "sqp_qp_elastic_gamma".to_string(),
11177            "sqp_qp_feas_tol".to_string(),
11178            "sqp_qp_max_iter".to_string(),
11179            "sqp_qp_max_schur_updates_before_refactor".to_string(),
11180            "sqp_qp_opt_tol".to_string(),
11181            "sqp_qp_use_homotopy".to_string(),
11182            "sqp_qp_use_schur_updates".to_string(),
11183        ];
11184        read_by_the_reader.sort();
11185
11186        assert_eq!(
11187            registered, read_by_the_reader,
11188            "registered sqp_qp_* options and the ones \
11189             `apply_qp_subproblem_options` reads have diverged. A key that is \
11190             registered but unread is a no-op knob with working documentation \
11191             (that is how `sqp_qp_use_homotopy` shipped); a key read but not \
11192             registered is gh #360. Wire it up in both places, assert it in \
11193             `application_sqp_qp_subproblem_options_are_registered_and_propagate`, \
11194             then add it here."
11195        );
11196    }
11197
11198    #[test]
11199    fn application_sqp_hessian_approximation_maps_to_damped_bfgs() {
11200        // The frontend sets `hessian_approximation = limited-memory` when no
11201        // exact Lagrangian Hessian is available (e.g. `pounce.minimize` with
11202        // no `hess`). On the active-set-SQP path that must resolve to the
11203        // dense Powell-damped BFGS, NOT the limited-memory update: L-BFGS
11204        // materializes the same dense Hessian for the QP subproblem yet stalls
11205        // (`Search_Direction_Becomes_Too_Small` / wrong `x`) on convex QPs with
11206        // an active inequality (issue #358); damped-BFGS solves them.
11207        let mut app = IpoptApplication::new();
11208        app.initialize().unwrap();
11209        app.initialize_with_options_str(
11210            "algorithm active-set-sqp\n\
11211             hessian_approximation limited-memory\n",
11212        )
11213        .unwrap();
11214        let snap = app.algorithm_builder_snapshot().sqp;
11215        assert_eq!(snap.hessian, crate::sqp::SqpHessianSource::QuasiNewtonAuto);
11216        // ...which is the dense update at or below the ceiling, and the
11217        // lifted limited-memory one above it (gh#1054).
11218        assert_eq!(
11219            snap.hessian
11220                .resolve(snap.dense_hessian_max_n, snap.dense_hessian_max_n),
11221            crate::sqp::SqpHessianSource::DampedBfgs
11222        );
11223        assert_eq!(
11224            snap.hessian
11225                .resolve(snap.dense_hessian_max_n + 1, snap.dense_hessian_max_n),
11226            crate::sqp::SqpHessianSource::Lbfgs
11227        );
11228
11229        // An explicit `sqp_hessian = lbfgs` is still honored (it is read after
11230        // `hessian_approximation`, so it wins): callers who genuinely want the
11231        // limited-memory update can still ask for it.
11232        let mut app = IpoptApplication::new();
11233        app.initialize().unwrap();
11234        app.initialize_with_options_str(
11235            "algorithm active-set-sqp\n\
11236             hessian_approximation limited-memory\n\
11237             sqp_hessian lbfgs\n",
11238        )
11239        .unwrap();
11240        assert_eq!(
11241            app.algorithm_builder_snapshot().sqp.hessian,
11242            crate::sqp::SqpHessianSource::Lbfgs
11243        );
11244    }
11245
11246    /// `builder.linear_solver` must name the backend that will actually be
11247    /// built, not the one the option string asked for.
11248    ///
11249    /// MA57 is behind the optional `ma57` cargo feature; without it
11250    /// `default_backend_factory` silently substitutes FERAL. Recording `Ma57`
11251    /// anyway made the field disagree with reality, and the Schur KKT gate in
11252    /// `alg_builder::build_with_backend` (which tests `== Feral`) consumed that
11253    /// disagreement — so `set_kkt_schur_block()` never engaged on the default
11254    /// pure-Rust build for any user, while the transparent fallback kept every
11255    /// answer correct and every test green.
11256    #[test]
11257    fn application_linear_solver_records_the_effective_backend() {
11258        // Default options resolve to FERAL in *every* build. The registry
11259        // used to default to upstream's "ma57", which meant an HSL build
11260        // silently ran MA57 without being asked and a pure-Rust build
11261        // advertised a backend it did not contain; the default now names
11262        // pounce's own solver and HSL is opt-in (gh#483 follow-up).
11263        let mut app = IpoptApplication::new();
11264        app.initialize().unwrap();
11265        assert_eq!(
11266            app.algorithm_builder_from_options().linear_solver,
11267            LinearSolverChoice::Feral,
11268            "the registered default is `feral`, in an ma57 build too"
11269        );
11270
11271        // An explicit ma57 request resolves the same way.
11272        let mut app = IpoptApplication::new();
11273        app.initialize().unwrap();
11274        app.initialize_with_options_str("linear_solver ma57\n")
11275            .unwrap();
11276        let got = app.algorithm_builder_from_options().linear_solver;
11277        if cfg!(feature = "ma57") {
11278            assert_eq!(got, LinearSolverChoice::Ma57);
11279        } else {
11280            assert_eq!(got, LinearSolverChoice::Feral);
11281        }
11282
11283        // An explicit feral request is honored in every build.
11284        let mut app = IpoptApplication::new();
11285        app.initialize().unwrap();
11286        app.initialize_with_options_str("linear_solver feral\n")
11287            .unwrap();
11288        assert_eq!(
11289            app.algorithm_builder_from_options().linear_solver,
11290            LinearSolverChoice::Feral
11291        );
11292    }
11293
11294    /// gh#746. `IpAlgBuilder.cpp:1059` substitutes `adaptive` for the
11295    /// registered `monotone` when `hessian_approximation` is
11296    /// limited-memory and the caller left `mu_strategy` alone. pounce
11297    /// read the registered default unconditionally, which is a
11298    /// different barrier schedule on the whole quasi-Newton arm.
11299    #[test]
11300    fn limited_memory_defaults_mu_strategy_to_adaptive() {
11301        // Exact Hessian, nothing set: monotone, as registered.
11302        let mut app = IpoptApplication::new();
11303        app.initialize().unwrap();
11304        assert_eq!(
11305            app.algorithm_builder_from_options().mu_strategy,
11306            MuStrategyChoice::Monotone,
11307            "the exact arm must keep the registered default"
11308        );
11309
11310        // Limited memory, nothing set: adaptive.
11311        let mut app = IpoptApplication::new();
11312        app.initialize().unwrap();
11313        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11314            .unwrap();
11315        assert_eq!(
11316            app.algorithm_builder_from_options().mu_strategy,
11317            MuStrategyChoice::Adaptive,
11318            "limited-memory must take upstream's quasi-Newton default"
11319        );
11320
11321        // An explicit `monotone` still wins — the substitution is only
11322        // for an absent option.
11323        let mut app = IpoptApplication::new();
11324        app.initialize().unwrap();
11325        app.initialize_with_options_str(
11326            "hessian_approximation limited-memory\n\
11327             mu_strategy monotone\n",
11328        )
11329        .unwrap();
11330        assert_eq!(
11331            app.algorithm_builder_from_options().mu_strategy,
11332            MuStrategyChoice::Monotone,
11333            "an explicit mu_strategy must not be overridden"
11334        );
11335    }
11336
11337    /// The μ-strategy auto-fallback retries with the *other* strategy.
11338    /// Under limited-memory the first attempt is adaptive, so the flip
11339    /// has to be monotone — reading the registered default there would
11340    /// re-run the strategy that just stalled (gh#746).
11341    #[test]
11342    fn fallback_flip_follows_the_resolved_mu_strategy() {
11343        let mut app = IpoptApplication::new();
11344        app.initialize().unwrap();
11345        assert!(
11346            !app.effective_mu_strategy_is_adaptive(),
11347            "unset + exact resolves to monotone"
11348        );
11349
11350        let mut app = IpoptApplication::new();
11351        app.initialize().unwrap();
11352        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11353            .unwrap();
11354        assert!(
11355            app.effective_mu_strategy_is_adaptive(),
11356            "unset + limited-memory resolves to adaptive"
11357        );
11358
11359        let mut app = IpoptApplication::new();
11360        app.initialize().unwrap();
11361        app.initialize_with_options_str(
11362            "hessian_approximation limited-memory\n\
11363             mu_strategy monotone\n",
11364        )
11365        .unwrap();
11366        assert!(
11367            !app.effective_mu_strategy_is_adaptive(),
11368            "an explicit monotone under limited-memory resolves to monotone"
11369        );
11370    }
11371
11372    #[test]
11373    fn application_limited_memory_options_propagate_to_builder() {
11374        use crate::hess::lim_mem_quasi_newton::UpdateType;
11375
11376        // Default: no options set -> bit-exact with Ipopt's default
11377        // (bfgs, history 6). This is what the IPM path runs unless the
11378        // user opts in, so it must not drift.
11379        let mut app = IpoptApplication::new();
11380        app.initialize().unwrap();
11381        let def = app.algorithm_builder_from_options();
11382        assert_eq!(def.limited_memory_update_type, UpdateType::Bfgs);
11383        assert_eq!(def.limited_memory_max_history, 6);
11384
11385        // `limited_memory_update_type=sr1` and a custom history length
11386        // must reach the builder (these were registered upstream but
11387        // read nowhere on the IPM path before — see #131). Honoring
11388        // them is what lets SR1 break the monotone L-BFGS stall.
11389        let mut app = IpoptApplication::new();
11390        app.initialize().unwrap();
11391        app.initialize_with_options_str(
11392            "hessian_approximation limited-memory\n\
11393             limited_memory_update_type sr1\n\
11394             limited_memory_max_history 9\n",
11395        )
11396        .unwrap();
11397        let snap = app.algorithm_builder_from_options();
11398        assert_eq!(snap.limited_memory_update_type, UpdateType::Sr1);
11399        assert_eq!(snap.limited_memory_max_history, 9);
11400    }
11401
11402    #[test]
11403    fn application_recalc_y_is_wired_and_defaults_off() {
11404        // #677. Upstream registers `recalc_y` as `no`, but its option
11405        // text ends "If a limited memory quasi-Newton option is chosen,
11406        // this is used by default" — the effective default is
11407        // conditional on the Hessian approximation. pounce refused the
11408        // option outright before this, so an L-BFGS user had no way to
11409        // reach Ipopt's behaviour.
11410
11411        // Exact Hessian: off, matching the registered default.
11412        let mut app = IpoptApplication::new();
11413        app.initialize().unwrap();
11414        let b = app.algorithm_builder_from_options();
11415        assert!(!b.recalc_y, "exact-Hessian default must stay off");
11416        assert_eq!(b.recalc_y_feas_tol, 1e-6, "default changed");
11417
11418        // Limited memory: also off. Upstream's option text says it is
11419        // used by default there; pounce deliberately does not, because
11420        // auto-enabling took 7 of 57 fixtures from solved to not solved
11421        // on the L-BFGS leg with nothing moving the other way. See the
11422        // read site in `algorithm_builder_from_options`. If this
11423        // assertion is what fails, the auto-enable is being restored —
11424        // re-run `scripts/sweep-fixtures.sh` and explain those 7 first.
11425        let mut app = IpoptApplication::new();
11426        app.initialize().unwrap();
11427        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11428            .unwrap();
11429        assert!(
11430            !app.algorithm_builder_from_options().recalc_y,
11431            "limited-memory must not silently enable recalc_y"
11432        );
11433
11434        // An explicit `yes` reaches the exact-Hessian path, which
11435        // used to be refused as unimplemented.
11436        let mut app = IpoptApplication::new();
11437        app.initialize().unwrap();
11438        app.initialize_with_options_str("recalc_y yes\nrecalc_y_feas_tol 1e-3\n")
11439            .unwrap();
11440        let b = app.algorithm_builder_from_options();
11441        assert!(b.recalc_y);
11442        assert_eq!(b.recalc_y_feas_tol, 1e-3);
11443    }
11444
11445    #[test]
11446    fn application_limited_memory_initialization_propagates_to_builder() {
11447        use crate::hess::lim_mem_quasi_newton::InitialApprox;
11448
11449        // #677: registered with upstream's `scalar1` default and read
11450        // nowhere, so every limited-memory solve ran `scalar2` and
11451        // setting the option was a silent no-op. Each keyword must now
11452        // reach the builder.
11453        for (kw, want) in [
11454            ("scalar1", InitialApprox::Scalar1),
11455            ("scalar2", InitialApprox::Scalar2),
11456            ("scalar3", InitialApprox::Scalar3),
11457            ("scalar4", InitialApprox::Scalar4),
11458            ("constant", InitialApprox::Constant),
11459            ("history-max", InitialApprox::HistoryMax),
11460        ] {
11461            let mut app = IpoptApplication::new();
11462            app.initialize().unwrap();
11463            app.initialize_with_options_str(&format!(
11464                "hessian_approximation limited-memory\n\
11465                 limited_memory_initialization {kw}\n"
11466            ))
11467            .unwrap();
11468            assert_eq!(
11469                app.algorithm_builder_from_options()
11470                    .limited_memory_initialization,
11471                want,
11472                "limited_memory_initialization={kw} did not reach the builder"
11473            );
11474        }
11475
11476        // `limited_memory_init_val` was unread too — the empty-history
11477        // branch hard-coded the same 1.0, so the miss was invisible.
11478        let mut app = IpoptApplication::new();
11479        app.initialize().unwrap();
11480        app.initialize_with_options_str(
11481            "hessian_approximation limited-memory\n\
11482             limited_memory_init_val 4.5\n",
11483        )
11484        .unwrap();
11485        assert_eq!(
11486            app.algorithm_builder_from_options().limited_memory_init_val,
11487            4.5
11488        );
11489
11490        // The effective default matches the registry and Ipopt
11491        // (`scalar1`). This is the assertion that would have caught #677
11492        // when the option was first registered: it pins the *selection*,
11493        // which the per-formula tests in `lim_mem_quasi_newton` cannot
11494        // see. Do not relax it to make an unrelated change pass.
11495        let mut app = IpoptApplication::new();
11496        app.initialize().unwrap();
11497        let def = app.algorithm_builder_from_options();
11498        assert_eq!(def.limited_memory_initialization, InitialApprox::Scalar1);
11499        assert_eq!(def.limited_memory_init_val, 1.0);
11500    }
11501
11502    #[test]
11503    fn application_sqp_warm_start_round_trip() {
11504        // Drive the convex-equality TNLP through the SQP path
11505        // twice. The first solve produces a working set; the
11506        // second is warm-started from it. The second must converge
11507        // with zero QP solves (the first KKT check declares
11508        // optimality immediately).
11509        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
11510        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
11511            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
11512                finalize_called: std::rc::Rc::clone(&finalize_slot),
11513            }));
11514
11515        let mut app = IpoptApplication::new();
11516        app.initialize().unwrap();
11517        app.initialize_with_options_str("algorithm active-set-sqp\n")
11518            .unwrap();
11519
11520        // Cold solve.
11521        let status_a = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11522        assert_eq!(status_a, ApplicationReturnStatus::SolveSucceeded);
11523        let ws = app.last_sqp_working_set().cloned();
11524        assert!(ws.is_some(), "cold solve must yield a working set");
11525
11526        // Build the warm-start iterate from the converged finalize
11527        // payload (just x; pad multipliers to 0 since the test
11528        // problem is convex).
11529        let (x_recv, _) = finalize_slot.borrow().clone().unwrap();
11530        let warm = crate::sqp::SqpIterates {
11531            x: x_recv,
11532            lambda_g: vec![1.0],
11533            lambda_x: vec![0.0, 0.0],
11534            working: ws,
11535        };
11536        app.set_sqp_warm_start(warm);
11537
11538        // Warm solve.
11539        let status_b = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11540        assert_eq!(status_b, ApplicationReturnStatus::SolveSucceeded);
11541        assert!(app.last_sqp_working_set().is_some());
11542    }
11543
11544    #[test]
11545    fn application_sqp_warm_start_auto_clears_after_use() {
11546        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
11547        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
11548            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
11549                finalize_called: std::rc::Rc::clone(&finalize_slot),
11550            }));
11551        let mut app = IpoptApplication::new();
11552        app.initialize().unwrap();
11553        app.initialize_with_options_str("algorithm active-set-sqp\n")
11554            .unwrap();
11555        app.set_sqp_warm_start(crate::sqp::SqpIterates {
11556            x: vec![0.0, 1.0],
11557            lambda_g: vec![1.0],
11558            lambda_x: vec![0.0, 0.0],
11559            working: None,
11560        });
11561        assert!(app.sqp_warm_start.is_some());
11562        let _ = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11563        assert!(
11564            app.sqp_warm_start.is_none(),
11565            "warm-start input must be auto-cleared after use"
11566        );
11567    }
11568
11569    #[test]
11570    fn application_sqp_suboptions_default_when_unset() {
11571        // Without any sqp_* settings, the snapshot should equal
11572        // SqpOptions::default().
11573        let mut app = IpoptApplication::new();
11574        app.initialize().unwrap();
11575        let snap = app.algorithm_builder_snapshot();
11576        let d = crate::sqp::SqpOptions::default();
11577        assert_eq!(snap.sqp.globalization, d.globalization);
11578        assert_eq!(snap.sqp.hessian, d.hessian);
11579        assert_eq!(snap.sqp.max_iter, d.max_iter);
11580        assert!((snap.sqp.tol - d.tol).abs() < 1e-18);
11581        assert!((snap.sqp.constr_viol_tol - d.constr_viol_tol).abs() < 1e-18);
11582        assert!((snap.sqp.dual_inf_tol - d.dual_inf_tol).abs() < 1e-18);
11583        assert!((snap.sqp.l1_penalty - d.l1_penalty).abs() < 1e-18);
11584        assert!((snap.sqp.bt_reduction - d.bt_reduction).abs() < 1e-18);
11585        assert!((snap.sqp.bt_min_alpha - d.bt_min_alpha).abs() < 1e-18);
11586        assert_eq!(snap.sqp.print_level, d.print_level);
11587        assert_eq!(snap.sqp.lbfgs_max_history, d.lbfgs_max_history);
11588    }
11589
11590    #[test]
11591    fn application_reports_problem_dimensions() {
11592        let app = IpoptApplication::new();
11593        let mut tnlp = Hs071Stub;
11594        let info = app.problem_dimensions(&mut tnlp).unwrap();
11595        assert_eq!(info.n, 4);
11596        assert_eq!(info.m, 2);
11597        assert_eq!(info.nnz_jac_g, 8);
11598        assert_eq!(info.nnz_h_lag, 10);
11599    }
11600
11601    /// Each of the four constant-derivative hints reaches the algorithm,
11602    /// and reaches its *own* slot (#551 / #677).
11603    ///
11604    /// All four were wired and consumed — gh#588 Q6 made pounce exploit
11605    /// them — but the read site looped over
11606    /// `constant_derivatives::HINT_OPTIONS`, so the registered-but-unread
11607    /// scan saw a loop variable where it needs a literal key and reported
11608    /// all four as silent no-ops. They are literals now, and this pins
11609    /// what a literal-per-name rewrite can get wrong that a loop could
11610    /// not: setting one hint must light up that hint's slot and no other,
11611    /// because `reconcile` pairs `asserted[k]` with the model's proof for
11612    /// `HINT_OPTIONS[k]` and a transposed pair would reuse the wrong
11613    /// derivative.
11614    #[test]
11615    fn each_constant_derivative_hint_lights_up_its_own_slot() {
11616        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
11617
11618        let app = IpoptApplication::new();
11619        assert_eq!(
11620            app.asserted_constant_derivative_hints(),
11621            [false; 4],
11622            "no hint is asserted on a fresh options list",
11623        );
11624
11625        for (k, name) in HINT_OPTIONS.iter().enumerate() {
11626            let mut app = IpoptApplication::new();
11627            app.initialize().unwrap();
11628            app.initialize_with_options_str(&format!("{name} yes\n"))
11629                .unwrap();
11630            let mut expected = [false; 4];
11631            expected[k] = true;
11632            assert_eq!(
11633                app.asserted_constant_derivative_hints(),
11634                expected,
11635                "`{name}=yes` must set slot {k} and nothing else",
11636            );
11637
11638            // …and the registered default asks for nothing, so an
11639            // `ipopt.opt` that spells it out changes no derivative reuse.
11640            let mut app = IpoptApplication::new();
11641            app.initialize().unwrap();
11642            app.initialize_with_options_str(&format!("{name} no\n"))
11643                .unwrap();
11644            assert_eq!(
11645                app.asserted_constant_derivative_hints(),
11646                [false; 4],
11647                "`{name}=no` is the registered default and asserts nothing",
11648            );
11649        }
11650    }
11651
11652    /// `min x²` on `[-10, 10]` from `x = 1`, with an *exactly correct*
11653    /// gradient `2x`. Unconstrained and one-dimensional so the only
11654    /// thing the derivative checker can react to is its own step size
11655    /// and threshold.
11656    ///
11657    /// The forward difference at step `h` is `((1+h)² − 1)/h = 2 + h`,
11658    /// so the deviation from the analytic `2` is exactly `h`, and the
11659    /// relative test flags it when `h > tol·(2 + h)`. That makes the
11660    /// verdict a closed-form function of the two knobs under test.
11661    struct ExactQuadratic;
11662    impl TNLP for ExactQuadratic {
11663        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
11664            Some(NlpInfo {
11665                n: 1,
11666                m: 0,
11667                nnz_jac_g: 0,
11668                nnz_h_lag: 0,
11669                index_style: IndexStyle::C,
11670            })
11671        }
11672        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
11673            b.x_l.copy_from_slice(&[-10.0]);
11674            b.x_u.copy_from_slice(&[10.0]);
11675            true
11676        }
11677        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
11678            sp.x.copy_from_slice(&[1.0]);
11679            true
11680        }
11681        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
11682            Some(x[0] * x[0])
11683        }
11684        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11685            grad[0] = 2.0 * x[0];
11686            true
11687        }
11688        fn eval_g(&mut self, _x: &[Number], _new_x: bool, _g: &mut [Number]) -> bool {
11689            true
11690        }
11691        fn eval_jac_g(
11692            &mut self,
11693            _x: Option<&[Number]>,
11694            _new_x: bool,
11695            _mode: SparsityRequest<'_>,
11696        ) -> bool {
11697            true
11698        }
11699        fn eval_h(
11700            &mut self,
11701            _x: Option<&[Number]>,
11702            _new_x: bool,
11703            _obj_factor: Number,
11704            _lambda: Option<&[Number]>,
11705            _new_lambda: bool,
11706            _mode: SparsityRequest<'_>,
11707        ) -> bool {
11708            true
11709        }
11710        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11711    }
11712
11713    struct RecordingQuadratic {
11714        gradient_points: Rc<RefCell<Vec<Number>>>,
11715        objective_points: Rc<RefCell<Vec<Number>>>,
11716        x_scaling: Number,
11717    }
11718
11719    impl TNLP for RecordingQuadratic {
11720        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
11721            ExactQuadratic.get_nlp_info()
11722        }
11723
11724        fn get_bounds_info(&mut self, bounds: BoundsInfo<'_>) -> bool {
11725            ExactQuadratic.get_bounds_info(bounds)
11726        }
11727
11728        fn get_starting_point(&mut self, start: StartingPoint<'_>) -> bool {
11729            ExactQuadratic.get_starting_point(start)
11730        }
11731
11732        fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
11733            self.objective_points.borrow_mut().push(x[0]);
11734            ExactQuadratic.eval_f(x, new_x)
11735        }
11736
11737        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11738            self.gradient_points.borrow_mut().push(x[0]);
11739            grad[0] = 2.0 * x[0];
11740            true
11741        }
11742
11743        fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
11744            ExactQuadratic.eval_g(x, new_x, g)
11745        }
11746
11747        fn eval_jac_g(
11748            &mut self,
11749            x: Option<&[Number]>,
11750            new_x: bool,
11751            mode: SparsityRequest<'_>,
11752        ) -> bool {
11753            ExactQuadratic.eval_jac_g(x, new_x, mode)
11754        }
11755
11756        fn get_scaling_parameters(&mut self, req: ScalingRequest<'_>) -> bool {
11757            *req.obj_scaling = 1.0;
11758            *req.use_x_scaling = true;
11759            req.x_scaling[0] = self.x_scaling;
11760            *req.use_g_scaling = false;
11761            true
11762        }
11763
11764        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11765    }
11766
11767    /// A floor replay makes the floor the recorded answer again, firing id
11768    /// included. The retries nest and each floors to `last_finalize`, so a
11769    /// replay that only re-delivered the payload left the inner retry's
11770    /// discarded payload there for an outer wrapper to floor to, and for
11771    /// `reported_on_converged_id` to name.
11772    #[test]
11773    fn restoring_a_floor_records_it_as_the_answer() {
11774        let snap = |x: Number, id: Option<u64>| FinalizeSnapshot {
11775            status: SolverReturn::Success,
11776            x: vec![x],
11777            z_l: vec![0.0],
11778            z_u: vec![0.0],
11779            g: vec![],
11780            lambda: vec![],
11781            obj_value: x * x,
11782            on_converged_id: id,
11783        };
11784        let app = IpoptApplication::new();
11785        let tnlp: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(ExactQuadratic));
11786        let base = snap(1.0, Some(1));
11787        // The retry's payload is the last one written, as after an inner
11788        // retry that lost.
11789        *app.last_finalize.borrow_mut() = Some(snap(2.0, Some(2)));
11790        assert_eq!(app.reported_on_converged_id(), Some(2));
11791
11792        app.restore_floor(&base, &tnlp);
11793        assert!(app.answer_restored_from_floor());
11794        assert_eq!(app.reported_on_converged_id(), Some(1));
11795        // What an outer wrapper would take as its own floor.
11796        let outer_floor = app.last_finalize.borrow().clone().unwrap();
11797        assert_eq!(outer_floor.x, base.x);
11798    }
11799
11800    fn derivative_test_verdict(extra: &str) -> pounce_nlp::derivative_test::DerivativeTestReport {
11801        let mut app = IpoptApplication::new();
11802        app.initialize().unwrap();
11803        app.initialize_with_options_str(&format!("derivative_test first-order\n{extra}"))
11804            .unwrap();
11805        let opts = app.derivative_test_options();
11806        pounce_nlp::derivative_test::run(&mut ExactQuadratic, &opts).expect("a report")
11807    }
11808
11809    /// `derivative_test_perturbation` and `derivative_test_tol` were
11810    /// registered, read into [`DerivativeTestOptions`], and consumed by
11811    /// the checker — but nothing proved a *set value* reached it, which
11812    /// is the only assertion that distinguishes a read site from a
11813    /// parse-and-discard (#677, #551).
11814    ///
11815    /// Each of the three verdicts below differs from the one above it by
11816    /// exactly one option, so a knob that stopped reaching the checker
11817    /// would collapse two of them together and fail here.
11818    #[test]
11819    fn the_derivative_checker_knobs_change_the_verdict() {
11820        // Registered defaults (1e-8 / 1e-4), which are also the read
11821        // site's fallbacks: a correct gradient looks correct.
11822        let clean = derivative_test_verdict("");
11823        assert_eq!(clean.checked, 1);
11824        assert_eq!(clean.suspicious, 0, "{:#?}", clean.lines);
11825
11826        // A coarse step makes the *same correct gradient* look wrong:
11827        // deviation 0.5 > 1e-4·2.5. Only `derivative_test_perturbation`
11828        // changed, so this is that option and nothing else.
11829        let coarse = derivative_test_verdict("derivative_test_perturbation 0.5\n");
11830        assert_eq!(coarse.checked, 1);
11831        assert_eq!(
11832            coarse.suspicious, 1,
11833            "derivative_test_perturbation never reached the checker: {:#?}",
11834            coarse.lines,
11835        );
11836
11837        // …and loosening the threshold at that same coarse step clears
11838        // it again: 0.5 < 0.5·2.5. Only `derivative_test_tol` changed.
11839        let tolerant =
11840            derivative_test_verdict("derivative_test_perturbation 0.5\nderivative_test_tol 0.5\n");
11841        assert_eq!(tolerant.checked, 1);
11842        assert_eq!(
11843            tolerant.suspicious, 0,
11844            "derivative_test_tol never reached the checker: {:#?}",
11845            tolerant.lines,
11846        );
11847
11848        // The report also prints what it used, so a user reading the
11849        // output can tell which step and threshold produced the verdict.
11850        assert!(
11851            tolerant.lines[0].contains("5.0e-1"),
11852            "{:#?}",
11853            tolerant.lines,
11854        );
11855    }
11856
11857    #[test]
11858    fn ordinary_derivative_test_keeps_the_conditioned_start() {
11859        let gradient_points = Rc::new(RefCell::new(Vec::new()));
11860        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11861            gradient_points: Rc::clone(&gradient_points),
11862            objective_points: Rc::new(RefCell::new(Vec::new())),
11863            x_scaling: 1.0,
11864        })) as Rc<RefCell<dyn TNLP>>;
11865        let mut app = IpoptApplication::new();
11866        app.initialize().unwrap();
11867        app.initialize_with_options_str(
11868            "derivative_test first-order\n\
11869             start_point_perturbation 0.5\n\
11870             hessian_approximation limited-memory\n\
11871             max_iter 0\n\
11872             print_level 0\n",
11873        )
11874        .unwrap();
11875
11876        let _ = app.optimize_tnlp(tnlp);
11877
11878        let first = gradient_points.borrow()[0];
11879        assert!((first - 1.7666216164272852).abs() < 1e-12, "{first}");
11880    }
11881
11882    #[test]
11883    fn ordinary_derivative_test_keeps_variable_scaling() {
11884        let objective_points = Rc::new(RefCell::new(Vec::new()));
11885        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11886            gradient_points: Rc::new(RefCell::new(Vec::new())),
11887            objective_points: Rc::clone(&objective_points),
11888            x_scaling: 0.5,
11889        })) as Rc<RefCell<dyn TNLP>>;
11890        let mut app = IpoptApplication::new();
11891        app.initialize().unwrap();
11892        app.initialize_with_options_str(
11893            "derivative_test first-order\n\
11894             derivative_test_perturbation 0.5\n\
11895             nlp_scaling_method user-scaling\n\
11896             hessian_approximation limited-memory\n\
11897             max_iter 0\n\
11898             print_level 0\n",
11899        )
11900        .unwrap();
11901
11902        let _ = app.optimize_tnlp(tnlp);
11903
11904        assert_eq!(&objective_points.borrow()[..2], &[1.0, 2.0]);
11905    }
11906
11907    // ---- gh#887: the dominance gate ------------------------------------
11908    //
11909    // These pin the rule directly, on numbers measured off real runs,
11910    // because the fixture that motivated the gate turned out not to be a
11911    // portable witness for it. `deb7` on the L-BFGS leg with
11912    // `limited_memory_ls_failure_restarts=1` reaches a *materially
11913    // different answer* on macOS and on Linux -- different objective
11914    // (99.677 vs 99.651) and, decisively, a different shape:
11915    //
11916    //   | run                 | unscaled dual | viol    | compl   | ratio   |
11917    //   | reproducer, .nl     | 7.90e4        | 1.1e-16 | 1.1e-9  | 1.5e-14 |
11918    //   | reproducer, TNLP    | 3.25e11       | 2.5e-16 | 2.8e-3  | 8.7e-15 |
11919    //   | deb7 + rung, macOS  | 9.90e1        | 8.0e-13 | 4.65e0  | 4.7e-2  |
11920    //   | deb7 + rung, Linux  | 5.5743e3      | 5.6e-14 | 2.08e-5 | 3.7e-9  |
11921    //
11922    // The Linux row is the one worth reading twice: that answer really is
11923    // gh#884's shape (scaled overall error 5.28e-1 against unscaled
11924    // 5.57e3, which is the `s_d` normalisation hiding a runaway exactly
11925    // as it did on `qpec_small`), so the retry there is the designed cost
11926    // and not the waste gh#887 filed. A CLI assertion of "deb7 declines"
11927    // is therefore false on Linux no matter what the threshold is, which
11928    // is why the pin lives here instead.
11929
11930    /// The dominance rule on its own, with the absolute floor switched
11931    /// off (`du_floor = 0`), so each of these tests is about one rule.
11932    fn ratio_only(dual_inf: Number, viol: Number, compl: Number) -> bool {
11933        runaway_is_the_whole_residual(dual_inf, viol, compl, 0.0)
11934    }
11935
11936    /// The gate as it actually runs: dominance *and* the detector's own
11937    /// absolute floor.
11938    fn runaway(dual_inf: Number, viol: Number, compl: Number) -> bool {
11939        runaway_is_the_whole_residual(dual_inf, viol, compl, DUAL_DIV_RETRY_DU_FLOOR)
11940    }
11941
11942    #[test]
11943    fn a_converged_point_with_a_runaway_multiplier_opens_the_retry() {
11944        // The gh#884 reproducer, both routes it reaches the gate by.
11945        assert!(runaway(7.90e4, 1.1e-16, 1.1e-9));
11946        assert!(runaway(3.25e11, 2.5e-16, 2.8e-3));
11947        // deb7 under the rung on Linux: primal exact, complementarity
11948        // eight orders under its own dual residual. Same shape.
11949        assert!(runaway(5.5743e3, 5.6e-14, 2.08e-5));
11950    }
11951
11952    #[test]
11953    fn an_unconverged_point_does_not_open_the_retry() {
11954        // deb7 under the rung on macOS: complementarity 4.65, five
11955        // percent of its own KKT error. Not a runaway multiplier on an
11956        // otherwise-converged point -- just an unconverged point.
11957        assert!(!ratio_only(9.90e1, 8.0e-13, 4.65e0));
11958        // Either residual alone is enough to close it: the gate takes the
11959        // max, so a clean complementarity does not excuse a violated
11960        // constraint. (`1.0e1` against `1.0e6` is a ratio of `1e-5`; note
11961        // that `1.0e0` there would be `1e-6` exactly, i.e. inside.)
11962        assert!(!ratio_only(1.0e6, 1.0e1, 1.0e-16));
11963        assert!(!ratio_only(1.0e6, 1.0e-16, 1.0e1));
11964    }
11965
11966    /// The dominance ratio is scale-free, and that is exactly why it
11967    /// cannot be the whole gate: a point converged to `1e-30` primal with
11968    /// a dual residual of `4.4e-1` satisfies it as comfortably as
11969    /// gh#884's `7.9e+04` does, and `4.4e-1` is not a runaway by any
11970    /// reading of the issue. Measured on the 400-model QPEC family, the
11971    /// floor alone removes 7 of 68 promotions, every one of them on an
11972    /// answer whose reported dual residual was below `1e2`.
11973    ///
11974    /// The floor is the *detector's*, so this is the answer-level gate
11975    /// asking about the same magnitude the iterate-level one did rather
11976    /// than being a strictly looser copy of it.
11977    #[test]
11978    fn a_small_dual_residual_is_not_a_runaway_however_dominant() {
11979        // Passes the ratio comfortably (1e-30 / 4.4e-1 = 2.3e-30) ...
11980        assert!(ratio_only(4.4e-1, 1.0e-30, 1.0e-30));
11981        // ... and is still refused, because it is not a runaway.
11982        assert!(!runaway(4.4e-1, 1.0e-30, 1.0e-30));
11983        // The two real `r`-family answers that reached the gate this way.
11984        assert!(!runaway(4.397e-1, 1.0e-16, 1.0e-16));
11985        assert!(!runaway(2.026e1, 1.0e-16, 1.0e-16));
11986        // Exactly at the floor is inside; a hair under is outside.
11987        assert!(runaway(DUAL_DIV_RETRY_DU_FLOOR, 0.0, 0.0));
11988        assert!(!runaway(DUAL_DIV_RETRY_DU_FLOOR * 0.999, 0.0, 0.0));
11989    }
11990
11991    #[test]
11992    fn the_threshold_is_where_the_constant_says_it_is() {
11993        // Exactly at the ratio is inside; a hair past it is outside.
11994        assert!(ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE, 0.0));
11995        assert!(!ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE * 1.001, 0.0));
11996    }
11997
11998    #[test]
11999    fn what_we_cannot_measure_does_not_buy_a_retry() {
12000        // A NaN compares false everywhere, so the condition is written so
12001        // that "we cannot tell" declines rather than retries. Each
12002        // argument in turn.
12003        assert!(!ratio_only(Number::NAN, 0.0, 0.0));
12004        assert!(!ratio_only(1.0e6, Number::NAN, 0.0));
12005        assert!(!ratio_only(1.0e6, 0.0, Number::NAN));
12006        assert!(!ratio_only(Number::INFINITY, 0.0, 0.0));
12007        // And a dual residual that is not a runaway at all: the ratio
12008        // would be meaningless, and a zero-dual point is not gh#884.
12009        assert!(!ratio_only(0.0, 0.0, 0.0));
12010        assert!(!ratio_only(-1.0, 0.0, 0.0));
12011    }
12012
12013    // ---- the promotion gate reads the ANSWER, not only the certificate --
12014    //
12015    // gh#884 ranked the two attempts on unscaled KKT error alone and
12016    // argued that this could not return a different local solution,
12017    // because "conjunct 4 requires the promoted answer to satisfy the KKT
12018    // conditions in the model's own units". Any other KKT point does too.
12019    // Measured on 400 random QPECs under the `prod_eq` lowering
12020    // (`bound_relax_factor=0 mu_strategy_fallback=no tol=1e-8`): 68
12021    // promotions, 42 of which moved the objective materially, and three
12022    // of which returned a strictly worse *feasible* point.
12023    //
12024    // Every number below is off a real run, and the two branches are
12025    // separated on purpose -- a rule that branches needs a case on each
12026    // side or the untaken one stays broken while the test is green.
12027    //
12028    //   | model      | base f      | base viol | retry f     | retry viol | branch |
12029    //   |------------|-------------|-----------|-------------|------------|--------|
12030    //   | qpec_small | +3.586e-28  | 1.11e-16  | +5.835e-11  | 5.47e-12   | admit  |
12031    //   | r116       | -1.3006e+01 | 2.22e-16  | -1.2072e+00 | 4.55e-13   | rule 1 |
12032    //   | r261       | -4.7919e+00 | 1.07e-14  | -9.8563e-01 | 7.99e-14   | rule 1 |
12033    //   | r201       | -2.9559e-01 | 6.25e-17  | -9.7321e-02 | 6.21e-13   | rule 1 |
12034    //   | scholtes4  | +1.8176e-09 | 2.07e-25  | -6.6088e-05 | 1.09e-09   | rule 2 |
12035
12036    const ACCEPT: Number = 1e-6;
12037    /// Minimization, which is every row of the table above.
12038    const MIN: Number = 1.0;
12039    /// Maximization, i.e. `obj_scaling_factor < 0`.
12040    const MAX: Number = -1.0;
12041
12042    fn admissible(bo: Number, bv: Number, ro: Number, rv: Number) -> bool {
12043        retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN)
12044    }
12045
12046    #[test]
12047    fn the_reproducers_promotion_is_still_admissible() {
12048        // `qpec_small`: the retry's objective is *worse*, by 5.8e-11 --
12049        // deliberately, since it buys nine orders of unscaled dual
12050        // residual. Five orders inside the tolerance, so rule 1 admits
12051        // it, which is the whole point of having a tolerance at all.
12052        assert!(admissible(3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12));
12053    }
12054
12055    /// Rule 1: a strictly worse feasible point is never an upgrade.
12056    #[test]
12057    fn a_worse_feasible_objective_is_refused_however_clean_the_certificate() {
12058        // r116: -13.0057 -> -1.2072, both independently verified feasible
12059        // by `pounce verify`. The retry's unscaled KKT error is 2.9e-11
12060        // against the base attempt's 3.0e+03, so every certificate
12061        // conjunct passes and only this one refuses it.
12062        assert!(!admissible(
12063            -1.3005680756e1,
12064            2.22e-16,
12065            -1.2072337962e0,
12066            4.55e-13
12067        ));
12068        assert!(!admissible(
12069            -4.7919265770e0,
12070            1.07e-14,
12071            -9.8562977711e-1,
12072            7.99e-14
12073        ));
12074        assert!(!admissible(
12075            -2.9558632401e-1,
12076            6.25e-17,
12077            -9.7321185691e-2,
12078            6.21e-13
12079        ));
12080    }
12081
12082    /// The declared-box conjunct is scale-safe: at a bound of `1e6`, two
12083    /// points pinned to the same widened bound differ by an ulp (`1.2e-10`),
12084    /// which an absolute `1e-12` floor read as the re-solve using more of the
12085    /// widening; relative to the bound it is rounding. A genuine excess at
12086    /// that magnitude -- the bound-magnitude probe's `2.5e-6`, i.e. `2.5e-12`
12087    /// relative -- is still refused, and at a unit bound `1e-8` is.
12088    #[test]
12089    fn the_declared_box_conjunct_is_relative_to_each_bounds_magnitude() {
12090        let (lo, up) = (-1e19, 1e19);
12091        let rel = |x: &[Number], l: &[Number], u: &[Number]| {
12092            declared_box_relative_violation(x, l, u, lo, up)
12093        };
12094        let ub: Number = 1e6;
12095        let pinned: Number = ub + 1e-4; // on the widened bound (`constr_viol_tol` cap)
12096        let one_ulp_out = f64::from_bits(pinned.to_bits() + 1);
12097        assert!(
12098            one_ulp_out - pinned > 1e-12,
12099            "premise: an ulp of 1e6 exceeds 1e-12"
12100        );
12101        let (l, u) = (vec![0.0], vec![ub]);
12102        let base = rel(&[pinned], &l, &u);
12103        assert!(retry_keeps_declared_box(base, rel(&[one_ulp_out], &l, &u)));
12104        // The absolute rule this replaces declined exactly that pair.
12105        assert!(one_ulp_out - ub > (pinned - ub) + 1e-12);
12106        let genuine = rel(&[ub + 9.9995e-5], &l, &u);
12107        let base_genuine = rel(&[ub + 9.7494e-5], &l, &u);
12108        assert!(!retry_keeps_declared_box(base_genuine, genuine));
12109        // Unit bound: the widening's own size is refused, rounding is not.
12110        let (l1, u1) = (vec![0.0], vec![1.0]);
12111        assert!(!retry_keeps_declared_box(0.0, rel(&[1.0 + 1e-8], &l1, &u1)));
12112        assert!(retry_keeps_declared_box(
12113            0.0,
12114            rel(&[f64::from_bits(1.0f64.to_bits() + 1)], &l1, &u1)
12115        ));
12116        // Lower bounds, sentinels, and single-point boxes.
12117        assert_eq!(rel(&[-2e-4], &[-1e4], &[1e19]), 0.0);
12118        assert!(rel(&[-1e4 - 1e-4], &[-1e4], &[1e19]) > 0.0);
12119        assert_eq!(rel(&[5.0], &[-1e19], &[1e19]), 0.0);
12120        assert_eq!(rel(&[0.5 + 1e-8], &[0.5], &[0.5]), 0.0);
12121        assert!(rel(&[1.0], &[0.0, 0.0], &[1.0, 1.0]).is_nan());
12122        // `NaN` is "not measured".
12123        assert!(retry_keeps_declared_box(Number::NAN, Number::NAN));
12124        assert!(!retry_keeps_declared_box(0.0, Number::NAN));
12125    }
12126
12127    /// Rule 2: an objective *improvement* bought with primal slack.
12128    ///
12129    /// `scholtes4` (`benchmarks/mpcc/cases.py`, and now a CLI fixture) has
12130    /// `f* = 0` exactly -- for the MPCC and for the smooth lowering alike,
12131    /// since `x1*x2 = 0` forces one of them to zero, hence `x3 <= 0`, hence
12132    /// `f = x1 - x3 >= 0`. The retry reports `-6.61e-05`, which no feasible
12133    /// point reaches, by moving the complementarity row 16 orders further
12134    /// out. Rule 1 cannot see it: the objective got *better*.
12135    #[test]
12136    fn an_improvement_bought_with_primal_slack_is_refused() {
12137        assert!(!admissible(
12138            1.8175997416e-9,
12139            2.07e-25,
12140            -6.6088333055e-5,
12141            1.09e-9
12142        ));
12143        // The same numbers with the primal *held* would be admissible --
12144        // this is the conjunct that refuses it, not the objective move.
12145        assert!(admissible(
12146            1.8175997416e-9,
12147            2.07e-25,
12148            -6.6088333055e-5,
12149            2.07e-25
12150        ));
12151    }
12152
12153    /// The window the tolerance sits in, from both sides, so it is a
12154    /// checkable claim rather than a fitted constant: the smallest move
12155    /// that must be admitted is `qpec_small`'s `5.8e-11` and the smallest
12156    /// that must be refused is `r201`'s `0.198`, four and five orders
12157    /// away from `acceptable_tol` on either side.
12158    #[test]
12159    fn the_objective_tolerance_is_not_fitted_to_one_model() {
12160        let admit = 5.835e-11;
12161        let refuse = 0.198;
12162        assert!(admit < ACCEPT / 1.0e4, "{admit} is not well inside");
12163        assert!(refuse > ACCEPT * 1.0e4, "{refuse} is not well outside");
12164        // Scale-relative above 1, absolute below it -- the same
12165        // convention `sigma_forward_error_is_small` uses for `norm(x)`.
12166        assert!(admissible(1.0e6, 0.0, 1.0e6 + 0.5, 0.0));
12167        assert!(!admissible(1.0e6, 0.0, 1.0e6 + 5.0, 0.0));
12168    }
12169
12170    /// gh#983 item 4: `x*y == 0` from `(0.3, 0.3)`. The base attempt sits at
12171    /// `f = 2` with a violation of `3e-38` and an unscaled dual infeasibility
12172    /// of `1.4e9`; the retry reaches `f = 1` at `1.96e-13`, six orders inside
12173    /// `constr_viol_tol`. Rule 2 compared the two violations bare and refused
12174    /// it. The floor admits arithmetic noise and nothing above it: the
12175    /// scholtes4 row (`1.09e-9`) is refused in the same breath.
12176    #[test]
12177    fn a_retry_violation_at_the_noise_floor_does_not_block_an_improvement() {
12178        assert!(retry_answer_is_admissible(
12179            2.0, 3.037e-38, 1.0, 1.9584e-13, ACCEPT, MIN
12180        ));
12181        assert!(retry_answer_is_admissible(
12182            -2.0, 3.037e-38, -1.0, 1.9584e-13, ACCEPT, MAX
12183        ));
12184        // Just above the floor is still slack.
12185        assert!(!retry_answer_is_admissible(
12186            2.0,
12187            3.037e-38,
12188            1.0,
12189            RETRY_VIOL_NOISE_FLOOR * 10.0,
12190            ACCEPT,
12191            MIN
12192        ));
12193        // ... and rule 1 is untouched by the floor.
12194        assert!(!retry_answer_is_admissible(
12195            1.0, 3.037e-38, 2.0, 1.0e-13, ACCEPT, MIN
12196        ));
12197    }
12198
12199    /// The audit input with every measurement given and the defaults for
12200    /// the rest (`tol 1e-8`, `acceptable_tol 1e-6`, threshold `1e-4`).
12201    #[allow(clippy::too_many_arguments)]
12202    fn audit_in(
12203        tol: Number,
12204        obj_scale: Number,
12205        rescaled: Number,
12206        start_grad: Number,
12207        final_grad: Number,
12208        kkt: Number,
12209        compl: Number,
12210        th: Number,
12211    ) -> ScaleAuditInput {
12212        ScaleAuditInput {
12213            tol,
12214            obj_scale,
12215            rescaled_obj_scale: rescaled,
12216            start_grad_max: start_grad,
12217            final_grad_max: final_grad,
12218            unscaled_kkt: kkt,
12219            unscaled_compl: compl,
12220            acceptable_tol: 1e-6,
12221            masked_threshold: th,
12222            warm_start: false,
12223        }
12224    }
12225
12226    /// `audit_in` for a warm start (`warm_start_init_point=yes`).
12227    #[allow(clippy::too_many_arguments)]
12228    fn audit_in_warm(
12229        tol: Number,
12230        obj_scale: Number,
12231        rescaled: Number,
12232        start_grad: Number,
12233        final_grad: Number,
12234        kkt: Number,
12235        compl: Number,
12236        th: Number,
12237    ) -> ScaleAuditInput {
12238        ScaleAuditInput {
12239            warm_start: true,
12240            ..audit_in(
12241                tol, obj_scale, rescaled, start_grad, final_grad, kkt, compl, th,
12242            )
12243        }
12244    }
12245
12246    /// gh#983 / CI: a warm start is an answer, so its gradient -- and the
12247    /// returned point's -- carry the model's scale only above the barrier
12248    /// level. Both branches of the warm rule need a row: the session's
12249    /// interior optimum (gradient at the complementarity) stays out, and the
12250    /// reactor warm-started at its answer (gradient `4e3` times it) is still
12251    /// up-scaled.
12252    #[test]
12253    fn a_warm_start_at_an_answer_is_not_read_as_a_tiny_objective() {
12254        let th = 1e-4;
12255        let t = |inp| scale_audit_trigger(inp);
12256        // `cold_then_warm_through_presolve`'s warm re-solve, measured.
12257        assert_eq!(
12258            t(audit_in_warm(
12259                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
12260            )),
12261            None
12262        );
12263        // The same numbers on a cold start are the tiny-objective signature:
12264        // the rule is the warm start's, not a change to the cold branch.
12265        assert!(matches!(
12266            t(audit_in(
12267                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
12268            )),
12269            Some(ScaleAudit::Upscale(_))
12270        ));
12271        // The reactor (fs = 1e-6) warm-started from its answer: the active
12272        // bound's multiplier keeps the gradient at 1e-5, the model's scale.
12273        match t(audit_in_warm(
12274            1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th,
12275        )) {
12276            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
12277            other => panic!("{other:?}"),
12278        }
12279        // A barrier-level seed does not mask an answer that carries scale.
12280        assert!(matches!(
12281            t(audit_in_warm(
12282                1e-8, 1.0, 1.0, 1e-11, 1e-5, 2.5e-9, 2.5e-9, th
12283            )),
12284            Some(ScaleAudit::Upscale(_))
12285        ));
12286        // The re-scale branch does not read the gradient scale at all.
12287        assert_eq!(
12288            t(audit_in_warm(
12289                1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th
12290            )),
12291            Some(ScaleAudit::Rescale)
12292        );
12293    }
12294
12295    /// gh#983: the audit's trigger branches on *which* scaling defect shows,
12296    /// and each branch needs its own row.
12297    #[test]
12298    fn the_scale_audit_trigger_takes_each_branch_and_neither_by_default() {
12299        let th = 1e-4;
12300        let t = |inp| scale_audit_trigger(inp);
12301        // Frozen factor, non-stationary in the model's own units, and the
12302        // factor re-evaluated at the returned point (gradient 2.9e-2 -> 1) is
12303        // seven orders from the frozen one: re-scale.
12304        assert_eq!(
12305            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th)),
12306            Some(ScaleAudit::Rescale)
12307        );
12308        // gh#983 review item 2(b): the same masked certificate on a
12309        // legitimately large objective (`hs71 x 1e8`) re-evaluates to the
12310        // factor it already has -- the re-solve would be the same solve.
12311        assert_eq!(
12312            t(audit_in(1e-8, 2.2e-7, 2.4e-7, 4.6e8, 4.2e8, 3e-6, 1e-9, th)),
12313            None
12314        );
12315        // Tiny gradient, complementarity 2.5e-4 of it (the reactor, fs = 1e-6).
12316        match t(audit_in(1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th)) {
12317            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
12318            other => panic!("{other:?}"),
12319        }
12320        // gh#983 review item 4: no band without a signal. fs = 3e-5 (gradient
12321        // 3e-4, relative complementarity 8.4e-6) and fs = 1e-3 (2.5e-7) are
12322        // both re-solved now; fs = 1 is left alone.
12323        assert!(matches!(
12324            t(audit_in(1e-8, 1.0, 1.0, 3e-4, 3e-4, 2.5e-9, 2.5e-9, th)),
12325            Some(ScaleAudit::Upscale(_))
12326        ));
12327        assert!(matches!(
12328            t(audit_in(1e-8, 1.0, 1.0, 1e-2, 1e-2, 2.5e-9, 2.5e-9, th)),
12329            Some(ScaleAudit::Upscale(_))
12330        ));
12331        assert_eq!(
12332            t(audit_in(1e-8, 1.0, 1.0, 10.0, 10.0, 2.5e-9, 2.5e-9, th)),
12333            None
12334        );
12335        // A gradient in [0.1, 1): the signature, but an up-scale below the
12336        // material factor -- warn, do not re-solve.
12337        assert_eq!(
12338            t(audit_in(1e-8, 1.0, 1.0, 0.5, 0.5, 1e-6, 1e-6, th)),
12339            Some(ScaleAudit::SmallObjective)
12340        );
12341        // gh#983 review item 2(a): a start near a stationary point
12342        // (`grad f(x0) = 2e-7`) is not a tiny objective when the gradient at
12343        // the answer is 1.
12344        assert_eq!(
12345            t(audit_in(1e-8, 1.0, 1.0, 2e-7, 1.0, 2.5e-9, 2.5e-9, th)),
12346            None
12347        );
12348        // A start measured at a stationary point (gradient exactly 0) carries
12349        // no scale: the audit stays out however small the answer's gradient.
12350        assert_eq!(
12351            t(audit_in(1e-8, 1.0, 1.0, 0.0, 2e-4, 6e-3, 2.5e-9, th)),
12352            None
12353        );
12354        // An unmeasured start (caller-owned scaling) defers to the answer.
12355        assert!(matches!(
12356            t(audit_in(
12357                1e-8,
12358                f64::NAN,
12359                f64::NAN,
12360                f64::NAN,
12361                1e-5,
12362                2.5e-9,
12363                2.5e-9,
12364                th
12365            )),
12366            Some(ScaleAudit::Upscale(_))
12367        ));
12368        // A big gradient never up-scales, whatever the complementarity.
12369        assert_eq!(
12370            t(audit_in(1e-8, 1.0, 1.0, 50.0, 50.0, 1e-3, 1e-3, th)),
12371            None
12372        );
12373        // An extreme factor at a stationary point is the honest case.
12374        assert_eq!(
12375            t(audit_in(1e-8, 1e-8, 1e-8, 1e9, 1e9, 1e-9, 1e-12, th)),
12376            None
12377        );
12378        // The masked opt-out (threshold 0) disables the re-scale branch.
12379        assert_eq!(
12380            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, 0.0)),
12381            None
12382        );
12383        // A caller who loosened tol asked for the complementarity they got.
12384        assert_eq!(
12385            t(audit_in(5e-2, 1.0, 1.0, 1e-5, 1e-5, 1e-2, 1e-2, th)),
12386            None
12387        );
12388        // NaN stays quiet.
12389        let nan = f64::NAN;
12390        assert_eq!(t(audit_in(1e-8, nan, nan, nan, nan, nan, nan, th)), None);
12391        // The upscale is capped.
12392        match t(audit_in(1e-8, 1.0, 1.0, 1e-14, 1e-14, 1.0, 1.0, th)) {
12393            Some(ScaleAudit::Upscale(k)) => assert_eq!(k, SCALE_AUDIT_MAX_UPSCALE),
12394            other => panic!("{other:?}"),
12395        }
12396    }
12397
12398    /// gh#1000 (II.22): the roundoff exemption, on the measured population
12399    /// named in `UNSCALED_DUAL_ROUNDOFF_ULPS`'s doc.
12400    #[test]
12401    fn a_residual_at_the_roundoff_floor_of_its_terms_is_not_a_miss() {
12402        // Pump network at H0_max 148: 1.6 ulps of its terms.
12403        assert!(unscaled_dual_inf_is_roundoff(5.54e-3, 1.57e13));
12404        assert!(unscaled_dual_inf_is_roundoff(7.39e-3, 2.66e13));
12405        // The downgrades that are right keep it: Haverly, the process
12406        // network's T2 and S2+T2 subproblems, the eps-perspective root, and
12407        // the gh#983 cusp.
12408        assert!(!unscaled_dual_inf_is_roundoff(1.33e-2, 6.6e10));
12409        assert!(!unscaled_dual_inf_is_roundoff(0.5, 7.55e11));
12410        assert!(!unscaled_dual_inf_is_roundoff(6.25e-2, 3.21e11));
12411        assert!(!unscaled_dual_inf_is_roundoff(3.92e-3, 5.03e9));
12412        assert!(!unscaled_dual_inf_is_roundoff(0.144, 3.55e9));
12413        // No scale measured: keep the downgrade.
12414        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, f64::NAN));
12415        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, 0.0));
12416        assert!(!unscaled_dual_inf_is_roundoff(f64::NAN, 1e13));
12417    }
12418
12419    /// gh#983 review item 7: one warning per code.
12420    #[test]
12421    fn a_warning_code_is_attached_at_most_once() {
12422        let mut w = vec!["unscaled_dual_inf_above_acceptable: downgraded".to_string()];
12423        push_warning_once(
12424            &mut w,
12425            "unscaled_dual_inf_above_acceptable: verify in your units".to_string(),
12426        );
12427        push_warning_once(&mut w, "large_dual_scale: terms of 1e9".to_string());
12428        assert_eq!(w.len(), 2, "{w:?}");
12429        assert!(w[0].ends_with("downgraded"));
12430    }
12431
12432    /// gh#983: the structured warnings, by code, on success verdicts only.
12433    #[test]
12434    fn quality_warnings_carry_a_code_and_only_on_success_verdicts() {
12435        use ApplicationReturnStatus::*;
12436        // The cusp: multipliers 3.5e9, residual 0.144.
12437        let w = quality_warnings(SolveSucceeded, 0.144, 3.55e9, 1.0, 1e-6, false);
12438        assert!(
12439            w.iter().any(|m| m.starts_with("large_dual_scale:")),
12440            "{w:?}"
12441        );
12442        assert!(
12443            w.iter()
12444                .any(|m| m.starts_with("unscaled_dual_inf_above_acceptable:")),
12445            "{w:?}"
12446        );
12447        // orthrds2-like: scale 1.6e10, residual 89.7 -> only the scale caveat
12448        // and the absolute one; never a status change (the function returns
12449        // text, not a verdict).
12450        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, false);
12451        assert!(w.iter().any(|m| m.starts_with("large_dual_scale:")));
12452        assert!(!w.iter().any(|m| m.contains("bound_relax_factor")), "{w:?}");
12453        // gh#1000: under bound_relax_factor = 0 the caveat names the option.
12454        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, true);
12455        assert!(
12456            w.iter()
12457                .any(|m| m.starts_with("large_dual_scale:") && m.contains("bound_relax_factor = 0")),
12458            "{w:?}"
12459        );
12460        // A clean point has none.
12461        assert!(quality_warnings(SolveSucceeded, 1e-9, 5.0, 1.0, 1e-6, false).is_empty());
12462        // A large objective with a stationary residual is not a failed CQ.
12463        assert!(quality_warnings(SolveSucceeded, 2.9e-7, 1.46e9, 1.0, 1e-6, false).is_empty());
12464        // 5e-4 is below the warning bar even though it exceeds acceptable_tol.
12465        assert!(quality_warnings(SolveSucceeded, 5e-4, 5.0, 1.0, 1e-6, false).is_empty());
12466        // Failures carry no success caveat.
12467        assert!(quality_warnings(RestorationFailed, 0.144, 3.55e9, 1.0, 1e-6, false).is_empty());
12468        assert!(quality_warnings(SolveSucceeded, f64::NAN, f64::NAN, 1.0, 1e-6, false).is_empty());
12469    }
12470
12471    /// gh#983 item 5: flooring an attempt must floor everything a solve
12472    /// report reads off the statistics, the iteration count and the row table
12473    /// included, or the report describes the declined retry.
12474    #[test]
12475    fn the_certificate_floor_carries_the_iteration_trace() {
12476        use pounce_nlp::solve_statistics::{IterRecord, SolveStatistics};
12477        let mut base = SolveStatistics::new();
12478        base.iteration_count = 64;
12479        base.iterations = vec![IterRecord::default(); 3];
12480        base.num_obj_evals = 159;
12481        base.restoration_calls = 2;
12482        let floor = SolutionCertificate::of(&base);
12483        let mut retry = SolveStatistics::new();
12484        retry.iteration_count = 15;
12485        retry.iterations = vec![IterRecord::default(); 15];
12486        retry.num_obj_evals = 86;
12487        floor.restore_into(&mut retry);
12488        assert_eq!(retry.num_obj_evals, 159);
12489        assert_eq!(retry.restoration_calls, 2);
12490        assert_eq!(retry.iteration_count, 64);
12491        assert_eq!(retry.iterations.len(), 3);
12492    }
12493
12494    /// An infeasible base attempt is not a point worth protecting, so
12495    /// both rules stand down and the certificate conjuncts decide alone.
12496    /// R2: `obj_scaling_factor < 0` poses a maximization, and
12497    /// `final_objective` is the user's **signed** objective, so both rules
12498    /// have to follow the sense. This is the table above with every
12499    /// objective negated: the same three answers must be refused and the
12500    /// same one admitted, with `MAX` instead of `MIN`.
12501    ///
12502    /// Without the normalization each row flips — rule 1 starts refusing
12503    /// genuine improvements (a regression against the behaviour before the
12504    /// conjunct existed) and rule 2 starts admitting strictly worse
12505    /// answers, which is the class it was added to block.
12506    #[test]
12507    fn the_rules_follow_the_objective_sense() {
12508        // qpec_small, mirrored: the retry is worse by 5.8e-11, well inside
12509        // the tolerance, so it is still admitted.
12510        assert!(retry_answer_is_admissible(
12511            -3.586e-28, 1.11e-16, -5.835e-11, 5.47e-12, ACCEPT, MAX
12512        ));
12513        // r116, mirrored: +13.0057 given up for +1.2072 is now a *worse*
12514        // maximum, and rule 1 must still refuse it.
12515        assert!(!retry_answer_is_admissible(
12516            1.3005680756e1,
12517            2.22e-16,
12518            1.2072337962e0,
12519            4.55e-13,
12520            ACCEPT,
12521            MAX
12522        ));
12523        // scholtes4, mirrored: +6.6088e-05 is now an improvement bought
12524        // with primal slack, and rule 2 must still refuse it.
12525        assert!(!retry_answer_is_admissible(
12526            -1.8175997416e-9,
12527            2.07e-25,
12528            6.6088333055e-5,
12529            1.09e-9,
12530            ACCEPT,
12531            MAX
12532        ));
12533        // ... and the same improvement with the primal held is admitted.
12534        assert!(retry_answer_is_admissible(
12535            -1.8175997416e-9,
12536            2.07e-25,
12537            6.6088333055e-5,
12538            2.07e-25,
12539            ACCEPT,
12540            MAX
12541        ));
12542    }
12543
12544    /// The mirror of the above, stated as the property rather than the
12545    /// rows: negating both objectives and flipping the sense must leave
12546    /// every verdict unchanged.
12547    #[test]
12548    fn negating_the_objective_and_the_sense_is_inert() {
12549        for &(bo, bv, ro, rv) in &[
12550            (3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12),
12551            (-1.3005680756e1, 2.22e-16, -1.2072337962e0, 4.55e-13),
12552            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 1.09e-9),
12553            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 2.07e-25),
12554            (-1.0e3, 1.0e-2, 0.0, 1.0e-12),
12555        ] {
12556            assert_eq!(
12557                retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN),
12558                retry_answer_is_admissible(-bo, bv, -ro, rv, ACCEPT, MAX),
12559                "verdict moved under (obj, sense) -> (-obj, -sense) at {bo:e}/{ro:e}"
12560            );
12561        }
12562    }
12563
12564    #[test]
12565    fn an_infeasible_base_attempt_protects_nothing() {
12566        assert!(admissible(-1.0e3, 1.0e-2, 0.0, 1.0e-12));
12567        // ... and what cannot be measured is refused, not admitted, the
12568        // same way `runaway_is_the_whole_residual` treats a NaN.
12569        assert!(admissible(Number::NAN, 0.0, 0.0, 0.0));
12570        assert!(!admissible(0.0, 0.0, Number::NAN, 0.0));
12571        assert!(!admissible(0.0, 0.0, -1.0, Number::NAN));
12572    }
12573}