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
944pub struct IpoptApplication {
945    options: OptionsList,
946    /// Diagnostics from the safeguarded `least_square_init_primal`
947    /// initializer step of the most recent solve (gh#605). `None` when
948    /// the step was not run. Read with
949    /// [`Self::least_square_init_report`].
950    least_square_init_report: Option<crate::init::default::LeastSquareInitReport>,
951    /// Per-variable scaling factors applied by the wrapper installed in
952    /// [`Self::optimize_tnlp`] (gh#486). Recorded so consumers that read
953    /// the algorithm's own iterate rather than the `finalize_solution`
954    /// payload — the CLI's `on_converged` hook feeding the `.sol` and
955    /// the JSON report — can undo the substitution. `None` when no
956    /// variable scaling was applied.
957    variable_scaling: RefCell<Option<Vec<Number>>>,
958    /// Whether the most recent `optimize_constrained` ran with per-row
959    /// constraint scaling active (`c_scale_vec`/`d_scale_vec` present).
960    ///
961    /// Read by [`Self::run_l1_penalty_outer_loop`], which measures the
962    /// user's rows in the model's own units and so may only write that
963    /// number into the `final_unscaled_*` family. `SolveStatistics`
964    /// documents `final_*` as the internally-scaled residuals and
965    /// `final_unscaled_*` as the same quantities in original units,
966    /// *equal when no scaling is active* — so the measurement may be
967    /// mirrored into the scaled family exactly when this is `false`
968    /// (gh#794 review). `None` when no solve has run.
969    row_scaling_active: std::cell::Cell<Option<bool>>,
970    /// Whether the submitted TNLP has already been explicitly wrapped by the
971    /// caller's presolve layer.
972    presolve_already_applied: bool,
973    reg_options: Rc<RegisteredOptions>,
974    journalist: Rc<Journalist>,
975    statistics: RefCell<SolveStatistics>,
976    /// Shared per-subsystem timing accumulator. Re-created at the top of
977    /// every solve (so back-to-back `optimize_tnlp` calls don't bleed
978    /// timings across invocations) and handed to the data, the NLP, and
979    /// any other consumer via `Rc`. Reported by [`Self::timing_stats`]
980    /// after the solve completes.
981    timing: RefCell<Rc<TimingStatistics>>,
982    /// Optional override factory for the symmetric linear-solver
983    /// backend. When `None`, we ship the workspace default (MA57 via
984    /// `pounce-hsl`). Tests can plug a stub via [`Self::set_linear_backend_factory`].
985    linear_backend_factory: Option<LinearBackendFactory>,
986    /// Optional factory for the restoration phase. Lives outside this
987    /// crate because `pounce-algorithm` cannot depend on
988    /// `pounce-restoration` (the dep edge is the other way). Callers
989    /// that need restoration plug a factory via
990    /// [`Self::set_restoration_factory`]; when unset, the outer
991    /// algorithm runs without a restoration fallback and surfaces
992    /// `RestorationFailure` as soon as the line-search would otherwise
993    /// jump into restoration.
994    restoration_factory: Option<RestorationFactory>,
995    /// Shared diagnostic-dump state, installed by the CLI when the
996    /// user passes `--dump <cat>:<spec>`. When set, the application
997    /// propagates an `Rc<DiagnosticsState>` into [`IpoptAlgorithm`]
998    /// via [`IpoptAlgorithm::with_diagnostics`] so the KKT solver and
999    /// other dump sites can consult per-iter gating.
1000    diagnostics: Option<Rc<DiagnosticsState>>,
1001    /// Optional interactive debugger hook. When set, it is moved into
1002    /// the main [`IpoptAlgorithm`] for the next `optimize_*` call via
1003    /// [`IpoptAlgorithm::with_debug_hook`], so a REPL or agent can pause
1004    /// at each iteration to inspect / mutate live state. Consumed on use
1005    /// (one solve per installed hook).
1006    debug_hook: Option<std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>>,
1007    /// Provider for the BNW outer loop (pounce#10 Phase 3). When set,
1008    /// `optimize_constrained` consults the provider before each inner
1009    /// solve, replacing `restoration_factory` with a fresh one so
1010    /// multi-pass drivers can run the inner IPM repeatedly without
1011    /// tripping the default factory's one-shot guard.
1012    restoration_factory_provider: Option<RestorationFactoryProvider>,
1013    /// Optional hook fired once per `optimize_*` call on convergence,
1014    /// before the user TNLP's `finalize_solution`. See
1015    /// [`ConvergedCallback`].
1016    on_converged: Option<ConvergedCallback>,
1017    /// When `true`, the per-iteration `IterRecord` trajectory is
1018    /// captured into [`SolveStatistics::iterations`] for downstream
1019    /// consumers (the JSON solve report in pounce-cli, pounce#8). Off
1020    /// by default so library callers that never read the iterations
1021    /// vector don't pay the per-iter alloc.
1022    record_iter_history: bool,
1023    /// Whether [`Self::initialize_with_option_file`] ran — i.e. whether
1024    /// anything on this application actually consulted
1025    /// `option_file_name` and resolved it to a file. Only the `pounce`
1026    /// CLI does; a library caller sets its options directly. The guard
1027    /// in [`Self::unhonored_option_file_name`] reads this so that
1028    /// setting the option on a surface that cannot honor it is refused
1029    /// rather than dropped (gh#518).
1030    option_file_resolved: bool,
1031    /// Whether this caller can route a model to the convex LP/QP/SOCP
1032    /// engines — i.e. whether the `qp_*` knobs those engines read
1033    /// configure anything here. Only the `pounce` CLI can (it owns the
1034    /// `.nl` structure extraction that classifies a model), and it says
1035    /// so via [`Self::set_convex_routing_available`]. The guard in
1036    /// [`Self::unhonored_convex_option`] reads this, on the same
1037    /// contract as `option_file_resolved` above (gh#604).
1038    convex_routing_available: bool,
1039    /// Whether the backend-knob warnings (gh#551) have already been
1040    /// printed for this application. The CLI emits them before routing —
1041    /// a convex model never reaches `optimize_tnlp` — and `optimize_tnlp`
1042    /// emits them for every other frontend; without this flag a CLI run
1043    /// would print each line twice, which is how a warning teaches its
1044    /// reader to skip it.
1045    backend_warnings_emitted: bool,
1046    /// Shared sink that the linear-solver backend writes a rolling
1047    /// [`LinearSolverSummary`] into after every factor. Reset at the
1048    /// top of every solve (so back-to-back `optimize_tnlp` calls don't
1049    /// bleed stats across invocations) and read out via
1050    /// [`Self::linear_solver_summary`] once the solve returns. Only
1051    /// the workspace-default FERAL backend (via
1052    /// [`default_backend_factory_with_sink`]) wires the sink today;
1053    /// custom factories plugged through [`Self::set_linear_backend_factory`]
1054    /// and the HSL MA57 backend leave the sink empty.
1055    linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1056    /// Companion to [`Self::linsol_summary_sink`] for the restoration
1057    /// phase's sub-solves. The frontends that wire a restoration factory
1058    /// install it via [`Self::restoration_summary_sink`]; it is reset with
1059    /// the main sink and surfaces as [`LinearSolverSummary::restoration`].
1060    resto_linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1061    /// The block-parallel KKT partition this solve resolved, published for
1062    /// the restoration sub-IPM (structured-KKT Phase 5b). Restoration's inner
1063    /// builder is minted by the frontend *before* the solve — before the KKT
1064    /// layout, and so the mapping onto it, exists — so the labels cannot be
1065    /// installed on it directly. They are written here as the outer algorithm
1066    /// is built and read when restoration runs. `AugRestoSystemSolver` reduces
1067    /// the restoration KKT onto the original 4-block system before delegating,
1068    /// so the matrix the inner solver factors is the one these labels
1069    /// describe. Reset with the sinks at the top of every solve.
1070    kkt_blocks_published: crate::alg_builder::KktBlocksCell,
1071    /// Shared tally of successful linear-solver quality escalations for
1072    /// the current solve (gh#857). Handed to every `AlgorithmBuilder`
1073    /// this application mints — [`Self::algorithm_builder_from_options`]
1074    /// and [`Self::algorithm_builder_snapshot`] — which is how the
1075    /// restoration sub-solve counts into the same total: each frontend
1076    /// builds the restoration provider's inner builder from
1077    /// `algorithm_builder_from_options`, so it receives this same `Rc`
1078    /// without any frontend having to know the counter exists.
1079    ///
1080    /// Reset at the top of every solve, beside the linear-solver summary
1081    /// sink and for the same reason: a second-opinion retry, or two
1082    /// back-to-back `optimize_tnlp` calls, must not inherit the previous
1083    /// solve's count. Read out into
1084    /// [`SolveStatistics::quality_escalations`] once the solve returns.
1085    quality_escalations: Rc<std::cell::Cell<u64>>,
1086    /// gh#990: the `mu_strategy` value in the option table was written by a
1087    /// POUNCE frontend (the Python no-`hessian` path pins `monotone`), not by
1088    /// the caller. See [`Self::mark_mu_strategy_pounce_chosen`].
1089    mu_strategy_pounce_chosen: bool,
1090    /// gh#884. Set when the running [`IpoptAlgorithm`] observed the
1091    /// biactive dual-divergence signature — a converged primal, a step
1092    /// that has gone to zero on a scale-relative measure, and an
1093    /// *unscaled* dual infeasibility still far above `dual_inf_tol`, all
1094    /// at the same iterate.
1095    ///
1096    /// Read out of the algorithm once `optimize_constrained` returns, so
1097    /// [`Self::run_with_dual_divergence_retry`] — which sits above that
1098    /// call — can see it. Reset at the top of every solve for the same
1099    /// reason as `quality_escalations`: a retry must not inherit the
1100    /// previous attempt's verdict. Also copied into
1101    /// [`SolveStatistics::dual_divergence_signature`].
1102    dual_divergence_signature: std::cell::Cell<bool>,
1103    /// gh#990 item 3: the derivative checker's structured result for the
1104    /// current solve; copied onto the statistics when the solve finishes.
1105    derivative_check: RefCell<Option<pounce_nlp::derivative_test::DerivativeCheckSummary>>,
1106    /// gh#990 item 13: some attempt of this run refused a termination
1107    /// certificate the objective scaling had masked (strict, acceptable).
1108    /// Sticky across the attempts a retry driver spends, like
1109    /// `dual_divergence_signature`: the returned run is often a re-solve, and
1110    /// the decision that led to it belongs on the record.
1111    obj_scale_refused: std::cell::Cell<(bool, bool)>,
1112    /// gh#884. Set when a dual-divergence retry actually replaced the base
1113    /// attempt's answer. Copied into
1114    /// [`SolveStatistics::dual_divergence_retry_promoted`].
1115    dual_divergence_retry_promoted: std::cell::Cell<bool>,
1116    /// Set when a losing retry's answer was thrown away and an earlier
1117    /// attempt's replayed through `FinalizeSnapshot::replay` — by the μ
1118    /// fallback (pounce#870) or the gh#884 dual-divergence retry.
1119    ///
1120    /// It exists because [`Self::set_on_converged`] fires **per attempt**
1121    /// and the floor does not reach it. A losing retry that reached
1122    /// `Solve_Succeeded` has already run the callback, so a consumer
1123    /// capturing the converged iterate there — the CLI's `nominal_capture`,
1124    /// which is where `.sol` `x`, the JSON's `solution.x` and the dual
1125    /// block all come from — holds the *discarded* attempt's point while
1126    /// the status, objective and every statistic beside it have been
1127    /// floored back to the attempt that won. Measured before this flag
1128    /// existed: on a declined retry the `.sol` carried `f = -6.3274` while
1129    /// the JSON report next to it said `-6.1768`, and `pounce verify` on
1130    /// the `.sol` confirmed the file held the losing point.
1131    ///
1132    /// The `finalize_solution` payload does not have this problem — the
1133    /// replay *is* a `finalize_solution` call, so the last one always
1134    /// carries the answer being reported — which is why the fix is to tell
1135    /// the caller "prefer that payload", not to re-run the callback (the
1136    /// converged KKT state the callback borrows belongs to the retry by
1137    /// then, and cannot be rewound).
1138    answer_restored_from_floor: std::cell::Cell<bool>,
1139    /// Set only for the duration of the gh#983 scale audit's re-solve: the
1140    /// interior-point arm then widens the inequality rows by
1141    /// `bound_relax_factor` as usual but leaves the **variable box as the
1142    /// caller declared it** (`OrigIpoptNlp::relax_bounds_keeping_box`). See
1143    /// `run_scale_retry` for why.
1144    retry_keeps_declared_box: std::cell::Cell<bool>,
1145    /// The payload of the most recent `finalize_solution` POUNCE sent to the
1146    /// user's TNLP, so a second-opinion retry that loses can put the winning
1147    /// attempt's answer back (pounce#870).
1148    ///
1149    /// Written by [`finalize_via_orig_nlp`] and [`finalize_via_sqp`], which are
1150    /// free functions and so take this as a sink rather than reaching for
1151    /// `self`. Read only by [`Self::run_with_mu_strategy_fallback`].
1152    last_finalize: RefCell<Option<FinalizeSnapshot>>,
1153    /// The last `IterStats` sent to the user's `intermediate_callback`
1154    /// (pounce#870), shared with the running `IpoptAlgorithm`.
1155    last_iter_stats: Rc<RefCell<Option<pounce_nlp::tnlp::IterStats>>>,
1156    /// Phase 5c (§6) SQP warm-start input. When `Some`, the next
1157    /// `optimize_tnlp` call on the SQP path consumes the iterate
1158    /// instead of cold-starting; consumed once per solve, then
1159    /// auto-cleared. The IPM path ignores this field. Wire-set
1160    /// via [`Self::set_sqp_warm_start`].
1161    sqp_warm_start: Option<crate::sqp::SqpIterates>,
1162    /// Phase 5c (§6) SQP warm-start output. Populated by every
1163    /// `optimize_sqp_tnlp` call with the final QP working set.
1164    /// Stays valid until the next solve (which overwrites it).
1165    /// Accessed via [`Self::last_sqp_working_set`].
1166    sqp_last_working_set: Option<pounce_qp::WorkingSet>,
1167    /// gh#986 review item 10: the fixed-variable elimination of the solve in
1168    /// progress, `(x_not_fixed_map, n_full_x)`. Working sets are published in
1169    /// the caller's full space (fixed variables marked `Fixed`) and warm
1170    /// starts are mapped through it, so a working set recorded on one node
1171    /// lands on the right columns of a node that fixes different variables.
1172    x_elimination: Option<(Vec<Index>, usize)>,
1173    /// What the post-convergence crossover phase did on the most recent
1174    /// IPM solve (gh#612). `None` when `crossover=no` (the default) or
1175    /// when the solve did not converge — crossover only runs on a
1176    /// converged interior iterate. Read via [`Self::crossover_report`].
1177    ///
1178    /// Kept separate from `sqp_last_working_set`, which crossover *also*
1179    /// populates on success: that field answers "what can the next solve
1180    /// warm-start from", this one answers "was the active set I am about
1181    /// to trust actually identified, or merely inferred".
1182    crossover_report: Option<crate::crossover::CrossoverReport>,
1183    /// Full primal-dual warm-start iterate for the IPM path, captured by
1184    /// the interactive debugger's `resolve` command. When `Some`, the
1185    /// next `optimize_tnlp` installs this 8-vector (algorithm space)
1186    /// directly onto `data.curr` before the iterate initializer runs, so
1187    /// a warm `resolve` continues from the paused interior point rather
1188    /// than cold-restarting the duals. Consumed once per solve, then
1189    /// auto-cleared. Requires `warm_start_init_point=yes` so the
1190    /// re-optimize branch of `WarmStartIterateInitializer` keeps the
1191    /// installed iterate. Wire-set via [`Self::set_warm_start_iterate`].
1192    warm_start_iterate: Option<crate::debug::IterateSnapshot>,
1193    /// The warm-start initializer's verdict on the most recent solve's
1194    /// supplied iterate (gh#606). Lifted off the solve-local
1195    /// `IpoptData` so a caller can read it after `optimize_tnlp`
1196    /// returns; `None` when the last solve was a cold start.
1197    warm_start_diag: RefCell<Option<crate::init::warm_start::WarmStartDiagnostics>>,
1198    /// Caller-supplied fill-reducing permutation for the KKT linear
1199    /// solver (pounce#180 item 1 / FERAL#107). When `Some`, it overrides
1200    /// whatever `feral_ordering` / `POUNCE_FERAL_ORDERING` resolves to,
1201    /// installing [`pounce_feral::OrderingMethod::External`] on the FERAL
1202    /// backend for the next solve. The vector is a **0-based, new-to-old
1203    /// permutation** whose length must equal the augmented KKT system
1204    /// dimension; FERAL validates it as a bijection and returns
1205    /// `InvalidInput` (never panics) on a wrong length / index. Unlike the
1206    /// warm-start hooks this is treated as persistent config — it is *not*
1207    /// auto-cleared after a solve, so a caller sets it once for a run.
1208    /// Wire-set via [`Self::set_external_ordering`]. Ignored by non-FERAL
1209    /// backends and by any custom factory plugged via
1210    /// [`Self::set_linear_backend_factory`].
1211    external_ordering: Option<Vec<usize>>,
1212    /// Caller-supplied block-triangular / Schur KKT partition (pounce#180
1213    /// item 2). When `Some`, the next IPM solve on the feral + exact-Hessian
1214    /// path routes the KKT linear solve through a
1215    /// [`crate::kkt::SchurAugSystemSolver`] over these **KKT-space indices**
1216    /// (`0..dim` in the `x, s, c, d` block order the aug-system solver
1217    /// assembles): the `S` block is Schur-complemented out and only the two
1218    /// diagonal blocks are factorized, with inertia recovered via Sylvester's
1219    /// law. Beneficial only when `|S| ≪` the eliminated block; the Schur solver
1220    /// falls back to the standard full-space solver transparently when the
1221    /// partition is unsuitable (too large, malformed, or the backend errors),
1222    /// so a stray hook never breaks a solve. Persistent config (not
1223    /// auto-cleared). Wire-set via [`Self::set_kkt_schur_block`].
1224    kkt_schur_block: Option<Vec<usize>>,
1225    /// Block-parallel KKT partition (structured-KKT Phase 5b): KKT-space block
1226    /// labels, `< 0` for the shared border, **empty** meaning "detect".
1227    /// Wire-set via [`Self::set_kkt_block_structure`].
1228    kkt_blocks: Option<Vec<i32>>,
1229    /// The same partition declared in the *model's* own terms — one block per
1230    /// variable and per constraint — which [`map_block_structure_to_kkt`]
1231    /// turns into `kkt_blocks` once the NLP layout is known. Wire-set via
1232    /// [`Self::set_block_structure`].
1233    model_blocks: Option<(Vec<i32>, Vec<i32>)>,
1234    /// The problem-statistics block most recently printed during the current
1235    /// run, so a retry attempt does not reprint an identical one.
1236    ///
1237    /// Every retry driver — the ℓ₁ fallback, the μ-strategy fallback, the
1238    /// second-opinion ladder, the dual-divergence retry — re-enters the solve
1239    /// routine that emits this block, so a run that retried once printed the
1240    /// whole Ipopt-style header twice with nothing between the copies saying a
1241    /// second attempt had started. Read as "the solver printed everything
1242    /// twice", which is what it looked like.
1243    ///
1244    /// Scoped to one run: reset at the top of
1245    /// [`Self::optimize_tnlp_with_derivative_test_tnlp`], which every entry
1246    /// point funnels through. Without that reset a library caller's second
1247    /// deliberate `optimize_tnlp` on the same application would lose its
1248    /// header, which is a different thing entirely from a retry inside one
1249    /// call.
1250    ///
1251    /// Compared rather than counted because the block can legitimately differ
1252    /// between attempts: the ℓ₁ wrapper adds slack variables, so its retry
1253    /// solves a genuinely larger problem and reprinting is informative.
1254    last_printed_problem_stats: RefCell<Option<pounce_solve_report::console::ProblemStats>>,
1255    /// Set while an *outside* retry driver is re-entering `optimize_tnlp` for
1256    /// another attempt on the same problem — today only
1257    /// `pounce_restoration::second_opinion_driver::run_second_opinion_ladder`.
1258    ///
1259    /// The retries that nest INSIDE one `optimize_tnlp` call (the ℓ₁ fallback,
1260    /// the μ-strategy fallback) are covered by `last_printed_problem_stats`
1261    /// alone, because the funnel that resets it runs once for all of them. The
1262    /// ladder's rungs are `optimize_tnlp` calls in their own right, so without
1263    /// this flag each one resets the memo and reprints the header — which is
1264    /// how a four-rung ladder printed five identical copies of it.
1265    ///
1266    /// It also decides who explains the retry. The ladder narrates every rung
1267    /// on stderr, naming the knob it varies and whether the rung recovered, so
1268    /// `emit_problem_stats` stays quiet and lets that narration stand. The
1269    /// in-call fallbacks say nothing at all, so there the suppressed header is
1270    /// replaced by a line announcing the attempt.
1271    in_retry_sequence: std::cell::Cell<bool>,
1272    /// Nesting depth of retry drivers that have taken ownership of the
1273    /// run-ending `EXIT:` / `POUNCE <version>:` verdict.
1274    ///
1275    /// `emit_end_summary` prints the per-attempt statistics block whatever
1276    /// this reads, and prints the verdict only at zero. A driver raises it
1277    /// before its first attempt and lowers it after its last, then prints the
1278    /// verdict once with the status it is actually returning.
1279    ///
1280    /// A counter rather than a flag because the drivers nest: the ℓ₁ fallback
1281    /// can wrap the μ-strategy fallback, which the dual-divergence retry can
1282    /// wrap in turn, and the CLI brackets the whole lot again around the
1283    /// second-opinion ladder. Only the outermost knows the run is over, and
1284    /// "outermost" is exactly "the one that brings this back to zero".
1285    end_verdict_deferrals: std::cell::Cell<u32>,
1286}
1287
1288impl fmt::Debug for IpoptApplication {
1289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1290        f.debug_struct("IpoptApplication")
1291            .field("options", &self.options)
1292            .field("statistics", &self.statistics)
1293            .finish_non_exhaustive()
1294    }
1295}
1296
1297impl Default for IpoptApplication {
1298    fn default() -> Self {
1299        Self::new()
1300    }
1301}
1302
1303impl IpoptApplication {
1304    /// New application with empty options and a default journalist.
1305    /// Equivalent to `IpoptApplication::IpoptApplication(true,true)`.
1306    pub fn new() -> Self {
1307        let reg = RegisteredOptions::default();
1308        // Registration of a fresh registry can only fail on a duplicate
1309        // name, which would be a programming error in `reg_op`.
1310        register_all_upstream_options(&reg)
1311            .unwrap_or_else(|e| panic!("Upstream options registration failed: {e}"));
1312        pounce_presolve::register_options(&reg)
1313            .unwrap_or_else(|e| panic!("Presolve options registration failed: {e}"));
1314        let reg = Rc::new(reg);
1315        Self {
1316            options: OptionsList::with_registered(Rc::clone(&reg)),
1317            least_square_init_report: None,
1318            variable_scaling: RefCell::new(None),
1319            row_scaling_active: std::cell::Cell::new(None),
1320            presolve_already_applied: false,
1321            reg_options: reg,
1322            journalist: Rc::new(Journalist::new()),
1323            statistics: RefCell::new(SolveStatistics::new()),
1324            timing: RefCell::new(Rc::new(TimingStatistics::new())),
1325            linear_backend_factory: None,
1326            restoration_factory: None,
1327            diagnostics: None,
1328            debug_hook: None,
1329            restoration_factory_provider: None,
1330            on_converged: None,
1331            record_iter_history: false,
1332            option_file_resolved: false,
1333            convex_routing_available: false,
1334            backend_warnings_emitted: false,
1335            linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1336            resto_linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1337            kkt_blocks_published: Arc::new(Mutex::new(None)),
1338            quality_escalations: Rc::new(std::cell::Cell::new(0)),
1339            mu_strategy_pounce_chosen: false,
1340            dual_divergence_signature: std::cell::Cell::new(false),
1341            derivative_check: RefCell::new(None),
1342            obj_scale_refused: std::cell::Cell::new((false, false)),
1343            dual_divergence_retry_promoted: std::cell::Cell::new(false),
1344            answer_restored_from_floor: std::cell::Cell::new(false),
1345            retry_keeps_declared_box: std::cell::Cell::new(false),
1346            last_finalize: RefCell::new(None),
1347            last_iter_stats: Rc::new(RefCell::new(None)),
1348            sqp_warm_start: None,
1349            sqp_last_working_set: None,
1350            x_elimination: None,
1351            crossover_report: None,
1352            warm_start_iterate: None,
1353            warm_start_diag: RefCell::new(None),
1354            external_ordering: None,
1355            kkt_schur_block: None,
1356            kkt_blocks: None,
1357            model_blocks: None,
1358            last_printed_problem_stats: RefCell::new(None),
1359            in_retry_sequence: std::cell::Cell::new(false),
1360            end_verdict_deferrals: std::cell::Cell::new(0),
1361        }
1362    }
1363
1364    pub fn options(&self) -> &OptionsList {
1365        &self.options
1366    }
1367
1368    pub fn options_mut(&mut self) -> &mut OptionsList {
1369        &mut self.options
1370    }
1371
1372    /// Declare whether callers have already applied an explicit presolve
1373    /// wrapper to the TNLPs submitted to [`Self::optimize_tnlp`].
1374    ///
1375    /// When set, `optimize_tnlp` leaves its input TNLP unchanged even if the
1376    /// `presolve` option is enabled. This preserves the option table for
1377    /// reporting and debugger use while allowing specialized frontends to
1378    /// supply a wrapper with capabilities unavailable to generic callback
1379    /// TNLPs, such as an expression provider for FBBT.
1380    pub fn set_presolve_already_applied(&mut self, applied: bool) {
1381        self.presolve_already_applied = applied;
1382    }
1383
1384    /// Solve without materializing the generic presolve wrapper.
1385    ///
1386    /// This is for consumers that require the original TNLP coordinate system
1387    /// for the solve's KKT matrix, such as sensitivity and reduced-Hessian
1388    /// drivers. It is scoped to this invocation and does not change the
1389    /// application's `presolve` option or persistent explicit-wrapper setting.
1390    pub fn optimize_tnlp_without_presolve(
1391        &mut self,
1392        tnlp: Rc<RefCell<dyn TNLP>>,
1393    ) -> ApplicationReturnStatus {
1394        let explicit_wrapper = self.presolve_already_applied;
1395        self.presolve_already_applied = true;
1396        let status = self.optimize_tnlp(tnlp);
1397        self.presolve_already_applied = explicit_wrapper;
1398        status
1399    }
1400
1401    pub fn registered_options(&self) -> &Rc<RegisteredOptions> {
1402        &self.reg_options
1403    }
1404
1405    pub fn journalist(&self) -> &Rc<Journalist> {
1406        &self.journalist
1407    }
1408
1409    /// Plug a custom symmetric-linear-solver factory. Useful for tests
1410    /// that want to swap MA57 for a stub. Production callers should
1411    /// leave this unset — the default ([`default_backend_factory`])
1412    /// returns the workspace's MA57 binding.
1413    pub fn set_linear_backend_factory(&mut self, factory: LinearBackendFactory) {
1414        self.linear_backend_factory = Some(factory);
1415    }
1416
1417    /// Plug a restoration-phase factory. Called once per
1418    /// `optimize_tnlp` invocation to mint a fresh
1419    /// `Box<dyn RestorationPhase>` that the outer algorithm uses as
1420    /// its line-search restoration fallback. Lives behind a setter
1421    /// (rather than at construction) because the concrete restoration
1422    /// strategies live in `pounce-restoration`, which depends on this
1423    /// crate; consumers in `pounce-cli` / integration tests wire the
1424    /// factory at the application boundary.
1425    pub fn set_restoration_factory(&mut self, factory: RestorationFactory) {
1426        self.restoration_factory = Some(factory);
1427    }
1428
1429    /// Install the shared diagnostics state. Once set, every
1430    /// subsequent `optimize_tnlp` call forwards the state into the
1431    /// algorithm via [`IpoptAlgorithm::with_diagnostics`] so the KKT
1432    /// solver can emit `--dump kkt:...` artifacts.
1433    pub fn set_diagnostics(&mut self, diag: Rc<DiagnosticsState>) {
1434        self.diagnostics = Some(diag);
1435    }
1436
1437    /// Install an interactive debugger hook for the next `optimize_*`
1438    /// call. The hook is moved into the main [`IpoptAlgorithm`] and
1439    /// consumed by that solve; reinstall it to debug a subsequent solve.
1440    pub fn set_debug_hook(
1441        &mut self,
1442        hook: std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>,
1443    ) {
1444        self.debug_hook = Some(hook);
1445    }
1446
1447    /// Read-side accessor for the installed diagnostics state, if any.
1448    /// Lets the CLI write the top-level manifest/timing files after
1449    /// the solve completes.
1450    pub fn diagnostics(&self) -> Option<Rc<DiagnosticsState>> {
1451        self.diagnostics.as_ref().map(Rc::clone)
1452    }
1453
1454    /// The three options that decide how the TNLP is *classified* before any
1455    /// algorithm sees it: the two infinity thresholds and the fixed-variable
1456    /// treatment.
1457    ///
1458    /// One reader, because there were three copies and they drifted. The
1459    /// active-set SQP path built its adapter with `TNLPAdapter::new`, which
1460    /// hard-codes the same three defaults — so the options were accepted and
1461    /// discarded on that arm, and a model with `fixed_variable_treatment=
1462    /// relax_bounds` or a non-default `nlp_upper_bound_inf` was classified one
1463    /// way for the interior-point arm and another for this one. Silently: the
1464    /// defaults coincide, so it only diverges for a caller who sets them, and
1465    /// nothing reported the difference.
1466    ///
1467    /// `make_constraint` / `make_parameter_nodual` are not implemented and
1468    /// fall back to `make_parameter`; the adapter auto-retries to
1469    /// `relax_bounds` when `make_parameter` would leave `n_x_var < n_c`
1470    /// (upstream `IpTNLPAdapter.cpp:623-633`).
1471    fn adapter_options(&self) -> (Number, Number, FixedVarTreatment) {
1472        let lo_inf = self
1473            .options
1474            .get_numeric_value("nlp_lower_bound_inf", "")
1475            .ok()
1476            .and_then(|(v, f)| f.then_some(v))
1477            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF);
1478        let up_inf = self
1479            .options
1480            .get_numeric_value("nlp_upper_bound_inf", "")
1481            .ok()
1482            .and_then(|(v, f)| f.then_some(v))
1483            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF);
1484        let fixed_treatment = match self
1485            .options
1486            .get_string_value("fixed_variable_treatment", "")
1487            .ok()
1488            .and_then(|(v, f)| f.then_some(v))
1489            .as_deref()
1490        {
1491            Some("relax_bounds") => FixedVarTreatment::RelaxBounds,
1492            _ => FixedVarTreatment::MakeParameter,
1493        };
1494        (lo_inf, up_inf, fixed_treatment)
1495    }
1496
1497    /// Whether the final solution reports bound multipliers for variables
1498    /// `make_parameter` removed (see
1499    /// `OrigIpoptNlp::complete_fixed_var_bound_multipliers`).
1500    /// Ipopt 3.14 does, for every treatment except `make_parameter_nodual`,
1501    /// which exists to ask it not to.
1502    pub fn reports_fixed_var_duals(&self) -> bool {
1503        !matches!(
1504            self.options
1505                .get_string_value("fixed_variable_treatment", "")
1506                .ok()
1507                .map(|(v, _)| v)
1508                .as_deref(),
1509            Some("make_parameter_nodual")
1510        )
1511    }
1512
1513    /// Mark that the next `optimize_*` calls are further **attempts at the
1514    /// same problem**, driven from outside, rather than new solves.
1515    ///
1516    /// Retry drivers that re-enter `optimize_tnlp` per attempt — the
1517    /// second-opinion ladder is the only one today — bracket their attempts
1518    /// with `true` … `false`. The effect is confined to console presentation:
1519    /// the Ipopt-style problem-statistics header is printed once for the run
1520    /// instead of once per attempt. Nothing about the solve changes.
1521    ///
1522    /// Callers must clear it on every exit path, including the early returns a
1523    /// ladder takes when a rung promotes; a stuck `true` costs a later solve
1524    /// its header and nothing worse.
1525    pub fn set_in_retry_sequence(&self, active: bool) {
1526        self.in_retry_sequence.set(active);
1527    }
1528
1529    /// Take ownership of the run-ending `EXIT:` / `POUNCE <version>:` verdict
1530    /// for the attempts that follow.
1531    ///
1532    /// Between this and [`Self::release_end_verdict`] the per-attempt end
1533    /// summary prints its statistics block but not the verdict, so a retried
1534    /// run no longer reports a mid-run verdict that reads as the final answer.
1535    /// The releaser prints it once, with the status it is returning.
1536    ///
1537    /// Callers must pair the two on every exit path. An unmatched acquire
1538    /// costs the run its verdict line; the counter saturates rather than
1539    /// wrapping, so an unmatched release cannot make a nested driver print
1540    /// one early.
1541    pub fn defer_end_verdict(&self) {
1542        self.end_verdict_deferrals
1543            .set(self.end_verdict_deferrals.get().saturating_add(1));
1544    }
1545
1546    /// Release one [`Self::defer_end_verdict`]. Returns `true` when this was
1547    /// the outermost one — i.e. when the caller now owns printing the verdict.
1548    #[must_use]
1549    pub fn release_end_verdict(&self) -> bool {
1550        let next = self.end_verdict_deferrals.get().saturating_sub(1);
1551        self.end_verdict_deferrals.set(next);
1552        next == 0
1553    }
1554
1555    /// Print the run-ending verdict, honouring `print_level`.
1556    ///
1557    /// The gate matches `emit_end_summary`'s, which is the block this follows:
1558    /// at `print_level 0` there is no summary for it to end.
1559    pub fn print_end_verdict(&self, status: ApplicationReturnStatus) {
1560        let console_output = match self.options.get_integer_value("print_level", "") {
1561            Ok((v, true)) => v >= 1,
1562            _ => true,
1563        };
1564        if console_output {
1565            pounce_solve_report::console::print_exit_verdict(status);
1566        }
1567    }
1568
1569    /// Plug a restoration-phase **factory provider** for drivers that
1570    /// need to run the inner IPM more than once per `optimize_tnlp`
1571    /// call (notably the Phase-3 ℓ₁-exact penalty-barrier outer loop,
1572    /// pounce#10). On each inner solve, the application consults the
1573    /// provider to mint a fresh [`RestorationFactory`], replacing any
1574    /// stale one, so the default one-shot restoration factory does
1575    /// not panic on its second invocation. If both `set_restoration_factory`
1576    /// and this are configured, the provider wins.
1577    pub fn set_restoration_factory_provider(&mut self, provider: RestorationFactoryProvider) {
1578        self.restoration_factory_provider = Some(provider);
1579    }
1580
1581    /// Register a callback to run once the IPM has converged (status
1582    /// [`ApplicationReturnStatus::SolveSucceeded`] or
1583    /// [`ApplicationReturnStatus::SolvedToAcceptableLevel`]) but before
1584    /// `finalize_solution` flows back to the TNLP. See
1585    /// [`ConvergedCallback`] for the use case (post-optimal sensitivity).
1586    pub fn set_on_converged(&mut self, cb: ConvergedCallback) {
1587        self.on_converged = Some(cb);
1588    }
1589
1590    /// Remove and return the registered on-converged callback, if any, so a
1591    /// caller that installs its own for a while can put the previous one
1592    /// back (`pounce_minima::IpoptLocalSolve` does, gh#966).
1593    pub fn take_on_converged(&mut self) -> Option<ConvergedCallback> {
1594        self.on_converged.take()
1595    }
1596
1597    /// Was the reported answer replayed from an earlier attempt's floor,
1598    /// after a later attempt lost?
1599    ///
1600    /// **A caller that captures the solution in [`Self::set_on_converged`]
1601    /// must consult this.** That callback fires once per *attempt*, and a
1602    /// losing retry that converged has already run it, so the capture
1603    /// belongs to the discarded point while everything else — status,
1604    /// objective, statistics — has been floored back. When this is `true`,
1605    /// take `x` and the multipliers from the last `finalize_solution`
1606    /// payload instead; that one is always the answer being reported,
1607    /// because the floor restores it *by* calling `finalize_solution`.
1608    ///
1609    /// The payload is in the **model's own units** and in the **reduced**
1610    /// presolve space: `CountingTnlp`-style consumers sit inside the gh#486
1611    /// scaling wrapper (so `x /= d`, `z *= d` have already been applied) and
1612    /// outside the presolve one (so the row/column lift has not). A caller
1613    /// swapping it in must therefore skip its own scaling correction and keep
1614    /// its own lift; getting that backwards squares the factor, which is a
1615    /// silent wrong answer of exactly the shape this flag exists to remove.
1616    ///
1617    /// **Not consulted, and known not to be**: the three other
1618    /// [`Self::set_on_converged`] consumers —
1619    /// `pounce-sensitivity/src/{solver,convenience}.rs` and
1620    /// `pounce-cli/src/minima/mod.rs` — read the converged KKT state and the
1621    /// factorization, which the `finalize_solution` payload does not carry
1622    /// and which cannot be rewound. After any floor replay their result
1623    /// describes the attempt that lost. Pre-existing, unfixed, and annotated
1624    /// at each site.
1625    ///
1626    /// `false` on every solve that never spent a second attempt, which is
1627    /// almost all of them, so the ordinary path is unaffected.
1628    pub fn answer_restored_from_floor(&self) -> bool {
1629        self.answer_restored_from_floor.get()
1630    }
1631
1632    /// Enable per-iteration trajectory capture. After the solve
1633    /// returns, [`Self::statistics()`] exposes
1634    /// [`pounce_nlp::solve_statistics::SolveStatistics::iterations`]
1635    /// populated with one [`pounce_nlp::solve_statistics::IterRecord`]
1636    /// per accepted iterate. Off by default — the `pounce_sens` and
1637    /// `pounce` binaries opt in when `--json-output` is passed.
1638    pub fn enable_iter_history(&mut self) {
1639        self.record_iter_history = true;
1640    }
1641
1642    /// Whether [`Self::enable_iter_history`] is in force — read by a stage
1643    /// that produces a verdict outside `optimize_tnlp` (the second-opinion
1644    /// ladder's square-system stage) so its statistics keep the same
1645    /// `iterations` / `iteration_count` pairing.
1646    pub fn iter_history_enabled(&self) -> bool {
1647        self.record_iter_history
1648    }
1649
1650    /// Read the run's options file, resolving *which* file the way
1651    /// upstream's `IpoptApplication::Initialize` does — with one
1652    /// deliberate difference, below.
1653    ///
1654    /// `explicit` is the file the caller named (upstream: the
1655    /// `option_file_name` option, read out of the option store before
1656    /// this point). With `None`, the working directory is probed for
1657    /// [`DEFAULT_OPTION_FILE_NAMES`] and the first hit is read; an
1658    /// absent default file is not an error, it just means "no file".
1659    ///
1660    /// The difference: upstream opens a named file with a bare
1661    /// `std::ifstream` and reads nothing if the open fails, so a typo'd
1662    /// `option_file_name` runs at stock defaults without a word. That
1663    /// silence is what gh#518 was reported for — a benchmark that
1664    /// measured defaults while claiming to measure a configuration — so
1665    /// a named file that cannot be read is an error here.
1666    pub fn initialize_with_option_file(
1667        &mut self,
1668        explicit: Option<&Path>,
1669    ) -> Result<OptionFileLoad, SolverException> {
1670        let mut load = OptionFileLoad::default();
1671        // Set before the early returns below: what this flag records is
1672        // that `option_file_name` was *consulted*, not that a file turned
1673        // up. A caller on this path who names nothing and has no
1674        // `pounce.opt` to find still gets the option honored — there was
1675        // simply nothing to read.
1676        self.option_file_resolved = true;
1677        let path = match explicit {
1678            Some(p) => {
1679                if !p.is_file() {
1680                    return Err(SolverException::new(
1681                        ExceptionKind::IPOPT_APPLICATION_ERROR,
1682                        format!(
1683                            "options file \"{}\" does not exist. It was named by \
1684                             --options-file / option_file_name, so the run would \
1685                             otherwise proceed at stock defaults with none of its \
1686                             settings applied.",
1687                            p.display()
1688                        ),
1689                        file!(),
1690                        line!() as Index,
1691                    ));
1692                }
1693                load.explicit = true;
1694                p.to_path_buf()
1695            }
1696            None => {
1697                let present: Vec<&&str> = DEFAULT_OPTION_FILE_NAMES
1698                    .iter()
1699                    .filter(|n| Path::new(n).is_file())
1700                    .collect();
1701                let Some(first) = present.first() else {
1702                    return Ok(load);
1703                };
1704                // Both default names in one directory: say which one lost,
1705                // rather than let the unread one look applied.
1706                for other in &present[1..] {
1707                    load.warnings.push(format!(
1708                        "`{first}` and `{other}` are both present; reading `{first}` \
1709                         only (pounce's own name wins). Pass \
1710                         `option_file_name={other}` to read that one instead."
1711                    ));
1712                }
1713                PathBuf::from(**first)
1714            }
1715        };
1716        self.initialize_with_options_file(&path)?;
1717        // `option_file_name` set *inside* an options file chains nowhere —
1718        // by the time it is read, the file naming it has already been
1719        // chosen. Upstream documents that ("it does not make any sense to
1720        // specify this option within the options file") and then ignores
1721        // it; name it instead, since an ignored setting that looks live is
1722        // the whole complaint behind gh#518.
1723        if let Ok((named, true)) = self.options.get_string_value("option_file_name", "")
1724            && !named.is_empty()
1725            && Path::new(&named) != path
1726        {
1727            load.warnings.push(format!(
1728                "`{}` sets option_file_name to `{named}`, which has no effect: \
1729                 the options file is chosen before it is read. Pass \
1730                 `option_file_name={named}` on the command line to read that file.",
1731                path.display()
1732            ));
1733        }
1734        load.path = Some(path);
1735        Ok(load)
1736    }
1737
1738    /// Read an `ipopt.opt`-format options file. Equivalent to
1739    /// `IpoptApplication::Initialize(const std::string& options_file)`.
1740    pub fn initialize_with_options_file(&mut self, path: &Path) -> Result<(), SolverException> {
1741        let txt = std::fs::read_to_string(path).map_err(|e| {
1742            SolverException::new(
1743                ExceptionKind::IPOPT_APPLICATION_ERROR,
1744                format!("could not read options file {}: {}", path.display(), e),
1745                file!(),
1746                line!() as Index,
1747            )
1748        })?;
1749        self.options.read_from_str(&txt, true)?;
1750        self.open_output_file_journal();
1751        Ok(())
1752    }
1753
1754    /// Read options from a string in `ipopt.opt` format. Useful for
1755    /// tests and embedded callers.
1756    pub fn initialize_with_options_str(&mut self, s: &str) -> Result<(), SolverException> {
1757        self.options.read_from_str(s, true)?;
1758        self.open_output_file_journal();
1759        Ok(())
1760    }
1761
1762    /// Honor `output_file` / `file_print_level` / `file_append`: when
1763    /// `output_file` is non-empty, attach a `FileJournal` named
1764    /// `"OutputFile:<fname>"` at the requested level. Mirrors
1765    /// `IpoptApplication::OpenOutputFile` (called from `Initialize`).
1766    /// No-op if `output_file` is unset, empty, or could not be opened.
1767    ///
1768    /// NOTE: pounce's iteration output currently bypasses the
1769    /// journalist and writes directly to stdout. The file journal is
1770    /// attached and the timing report (gated by `print_timing_statistics`)
1771    /// is mirrored to it; per-iter rows will start landing in the file
1772    /// once the iter-output path is routed through the journalist.
1773    fn open_output_file_journal(&self) {
1774        let fname = match self.options.get_string_value("output_file", "") {
1775            Ok((v, true)) if !v.is_empty() => v,
1776            _ => return,
1777        };
1778        let level_int = self
1779            .options
1780            .get_integer_value("file_print_level", "")
1781            .ok()
1782            .and_then(|(v, f)| f.then_some(v))
1783            .unwrap_or(5);
1784        let level = journal_level_from_int(level_int);
1785        let append = self
1786            .options
1787            .get_bool_value("file_append", "")
1788            .ok()
1789            .and_then(|(v, f)| f.then_some(v))
1790            .unwrap_or(false);
1791        let jname = format!("OutputFile:{}", fname);
1792        let _ = self
1793            .journalist
1794            .add_file_journal(&jname, &fname, level, append);
1795    }
1796
1797    /// No-op initialize (just succeeds). Mirrors
1798    /// `IpoptApplication::Initialize(bool allow_clobber)` with no
1799    /// options file.
1800    pub fn initialize(&mut self) -> Result<(), SolverException> {
1801        Ok(())
1802    }
1803
1804    /// Mirror `IpoptApplication::OpenOutputFile`. Sets the `output_file`
1805    /// / `file_print_level` options and attaches a matching
1806    /// `FileJournal` named `OutputFile:<fname>` to the journalist.
1807    /// Returns `false` if the file could not be opened or the option
1808    /// store rejected the request (e.g. clamped print level).
1809    pub fn open_output_file(&mut self, fname: &str, print_level: i32) -> bool {
1810        if self
1811            .options
1812            .set_string_value("output_file", fname, true, false)
1813            .is_err()
1814        {
1815            return false;
1816        }
1817        if self
1818            .options
1819            .set_integer_value("file_print_level", print_level as Index, true, false)
1820            .is_err()
1821        {
1822            return false;
1823        }
1824        let level = journal_level_from_int(print_level);
1825        let jname = format!("OutputFile:{}", fname);
1826        // Drop any previous file journal so a second call switches files
1827        // cleanly. `add_file_journal` would otherwise refuse to attach
1828        // a duplicate by name; remove-by-name isn't in the journalist
1829        // API, so we settle for the name-collision case here.
1830        self.journalist
1831            .add_file_journal(&jname, fname, level, false)
1832            .is_some()
1833    }
1834
1835    /// Wrap a TNLP and report problem dimensions. Used in tests until
1836    /// the full IPM path covers every entry shape.
1837    pub fn problem_dimensions(&self, tnlp: &mut dyn TNLP) -> Option<NlpInfo> {
1838        tnlp.get_nlp_info()
1839    }
1840
1841    /// Diagnostics from the safeguarded `least_square_init_primal`
1842    /// initializer step of the last solve (gh#605): the nonlinear
1843    /// violation before and after, the accepted step norm, how many
1844    /// backtracking trials were rejected, and why it stopped. `None`
1845    /// when `least_square_init_primal` was off or the model had no
1846    /// constraints.
1847    pub fn least_square_init_report(&self) -> Option<crate::init::default::LeastSquareInitReport> {
1848        self.least_square_init_report.clone()
1849    }
1850
1851    pub fn statistics(&self) -> SolveStatistics {
1852        self.statistics.borrow().clone()
1853    }
1854
1855    /// What the warm-start initializer made of the iterate the caller
1856    /// supplied to the most recent solve (gh#606): the residuals it
1857    /// measured, whether each multiplier block was accepted,
1858    /// reconstructed or discarded, and the barrier parameter it
1859    /// settled on.
1860    ///
1861    /// `None` when the last solve was a cold start
1862    /// (`warm_start_init_point=no`), or when no solve has run. Reset at
1863    /// the top of every solve, like [`Self::timing_stats`].
1864    pub fn warm_start_diagnostics(&self) -> Option<crate::init::warm_start::WarmStartDiagnostics> {
1865        self.warm_start_diag.borrow().clone()
1866    }
1867
1868    /// Shared timing accumulator from the most recent `optimize_tnlp`
1869    /// call. Each subsystem (algorithm, NLP, KKT solver) bumped its own
1870    /// fields during the solve; consumers read totals out of the
1871    /// returned `Rc`. The instance is replaced at the top of every
1872    /// subsequent solve, so cloning the `Rc` and holding it past a
1873    /// re-solve will give you the previous solve's timings — by design.
1874    pub fn timing_stats(&self) -> Rc<TimingStatistics> {
1875        Rc::clone(&self.timing.borrow())
1876    }
1877
1878    /// Aggregate linear-solver post-mortem from the most recent
1879    /// `optimize_tnlp` call. `Some` when the workspace-default FERAL
1880    /// backend ran at least one factor; `None` when no factors were
1881    /// recorded (custom factory plugged via
1882    /// [`Self::set_linear_backend_factory`], or solve aborted before
1883    /// the first KKT factor). Reset at the top of every solve.
1884    ///
1885    /// Restoration-phase factorizations are attached as
1886    /// [`LinearSolverSummary::restoration`] when the frontend wired
1887    /// [`Self::restoration_summary_sink`] into its restoration factory.
1888    pub fn linear_solver_summary(&self) -> Option<LinearSolverSummary> {
1889        let mut main = self.linsol_summary_sink.lock().ok()?.clone();
1890        let resto = self
1891            .resto_linsol_summary_sink
1892            .lock()
1893            .ok()
1894            .map(|g| g.clone())
1895            .filter(|r| !r.is_empty());
1896        if main.is_empty() && resto.is_none() {
1897            return None;
1898        }
1899        main.restoration = resto.map(Box::new);
1900        // gh#990 item 7: name what was asked for beside what ran.
1901        main.requested = self
1902            .options
1903            .get_string_value("linear_solver", "")
1904            .ok()
1905            .map(|(v, _)| v);
1906        Some(main)
1907    }
1908
1909    /// Snapshot of both linear-solver summary sinks (main and
1910    /// restoration), for a driver that re-solves and must report the
1911    /// summary of the solve whose verdict it keeps. The second-opinion
1912    /// ladder takes one before its rungs and restores it when no rung is
1913    /// promoted, exactly as it does for the statistics.
1914    pub fn linear_solver_summary_state(&self) -> LinearSolverSummaryState {
1915        let read =
1916            |s: &Arc<Mutex<LinearSolverSummary>>| s.lock().map(|g| g.clone()).unwrap_or_default();
1917        LinearSolverSummaryState {
1918            main: read(&self.linsol_summary_sink),
1919            restoration: read(&self.resto_linsol_summary_sink),
1920        }
1921    }
1922
1923    /// Put back a [`Self::linear_solver_summary_state`] snapshot.
1924    pub fn restore_linear_solver_summary_state(&self, state: LinearSolverSummaryState) {
1925        if let Ok(mut g) = self.linsol_summary_sink.lock() {
1926            *g = state.main;
1927        }
1928        if let Ok(mut g) = self.resto_linsol_summary_sink.lock() {
1929            *g = state.restoration;
1930        }
1931    }
1932
1933    /// The sink a restoration backend factory should record into, e.g.
1934    /// through [`default_backend_factory_with_sink`]. Kept separate from
1935    /// the main solve's sink so the main-solve totals stay about the main
1936    /// solve.
1937    pub fn restoration_summary_sink(&self) -> Arc<Mutex<LinearSolverSummary>> {
1938        Arc::clone(&self.resto_linsol_summary_sink)
1939    }
1940
1941    /// Drive a solve.
1942    ///
1943    /// * Constrained problems (`m > 0`) take the primal-dual IPM path:
1944    ///   build a `TNLPAdapter` → `OrigIpoptNlp`, run the
1945    ///   [`AlgorithmBuilder`] with the workspace MA57 backend, and
1946    ///   call [`IpoptAlgorithm::optimize`]. The `SolverReturn` →
1947    ///   `ApplicationReturnStatus` mapping mirrors the table in
1948    ///   `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception →
1949    ///   SolverReturn map").
1950    /// * Unconstrained problems (`m == 0`) keep going through the
1951    ///   in-`pounce-nlp` Newton driver so the trivial path is
1952    ///   independent of the linear-solver backend.
1953    /// Wrap `tnlp` so per-variable scaling factors are applied as a
1954    /// change of variables, when `nlp_scaling_method=user-scaling` is
1955    /// in effect and the problem supplies non-unit factors (gh#486).
1956    ///
1957    /// Returns the TNLP unchanged under any other scaling method, or
1958    /// when the problem asks for no variable scaling, so an unscaled
1959    /// solve pays nothing. The `Err` carries a message ready to print.
1960    fn install_variable_scaling(
1961        &self,
1962        tnlp: Rc<RefCell<dyn TNLP>>,
1963    ) -> Result<Rc<RefCell<dyn TNLP>>, String> {
1964        // Cleared first so the accessor describes *this* solve. An
1965        // application is reusable across solves (`pounce-cinterface`
1966        // holds one across `IpoptSolve` calls), and a stale vector
1967        // would have a later unscaled solve reporting the previous
1968        // solve's factors.
1969        *self.variable_scaling.borrow_mut() = None;
1970        let method = self
1971            .options
1972            .get_string_value("nlp_scaling_method", "")
1973            .ok()
1974            .and_then(|(v, f)| f.then_some(v))
1975            .unwrap_or_else(|| "gradient-based".to_string());
1976        // `curvature-based` (gh #703) delivers its factors through the
1977        // same `get_scaling_parameters` callback, so the per-variable half
1978        // needs the same substitution wrapper user factors get.
1979        if method != "user-scaling" && method != "curvature-based" {
1980            return Ok(tnlp);
1981        }
1982        match pounce_nlp::scaling_tnlp::wrap_with_scaling(
1983            Rc::clone(&tnlp),
1984            self.nlp_lower_bound_inf(),
1985            self.nlp_upper_bound_inf(),
1986        ) {
1987            Ok(Some(wrapped)) => {
1988                *self.variable_scaling.borrow_mut() =
1989                    pounce_nlp::scaling_tnlp::factors_of(&wrapped);
1990                Ok(wrapped)
1991            }
1992            Ok(None) => Ok(tnlp),
1993            Err(why) => Err(format!(
1994                // The trailing newline belongs to the message: the
1995                // caller emits it with `eprint!` and hands the same
1996                // string to the journalist, as the refusals below do.
1997                "pounce: nlp_scaling_method={method} supplied per-variable \
1998                 scaling factors that cannot be applied. {why}. Correct the \
1999                 factors, or drop nlp_scaling_method={method}.\n"
2000            )),
2001        }
2002    }
2003
2004    /// The per-variable scaling factors applied to the last solve, if
2005    /// any (gh#486). A consumer reading the algorithm's iterate rather
2006    /// than the `finalize_solution` payload sees scaled coordinates and
2007    /// must divide `x` by these, and multiply bound multipliers.
2008    pub fn variable_scaling(&self) -> Option<Vec<Number>> {
2009        self.variable_scaling.borrow().clone()
2010    }
2011
2012    /// Install a starting-point conditioner, if one is asked for.
2013    ///
2014    /// Returns the TNLP unchanged when neither `start_point_perturbation` nor
2015    /// `start_point_conditioner` is set, which is the default — so an ordinary
2016    /// solve pays nothing and its trajectory is untouched.
2017    ///
2018    /// Sits *above* the presolve wrapper and *below* the variable-scaling one,
2019    /// so the point it conditions is the point the algorithm will actually
2020    /// start from, in the coordinates the algorithm will see. Both
2021    /// conditioners override only `get_starting_point`; every other callback
2022    /// forwards, so the solve that follows is the solve pounce would have run
2023    /// had the conditioned point been submitted directly.
2024    ///
2025    /// The two are mutually exclusive by construction rather than by refusal:
2026    /// the displacement is the failure-recovery rung and the Adam warm-up is a
2027    /// user opt-in, and stacking them would put random noise on top of a point
2028    /// the warm-up just spent 200 evaluations choosing. The displacement wins
2029    /// when both are set, because the only thing that sets it is a solve that
2030    /// has already failed.
2031    fn install_start_conditioner(&self, tnlp: Rc<RefCell<dyn TNLP>>) -> Rc<RefCell<dyn TNLP>> {
2032        use pounce_nlp::start_conditioner::{AdamConfig, ConditionedStartTnlp, StartConditioner};
2033        // Each option is read with its literal tag rather than through a
2034        // `|name, fallback|` helper. A helper reads better and costs the
2035        // wiring guard in `tests/init_options_wiring.rs` its evidence: that
2036        // test scans the source for `get_*_value("<tag>"` to prove every
2037        // registered Initialization option is actually consumed, and a tag
2038        // passed as a variable is invisible to it. A registered knob nothing
2039        // reads validates, accepts a value, and lies.
2040        let perturbation = self
2041            .options
2042            .get_numeric_value("start_point_perturbation", "")
2043            .map(|(v, _found)| v)
2044            .unwrap_or(0.0);
2045        let conditioner = if perturbation > 0.0 {
2046            let seed = self
2047                .options
2048                .get_integer_value("start_point_perturbation_seed", "")
2049                .map(|(v, _found)| v)
2050                .unwrap_or(0);
2051            StartConditioner::Jitter {
2052                // `Index` is signed and the option is lower-bounded at 0, so
2053                // this cast cannot lose a set bit for any accepted value.
2054                seed: seed.max(0) as u64,
2055                scale: perturbation,
2056            }
2057        } else {
2058            let which = self
2059                .options
2060                .get_string_value("start_point_conditioner", "")
2061                .map(|(v, _found)| v)
2062                .unwrap_or_else(|_| "none".to_string());
2063            if which != "adam" {
2064                return tnlp;
2065            }
2066            let d = AdamConfig::default();
2067            StartConditioner::Adam(AdamConfig {
2068                iters: self
2069                    .options
2070                    .get_integer_value("adam_warmup_iters", "")
2071                    .map(|(v, _found)| v.max(0) as usize)
2072                    .unwrap_or(d.iters),
2073                lr: self
2074                    .options
2075                    .get_numeric_value("adam_warmup_learning_rate", "")
2076                    .map(|(v, _found)| v)
2077                    .unwrap_or(d.lr),
2078                rho: self
2079                    .options
2080                    .get_numeric_value("adam_warmup_penalty", "")
2081                    .map(|(v, _found)| v)
2082                    .unwrap_or(d.rho),
2083                ..d
2084            })
2085        };
2086        // The sentinels have to come from the options, not from the
2087        // conditioner's own default: a caller who moved `nlp_lower_bound_inf`
2088        // would otherwise have a bound the algorithm treats as absent clipped
2089        // against as if it were real.
2090        //
2091        // Passed through unclamped. These were once `lower.min(-DEFAULT)` /
2092        // `upper.max(DEFAULT)`, which honours only a *loosened* sentinel and
2093        // leaves the failure above intact for a tightened one: at
2094        // `nlp_lower_bound_inf=-1e10` the conditioner still used `-1e19`, so a
2095        // `-1e15` bound was absent to the algorithm and present to the
2096        // clipper — the exact case the comment exists to rule out. The
2097        // sentinel means "absent"; there is only one right answer for what it
2098        // is, and it is the caller's.
2099        let lower = self.nlp_lower_bound_inf();
2100        let upper = self.nlp_upper_bound_inf();
2101        let wrapped = ConditionedStartTnlp::new(tnlp, conditioner).with_bound_inf(lower, upper);
2102        Rc::new(RefCell::new(wrapped))
2103    }
2104
2105    pub fn optimize_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2106        self.optimize_tnlp_with_derivative_test_tnlp(tnlp, None)
2107    }
2108
2109    /// Solve through `tnlp`, optionally overriding the derivative-test target.
2110    /// `None` tests the scaled and conditioned TNLP.
2111    pub fn optimize_tnlp_with_derivative_test_tnlp(
2112        &mut self,
2113        tnlp: Rc<RefCell<dyn TNLP>>,
2114        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2115    ) -> ApplicationReturnStatus {
2116        // gh#983 review item 1: warnings belong to this solve. Cleared here as
2117        // well as per attempt, so a solve that returns before any attempt runs
2118        // (an option refusal, a presolve proof) does not report the previous
2119        // solve's.
2120        self.statistics.borrow_mut().warnings.clear();
2121        self.statistics.borrow_mut().sqp_warm_working_set_applied = false;
2122        // Belongs to the scale audit's re-solve alone, which runs below this
2123        // entry point (`optimize_constrained`, never `optimize_tnlp`), so no
2124        // solve that starts here may inherit it. `RetryOptionScope` clears it
2125        // on every exit already; this is the belt to that, for a solve on an
2126        // application a caught panic left behind.
2127        self.retry_keeps_declared_box.set(false);
2128        let status = self.optimize_tnlp_dispatch(tnlp, derivative_test_tnlp);
2129        // Printed once, for the run whose point is returned. They used to be
2130        // printed by every audited attempt, so a promoted retry's console
2131        // carried the discarded base attempt's `WARNING:` lines too.
2132        let console_output = match self.options.get_integer_value("print_level", "") {
2133            Ok((v, true)) => v >= 1,
2134            _ => true,
2135        };
2136        if console_output {
2137            for w in &self.statistics.borrow().warnings {
2138                println!("WARNING: {w}");
2139            }
2140        }
2141        status
2142    }
2143
2144    /// The body of [`Self::optimize_tnlp_with_derivative_test_tnlp`].
2145    fn optimize_tnlp_dispatch(
2146        &mut self,
2147        tnlp: Rc<RefCell<dyn TNLP>>,
2148        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2149    ) -> ApplicationReturnStatus {
2150        // gh#884. Both belong to this solve, not to whatever ran before
2151        // it. Reset *here* rather than in `optimize_constrained`, which
2152        // runs once per attempt: the signature accumulates across the
2153        // attempts a lower wrapper may spend, so
2154        // `run_with_dual_divergence_retry` reads "some attempt of the base
2155        // solve saw it" rather than "the last one did".
2156        self.dual_divergence_signature.set(false);
2157        self.obj_scale_refused.set((false, false));
2158        self.dual_divergence_retry_promoted.set(false);
2159        self.answer_restored_from_floor.set(false);
2160        // Same scoping argument as the three above, for the same reason: the
2161        // memo suppresses a REPEATED header within one run, so it must not
2162        // carry across runs. A library caller solving twice on one
2163        // application gets its header both times — which is exactly what the
2164        // guard protects: an outside retry driver re-entering here for another
2165        // attempt is not such a caller, and says so by setting the flag.
2166        if !self.in_retry_sequence.get() {
2167            *self.last_printed_problem_stats.borrow_mut() = None;
2168        }
2169        // gh#486 stage 2: per-variable `scaling_factor` is applied by
2170        // substituting variables one level below the algorithm, since
2171        // the core's scaling models the objective and the constraint
2172        // rows only. The wrapper consumes the variable factors and
2173        // forwards the rest, so `OrigIpoptNlp` sees exactly what it
2174        // has always handled. Installed here because every entry point
2175        // funnels through this method, and only under `user-scaling`,
2176        // the one method that consults the TNLP for factors at all.
2177        let tnlp = match self.install_variable_scaling(tnlp) {
2178            Ok(t) => t,
2179            Err(msg) => {
2180                use pounce_common::journalist::JournalCategory;
2181                eprint!("{msg}");
2182                self.journalist
2183                    .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2184                return ApplicationReturnStatus::InvalidOption;
2185            }
2186        };
2187
2188        // Starting-point conditioning (`start_point_perturbation`,
2189        // `start_point_conditioner`). A no-op unless one is set, and set by
2190        // nothing automatic except the local-infeasibility ladder's third
2191        // rung, which only runs after a solve has already failed.
2192        let tnlp = self.install_start_conditioner(tnlp);
2193        let derivative_test_tnlp = derivative_test_tnlp.as_ref().unwrap_or(&tnlp);
2194
2195        if let Some(value) = self.unsupported_library_solver_selection() {
2196            use pounce_common::journalist::JournalCategory;
2197            self.journalist.print(
2198                JournalLevel::J_ERROR,
2199                JournalCategory::J_MAIN,
2200                &format!(
2201                    "pounce: solver_selection={value} routing is only available \
2202                     through the pounce CLI (.nl input); library consumers can use \
2203                     qp-active-set, nlp, or auto.\n"
2204                ),
2205            );
2206            return ApplicationReturnStatus::InvalidOption;
2207        }
2208
2209        // A `linear_solver` pounce does not implement is refused rather
2210        // than quietly served by FERAL (gh#483 follow-up). Checked here,
2211        // before any work, so a library consumer gets the same verdict the
2212        // CLI gives before its banner.
2213        if let Some(value) = self.unimplemented_linear_solver() {
2214            use pounce_common::journalist::JournalCategory;
2215            let msg = format!("{}\n", Self::unimplemented_linear_solver_message(&value));
2216            eprint!("{msg}");
2217            self.journalist
2218                .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2219            return ApplicationReturnStatus::InvalidOption;
2220        }
2221
2222        // gh#483 follow-up: an option naming a feature pounce does not
2223        // implement is refused, not shrugged off. See
2224        // `unimplemented_options` for how membership was established and
2225        // why an explicitly-set *default* is deliberately still allowed.
2226        // gh#518: same treatment for `option_file_name` on an entry point
2227        // that cannot resolve it. Separate from the table above because
2228        // the *feature* now exists — just not here.
2229        // gh#604: same treatment one level down, for a registered *value*
2230        // of an option pounce otherwise reads (`bound_mult_init_method=
2231        // mu-based`).
2232        // gh#604: and for a convex-engine knob on an entry point that
2233        // cannot route to that engine — `option_file_name`'s case, one
2234        // feature over.
2235        if let Some(msg) = self
2236            .unimplemented_option_refusal()
2237            .or_else(|| self.unimplemented_option_value_refusal())
2238            .or_else(|| self.unhonored_option_file_name())
2239            .or_else(|| self.unhonored_convex_option())
2240        {
2241            use pounce_common::journalist::JournalCategory;
2242            eprintln!("{msg}");
2243            self.journalist.print(
2244                JournalLevel::J_ERROR,
2245                JournalCategory::J_MAIN,
2246                &format!("{msg}\n"),
2247            );
2248            return ApplicationReturnStatus::InvalidOption;
2249        }
2250        // A `ma57_pivtolmax` the user set *below* `ma57_pivtol` is a
2251        // contradiction — the escalation ceiling under its floor — and
2252        // upstream refuses it outright
2253        // (`IpMa57TSolverInterface.cpp:313`, `OPTION_INVALID`). pounce
2254        // used to silently rewrite it to `ma57_pivtol`. That was
2255        // unreachable while gh#825 was live, since no `ma57_*` value
2256        // reached the backend at all, and became reachable the moment
2257        // that was fixed — so it is refused here rather than shipped as
2258        // a new way to be quietly ignored.
2259        if let Some(msg) = self.ma57_pivtol_bracket_refusal() {
2260            use pounce_common::journalist::JournalCategory;
2261            eprintln!("{msg}");
2262            self.journalist.print(
2263                JournalLevel::J_ERROR,
2264                JournalCategory::J_MAIN,
2265                &format!("{msg}\n"),
2266            );
2267            return ApplicationReturnStatus::InvalidOption;
2268        }
2269
2270        let backend_warnings = self.take_unimplemented_backend_warnings();
2271        for warning in self
2272            .unexploited_hint_warnings()
2273            .into_iter()
2274            .chain(backend_warnings)
2275        {
2276            eprintln!("{warning}");
2277        }
2278
2279        // Test before presolve, using the requested coordinate space.
2280        self.run_derivative_test(derivative_test_tnlp);
2281
2282        // Top-level algorithm dispatch (Phase 5b §7.1). When the
2283        // `algorithm` option resolves to "active-set-sqp", route
2284        // to the Phase 5b SQP path; otherwise fall through to the
2285        // existing IPM flow unchanged.
2286        // Materialize generic TNLP presolve once at the public entry point.
2287        // The wrapper owns the submitted callback TNLP, so every algorithm
2288        // path below (including retry paths) continues to postsolve into
2289        // the original user-facing space. With `presolve=no`, this returns
2290        // the exact same Rc unchanged.
2291        let tnlp = if self.presolve_already_applied {
2292            tnlp
2293        } else {
2294            match pounce_presolve::wrap_from_options(tnlp, &self.options) {
2295                Ok(tnlp) => tnlp,
2296                Err(err) => {
2297                    use pounce_common::journalist::JournalCategory;
2298                    self.journalist.print(
2299                        JournalLevel::J_ERROR,
2300                        JournalCategory::J_MAIN,
2301                        &format!("pounce: could not materialize presolve options: {err}\n"),
2302                    );
2303                    return ApplicationReturnStatus::InvalidOption;
2304                }
2305            }
2306        };
2307
2308        if self.is_sqp_algorithm_selected() {
2309            return self.optimize_sqp_tnlp(tnlp);
2310        }
2311        let info = match tnlp.borrow_mut().get_nlp_info() {
2312            Some(info) => info,
2313            None => return ApplicationReturnStatus::InvalidProblemDefinition,
2314        };
2315
2316        // Presolve-certified infeasibility. `get_nlp_info` above is what forces
2317        // the (lazy) presolve init, so this is the first point at which the
2318        // proof exists. If bound propagation or FBBT established that the
2319        // feasible region is empty, there is nothing left to compute: return
2320        // the verdict directly.
2321        //
2322        // Short-circuiting *here*, before dispatch, is deliberate. Running the
2323        // solve anyway would only re-derive a strictly weaker result — a
2324        // stationary point of the constraint violation, which for a nonconvex
2325        // problem proves nothing globally — and would also hand an
2326        // `InfeasibleProblemDetected` to the ℓ₁ auto-fallback below
2327        // (`is_l1_fallback_trigger`), which would then burn a whole second
2328        // solve retrying a problem already proved to have no solution.
2329        //
2330        // Soundness rests on `presolve_infeasibility_proof` returning `Some`
2331        // only for a contradiction derived on an *un-clamped* box — a
2332        // detection made while a Phase-0 auxiliary elimination is in force can
2333        // be an artifact of that elimination and is re-checked after rollback
2334        // before it is certified. See `PresolveState::certified_infeasible`.
2335        if let Some(proof) = tnlp.borrow().presolve_infeasibility_proof() {
2336            use pounce_common::journalist::JournalCategory;
2337            let detail = match proof {
2338                pounce_nlp::tnlp::InfeasibilityProof::BoundPropagation => {
2339                    "bound propagation crossed a variable's bounds".to_string()
2340                }
2341                pounce_nlp::tnlp::InfeasibilityProof::IntervalArithmetic { witness } => {
2342                    format!("interval arithmetic emptied constraint {witness}'s range")
2343                }
2344            };
2345            self.journalist.print(
2346                JournalLevel::J_SUMMARY,
2347                JournalCategory::J_MAIN,
2348                &format!(
2349                    "\nEXIT: Presolve detected the feasible region is empty ({detail}).\n\
2350                     No feasible point exists; the solve was not run.\n"
2351                ),
2352            );
2353            return ApplicationReturnStatus::InfeasibleProblemDetected;
2354        }
2355        // ℓ₁-exact penalty-barrier opt-in (pounce#10).
2356        // Phase 3 wraps the user TNLP and runs an outer Byrd-Nocedal-
2357        // Waltz ρ-escalation loop around the constrained IPM, with a
2358        // honest-infeasibility status upgrade when the slacks fail to
2359        // collapse at saturated ρ. Phase-1/2 one-shot use is preserved
2360        // when `l1_penalty_max_outer_iter == 1`. The wrapper is a
2361        // no-op for problems with no equality rows, so the
2362        // unconstrained dispatch below is unaffected when there is
2363        // nothing to wrap.
2364        if info.m > 0 && self.is_l1_penalty_enabled() {
2365            if let Some(status) = self.run_l1_penalty_outer_loop(Rc::clone(&tnlp)) {
2366                return status;
2367            }
2368            // Falls through: wrapper construction failed (inner refused
2369            // get_nlp_info / get_bounds_info) or no equality rows to
2370            // slack. Standard dispatch runs unmodified.
2371        }
2372        // Phase 3.5 auto-fallback (pounce#10): if the standard solve
2373        // ends in a trigger-class status, retry transparently with
2374        // the wrapper. Promote the retry's status only if it returns
2375        // SolveSucceeded — otherwise return the original. Skipped if
2376        // the user already opted into the wrapper above (this avoids
2377        // a double pass and keeps semantics predictable).
2378        if info.m > 0 && self.is_l1_fallback_enabled() && !self.is_l1_penalty_enabled() {
2379            return self.run_with_l1_fallback(tnlp);
2380        }
2381        // Biactive dual-divergence retry (gh#884): if the solve settles
2382        // its primal while its multipliers run away, throw the iterate
2383        // away and solve again from scratch with the constraint-Jacobian
2384        // perturbation on. Outermost of the two retry wrappers, so its
2385        // "base solve" is the whole standard dispatch below including the
2386        // μ flip — the signature is about a *solve*, and spending the μ
2387        // flip first is strictly cheaper than spending this one first.
2388        let status = if self.is_dual_divergence_retry_enabled() {
2389            self.run_with_dual_divergence_retry(tnlp)
2390        } else {
2391            self.dispatch_standard_solve(tnlp)
2392        };
2393        // gh#983 review item 3: the verdict-level audit runs once, on the
2394        // final verdict, after every retry and fallback has decided.
2395        self.finalize_quality_verdict(status)
2396    }
2397
2398    /// The standard solve dispatch: the μ-strategy fallback if it is
2399    /// enabled, otherwise one `optimize_constrained` call.
2400    ///
2401    /// Factored out of `optimize_tnlp_with_derivative_test_tnlp` so
2402    /// [`Self::run_with_dual_divergence_retry`] can wrap the whole of it
2403    /// rather than only the bare IPM call (gh#884).
2404    fn dispatch_standard_solve(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2405        let status = self.dispatch_standard_solve_inner(Rc::clone(&tnlp));
2406        self.audit_solve_quality(tnlp, status)
2407    }
2408
2409    /// [`Self::dispatch_standard_solve`] without the gh#983 quality audit.
2410    fn dispatch_standard_solve_inner(
2411        &mut self,
2412        tnlp: Rc<RefCell<dyn TNLP>>,
2413    ) -> ApplicationReturnStatus {
2414        // μ-strategy auto-fallback (pounce#138): if the standard solve
2415        // stalls, retry once with the opposite mu_strategy and promote
2416        // only on Solve_Succeeded. Which stalls qualify depends on
2417        // whether the caller asked for the retry — see
2418        // `run_with_mu_strategy_fallback` (pounce#748).
2419        // Applies to constrained and unconstrained alike (both run the
2420        // same IPM). Independent of, and lower priority than, the ℓ₁
2421        // fallback above.
2422        if self.is_mu_strategy_fallback_enabled() {
2423            return self.run_with_mu_strategy_fallback(tnlp);
2424        }
2425        // Every problem — constrained or not — goes through the same
2426        // primal-dual IPM, exactly as upstream Ipopt does. There is no
2427        // separate "unconstrained Newton" path: the linear-solver
2428        // backend (FERAL/MA57) handles the augmented system, so the
2429        // sparse IPM covers `m == 0` at any `n` without a dense-Hessian
2430        // blowup.
2431        self.optimize_constrained(tnlp)
2432    }
2433
2434    /// Read the ℓ₁ wrapper master switch from the OptionsList.
2435    /// Default `false` when the option is not set.
2436    fn is_l1_penalty_enabled(&self) -> bool {
2437        self.options
2438            .get_bool_value("l1_exact_penalty_barrier", "")
2439            .ok()
2440            .and_then(|(v, found)| found.then_some(v))
2441            .unwrap_or(false)
2442    }
2443
2444    fn l1_penalty_init(&self) -> Number {
2445        self.options
2446            .get_numeric_value("l1_penalty_init", "")
2447            .ok()
2448            .and_then(|(v, found)| found.then_some(v))
2449            .unwrap_or(1.0)
2450    }
2451    fn l1_penalty_max(&self) -> Number {
2452        self.options
2453            .get_numeric_value("l1_penalty_max", "")
2454            .ok()
2455            .and_then(|(v, found)| found.then_some(v))
2456            .unwrap_or(1.0e6)
2457    }
2458    fn l1_penalty_increase_factor(&self) -> Number {
2459        self.options
2460            .get_numeric_value("l1_penalty_increase_factor", "")
2461            .ok()
2462            .and_then(|(v, found)| found.then_some(v))
2463            .unwrap_or(8.0)
2464    }
2465    fn l1_penalty_max_outer_iter(&self) -> usize {
2466        self.options
2467            .get_integer_value("l1_penalty_max_outer_iter", "")
2468            .ok()
2469            .and_then(|(v, found)| found.then_some(v))
2470            .unwrap_or(8) as usize
2471    }
2472    fn l1_slack_tol(&self) -> Number {
2473        self.options
2474            .get_numeric_value("l1_slack_tol", "")
2475            .ok()
2476            .and_then(|(v, found)| found.then_some(v))
2477            .unwrap_or(1.0e-6)
2478    }
2479    fn l1_steering_factor(&self) -> Number {
2480        self.options
2481            .get_numeric_value("l1_steering_factor", "")
2482            .ok()
2483            .and_then(|(v, found)| found.then_some(v))
2484            .unwrap_or(10.0)
2485    }
2486    fn is_l1_fallback_enabled(&self) -> bool {
2487        self.options
2488            .get_bool_value("l1_fallback_on_restoration_failure", "")
2489            .ok()
2490            .and_then(|(v, found)| found.then_some(v))
2491            .unwrap_or(false)
2492    }
2493
2494    /// Did the caller set `mu_strategy` explicitly?
2495    ///
2496    /// The answer decides whether the limited-memory default applies
2497    /// (see `algorithm_builder_from_options`): upstream only substitutes
2498    /// `adaptive` for the registered `monotone` when the option is
2499    /// absent from the list.
2500    fn mu_strategy_was_set(&self) -> bool {
2501        matches!(
2502            self.options.get_string_value("mu_strategy", ""),
2503            Ok((_, true))
2504        )
2505    }
2506
2507    /// Did the caller set `mu_strategy_fallback` themselves? Separates
2508    /// the opted-in retry from the default-on one, which triggers on a
2509    /// narrower set of statuses (pounce#748).
2510    ///
2511    /// True for an explicit `no` as well as an explicit `yes`, which is
2512    /// harmless: this is only ever read downstream of
2513    /// [`Self::is_mu_strategy_fallback_enabled`], and an explicit `no`
2514    /// stops there.
2515    fn mu_strategy_fallback_was_set(&self) -> bool {
2516        matches!(
2517            self.options.get_bool_value("mu_strategy_fallback", ""),
2518            Ok((_, true))
2519        )
2520    }
2521
2522    /// Options whose presence means a `Solved_To_Acceptable_Level`
2523    /// exit may be something the *caller* asked for rather than a stall
2524    /// POUNCE fell into (gh #757).
2525    ///
2526    /// Every one of them either moves the bar a certificate has to clear
2527    /// (`tol` and the component tolerances, the `acceptable_*` family),
2528    /// arms a guard that refuses a certificate the iterate would
2529    /// otherwise have earned (`kkt_fidelity_tol`, the certificate-mask
2530    /// and noise-floor kappas, the divergence / infeasibility streaks,
2531    /// the restoration-decline pair).
2532    ///
2533    /// Options that only move the *starting point* are deliberately not
2534    /// here. `least_square_init_primal` was tried and removed: a caller
2535    /// who picks an initialization heuristic has said nothing about what
2536    /// convergence means, and listing it made an explicit `=no` behave
2537    /// differently from omitting the option, which is a distinction the
2538    /// rest of the solver does not draw.
2539    const TERMINATION_POLICY_OPTIONS: &'static [&'static str] = &[
2540        "tol",
2541        "dual_inf_tol",
2542        "constr_viol_tol",
2543        "compl_inf_tol",
2544        "acceptable_tol",
2545        "acceptable_iter",
2546        "acceptable_dual_inf_tol",
2547        "acceptable_constr_viol_tol",
2548        "acceptable_compl_inf_tol",
2549        "acceptable_obj_change_tol",
2550        "kkt_fidelity_tol",
2551        "obj_scale_certificate_threshold",
2552        "dual_inf_scale_kappa",
2553        "primal_noise_floor_kappa",
2554        "dual_diverging_streak",
2555        "infeas_max_streak",
2556        "resto_decline_deferrals",
2557        "resto_decline_progress_ratio",
2558        "neg_curv_escapes",
2559        "limited_memory_ls_failure_restarts",
2560    ];
2561
2562    /// Did the caller set any option from
2563    /// [`Self::TERMINATION_POLICY_OPTIONS`]?
2564    ///
2565    /// This is what separates the two readings of a
2566    /// `Solved_To_Acceptable_Level` exit. Under stock convergence
2567    /// settings it means POUNCE's own schedule parked the dual term
2568    /// above `tol` and a flipped schedule is worth one try. Under a
2569    /// caller-modified one it may be the signal the caller armed the
2570    /// option to receive, and erasing it with a retry is exactly the
2571    /// laundering pounce#748 refused to do by default.
2572    fn caller_set_termination_policy(&self) -> bool {
2573        Self::TERMINATION_POLICY_OPTIONS.iter().any(|name| {
2574            matches!(self.options.get_numeric_value(name, ""), Ok((_, true)))
2575                || matches!(self.options.get_integer_value(name, ""), Ok((_, true)))
2576                || matches!(self.options.get_bool_value(name, ""), Ok((_, true)))
2577                || matches!(self.options.get_string_value(name, ""), Ok((_, true)))
2578        })
2579    }
2580
2581    /// The μ strategy this option table actually resolves to, as
2582    /// `algorithm_builder_from_options` will build it: the explicit
2583    /// value when there is one, otherwise `adaptive` for a
2584    /// limited-memory Hessian and `monotone` for anything else.
2585    ///
2586    /// The fallback below flips *this*, not the registered default —
2587    /// flipping the registered default under limited-memory would
2588    /// "retry" with the strategy that just failed.
2589    fn effective_mu_strategy_is_adaptive(&self) -> bool {
2590        if let Ok((v, true)) = self.options.get_string_value("mu_strategy", "") {
2591            return v == "adaptive";
2592        }
2593        matches!(
2594            self.options.get_string_value("hessian_approximation", ""),
2595            Ok((ref v, true)) if v == "limited-memory"
2596        )
2597    }
2598
2599    /// Read the μ-strategy auto-fallback switch (pounce#138).
2600    ///
2601    /// An explicit setting always wins. Absent one the default is **on**
2602    /// (pounce#748) — but only while the user has not chosen a
2603    /// `mu_strategy` themselves. Retrying under the other schedule is a
2604    /// recovery for a solve that stalled on a strategy POUNCE picked; it
2605    /// is not licence to override a strategy the caller named. Without
2606    /// that condition, flipping the default would silently contaminate
2607    /// every controlled comparison that pins `mu_strategy` on purpose,
2608    /// this repository's own benchmark arms included. The motivating
2609    /// case is unaffected: `dirichlet120` stalls under the
2610    /// limited-memory substitution (pounce#746), which by definition
2611    /// only happens when `mu_strategy` is unset.
2612    fn is_mu_strategy_fallback_enabled(&self) -> bool {
2613        match self.options.get_bool_value("mu_strategy_fallback", "") {
2614            Ok((v, true)) => v,
2615            _ => !self.mu_strategy_was_set() || self.mu_strategy_pounce_chosen,
2616        }
2617    }
2618
2619    /// Record that the `mu_strategy` now in the option table was chosen by a
2620    /// POUNCE frontend, not by the caller (gh#990).
2621    ///
2622    /// The Python path for a problem without `hessian` writes
2623    /// `mu_strategy=monotone` so that gh#746's limited-memory -> adaptive
2624    /// substitution does not read a barrier preference out of a Hessian
2625    /// choice POUNCE made itself. Written as an ordinary option, that pin
2626    /// also read as "the caller named a strategy" to
2627    /// [`Self::is_mu_strategy_fallback_enabled`], which switched off the
2628    /// default-on stall retry (gh#748) on exactly that path — the same
2629    /// set-ness defect the second-opinion ladder's write-backs once had.
2630    /// With this mark the pin still decides the schedule, and the fallback
2631    /// stays on. A frontend calls it only when the caller's own options carry
2632    /// no `mu_strategy`.
2633    pub fn mark_mu_strategy_pounce_chosen(&mut self) {
2634        self.mu_strategy_pounce_chosen = true;
2635    }
2636
2637    /// Has the user set `algorithm = active-set-sqp`? Reads the
2638    /// string option and matches case-insensitively against the
2639    /// design-note §7.1 spelling. Any value other than
2640    /// "active-set-sqp" (including absence) routes to the
2641    /// default IPM path.
2642    /// Stash a warm-start iterate for the SQP path. Consumed by
2643    /// the next `optimize_tnlp` call when the `algorithm` option
2644    /// resolves to `active-set-sqp`; the IPM path ignores it.
2645    /// Phase 5c (§6) — the parametric / MPC warm-start hand-off.
2646    ///
2647    /// The iterate is auto-cleared after use, so a follow-up
2648    /// solve without an intervening `set_sqp_warm_start` call
2649    /// cold-starts.
2650    ///
2651    /// `x`, `lambda_g` and `lambda_x` are in the **caller's** space — what
2652    /// `finalize_solution` reports: full-`n` `x` in model units, `lambda_g`
2653    /// in `g` order on the unscaled Lagrangian `f + λᵀg`, and
2654    /// `lambda_x = z_L − z_U`. The solve maps them into the algorithm's
2655    /// space (fixed variables dropped, `[y_c; y_d]` row order, objective,
2656    /// constraint and per-variable scaling) itself, so a converged solve's
2657    /// reported multipliers can be fed back unchanged. The working set is in
2658    /// the same space: bound statuses full-`n` in variable order (fixed
2659    /// variables' entries are ignored), constraint statuses one per `g` row
2660    /// in the user's row order — exactly what [`Self::last_sqp_working_set`]
2661    /// publishes, so a published set can be fed back as-is.
2662    pub fn set_sqp_warm_start(&mut self, warm: crate::sqp::SqpIterates) {
2663        self.sqp_warm_start = Some(warm);
2664    }
2665
2666    /// Drop any pending warm-start iterate without solving.
2667    pub fn clear_sqp_warm_start(&mut self) {
2668        self.sqp_warm_start = None;
2669    }
2670
2671    /// What the crossover phase did on the most recent solve (gh#612).
2672    ///
2673    /// `None` means crossover never ran — either `crossover=no` (the
2674    /// default) or the solve did not converge. A `Some` whose
2675    /// [`CrossoverReport::accepted`] is false means it ran and *declined*;
2676    /// the two are different facts about a solve and consumers that reason
2677    /// about active-set certainty (sensitivity's AMBIGUOUS class, a
2678    /// downstream `var_status`) need to tell them apart.
2679    ///
2680    /// [`CrossoverReport::accepted`]: crate::crossover::CrossoverReport::accepted
2681    pub fn crossover_report(&self) -> Option<&crate::crossover::CrossoverReport> {
2682        self.crossover_report.as_ref()
2683    }
2684
2685    /// Install a full primal-dual warm-start iterate for the next IPM
2686    /// `optimize_tnlp`. Captured by the debugger's `resolve` so the
2687    /// re-solve continues from the paused interior point. The caller is
2688    /// responsible for also enabling `warm_start_init_point=yes` (and
2689    /// usually `warm_start_target_mu=<μ>`) so the re-optimize branch of
2690    /// `WarmStartIterateInitializer` preserves the installed iterate.
2691    /// Consumed once per solve, then auto-cleared.
2692    pub fn set_warm_start_iterate(&mut self, snap: crate::debug::IterateSnapshot) {
2693        self.warm_start_iterate = Some(snap);
2694    }
2695
2696    /// Install a caller-supplied fill-reducing permutation for the KKT
2697    /// linear solver (pounce#180 item 1). The next `optimize_*` builds
2698    /// the FERAL backend with [`pounce_feral::OrderingMethod::External`],
2699    /// overriding the `feral_ordering` string option / env var. Use this
2700    /// to inject a block-triangular / Schur ordering a generic algorithm
2701    /// cannot see (Parker, Garcia & Bent, arXiv:2602.17968) or a tearing
2702    /// ordering from equation-oriented decomposition.
2703    ///
2704    /// `perm` is a **0-based, new-to-old permutation** (`perm[k]` is the
2705    /// original index that becomes index `k`), and its length must equal
2706    /// the augmented KKT system dimension (variables + slacks +
2707    /// constraint duals), *not* the problem's `n`. A wrong length or a
2708    /// non-bijection is rejected by FERAL at the first factorization with
2709    /// an `InvalidInput` error (never a panic), surfacing as a solver
2710    /// failure rather than a silently-wrong solve — the ordering only
2711    /// affects fill/time, never the computed solution.
2712    ///
2713    /// Persistent config: unlike the warm-start hooks it is *not*
2714    /// auto-cleared after a solve. Call [`Self::clear_external_ordering`]
2715    /// to drop it. Ignored by non-FERAL backends and by any custom
2716    /// factory plugged via [`Self::set_linear_backend_factory`].
2717    pub fn set_external_ordering(&mut self, perm: Vec<usize>) {
2718        self.external_ordering = Some(perm);
2719    }
2720
2721    /// Drop any installed external KKT ordering, restoring the
2722    /// `feral_ordering`-driven default for subsequent solves.
2723    pub fn clear_external_ordering(&mut self) {
2724        self.external_ordering = None;
2725    }
2726
2727    /// The currently-installed external KKT ordering, if any.
2728    pub fn external_ordering(&self) -> Option<&[usize]> {
2729        self.external_ordering.as_deref()
2730    }
2731
2732    /// Install a block-triangular / Schur KKT partition (pounce#180 item 2).
2733    /// `indices` are KKT-space indices (`0..dim` in the `x, s, c, d` block
2734    /// order the aug-system solver assembles) naming the Schur block `S`; that
2735    /// block is Schur-complemented out and only the two diagonal blocks are
2736    /// factorized (inertia via Sylvester's law). Honored on the IPM + feral +
2737    /// exact-Hessian path; the Schur solver falls back to the standard
2738    /// full-space solver transparently when the partition is unsuitable (too
2739    /// large a fraction of the system, malformed, or a backend error), so a
2740    /// stray hook never breaks a solve. Persistent config (not auto-cleared);
2741    /// drop it via [`Self::clear_kkt_schur_block`].
2742    /// Declare the block structure in the **model's own terms**: one block id
2743    /// per variable and per constraint, negative for the shared ones
2744    /// (structured-KKT Phase 5b). Blocks must couple only through the shared
2745    /// entries; the solver checks that against the assembled KKT and falls
2746    /// back when it does not hold.
2747    ///
2748    /// This is the form a model can produce — "`pg[g]` is shared, everything
2749    /// in contingency `k` is block `k`" — and pounce maps it to KKT indices
2750    /// itself, accounting for fixed variables and the equality / inequality
2751    /// split. Lengths are the problem's own `n` and `m`; a mismatch is
2752    /// reported and the solve proceeds monolithically.
2753    ///
2754    /// Persistent config; drop it with [`Self::clear_block_structure`].
2755    pub fn set_block_structure(&mut self, var_blocks: Vec<i32>, con_blocks: Vec<i32>) {
2756        self.model_blocks = Some((var_blocks, con_blocks));
2757    }
2758
2759    /// Drop any declared model-space block structure.
2760    pub fn clear_block_structure(&mut self) {
2761        self.model_blocks = None;
2762    }
2763
2764    /// The declared model-space block structure, if any.
2765    pub fn block_structure(&self) -> Option<(&[i32], &[i32])> {
2766        self.model_blocks
2767            .as_ref()
2768            .map(|(v, c)| (v.as_slice(), c.as_slice()))
2769    }
2770
2771    /// Install a block-parallel KKT partition (structured-KKT Phase 5b).
2772    /// `labels` are KKT-space block ids in the solver's internal
2773    /// `x, slack, eq-dual, ineq-dual` order, `< 0` for the shared border; an
2774    /// **empty** vector asks the solver to detect the structure from the
2775    /// assembled KKT. Honored on the IPM + feral + exact-Hessian path, with a
2776    /// transparent fallback to the standard solver when the partition does not
2777    /// match the matrix. Persistent config; drop it with
2778    /// [`Self::clear_kkt_block_structure`].
2779    pub fn set_kkt_block_structure(&mut self, labels: Vec<i32>) {
2780        self.kkt_blocks = Some(labels);
2781    }
2782
2783    /// Drop any installed block partition.
2784    pub fn clear_kkt_block_structure(&mut self) {
2785        self.kkt_blocks = None;
2786    }
2787
2788    /// The currently-installed block partition, if any.
2789    pub fn kkt_block_structure(&self) -> Option<&[i32]> {
2790        self.kkt_blocks.as_deref()
2791    }
2792
2793    pub fn set_kkt_schur_block(&mut self, indices: Vec<usize>) {
2794        self.kkt_schur_block = Some(indices);
2795    }
2796
2797    /// Drop any installed Schur KKT partition, restoring the standard
2798    /// full-space solver for subsequent solves.
2799    pub fn clear_kkt_schur_block(&mut self) {
2800        self.kkt_schur_block = None;
2801    }
2802
2803    /// The currently-installed Schur KKT partition, if any.
2804    pub fn kkt_schur_block(&self) -> Option<&[usize]> {
2805        self.kkt_schur_block.as_deref()
2806    }
2807
2808    /// Return the final QP working set from the most recent SQP
2809    /// solve, or `None` if the last solve wasn't SQP, didn't
2810    /// produce a working set (cold-start declared the iterate
2811    /// optimal before solving any QP), or no SQP solve has run.
2812    ///
2813    /// The set is in the **caller's** index spaces, the ones
2814    /// `finalize_solution` uses: `bounds[j]` is variable `j` of the full
2815    /// `n` (a variable `fixed_variable_treatment = make_parameter` removed
2816    /// reads `Fixed`), and `constraints[i]` is `g` row `i` in the model's
2817    /// own row order — not the SQP's internal equalities-first order. It is
2818    /// the form [`Self::set_sqp_warm_start`] takes back.
2819    pub fn last_sqp_working_set(&self) -> Option<&pounce_qp::WorkingSet> {
2820        self.sqp_last_working_set.as_ref()
2821    }
2822
2823    /// A working set computed in the solve's algorithm space, mapped to the
2824    /// caller's: bound statuses lifted to the full variable vector (gh#986
2825    /// review item 10 — fixed variables are `Fixed`), constraint statuses
2826    /// moved from the algorithm's `[c; d]` row order (equalities first) to
2827    /// the user's `g` row order through the NLP's `c_map` / `d_map`. A
2828    /// bound vector that is not reduced-sized is left as it is.
2829    fn working_set_to_user(
2830        &self,
2831        nlp: &dyn IpoptNlp,
2832        ws: pounce_qp::WorkingSet,
2833    ) -> pounce_qp::WorkingSet {
2834        let bounds = match &self.x_elimination {
2835            Some((map, n_full)) if ws.bounds.len() == map.len() && map.len() != *n_full => {
2836                let mut bounds = vec![pounce_qp::BoundStatus::Fixed; *n_full];
2837                for (k, &j) in map.iter().enumerate() {
2838                    bounds[j as usize] = ws.bounds[k];
2839                }
2840                bounds
2841            }
2842            _ => ws.bounds,
2843        };
2844        pounce_qp::WorkingSet {
2845            bounds,
2846            constraints: working_set_rows_to_user(nlp, ws.constraints),
2847        }
2848    }
2849
2850    /// If `solver_selection` is explicitly set to a value whose routing lives
2851    /// only in the CLI's `.nl` dispatch, return  it; otherwise `None`.
2852    /// `optimize_tnlp` uses this to reject a forced convex selection a library
2853    /// consumer cannot honor.
2854    fn unsupported_library_solver_selection(&self) -> Option<&'static str> {
2855        let (v, found) = self.options.get_string_value("solver_selection", "").ok()?;
2856        if !found {
2857            return None;
2858        }
2859        ["lp-ipm", "qp-ipm", "socp"]
2860            .into_iter()
2861            .find(|c| v.eq_ignore_ascii_case(c))
2862    }
2863
2864    /// The `linear_solver` value when the caller explicitly asked for a
2865    /// backend pounce does not implement; `None` when the request can be
2866    /// served (or was never made).
2867    ///
2868    /// pounce ships two: **FERAL** (pure Rust, the effective default) and
2869    /// **MA57** (HSL, behind the `ma57` feature). The option's valid-value
2870    /// list is a faithful port of upstream Ipopt's — `ma27`, `ma77`,
2871    /// `ma86`, `ma97`, `mumps`, `pardiso`, `pardisomkl`, `spral`, `wsmp`,
2872    /// `custom` — so an `ipopt.opt` written for Ipopt parses here, and
2873    /// every one of those names used to fall through a `_ =>` arm to
2874    /// FERAL. A run "using MUMPS" was a FERAL run; a benchmark comparing
2875    /// backends compared FERAL with itself (gh#483 follow-up).
2876    ///
2877    /// The registered default is `feral`, which pounce implements, so no
2878    /// explicit-vs-default distinction is needed: whatever the option
2879    /// resolves to must be a backend that exists. (It is checked
2880    /// unconditionally on purpose — a future default naming something
2881    /// unimplemented should trip this, not slip past it.)
2882    ///
2883    /// Explicit `ma57` on a build that lacks the feature is *not* refused;
2884    /// that fallback is reported in the banner ("ma57 requested but not
2885    /// compiled"), so it is visible rather than silent, and failing a
2886    /// portable `ipopt.opt` over a build flag would cost more than it buys.
2887    pub fn unimplemented_linear_solver(&self) -> Option<String> {
2888        let (v, _) = self.options.get_string_value("linear_solver", "").ok()?;
2889        ["feral", "ma57"]
2890            .iter()
2891            .all(|ok| !v.eq_ignore_ascii_case(ok))
2892            .then_some(v)
2893    }
2894
2895    /// The message for the first option the caller set that names a
2896    /// feature pounce does not implement, or `None`. Public so the CLI
2897    /// can refuse before routing — the convex dispatch never reaches
2898    /// `optimize_tnlp`. See [`crate::unimplemented_options`].
2899    ///
2900    /// A run configuring nothing but backends pounce does not ship is
2901    /// refused here too, after the per-option table has had its say —
2902    /// see [`crate::unimplemented_options::backend_only_refusal`]. It
2903    /// is folded in rather than given its own accessor so that every
2904    /// surface already refusing on this method refuses on it as well;
2905    /// the CLI is not the only frontend, and a condition worth failing
2906    /// on is not worth failing on only from the CLI.
2907    pub fn unimplemented_option_refusal(&self) -> Option<String> {
2908        crate::unimplemented_options::refusal(&self.options, &self.reg_options).or_else(|| {
2909            crate::unimplemented_options::backend_only_refusal(&self.options, &self.reg_options)
2910        })
2911    }
2912
2913    /// The message for the first string option the caller set to a
2914    /// registered *value* pounce does not implement, or `None`.
2915    ///
2916    /// Separate from [`Self::unimplemented_option_refusal`] because the
2917    /// option itself is read and its other values work — it is one mode
2918    /// that is missing, not the feature. See
2919    /// [`crate::unimplemented_options::UNIMPLEMENTED_VALUES`].
2920    pub fn unimplemented_option_value_refusal(&self) -> Option<String> {
2921        crate::unimplemented_options::value_refusal(&self.options)
2922    }
2923
2924    /// `option_file_name` set on a surface that never resolves it.
2925    ///
2926    /// The option reaches a file through exactly one path —
2927    /// [`Self::initialize_with_option_file`], which the `pounce` CLI
2928    /// drives. A library caller (Python, the C interface, WASM) sets its
2929    /// options directly and calls no such thing, so on those surfaces the
2930    /// option names a whole configuration and applies none of it: gh#518's
2931    /// failure mode, one surface over. It used to be caught by the blanket
2932    /// [`crate::unimplemented_options`] refusal, which no longer covers it
2933    /// now that the feature exists; this keeps the guard exactly where the
2934    /// feature still doesn't.
2935    ///
2936    /// Deliberately *not* fixed by having the library read an options file
2937    /// too: an implicit `./ipopt.opt` lookup under Python or the GAMS C
2938    /// link would be a surprising action at a distance, and `pounce.opt`
2939    /// already means something else to GAMS.
2940    pub fn unhonored_option_file_name(&self) -> Option<String> {
2941        if self.option_file_resolved {
2942            return None;
2943        }
2944        // Same default gate as the table: an explicitly-set *default*
2945        // asks for nothing, so it must not fail. `option_file_name`
2946        // defaults to `ipopt.opt`, and a caller round-tripping a full
2947        // option dump — or a generated config that spells out every
2948        // registered name — hits that value without asking for anything.
2949        if !crate::unimplemented_options::set_to_a_non_default(
2950            &self.options,
2951            &self.reg_options,
2952            "option_file_name",
2953        ) {
2954            return None;
2955        }
2956        match self.options.get_string_value("option_file_name", "") {
2957            Ok((name, true)) if !name.is_empty() => Some(format!(
2958                "pounce: `option_file_name` was set to `{name}`, but this entry \
2959                 point does not read options files — it would configure nothing. \
2960                 The `pounce` CLI honors it (and `./pounce.opt` / `./ipopt.opt`); \
2961                 from a library, read the file yourself and pass its contents to \
2962                 `initialize_with_options_str`, or set the options directly. \
2963                 Tracking issue: https://github.com/jkitchin/pounce/issues/518"
2964            )),
2965            _ => None,
2966        }
2967    }
2968
2969    /// Declare that this caller can route a model to the convex LP/QP /
2970    /// SOCP engines, so the `qp_*` knobs they read configure something.
2971    ///
2972    /// The `pounce` CLI calls this: it owns the `.nl` structure
2973    /// extraction that classifies a model, which is the whole of what
2974    /// `solver_selection`'s convex values need. No library frontend can
2975    /// (see [`Self::unsupported_library_solver_selection`]), so the
2976    /// default is `false` and [`Self::unhonored_convex_option`] refuses
2977    /// the knobs there.
2978    ///
2979    /// Declaring it also covers the CLI's *fallback*: a convex attempt
2980    /// that returns no verified point hands the model to
2981    /// [`Self::optimize_tnlp`], and the `qp_*` values it was given
2982    /// configured that attempt for real. Refusing them at the handoff
2983    /// would fail a run that used them.
2984    pub fn set_convex_routing_available(&mut self, available: bool) {
2985        self.convex_routing_available = available;
2986    }
2987
2988    /// The convex LP/QP knobs are registered core-side so every frontend
2989    /// parses them — but only the CLI can reach the engines that read
2990    /// them. On any other entry point the option names a whole
2991    /// configuration and applies none of it; this is the message that
2992    /// says so, in place of the silence.
2993    ///
2994    /// gh#604. Same shape and same default gate as
2995    /// [`Self::unhonored_option_file_name`]: an explicitly-set *default*
2996    /// asks for nothing and must keep working, so only a value that
2997    /// differs is refused.
2998    pub fn unhonored_convex_option(&self) -> Option<String> {
2999        if self.convex_routing_available {
3000            return None;
3001        }
3002        const CONVEX_ONLY: &[&str] = &[
3003            "qp_presolve",
3004            "qp_tau",
3005            "qp_tau_max",
3006            "qp_reg",
3007            "qp_gondzio_corr",
3008            "qp_infeas_tol",
3009            "qp_hsde",
3010            "qp_equilibrate",
3011            "qp_crossover",
3012        ];
3013        let name = CONVEX_ONLY.iter().find(|name| {
3014            crate::unimplemented_options::set_to_a_non_default(
3015                &self.options,
3016                &self.reg_options,
3017                name,
3018            )
3019        })?;
3020        Some(format!(
3021            "pounce: `{name}` tunes the convex LP/QP interior-point engine, but \
3022             this entry point cannot route a model to it — the option would \
3023             configure nothing. The `pounce` CLI reaches that engine on `.nl` \
3024             input (`solver_selection=lp-ipm` / `qp-ipm` / `socp`, or `auto` on \
3025             a model that classifies as one); the `qp_*` options themselves are \
3026             read only there and by `pounce.solve_qp`. From Python, \
3027             `pounce.solve_qp` drives the engine directly and takes `qp_presolve`, \
3028             `qp_reg`, `qp_hsde`, `qp_equilibrate` and `qp_crossover` as keyword \
3029             arguments (presolve is off there unless asked for). \
3030             On this path, `solver_selection=qp-active-set` \
3031             (or `algorithm=active-set-sqp`) is the nearest thing, tuned by the \
3032             `sqp_qp_*` options. Tracking issue: \
3033             https://github.com/jkitchin/pounce/issues/604"
3034        ))
3035    }
3036
3037    /// Warnings for caching hints pounce does not exploit. These never
3038    /// block a solve: the answer is identical either way, so refusing
3039    /// would cost the caller more than the silence did.
3040    pub fn unexploited_hint_warnings(&self) -> Vec<String> {
3041        crate::unimplemented_options::hint_warnings(&self.options, &self.reg_options)
3042    }
3043
3044    /// Warnings for the constant-derivative hints when the solve routes to
3045    /// `pounce-convex` instead of here. Call site is the convex dispatch
3046    /// in the CLI, next to the other guards that live there for the same
3047    /// reason: that dispatch never reaches [`Self::optimize_tnlp`], so
3048    /// `install_constant_derivative_hints` never runs and the hints are
3049    /// unread. On the NLP route they are honoured, so this must not be
3050    /// called there.
3051    pub fn convex_unexploited_hint_warnings(&self) -> Vec<String> {
3052        crate::unimplemented_options::convex_hint_warnings(&self.options, &self.reg_options)
3053    }
3054
3055    /// Which of the four constant-derivative hints the caller actually
3056    /// asserted, in [`pounce_nlp::constant_derivatives::HINT_OPTIONS`]
3057    /// order — the order [`reconcile`] pairs against the model's own
3058    /// proofs.
3059    ///
3060    /// Each name is read as a literal rather than through the loop
3061    /// variable the caller used to use. The registered-but-unread scan
3062    /// (`tests/no_silent_options.rs`) keys on the option name as it
3063    /// appears at the accessor, so `get_bool_value(name, "")` over an
3064    /// array read as "no key here" and left all four sitting in the
3065    /// silent list while they were fully wired and consumed (#551 /
3066    /// #677).
3067    ///
3068    /// Matching over `HINT_OPTIONS` rather than writing a bare array
3069    /// keeps the slots right by construction, and a fifth hint added to
3070    /// `HINT_OPTIONS` trips the fallback arm instead of silently reading
3071    /// as "not asserted" — which is the failure mode this whole line of
3072    /// work exists to kill.
3073    fn asserted_constant_derivative_hints(&self) -> [bool; 4] {
3074        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
3075        let read_yes = |key: &str| matches!(self.options.get_bool_value(key, ""), Ok((true, true)));
3076        HINT_OPTIONS.map(|name| match name {
3077            "grad_f_constant" => read_yes("grad_f_constant"),
3078            "hessian_constant" => read_yes("hessian_constant"),
3079            "jac_c_constant" => read_yes("jac_c_constant"),
3080            "jac_d_constant" => read_yes("jac_d_constant"),
3081            other => unreachable!("`{other}` is in HINT_OPTIONS with no read site"),
3082        })
3083    }
3084
3085    /// Resolve the four constant-derivative hints for this solve and
3086    /// install the result on the NLP (gh #588, phase Q6).
3087    ///
3088    /// `grad_f_constant` / `hessian_constant` / `jac_c_constant` /
3089    /// `jac_d_constant` are, upstream, unchecked user assertions: Ipopt
3090    /// reuses the derivative and returns a wrong answer if the assertion
3091    /// was false. pounce asks the model first. Where the model *proves*
3092    /// the derivative constant, the reuse happens whether or not the
3093    /// option was set — the hint is redundant. Where the model proves it
3094    /// **varies** and the option was set anyway, the option is refused
3095    /// with a warning, which is the deliberate divergence. Where the
3096    /// model can prove nothing — every callback front end, both GAMS
3097    /// links — the user's assertion is honoured on trust, exactly as
3098    /// upstream, because "unproved" is not "disproved" and silently
3099    /// overriding the caller there would be its own wrong answer.
3100    fn install_constant_derivative_hints(&self, orig_nlp: &mut OrigIpoptNlp) {
3101        use pounce_common::journalist::JournalCategory;
3102        use pounce_nlp::constant_derivatives::reconcile;
3103
3104        // Each name is read as a literal rather than through the loop
3105        // variable: the registered-but-unread scan
3106        // (`tests/no_silent_options.rs`) keys on the option name as it
3107        // appears at the accessor, so `get_bool_value(name, "")` read as
3108        // "no key here" and left all four of these sitting in the silent
3109        // list while they were fully wired and consumed (#551 / #677).
3110        //
3111        // Matching over `HINT_OPTIONS` rather than writing a bare array
3112        // keeps the order right by construction — `reconcile` pairs
3113        // `asserted[k]` with `proofs[k]` — and a fifth hint added to
3114        // `HINT_OPTIONS` trips the fallback arm instead of silently
3115        // reading as "not asserted", which is the failure mode this
3116        // whole line of work exists to kill.
3117        let asserted = self.asserted_constant_derivative_hints();
3118        let proofs = orig_nlp.derivative_proofs();
3119        let (outcomes, enabled) = reconcile(proofs, asserted);
3120
3121        for outcome in &outcomes {
3122            if let Some(warning) = outcome.warning() {
3123                eprintln!("{warning}");
3124                self.journalist.print(
3125                    JournalLevel::J_STRONGWARNING,
3126                    JournalCategory::J_MAIN,
3127                    &format!("{warning}\n"),
3128                );
3129            }
3130        }
3131        if std::env::var("POUNCE_DBG_CONSTDERIV").is_ok() {
3132            for outcome in &outcomes {
3133                eprintln!(
3134                    "[const deriv] {:<15} proof={:?} asserted={} reused={}",
3135                    outcome.name, outcome.proof, outcome.asserted, outcome.honoured,
3136                );
3137            }
3138        }
3139        orig_nlp.set_constant_derivatives(enabled);
3140    }
3141
3142    /// Warnings for knobs of a linear-solver backend pounce does not
3143    /// ship (`ma97_*`, `pardiso_*`, …), one line per backend family.
3144    ///
3145    /// Warnings and not refusals: an `ipopt.opt` carrying settings for
3146    /// several backends so that one file runs everywhere is exactly what
3147    /// the registry exists to accept, and refusing it would fail a run
3148    /// over knobs it never touches. See the "Backend knobs warn, they do
3149    /// not refuse" section of [`crate::unimplemented_options`]. gh#551.
3150    pub fn unimplemented_backend_warnings(&self) -> Vec<String> {
3151        crate::unimplemented_options::backend_warnings(&self.options, &self.reg_options)
3152    }
3153
3154    /// The same warnings, but at most once per application: the second
3155    /// caller gets nothing.
3156    ///
3157    /// Two sites emit them — the CLI, before routing, because a convex
3158    /// model never reaches [`Self::optimize_tnlp`], and `optimize_tnlp`
3159    /// itself, for every frontend that is not the CLI. A CLI run passes
3160    /// through both, and printing the identical paragraph twice is how a
3161    /// warning teaches its reader to skip warnings.
3162    pub fn take_unimplemented_backend_warnings(&mut self) -> Vec<String> {
3163        if self.backend_warnings_emitted {
3164            return Vec::new();
3165        }
3166        self.backend_warnings_emitted = true;
3167        self.unimplemented_backend_warnings()
3168    }
3169
3170    /// Resolve the five registered `derivative_test*` knobs. Every one
3171    /// of them was registered and never read, so `derivative_test=
3172    /// first-order` ran no test and printed nothing — a checker that
3173    /// silently checks nothing reports success by omission (gh#483
3174    /// follow-up).
3175    ///
3176    /// The numeric helper is named `read_num` to match the accessor
3177    /// idiom the rest of this file uses: the registered-but-unread scan
3178    /// (`tests/no_silent_options.rs`) discovers `read_*` helpers and the
3179    /// literal key passed to them, so a differently-named local closure
3180    /// made `derivative_test_perturbation` and `derivative_test_tol`
3181    /// read as silent when they are wired and consumed (#677, #551).
3182    fn derivative_test_options(&self) -> DerivativeTestOptions {
3183        let read_num = |key: &str, default: Number| -> Number {
3184            self.options
3185                .get_numeric_value(key, "")
3186                .ok()
3187                .and_then(|(v, f)| f.then_some(v))
3188                .unwrap_or(default)
3189        };
3190        DerivativeTestOptions {
3191            mode: self
3192                .options
3193                .get_string_value("derivative_test", "")
3194                .ok()
3195                .and_then(|(v, f)| f.then_some(v))
3196                .map(|v| DerivativeTest::from_option(&v))
3197                .unwrap_or_default(),
3198            perturbation: read_num("derivative_test_perturbation", 1e-8),
3199            tol: read_num("derivative_test_tol", 1e-4),
3200            first_index: self
3201                .options
3202                .get_integer_value("derivative_test_first_index", "")
3203                .ok()
3204                .and_then(|(v, f)| f.then_some(v))
3205                .unwrap_or(-2),
3206            print_all: self
3207                .options
3208                .get_bool_value("derivative_test_print_all", "")
3209                .ok()
3210                .and_then(|(v, f)| f.then_some(v))
3211                .unwrap_or(false),
3212        }
3213    }
3214
3215    /// The derivative checker's structured verdict from the most recent
3216    /// [`Self::run_derivative_test`], or `None` when no test ran (gh#990).
3217    /// The IPM and SQP drains copy it into `SolveStatistics`; a caller that
3218    /// builds its own report (the CLI's convex route) reads it here.
3219    pub fn derivative_check(&self) -> Option<pounce_nlp::derivative_test::DerivativeCheckSummary> {
3220        self.derivative_check.borrow().clone()
3221    }
3222
3223    /// Run the derivative checker, if requested, against `tnlp`.
3224    ///
3225    /// Advisory, like upstream: a suspicious entry is reported and the
3226    /// solve continues. The report goes to stderr so it survives
3227    /// `print_level=0` and leaves `--json-output`'s stdout clean.
3228    pub fn run_derivative_test(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
3229        // gh#990 item 3: the structured result belongs to this solve; a solve
3230        // that asks for no test must not inherit the previous one's.
3231        *self.derivative_check.borrow_mut() = None;
3232        let opts = self.derivative_test_options();
3233        if matches!(opts.mode, DerivativeTest::None) {
3234            return;
3235        }
3236        let report = {
3237            let mut borrowed = tnlp.borrow_mut();
3238            pounce_nlp::derivative_test::run(&mut *borrowed, &opts)
3239        };
3240        let Some(report) = report else {
3241            eprintln!(
3242                "pounce: derivative_test was requested but the TNLP declined to \
3243                 supply the information the check needs (dimensions, bounds, or \
3244                 a starting point); no test was run."
3245            );
3246            return;
3247        };
3248        *self.derivative_check.borrow_mut() = Some(report.summary.clone());
3249        use pounce_common::journalist::JournalCategory;
3250        for line in &report.lines {
3251            eprintln!("{line}");
3252            self.journalist.print(
3253                JournalLevel::J_SUMMARY,
3254                JournalCategory::J_MAIN,
3255                &format!("{line}\n"),
3256            );
3257        }
3258    }
3259
3260    /// The message [`Self::unimplemented_linear_solver`] earns, shared by
3261    /// every frontend so they cannot drift apart.
3262    pub fn unimplemented_linear_solver_message(value: &str) -> String {
3263        format!(
3264            "pounce: linear_solver={value} is not implemented. pounce provides \
3265             `feral` (pure-Rust sparse symmetric, the default) and `ma57` (HSL, \
3266             in a `--features ma57` build); the other names in the option's \
3267             list come from the upstream Ipopt registry so an ipopt.opt written \
3268             for Ipopt still parses. Selecting one used to run FERAL silently, \
3269             which makes a backend comparison measure nothing — so it is \
3270             refused instead. Use linear_solver=feral or linear_solver=ma57."
3271        )
3272    }
3273
3274    /// Will the next `optimize_tnlp` run the active-set SQP driver rather
3275    /// than the interior-point one?
3276    ///
3277    /// Public because the dispatch decision has to be *reportable*, not just
3278    /// taken: before this was reachable, the CLI's `Selected solver:` line
3279    /// and the JSON report's `solution.engine` both named the filter-IPM on
3280    /// every `algorithm=active-set-sqp` run, because the only thing either
3281    /// consulted was `solver_selection` — which is `auto` on a general NLP
3282    /// however the `algorithm` option is set. Reading the same predicate
3283    /// `optimize_tnlp` dispatches on is what keeps the report and the run
3284    /// from disagreeing; deriving it a second time in the CLI is how they
3285    /// drifted in the first place.
3286    pub fn is_sqp_algorithm_selected(&self) -> bool {
3287        // `algorithm` is the primary selector.
3288        // `solver_selection = qp-active-set` selects the
3289        // same active-set SQP engine.
3290        let algo_sqp = matches!(
3291            self.options.get_string_value("algorithm", ""),
3292            Ok((v, true)) if v.eq_ignore_ascii_case("active-set-sqp")
3293        );
3294        let selection_sqp = matches!(
3295            self.options.get_string_value("solver_selection", ""),
3296            Ok((v, true)) if v.eq_ignore_ascii_case("qp-active-set")
3297        );
3298        algo_sqp || selection_sqp
3299    }
3300
3301    /// Phase 5b SQP entry point. Builds the same NLP chain
3302    /// (`TNLPAdapter` → `OrigIpoptNlp` → `IpoptNlpAdapter`) the
3303    /// IPM uses, then runs `SqpAlgorithm::optimize`. Maps the
3304    /// `SqpResult.status` back to `ApplicationReturnStatus` and
3305    /// hands the final iterate to the user TNLP's
3306    /// `finalize_solution` callback via `finalize_via_sqp`.
3307    fn optimize_sqp_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
3308        use pounce_nlp::ConstObjScaling;
3309        use pounce_nlp::orig_ipopt_nlp::OrigIpoptNlp;
3310        use pounce_nlp::tnlp_adapter::TNLPAdapter;
3311
3312        // Wall-clock for the whole SQP solve, mirroring the IPM path's
3313        // `t_start` (see the `total_wallclock_time_secs` assignment in
3314        // `optimize_tnlp`). Without this the field stayed at its struct
3315        // default of 0.0 on every active-set solve, so `--json-output`
3316        // reported an instantaneous solve regardless of actual runtime and
3317        // the engine could not be speed-compared against qp-ipm at all
3318        // (benchmarks/scripts/compare_qp_four_way.py had to skip the column).
3319        let t_start = std::time::Instant::now();
3320
3321        // `new_with_options`, not `new`: the latter hard-codes the same three
3322        // defaults, so `fixed_variable_treatment`, `nlp_lower_bound_inf` and
3323        // `nlp_upper_bound_inf` were accepted and discarded on this arm. The
3324        // defaults coincide, which is why it went unnoticed — it diverges only
3325        // for a caller who sets one, and then the two arms CLASSIFY THE MODEL
3326        // DIFFERENTLY: a bound at the caller's own infinity threshold is a
3327        // bound here and no bound there, and a fixed variable is eliminated on
3328        // one arm and relaxed on the other. That is a different problem, not a
3329        // different trajectory on one.
3330        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
3331        let adapter = match TNLPAdapter::new_with_options(
3332            Rc::clone(&tnlp),
3333            lo_inf,
3334            up_inf,
3335            fixed_treatment,
3336        ) {
3337            Ok(a) => Rc::new(RefCell::new(a)),
3338            Err(_) => return ApplicationReturnStatus::InvalidProblemDefinition,
3339        };
3340        // The SQP path never runs gradient-based scaling, but the
3341        // constant `obj_scaling_factor` (negative ⇒ maximize) still
3342        // applies via the OrigIpoptNlp constructor.
3343        let obj_scaling_factor = self
3344            .options
3345            .get_numeric_value("obj_scaling_factor", "")
3346            .ok()
3347            .and_then(|(v, f)| f.then_some(v))
3348            .unwrap_or(1.0);
3349        let mut orig_nlp = match OrigIpoptNlp::new(
3350            Rc::clone(&adapter),
3351            Rc::new(ConstObjScaling(obj_scaling_factor)),
3352        ) {
3353            Ok(n) => n,
3354            Err(_) => return ApplicationReturnStatus::InternalError,
3355        };
3356        // Same Q6 reconciliation as the IPM route: the SQP driver
3357        // evaluates the same derivatives through the same NLP object.
3358        self.install_constant_derivative_hints(&mut orig_nlp);
3359        // `bound_relax_factor`, on the convex arm's rule (gh#745's
3360        // `convex_bound_relax`), because this arm's position is the convex
3361        // arm's and not the interior-point arm's.
3362        //
3363        // The widening is a change to the MODEL, and its error is one-signed:
3364        // enlarging the feasible set can only flatter the objective, by `δ`
3365        // times the bound's multiplier, with nothing bounding that product and
3366        // no amount of tightening `tol` closing it. On `LISWET1` it buys `9.0`
3367        // of objective (`27.1221` against the true `36.1224`); over the
3368        // 91-instance netlib LP corpus, dropping it took the median objective
3369        // error from `1.2e-08` to `3.8e-11`.
3370        //
3371        // The interior-point arm keeps it and must: it is a feasible-iterate
3372        // log-barrier that needs `x` strictly inside its bounds, and matching
3373        // Ipopt is that arm's contract — the fixture sweep at
3374        // `bound_relax_factor=0` turns `square_flowsheet_resto` into
3375        // `InfeasibleProblemDetected`. An active-set QP needs none of it: its
3376        // iterates are feasible for the box by construction, which is why this
3377        // arm has always run un-widened without incident.
3378        //
3379        // So: unset means solve the model as declared, which is what this arm
3380        // already did. What it did NOT do is honour an explicit request — the
3381        // option was accepted and discarded, the gh#677 shape, and a caller
3382        // comparing arms under a named `bound_relax_factor` was comparing two
3383        // different models without being told. Set means the caller asked by
3384        // name and gets exactly the interior-point arm's model.
3385        //
3386        // Either branch snapshots the declared bounds first (`relax_bounds`
3387        // does it before widening), which `declared_box_violation` needs: its
3388        // absence is what printed `Variable bound violation: nan` here.
3389        let requested_relax = self
3390            .options
3391            .get_numeric_value("bound_relax_factor", "")
3392            .ok()
3393            .and_then(|(v, set)| set.then_some(v));
3394        match requested_relax {
3395            Some(factor) => {
3396                let cap = self
3397                    .options
3398                    .get_numeric_value("constr_viol_tol", "")
3399                    .ok()
3400                    .and_then(|(v, set)| set.then_some(v))
3401                    .unwrap_or(1e-4);
3402                orig_nlp.relax_bounds(factor, cap);
3403            }
3404            None => orig_nlp.snapshot_declared_bounds(),
3405        }
3406        let nlp_rc: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
3407
3408        let mut sqp_adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(&nlp_rc));
3409
3410        let mut builder = self.algorithm_builder_snapshot();
3411        builder.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
3412        // Prefer a caller-installed factory, exactly as `optimize_constrained`
3413        // does, so an embedder that plugs its own backend gets it on both
3414        // arms. `take()` matches the IPM's one-shot semantics rather than
3415        // introducing a second, different lifetime for the same hook.
3416        //
3417        // `maybe_crossover` deliberately does NOT do this: it runs after the
3418        // IPM solve has already taken the factory, so there is never one left
3419        // to find, and its two closures cannot both hold `&mut self` anyway.
3420        let factory = self
3421            .linear_backend_factory
3422            .take()
3423            .unwrap_or_else(|| self.make_backend_factory());
3424        let mut alg = match builder.build_sqp_with_backend(factory) {
3425            Some(a) => a,
3426            None => return ApplicationReturnStatus::InternalError,
3427        };
3428
3429        // Problem statistics + end-of-run summary are emitted by the engine
3430        // itself here (#206), gated on the main `print_level`, so the SQP
3431        // route matches the IPM route across every frontend (CLI, Python, C).
3432        // The SQP's own per-iteration rows stay gated on the separate
3433        // `sqp_print_level`.
3434        let console_output = match self.options.get_integer_value("print_level", "") {
3435            Ok((v, true)) => v >= 1,
3436            _ => true,
3437        };
3438        self.emit_problem_stats(&tnlp, console_output);
3439
3440        // Phase 5c (§6): consume any stashed warm-start iterate.
3441        // `optimize_with_warm_start(warm=None)` is equivalent to
3442        // `optimize`, so cold callers see no change.
3443        let mut warm = self.sqp_warm_start.take();
3444        // gh#986 review item 10: map a warm start given in the caller's full
3445        // variable space through this problem's fixed-variable elimination.
3446        // The working set this application publishes is in that space
3447        // (`working_set_to_user`), and so is what Python's
3448        // `solve(..., working_set=...)` decodes, so a child that fixes `x1`
3449        // gets the parent's statuses for exactly the columns it still has.
3450        // The first pass compared lengths only: a fixed variable made the
3451        // full-space hint "the wrong size" and it was dropped (a cold solve
3452        // and `info["working_set"] = None`), while a reduced-space hint from a
3453        // sibling that fixed a *different* variable had the right size and was
3454        // applied to the wrong columns.
3455        let (x_map, n_full) = {
3456            let a = adapter.borrow();
3457            let cls = a.classification();
3458            (cls.x_not_fixed_map.clone(), cls.n_full_x as usize)
3459        };
3460        let reduced = x_map.len() != n_full;
3461        let prev_elimination = self.x_elimination.replace((x_map.clone(), n_full));
3462        if let Some(w) = warm.as_mut() {
3463            // The staged iterate is in the caller's (user) space; the
3464            // algorithm's is not. Converted here, once, for every frontend.
3465            sqp_warm_start_to_algorithm(&*nlp_rc.borrow(), w);
3466            if reduced {
3467                let mut drop_reason: Option<String> = None;
3468                if let Some(ws) = w.working.as_mut() {
3469                    if ws.bounds.len() == n_full {
3470                        ws.bounds = x_map.iter().map(|&j| ws.bounds[j as usize]).collect();
3471                    } else if ws.bounds.len() == x_map.len()
3472                        && prev_elimination.as_ref() != Some(&(x_map.clone(), n_full))
3473                    {
3474                        // A reduced-space working set from a solve that
3475                        // eliminated *different* variables: its columns do
3476                        // not line up with this problem's, however equal the
3477                        // count.
3478                        drop_reason = Some(
3479                            "its bound statuses are in the reduced space of a solve that \
3480                             fixed different variables"
3481                                .into(),
3482                        );
3483                    }
3484                }
3485                if let Some(why) = drop_reason {
3486                    tracing::warn!(
3487                        target: "pounce::sqp",
3488                        "SQP warm-start working set dropped: {why}; pass the full-space \
3489                         working set (last_sqp_working_set / info[\"working_set\"]) instead"
3490                    );
3491                    w.working = None;
3492                }
3493            }
3494        }
3495        // `warm_start_init_point=yes` with nothing staged: take the TNLP's
3496        // own starting multipliers, as the interior-point arm does. They
3497        // arrive through the same `IpoptNlp` projections the IPM's warm
3498        // initializer uses, so they are already in algorithm space (scaled,
3499        // compressed, `[y_c; y_d]`). Without this the SQP arm read only the
3500        // primal: a `.nl` `d` segment or `ipopt_z*_in` suffix, or a Python
3501        // `lagrange=` start, began from zero multipliers on this arm alone.
3502        if warm.is_none()
3503            && matches!(
3504                self.options.get_bool_value("warm_start_init_point", ""),
3505                Ok((true, _))
3506            )
3507        {
3508            warm = sqp_tnlp_warm_start(&nlp_rc);
3509        }
3510        // gh#986: a warm start recorded on one problem is dimensioned for
3511        // that problem. A child that fixes a variable (branching) reaches
3512        // here with a smaller reduced `n` (and possibly `m`), where the
3513        // algorithm's contract is to refuse a mismatched iterate outright —
3514        // which surfaced as `Internal_Error` on a perfectly legal solve.
3515        // A warm start is only a hint, so drop it with a warning and solve
3516        // cold instead.
3517        if let Some(w) = warm.as_ref() {
3518            use crate::sqp::SqpProblemSpec;
3519            let (n, m) = (sqp_adapter.n(), sqp_adapter.m());
3520            let fits = w.x.len() == n
3521                && w.lambda_x.len() == n
3522                && w.lambda_g.len() == m
3523                && w.working
3524                    .as_ref()
3525                    .map(|ws| ws.validate_dims(n, m).is_ok())
3526                    .unwrap_or(true);
3527            if !fits {
3528                tracing::warn!(
3529                    target: "pounce::sqp",
3530                    "SQP warm start dropped: it is sized for a problem with n = {}, m = {} \
3531                     but this one has n = {n}, m = {m} (a fixed variable or removed row \
3532                     changes the reduced dimensions); solving cold",
3533                    w.x.len(),
3534                    w.lambda_g.len(),
3535                );
3536                warm = None;
3537            }
3538        }
3539        let warm_working_set_applied = warm.as_ref().is_some_and(|w| w.working.is_some());
3540        // gh#1015: the user's `intermediate_callback`, once per iteration,
3541        // with `GetIpoptCurrentIterate` answering from the SQP iterate. The
3542        // snapshot is built before the callback runs because the callback
3543        // holds the TNLP; nothing in it may call back into the user's
3544        // `eval_*`.
3545        {
3546            let hook_nlp = Rc::clone(&nlp_rc);
3547            let hook_tnlp = Rc::clone(&tnlp);
3548            let fixed_var_duals = self.reports_fixed_var_duals();
3549            alg.set_iteration_hook(Box::new(move |info| {
3550                // Built only for a TNLP that reads it, as on the
3551                // interior-point arm: the fixed-variable recovery is not
3552                // free, and most callbacks read only the stats.
3553                let _guard = hook_tnlp.borrow().wants_current_iterate().then(|| {
3554                    crate::intermediate::UserIterateGuard::install(sqp_user_iterate(
3555                        &hook_nlp,
3556                        info.x,
3557                        info.lambda_g,
3558                        info.lambda_x,
3559                        info.c_vals,
3560                        info.grad_lag_x,
3561                        fixed_var_duals,
3562                    ))
3563                });
3564                let stats = pounce_nlp::tnlp::IterStats {
3565                    mode: pounce_nlp::return_codes::AlgorithmMode::RegularMode,
3566                    iter: info.iter as Index,
3567                    obj_value: info.obj,
3568                    inf_pr: info.inf_pr,
3569                    inf_du: info.inf_du,
3570                    // No barrier, no regularisation, no dual step length.
3571                    mu: 0.0,
3572                    d_norm: info.p_inf,
3573                    regularization_size: 0.0,
3574                    alpha_du: 0.0,
3575                    alpha_pr: info.alpha,
3576                    ls_trials: 0,
3577                };
3578                hook_tnlp.borrow_mut().intermediate_callback(
3579                    stats,
3580                    &pounce_nlp::tnlp::IpoptData::default(),
3581                    &pounce_nlp::tnlp::IpoptCq::default(),
3582                )
3583            }));
3584        }
3585        let res = match alg.optimize_with_warm_start(&mut sqp_adapter, warm) {
3586            Ok(r) => r,
3587            Err(e) => {
3588                // Always surface this. It used to be gated on the
3589                // undocumented `POUNCE_DBG_SQP`, so the only thing a user saw
3590                // was a bare `Internal_Error` with no indication of what went
3591                // wrong -- the underlying message here was
3592                // `QpFailure(LinearSolverFailure("QP subproblem returned
3593                // status unbounded"))`, which points straight at the cause.
3594                // A solve that is about to fail is exactly when the reason
3595                // should be cheapest to obtain.
3596                tracing::warn!(
3597                    target: "pounce::sqp",
3598                    "SQP solve failed: {e:?}"
3599                );
3600                return ApplicationReturnStatus::InternalError;
3601            }
3602        };
3603        // Stash the result's working set so the next solve in a
3604        // sequence can fetch it via `last_sqp_working_set` -- in the caller's
3605        // full variable space (gh#986 review item 10).
3606        self.sqp_last_working_set = res
3607            .working_set
3608            .clone()
3609            .map(|ws| self.working_set_to_user(&*nlp_rc.borrow(), ws));
3610        // Populate the shared `SolveStatistics` so the Python /
3611        // C-API post-solve accessors (`GetIpoptIterCount`,
3612        // `info["iter_count"]`, etc.) report the SQP outer-iter
3613        // count rather than zero. Constraint-violation /
3614        // dual-infeasibility residuals get the SQP-side values
3615        // too. The IPM path overwrites this dict on its own
3616        // solves, so SQP-vs-IPM mixing across solves stays
3617        // honest.
3618        {
3619            let mut stats = self.statistics.borrow_mut();
3620            stats.iteration_count = res.n_iter as Index;
3621            // Subproblem counters. The outer iteration count alone
3622            // cannot show what a working-set warm start bought — the
3623            // saved work is inside the QPs — so both are reported.
3624            stats.sqp_qp_solves = res.n_qp_solves as Index;
3625            stats.sqp_qp_working_set_changes = res.n_qp_working_set_changes as Index;
3626            stats.sqp_warm_working_set_applied = warm_working_set_applied;
3627            stats.final_objective = res.obj;
3628            // `final_scaled_objective` defaults to NaN; the SQP path does not
3629            // thread nlp_scaling through the objective (same as the residuals
3630            // mirrored below), so the scaled objective equals the unscaled
3631            // one. Without this it stayed NaN and the console printed
3632            // "Objective ...: nan  <unscaled>" on every active-set solve
3633            // (gh #313), even on a clean optimal solve.
3634            stats.final_scaled_objective = res.obj;
3635            stats.final_dual_inf = res.final_stationarity;
3636            stats.final_constr_viol = res.final_constr_viol;
3637            stats.final_compl = 0.0; // SQP has no barrier — no compl term.
3638            // Overall KKT error. This was previously left at the struct
3639            // default, which made every successful SQP solve report an
3640            // overall error of exactly 0.0 — indistinguishable from a
3641            // genuinely perfect solve, and enough on its own to make
3642            // `pounce.minimize`'s acceptable-KKT fallback upgrade any status
3643            // on this path to `success=True`. Same expression as the unscaled
3644            // twin below; the two agree because the SQP path does not thread
3645            // nlp_scaling through its residuals.
3646            stats.final_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3647            // Unscaled residuals (pounce#173). The SQP path does not thread
3648            // the nlp_scaling factors through to its residuals yet, so these
3649            // mirror the SQP-side values: correct when no scaling is active
3650            // (the common case) and a conservative proxy otherwise. Populated
3651            // here so the info dict's `final_unscaled_*` keys are honest
3652            // rather than left at the 0.0 default.
3653            stats.final_unscaled_dual_inf = res.final_stationarity;
3654            stats.final_unscaled_constr_viol = res.final_constr_viol;
3655            stats.final_unscaled_compl = 0.0;
3656            stats.final_unscaled_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3657            // Ipopt's `Variable bound violation` — how far the returned point
3658            // sits outside the box the caller wrote. Left at its `NaN` default
3659            // until now, which printed `nan` on this arm's every summary.
3660            //
3661            // Measured through the same `declared_box_violation` accessor the
3662            // interior-point arm reads (`curr_declared_box_violation_max`), so
3663            // the two arms cannot drift into reporting different quantities
3664            // under one heading. gh#900 is the precedent and the warning: it
3665            // fixed this row on the NLP and convex arms and noted the two were
3666            // "independent code paths, so a test that exercised one would say
3667            // nothing about the other" — this is the third, and it was missed.
3668            //
3669            // `res.x` is algorithm-space, which is what the accessor expects
3670            // (it lifts to full-x itself); `finalize_via_sqp` wraps it exactly
3671            // this way for the same reason.
3672            stats.final_declared_box_viol = {
3673                use pounce_linalg::dense_vector::DenseVectorSpace;
3674                let nlp_borrow = nlp_rc.borrow();
3675                let x_space = DenseVectorSpace::new(nlp_borrow.n());
3676                let mut x_dv = x_space.make_new_dense();
3677                x_dv.set_values(&res.x);
3678                // `NaN`, not `0.0`, on the abstention — deliberately unlike
3679                // the IPM path's `unwrap_or(0.0)`.
3680                //
3681                // `None` from this accessor means one thing only: the declared
3682                // bounds were never snapshotted. It is NOT "the model has no
3683                // finite bounds" — an unbounded model still snapshots, the
3684                // loops find nothing, and the answer is a measured `Some(0.0)`.
3685                // So on this arm `None` can only mean the
3686                // `snapshot_declared_bounds` call above was lost, and mapping
3687                // that to zero would replace a visible "no answer" with an
3688                // invisible false claim that the point is inside its box.
3689                // gh#900's subject is exactly that: a zero that must not be
3690                // fabricated. Checked by mutation — delete the snapshot call
3691                // and this row goes back to `nan` rather than quietly reading
3692                // `0.00e+00`.
3693                nlp_borrow
3694                    .declared_box_violation(&x_dv)
3695                    .unwrap_or(Number::NAN)
3696            };
3697            // gh#990: the derivative checker's verdict reaches `info` and the
3698            // report on this arm too; it was copied on the IPM drain only.
3699            stats.derivative_check = self.derivative_check.borrow().clone();
3700            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
3701        }
3702        let (app_status, solver_status) = match res.status {
3703            crate::sqp::SqpStatus::Optimal => (
3704                ApplicationReturnStatus::SolveSucceeded,
3705                pounce_nlp::SolverReturn::Success,
3706            ),
3707            crate::sqp::SqpStatus::MaxIter => (
3708                ApplicationReturnStatus::MaximumIterationsExceeded,
3709                pounce_nlp::SolverReturn::MaxiterExceeded,
3710            ),
3711            crate::sqp::SqpStatus::InfeasibleSubproblem => (
3712                ApplicationReturnStatus::InfeasibleProblemDetected,
3713                pounce_nlp::SolverReturn::LocalInfeasibility,
3714            ),
3715            crate::sqp::SqpStatus::LineSearchFailed => (
3716                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3717                pounce_nlp::SolverReturn::ErrorInStepComputation,
3718            ),
3719            // Honest non-committal QP-subproblem failure (#282): the QP
3720            // solver could not compute a step and did NOT certify
3721            // infeasibility. Never report Infeasible_Problem_Detected here
3722            // — a feasible problem has no infeasibility certificate.
3723            crate::sqp::SqpStatus::QpStepFailed => (
3724                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3725                pounce_nlp::SolverReturn::ErrorInStepComputation,
3726            ),
3727            // The QP subproblem ran out of its own iteration budget. Same
3728            // #282 guarantee — no infeasibility is asserted — but reported as
3729            // the budget exhaustion it is, so the user sees a limit they can
3730            // raise (`sqp_qp_max_iter`) instead of a step-size stall with no
3731            // remedy. See `SqpStatus::QpIterationLimit` for why these were
3732            // split.
3733            crate::sqp::SqpStatus::QpIterationLimit => (
3734                ApplicationReturnStatus::MaximumIterationsExceeded,
3735                pounce_nlp::SolverReturn::MaxiterExceeded,
3736            ),
3737            // Unbounded below, with a recession ray verified against the
3738            // true NLP (gh #388). `Diverging_Iterates` is POUNCE's (Ipopt's)
3739            // unboundedness verdict and maps to AMPL `solve_result_num=300`
3740            // — the same answer the IPM selectors give on the same model,
3741            // instead of the `Internal_Error` / 500 ("the solver broke")
3742            // this path used to report.
3743            crate::sqp::SqpStatus::Unbounded => (
3744                ApplicationReturnStatus::DivergingIterates,
3745                pounce_nlp::SolverReturn::DivergingIterates,
3746            ),
3747            // A non-finite iterate or constraint value (gh #876). Same
3748            // verdict, from the same condition, as the interior-point arm's
3749            // `if !nlp_err.is_finite()` screen — the two arms must not
3750            // disagree about what a `NaN` iterate means.
3751            crate::sqp::SqpStatus::InvalidNumber => (
3752                ApplicationReturnStatus::InvalidNumberDetected,
3753                pounce_nlp::SolverReturn::InvalidNumberDetected,
3754            ),
3755            crate::sqp::SqpStatus::UserRequestedStop => (
3756                ApplicationReturnStatus::UserRequestedStop,
3757                pounce_nlp::SolverReturn::UserRequestedStop,
3758            ),
3759        };
3760
3761        // Same gate as the IPM path: an infeasible-subproblem exit is a
3762        // numerical inference, and a feasible starting point disproves it
3763        // (gh #379). Only the infeasibility verdict is rewritten — every other
3764        // status passes through untouched, so the pair stays in lockstep.
3765        let refuted = withdraw_infeasibility_if_refuted(
3766            &tnlp,
3767            solver_status,
3768            self.nlp_lower_bound_inf(),
3769            self.nlp_upper_bound_inf(),
3770            self.user_tol(),
3771        );
3772        let (app_status, solver_status) = if refuted == solver_status {
3773            (app_status, solver_status)
3774        } else {
3775            (solver_return_to_app_status(refuted), refuted)
3776        };
3777
3778        // Forward to the user TNLP's finalize_solution. We pass
3779        // the SQP iterate and recovered multipliers via the
3780        // OrigIpoptNlp's lifting hooks. Failure here is silent
3781        // (we still return the algorithm's status) — the user
3782        // sees the right ApplicationReturnStatus regardless.
3783        let _ = finalize_via_sqp(
3784            &nlp_rc,
3785            &res,
3786            solver_status,
3787            &tnlp,
3788            &self.last_finalize,
3789            self.reports_fixed_var_duals(),
3790        );
3791
3792        // Honor the opt-in status-fidelity gate on the SQP path too
3793        // (pounce#173), then emit the end-of-run summary with the final
3794        // (possibly downgraded) status so the console matches the returned
3795        // ApplicationReturnStatus.
3796        let final_status = self.apply_kkt_fidelity_gate(app_status);
3797        self.emit_end_summary(final_status, &nlp_rc, console_output);
3798        final_status
3799    }
3800
3801    /// Opt-in status-fidelity gate (pounce#173), shared by the IPM and
3802    /// SQP solve paths. When the user sets a positive `kkt_fidelity_tol`,
3803    /// a reported `Solve_Succeeded` whose max-norm UNSCALED KKT error
3804    /// (`SolveStatistics::final_unscaled_kkt_error`) exceeds it is
3805    /// downgraded to `Solved_To_Acceptable_Level` — the honest "this is a
3806    /// point, but not converged to the requested fidelity" status. This
3807    /// catches the ill-conditioned / nlp_scaling-deflated case where the
3808    /// scaled convergence test passes but the user-space duals have
3809    /// drifted. It is a pure relabel at termination (no extra iterations);
3810    /// unset or non-positive (the default) is a strict no-op, so every
3811    /// existing caller keeps the Ipopt-faithful status.
3812    fn apply_kkt_fidelity_gate(
3813        &self,
3814        app_status: ApplicationReturnStatus,
3815    ) -> ApplicationReturnStatus {
3816        if !matches!(app_status, ApplicationReturnStatus::SolveSucceeded) {
3817            return app_status;
3818        }
3819        if let Ok((ftol, true)) = self.options.get_numeric_value("kkt_fidelity_tol", "") {
3820            if ftol > 0.0 {
3821                let unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
3822                if unscaled_kkt > ftol {
3823                    tracing::info!(target: "pounce::diagnostics",
3824                        "kkt_fidelity_tol={ftol:.3e}: unscaled KKT error {unscaled_kkt:.3e} \
3825                         exceeds it — downgrading Solve_Succeeded → \
3826                         Solved_To_Acceptable_Level (pounce#173)");
3827                    return ApplicationReturnStatus::SolvedToAcceptableLevel;
3828                }
3829            }
3830        }
3831        app_status
3832    }
3833
3834    /// `nlp_lower_bound_inf` — the magnitude at or below which a bound is
3835    /// treated as absent.
3836    fn nlp_lower_bound_inf(&self) -> Number {
3837        self.options
3838            .get_numeric_value("nlp_lower_bound_inf", "")
3839            .ok()
3840            .and_then(|(v, f)| f.then_some(v))
3841            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF)
3842    }
3843
3844    /// `nlp_upper_bound_inf` — the magnitude at or above which a bound is
3845    /// treated as absent.
3846    fn nlp_upper_bound_inf(&self) -> Number {
3847        self.options
3848            .get_numeric_value("nlp_upper_bound_inf", "")
3849            .ok()
3850            .and_then(|(v, f)| f.then_some(v))
3851            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF)
3852    }
3853
3854    /// The user's convergence tolerance `tol`.
3855    fn user_tol(&self) -> Number {
3856        self.options
3857            .get_numeric_value("tol", "")
3858            .ok()
3859            .and_then(|(v, f)| f.then_some(v))
3860            .unwrap_or(1e-8)
3861    }
3862
3863    /// The user's `acceptable_tol` — the standard behind
3864    /// `Solved_To_Acceptable_Level`.
3865    fn user_acceptable_tol(&self) -> Number {
3866        self.options
3867            .get_numeric_value("acceptable_tol", "")
3868            .ok()
3869            .and_then(|(v, f)| f.then_some(v))
3870            .unwrap_or(1e-6)
3871    }
3872
3873    /// The user's `constr_viol_tol` — the **absolute** feasibility standard
3874    /// the strict gate's primal component judges by
3875    /// (`OptErrorConvCheck::primal_component_passes`).
3876    fn user_constr_viol_tol(&self) -> Number {
3877        self.options
3878            .get_numeric_value("constr_viol_tol", "")
3879            .ok()
3880            .and_then(|(v, f)| f.then_some(v))
3881            .unwrap_or(1e-4)
3882    }
3883
3884    /// The user's `acceptable_constr_viol_tol` — the same standard at the
3885    /// acceptable tier.
3886    fn user_acceptable_constr_viol_tol(&self) -> Number {
3887        self.options
3888            .get_numeric_value("acceptable_constr_viol_tol", "")
3889            .ok()
3890            .and_then(|(v, f)| f.then_some(v))
3891            .unwrap_or(1e-2)
3892    }
3893
3894    /// `primal_noise_floor_kappa` — the safety factor on the per-row
3895    /// floating-point noise floor (gh#528/gh#590). `0` opts out.
3896    fn user_primal_noise_floor_kappa(&self) -> Number {
3897        self.options
3898            .get_numeric_value("primal_noise_floor_kappa", "")
3899            .ok()
3900            .and_then(|(v, f)| f.then_some(v))
3901            .unwrap_or(64.0)
3902    }
3903
3904    /// Emit the Ipopt-style problem-statistics block (#206) from the
3905    /// engine's own reduced problem, gated on `console_output`
3906    /// (print_level >= 1). Shared by the IPM (`optimize_tnlp`) and SQP
3907    /// (`optimize_sqp_tnlp`) entry points so every algorithm and every
3908    /// frontend (CLI, Python, C) gets the identical block. Built from the
3909    /// same `collect_stats` inputs the CLI used, so the output is
3910    /// byte-identical to the historical CLI block.
3911    fn emit_problem_stats(&self, tnlp: &Rc<RefCell<dyn TNLP>>, console_output: bool) {
3912        if !console_output {
3913            return;
3914        }
3915        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
3916        if let Some(stats) =
3917            pounce_solve_report::console::collect_stats(tnlp, lo_inf, up_inf, fixed_treatment)
3918        {
3919            // A retry re-enters here with the same problem. Reprinting the
3920            // block verbatim is what made a retried run look like it had
3921            // printed its whole report twice for no reason, so say what is
3922            // actually happening instead: a new attempt on an unchanged
3923            // problem. One line, in place of seventeen that carry no
3924            // information the reader does not already have.
3925            //
3926            // The attempt is announced rather than merely suppressed because
3927            // the iteration table below it restarts at iteration 0 either way.
3928            // Silence would leave that table appearing from nowhere — trading
3929            // a confusing duplicate for a confusing gap.
3930            let mut memo = self.last_printed_problem_stats.borrow_mut();
3931            if memo.as_ref() == Some(&stats) {
3932                // Silent under an outside retry driver, which narrates its own
3933                // attempts in more detail than this line could ("pounce:
3934                // second opinion — re-solving with feral_scaling=mc64…").
3935                // Printing both would be two announcements of one event.
3936                if !self.in_retry_sequence.get() {
3937                    println!("Re-solving the same problem (a further attempt follows).");
3938                    println!();
3939                }
3940            } else {
3941                pounce_solve_report::console::print_problem_stats(&stats);
3942                *memo = Some(stats);
3943            }
3944        }
3945    }
3946
3947    /// Drain the NLP's per-eval counters into the shared `SolveStatistics`
3948    /// and emit the Ipopt-style end-of-run summary (#206). Shared by both
3949    /// solve paths. The counts are read from the NLP AFTER the solve (so the
3950    /// final solution evaluation is included, matching the historical count)
3951    /// and written into `SolveStatistics` so the post-solve API accessors
3952    /// (`info["n_obj_evals"]`, …) report them even when the console is
3953    /// silent. c/d (and jac_c/jac_d) are per-subsystem, so the max recovers
3954    /// the eval_g / eval_jac_g call count. The console summary itself is
3955    /// gated on `console_output` (print_level >= 1).
3956    fn emit_end_summary(
3957        &self,
3958        app_status: ApplicationReturnStatus,
3959        nlp: &Rc<RefCell<dyn IpoptNlp>>,
3960        console_output: bool,
3961    ) {
3962        {
3963            let ec = nlp.borrow().eval_counts();
3964            let mut stats = self.statistics.borrow_mut();
3965            stats.num_obj_evals = ec[0];
3966            stats.num_obj_grad_evals = ec[1];
3967            stats.num_constr_evals = ec[2].max(ec[3]);
3968            stats.num_constr_jac_evals = ec[4].max(ec[5]);
3969            stats.num_hess_evals = ec[6];
3970        }
3971        if !console_output {
3972            return;
3973        }
3974        let stats = self.statistics.borrow();
3975        let counts = pounce_solve_report::console::EvalCounts {
3976            n_obj: stats.num_obj_evals as u64,
3977            n_grad_f: stats.num_obj_grad_evals as u64,
3978            n_g: stats.num_constr_evals as u64,
3979            n_jac_g: stats.num_constr_jac_evals as u64,
3980            n_h: stats.num_hess_evals as u64,
3981        };
3982        // gh#987: no widening at `bound_relax_factor = 0`, so the console's
3983        // "before the bound_relax_factor widening" line has nothing to report.
3984        let widening_applied = self
3985            .options
3986            .get_numeric_value("bound_relax_factor", "")
3987            .map(|(v, _)| v > 0.0)
3988            .unwrap_or(true);
3989        pounce_solve_report::console::print_summary_with_widening(
3990            app_status,
3991            &stats,
3992            &counts,
3993            widening_applied,
3994        );
3995        // The verdict belongs to the run, not to the attempt. Held back while
3996        // any retry driver is managing attempts; that driver prints it once,
3997        // with the status it actually returns.
3998        if self.end_verdict_deferrals.get() == 0 {
3999            pounce_solve_report::console::print_exit_verdict(app_status);
4000        }
4001    }
4002
4003    /// Build a *copy* of the algorithm builder configured per the
4004    /// current options. The SQP path uses this so it gets a
4005    /// fresh builder without mutating the application's state.
4006    /// Read the `crossover*` option family into a [`CrossoverOptions`].
4007    fn crossover_options(&self) -> crate::crossover::CrossoverOptions {
4008        let mut o = crate::crossover::CrossoverOptions::default();
4009        if let Ok((v, true)) = self.options.get_bool_value("crossover", "") {
4010            o.enabled = v;
4011        }
4012        if let Ok((v, true)) = self.options.get_integer_value("crossover_max_iter", "") {
4013            o.max_iter = v.max(0) as u32;
4014        }
4015        if let Ok((v, true)) = self.options.get_numeric_value("crossover_mult_tol", "") {
4016            o.mult_tol = v;
4017        }
4018        if let Ok((v, true)) = self.options.get_numeric_value("crossover_primal_tol", "") {
4019            o.primal_tol = v;
4020        }
4021        o
4022    }
4023
4024    /// Post-convergence crossover (gh#612): hand the converged interior
4025    /// iterate to the active-set path so the solve ends on an exact active
4026    /// set. See [`crate::crossover`] for the algorithm.
4027    ///
4028    /// On acceptance this **replaces `data.curr`** rather than reporting
4029    /// alongside it. Everything downstream — the residual drain, the KKT
4030    /// fidelity gate, `on_converged`, `finalize_via_orig_nlp`, the end
4031    /// summary — already reads that one iterate, so replacing it is what
4032    /// makes the crossed-over point the solution instead of an annotation on
4033    /// it, and it does so without a second copy of the unscaling path.
4034    ///
4035    /// A no-op unless `crossover=yes` and the solve converged: an
4036    /// unconverged interior point is not a KKT point, so there is no active
4037    /// set at it worth identifying.
4038    fn maybe_crossover(
4039        &mut self,
4040        alg: &mut IpoptAlgorithm,
4041        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4042        solver_status: SolverReturn,
4043    ) {
4044        self.crossover_report = None;
4045        // Cleared on every entry, alongside the report, so the flag
4046        // describes this solve and not a previous one — the same reason
4047        // `crossover_report` is reset here rather than only written on
4048        // the accept path.
4049        alg.data.borrow_mut().curr_from_crossover = false;
4050        let xopts = self.crossover_options();
4051        if !xopts.enabled {
4052            return;
4053        }
4054        if !matches!(
4055            solver_status,
4056            SolverReturn::Success | SolverReturn::StopAtAcceptablePoint
4057        ) {
4058            return;
4059        }
4060        let Some(curr) = alg.data.borrow().curr.clone() else {
4061            return;
4062        };
4063
4064        // Seed, in the algorithm's compressed / scaled space. The SQP
4065        // adapter presents that same space, so nothing is translated here
4066        // beyond repacking the bound duals: `λ_x = z_l − z_u`.
4067        let seed = crate::crossover::CrossoverSeed {
4068            x: dense_values(&*curr.x),
4069            lambda_g: {
4070                let mut v = dense_values(&*curr.y_c);
4071                v.extend(dense_values(&*curr.y_d));
4072                v
4073            },
4074            lambda_x: crate::sqp::ipopt_adapter::pack_bound_multipliers(
4075                nlp_handle,
4076                &dense_values(&*curr.z_l),
4077                &dense_values(&*curr.z_u),
4078            ),
4079        };
4080
4081        let snapshot = self.algorithm_builder_snapshot();
4082        let sqp_opts = snapshot.sqp.clone();
4083        let qp_opts = snapshot.sqp_qp.clone();
4084        // Declared bounds, not the live relaxed ones: crossover's whole claim
4085        // is that the returned point sits *on* the constraints the user
4086        // wrote. Against the `bound_relax_factor`-widened box it would pivot
4087        // to a point `1e-8` shy of every one of them and then correctly
4088        // report an empty active set.
4089        let mut adapter =
4090            crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(nlp_handle));
4091        let (report, accepted) = crate::crossover::run(
4092            &mut adapter,
4093            &seed,
4094            &xopts,
4095            &sqp_opts,
4096            &qp_opts,
4097            || {
4098                let mut f = self.make_backend_factory();
4099                // `make_backend_factory` ships the workspace-default
4100                // backend regardless of the choice passed, exactly as the
4101                // SQP path's `build_sqp_with_backend` call does; naming
4102                // `Feral` here keeps that visible rather than implicit.
4103                f(crate::alg_builder::LinearSolverChoice::Feral)
4104            },
4105            |step4_opts| {
4106                let mut b = self.algorithm_builder_snapshot();
4107                b.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
4108                b.sqp = step4_opts;
4109                b.build_sqp_with_backend(self.make_backend_factory())
4110            },
4111        );
4112
4113        if let Some(res) = accepted {
4114            self.install_crossover_iterate(alg, nlp_handle, &curr, &res);
4115            // Publish the identified set as the SQP warm-start output. This
4116            // is the IPM → SQP handoff the active-set path never had: a
4117            // sequence whose first solve wants the interior method can now
4118            // feed the next `algorithm=active-set-sqp` solve a working set.
4119            self.sqp_last_working_set = res
4120                .working_set
4121                .clone()
4122                .map(|ws| self.working_set_to_user(&*nlp_handle.borrow(), ws));
4123        }
4124        tracing::debug!(target: "pounce::crossover", "crossover: {report:?}");
4125        self.crossover_report = Some(report);
4126    }
4127
4128    /// Write an accepted crossover result back onto the IPM iterate.
4129    ///
4130    /// All eight components have to move together: leaving `s`, `v_l` or
4131    /// `v_u` describing the interior point while `x` and the duals describe
4132    /// the crossed-over one would make the calculated quantities read off an
4133    /// iterate that never existed, and the residuals reported to the user
4134    /// would be neither point's. The slack relations are the barrier
4135    /// problem's own — `s = d(x)` and `v_l − v_u = −y_d`.
4136    fn install_crossover_iterate(
4137        &self,
4138        alg: &mut IpoptAlgorithm,
4139        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4140        curr: &crate::iterates_vector::IteratesVector,
4141        res: &crate::sqp::SqpResult,
4142    ) {
4143        let (m_c, m_d) = {
4144            let b = nlp_handle.borrow();
4145            (b.m_eq() as usize, b.m_ineq() as usize)
4146        };
4147        let y_c = &res.lambda_g[..m_c];
4148        let y_d = &res.lambda_g[m_c..];
4149        // `s = d(x)`: the adapter's combined constraint vector is `[c ; d]`,
4150        // so the inequality block is its tail.
4151        let mut adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(nlp_handle));
4152        let c_all = crate::sqp::SqpProblemSpec::eval_c(&mut adapter, &res.x);
4153        let s_new = &c_all[m_c..];
4154        debug_assert_eq!(s_new.len(), m_d);
4155        let (z_l, z_u) =
4156            crate::sqp::ipopt_adapter::split_bound_multipliers(nlp_handle, &res.lambda_x);
4157        let (v_l, v_u) = crate::sqp::ipopt_adapter::split_slack_multipliers(nlp_handle, y_d);
4158
4159        let mut out = curr.deep_copy();
4160        let ok = set_dense(&mut *out.x, &res.x)
4161            && set_dense(&mut *out.s, s_new)
4162            && set_dense(&mut *out.y_c, y_c)
4163            && set_dense(&mut *out.y_d, y_d)
4164            && set_dense(&mut *out.z_l, &z_l)
4165            && set_dense(&mut *out.z_u, &z_u)
4166            && set_dense(&mut *out.v_l, &v_l)
4167            && set_dense(&mut *out.v_u, &v_u);
4168        if !ok {
4169            // A non-dense backing or a length mismatch. POUNCE is dense-only,
4170            // so this is defensive — but a partially-written iterate is worse
4171            // than no crossover at all, so bail without touching `curr`.
4172            tracing::warn!(
4173                target: "pounce::crossover",
4174                "crossover result did not fit the iterate; keeping the interior point"
4175            );
4176            return;
4177        }
4178        let mut d = alg.data.borrow_mut();
4179        d.set_curr(out.freeze());
4180        // Mark which frame the installed iterate belongs to. It sits on the
4181        // *declared* bounds, and every barrier quantity built off `curr` —
4182        // slacks, and through them `Σ = z/s` — is measured against the
4183        // `bound_relax_factor`-widened ones, so a consumer that wants the
4184        // point's own geometry rather than the barrier's has to know this
4185        // happened (gh#654). Set only on the path that actually replaced
4186        // `curr`: a declined or abandoned crossover leaves the interior
4187        // iterate, which is an interior-frame point.
4188        d.curr_from_crossover = true;
4189    }
4190
4191    fn algorithm_builder_snapshot(&self) -> AlgorithmBuilder {
4192        let mut builder = AlgorithmBuilder {
4193            quality_escalation_counter: Some(Rc::clone(&self.quality_escalations)),
4194            ..AlgorithmBuilder::default()
4195        };
4196        apply_sqp_options(&self.options, &mut builder.sqp);
4197        apply_qp_subproblem_options(&self.options, &mut builder.sqp_qp);
4198        builder
4199    }
4200
4201    /// Refuse an explicitly set `ma57_pivtolmax` that sits below
4202    /// `ma57_pivtol`, at either option prefix.
4203    ///
4204    /// Upstream's `Ma57TSolverInterface::InitializeImpl` asserts
4205    /// `pivtolmax >= pivtol` and raises `OPTION_INVALID`, but only when
4206    /// the user set `ma57_pivtolmax` explicitly; left unset, the
4207    /// registered default is lifted to `ma57_pivtol` instead. Both
4208    /// halves are mirrored — the lifting in
4209    /// `pounce_hsl::ma57::Options::from_options_list`, the refusal here.
4210    ///
4211    /// Checked at **both** prefixes because the restoration sub-IPM
4212    /// configures its own MA57 backend from `"resto."`-scoped options
4213    /// (gh#825), so `resto.ma57_pivtolmax` can contradict
4214    /// `resto.ma57_pivtol` without the un-prefixed pair being wrong.
4215    ///
4216    /// Deliberately **not** gated on the `ma57` cargo feature or on
4217    /// `linear_solver` resolving to MA57. It is a consistency check on
4218    /// two numbers the user wrote, needs no HSL to perform, and a
4219    /// verdict that changed with a build flag would be worse than a
4220    /// consistent one — it would also be untestable in CI, which cannot
4221    /// link CoinHSL. Only an *explicitly set* `ma57_pivtolmax` can
4222    /// trigger it, so an options file that never mentions the option is
4223    /// unaffected.
4224    fn ma57_pivtol_bracket_refusal(&self) -> Option<String> {
4225        for prefix in ["", "resto."] {
4226            // `(_, true)` is the explicitly-set arm; an unset option
4227            // reports the registry default with `false` and is the
4228            // branch upstream lifts rather than refuses.
4229            let Ok((pivtolmax, true)) = self.options.get_numeric_value("ma57_pivtolmax", prefix)
4230            else {
4231                continue;
4232            };
4233            let pivtol = self
4234                .options
4235                .get_numeric_value("ma57_pivtol", prefix)
4236                .map(|(v, _)| v)
4237                .unwrap_or(1e-8);
4238            if pivtolmax < pivtol {
4239                return Some(format!(
4240                    "pounce: {prefix}ma57_pivtolmax ({pivtolmax:e}) is below \
4241                     {prefix}ma57_pivtol ({pivtol:e}). ma57_pivtolmax is the ceiling MA57 \
4242                     may raise the pivot tolerance to when it escalates for accuracy, so it \
4243                     cannot sit below the tolerance it starts from. Raise \
4244                     {prefix}ma57_pivtolmax to at least {pivtol:e}, or lower \
4245                     {prefix}ma57_pivtol."
4246                ));
4247            }
4248        }
4249        None
4250    }
4251
4252    /// Build a linear-solver factory from the application's current options,
4253    /// for the paths that do not go through `optimize_constrained`'s own
4254    /// factory plumbing — the active-set SQP driver and the post-convergence
4255    /// crossover.
4256    ///
4257    /// This used to ignore its `choice` argument and return
4258    /// `FeralSolverInterface::new()`: a default-configured FERAL, whatever the
4259    /// caller asked for. Three things were silently dropped on every SQP
4260    /// solve. `linear_solver=ma57` ran FERAL while the banner said
4261    /// `MA57 (HSL)`, so an MA57-vs-FERAL comparison on this path measured
4262    /// nothing — the same defect as gh#825, one path over. Every `feral_*`
4263    /// option (`feral_refine`, `feral_ordering`, `feral_scaling`,
4264    /// `feral_increase_quality`, …) was accepted and discarded. And
4265    /// `set_external_ordering` — whose whole purpose is to inject an ordering
4266    /// a generic algorithm cannot derive — reached the IPM and not this arm.
4267    ///
4268    /// Reads the same two snapshots and calls the same constructor the IPM
4269    /// path does, so there is one answer to "what does `linear_solver` mean"
4270    /// rather than one per algorithm.
4271    fn make_backend_factory(&self) -> LinearBackendFactory {
4272        // `RefineCarveOut::None`: this arm does not refine the unreduced system
4273        // itself, so the backend loop is the only refinement in the stack and
4274        // the interior-point carve-out's premise is false here. See
4275        // `feral_config_from_options_scoped` for the measurement.
4276        let mut feral_cfg = feral_config_from_options_scoped(&self.options, RefineCarveOut::None);
4277        // Same override, and for the same reason, as the IPM path: the
4278        // external permutation carries a vector, which no string option can
4279        // express, so it arrives through the side-channel field instead.
4280        if let Some(perm) = &self.external_ordering {
4281            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
4282        }
4283        let ma57_cfg = ma57_config_from_options(&self.options, "");
4284        default_backend_factory_with_sink(
4285            feral_cfg,
4286            ma57_cfg,
4287            Arc::clone(&self.linsol_summary_sink),
4288        )
4289    }
4290
4291    /// Phase 3.5 auto-fallback driver.
4292    ///
4293    /// Runs the standard solve (no wrapper) first. If it ends in a
4294    /// trigger-class status (`Restoration_Failed`, `Infeasible_Problem_Detected`,
4295    /// `Solved_To_Acceptable_Level`, `Maximum_Iterations_Exceeded`, or
4296    /// `Not_Enough_Degrees_Of_Freedom`), retries transparently with
4297    /// the ℓ₁ wrapper enabled. Promotes the retry's status only if
4298    /// it returns `Solve_Succeeded`; otherwise returns the original
4299    /// status.
4300    ///
4301    /// Caveat: the user TNLP's `finalize_solution` runs once per
4302    /// attempt. When the retry doesn't promote, the user's captured
4303    /// fields hold the retry's iterate (the ℓ₁-best least-infeasible
4304    /// point) even though the returned status is the original's.
4305    /// Documented on the option's help text; tightening this is a
4306    /// Phase-4 follow-up.
4307    fn run_with_l1_fallback(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
4308        // First attempt: the standard IPM solve, no ℓ₁ wrapper. Only
4309        // reached for `m > 0`, so `optimize_constrained` is exact.
4310        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4311        if !is_l1_fallback_trigger(first_status) {
4312            return first_status;
4313        }
4314        // gh#987 item 6: the plain attempt's iterations are part of what this
4315        // call spent, and the retry's `optimize_constrained` resets them.
4316        let first_attempt = self.statistics.borrow().clone();
4317        // Trigger fired. Flip the wrapper option for the retry and
4318        // restore it after — keeps the user's option-table view of the
4319        // session exactly as they left it.
4320        let prev = self
4321            .options
4322            .get_string_value("l1_exact_penalty_barrier", "")
4323            .ok();
4324        let _ = self
4325            .options
4326            .set_string_value("l1_exact_penalty_barrier", "yes", true, false);
4327        let retry_status = self
4328            .run_l1_penalty_outer_loop(Rc::clone(&tnlp))
4329            .unwrap_or(ApplicationReturnStatus::InternalError);
4330        let _ = self.options.set_string_value(
4331            "l1_exact_penalty_barrier",
4332            prev.as_ref().map(|(v, _)| v.as_str()).unwrap_or("no"),
4333            true,
4334            false,
4335        );
4336        // Fold the plain attempt in ahead of the retry's passes. A retry that
4337        // never ran a pass (wrapper construction declined) leaves the plain
4338        // attempt's own statistics standing untouched.
4339        {
4340            let mut st = self.statistics.borrow_mut();
4341            if !st.passes.is_empty() {
4342                let mut head = MultiPassTotals::default();
4343                head.push_pass(&first_attempt, None, first_status);
4344                let shift = head.rows.len();
4345                let mut passes = head.passes;
4346                passes.extend(st.passes.iter().cloned().map(|mut p| {
4347                    p.first_row += shift;
4348                    p
4349                }));
4350                let mut rows = head.rows;
4351                rows.append(&mut st.iterations);
4352                st.iterations = rows;
4353                st.iteration_count += first_attempt.iteration_count;
4354                st.num_obj_evals += first_attempt.num_obj_evals;
4355                st.num_constr_evals += first_attempt.num_constr_evals;
4356                st.num_obj_grad_evals += first_attempt.num_obj_grad_evals;
4357                st.num_constr_jac_evals += first_attempt.num_constr_jac_evals;
4358                st.num_hess_evals += first_attempt.num_hess_evals;
4359                st.restoration_calls += first_attempt.restoration_calls;
4360                st.restoration_inner_iters += first_attempt.restoration_inner_iters;
4361                st.restoration_outer_iters += first_attempt.restoration_outer_iters;
4362                st.passes = passes;
4363            }
4364        }
4365        if matches!(retry_status, ApplicationReturnStatus::SolveSucceeded) {
4366            retry_status
4367        } else {
4368            first_status
4369        }
4370    }
4371
4372    /// μ-strategy auto-fallback driver (pounce#138).
4373    ///
4374    /// Runs the standard solve first. If it stalls short of optimal in a
4375    /// way a μ-strategy flip can plausibly fix — `Solved_To_Acceptable_Level`
4376    /// or `Maximum_Iterations_Exceeded`, the two signatures seen on the
4377    /// princetonlib instances where the dual infeasibility parks above
4378    /// `tol` while constraint violation and complementarity are already
4379    /// deeply converged — it flips `mu_strategy` (adaptive↔monotone) and
4380    /// solves once more. The retry's status is promoted only if it returns
4381    /// `Solve_Succeeded`; otherwise the original status is returned.
4382    ///
4383    /// (maxcut/price stall at acceptable-level under adaptive; fermat2_vareps
4384    /// stalls at `max_iter` — hence both triggers. flosp2tm is μ-independent
4385    /// and correctly does not promote.)
4386    ///
4387    /// The flip direction is taken from the strategy the option table
4388    /// actually resolves to (`effective_mu_strategy_is_adaptive`):
4389    /// `adaptive` → `monotone`, otherwise → `adaptive`. Absence is not
4390    /// the same as `monotone` — under a limited-memory Hessian an unset
4391    /// `mu_strategy` resolves to `adaptive` (gh#746), and flipping the
4392    /// *registered* default there would re-run the strategy that just
4393    /// stalled. The option table is restored to the resolved view
4394    /// afterward.
4395    ///
4396    /// Caveat (shared with the ℓ₁ fallback): the user TNLP's
4397    /// `finalize_solution` runs once per attempt, so when the retry
4398    /// doesn't promote the captured fields hold the retry's iterate.
4399    fn run_with_mu_strategy_fallback(
4400        &mut self,
4401        tnlp: Rc<RefCell<dyn TNLP>>,
4402    ) -> ApplicationReturnStatus {
4403        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4404        // Which statuses are worth a second solve depends on who asked
4405        // for the retry (pounce#748).
4406        //
4407        // An explicit `mu_strategy_fallback=yes` keeps the historical
4408        // pair: the caller opted in and can afford the second solve.
4409        //
4410        // The *default*-on retry takes `Maximum_Iterations_Exceeded`
4411        // unconditionally, and `Solved_To_Acceptable_Level` only when
4412        // the caller left the convergence configuration alone
4413        // (gh #757). pounce#748 refused the latter status outright, for
4414        // three reasons; two of them are properties of a *caller-
4415        // modified* configuration, not of the status. It launders
4416        // downgrades the caller induced deliberately -- a tight
4417        // `kkt_fidelity_tol`, a certificate veto, `least_square_init_
4418        // primal` -- so the signal the option exists to produce never
4419        // reaches them. And because the retry returns the other run's
4420        // *point*, not just its status, it can hand back a different
4421        // local solution: on `autocorr_bern55-06` with the
4422        // dual-divergence guard on it swaps -2304.0000278 for
4423        // -2320.0000298 (crates/pounce-cli/tests/
4424        // issue_250_dual_guard_never_worse.rs). Both cases -- and all
4425        // five test targets the wide trigger broke -- arm a
4426        // non-default option from `TERMINATION_POLICY_OPTIONS`, so
4427        // deferring to that set preserves every one of them while
4428        // leaving a stock-options stall retryable. The third reason,
4429        // cost, stands and is the price: one extra solve on a run that
4430        // reached only the acceptable tolerance, paid to try for the
4431        // certificate. `cho_parmest` is the motivating case -- monotone
4432        // parks `inf_du` on a ~1e-6 evaluation-noise floor and misses
4433        // `tol` by 5%, taking six null steps of 1e-12 at `mu_min`,
4434        // while adaptive certifies it in 20 iterations.
4435        //
4436        // `dirichlet120`, the case that motivated turning the retry on,
4437        // stalls at `Maximum_Iterations_Exceeded`, so it is recovered
4438        // either way.
4439        let retry_worthy = match first_status {
4440            ApplicationReturnStatus::MaximumIterationsExceeded => true,
4441            ApplicationReturnStatus::SolvedToAcceptableLevel => {
4442                self.mu_strategy_fallback_was_set() || !self.caller_set_termination_policy()
4443            }
4444            _ => false,
4445        };
4446        if !retry_worthy {
4447            return first_status;
4448        }
4449        // gh#857: decline the flip when the solve that just failed escalated
4450        // the factorization and an escalation-off re-solve is enabled.
4451        //
4452        // The mu flip is a *blind* second opinion: it changes the barrier
4453        // schedule and hopes. A `feral_increase_quality` escalation is a
4454        // *measured* fact about the run that just failed -- FERAL reroutes
4455        // which pivots are taken and never steps back down, so every
4456        // iteration after the first escalation, restoration sub-solves
4457        // included, ran on a trajectory the defaults do not describe. Flipping
4458        // `mu_strategy` while leaving that in place is not a controlled
4459        // experiment: it varies the knob that is not implicated and holds the
4460        // one that is.
4461        //
4462        // It is not free either. On `square_flowsheet_resto`'s lbfgs leg the
4463        // flip escalates 25 times all over again, burns a second full
4464        // 3000-iteration budget, and ends no better than the first -- after
4465        // which rung 4 of the second-opinion ladder converges the model in 178
4466        // with the escalation off. That is 6178 real iterations to reach an
4467        // answer that 3178 reach without the flip, and the flip contributes
4468        // nothing to it. Measured both ways: `mu_strategy=adaptive` alone
4469        // still gives 3000 with 25 escalations, and `feral_increase_quality=no`
4470        // gives 178 under *either* mu strategy.
4471        //
4472        // Why decline rather than fold the escalation off into this retry: the
4473        // backend factory is minted from an options snapshot taken by the
4474        // caller *before* `solve()`, so writing `feral_increase_quality` here
4475        // is too late to reach the retry's linear solver. `mu_strategy` is read
4476        // per-solve from the option table and is not; that asymmetry is why
4477        // this layer can only choose whether to spend the solve, not what to
4478        // spend it on.
4479        //
4480        // Restricted to `Maximum_Iterations_Exceeded`, which is exactly the
4481        // status rung 4 opens on. A `Solved_To_Acceptable_Level` exit opens no
4482        // escalation rung, so declining there would drop a retry with nothing
4483        // in its place. Gated on `feral_increase_quality_retry`, so setting
4484        // that option to `no` restores the historical behaviour on both sides
4485        // at once: no rung 4, and no decline here.
4486        //
4487        // The one place the stand-down is not paired with the rung is the
4488        // multi-start paths (`solve_nlp_batch`, the CLI's `minima` search),
4489        // which deliberately do not drive the ladder -- a failed start there is
4490        // routine and extra solves per start multiply. Those paths lose the
4491        // flip on an escalating budget exit and gain nothing back, which is the
4492        // one behaviour change here that is not a strict improvement. It is the
4493        // same trade they already take on every other rung, and for the same
4494        // reason: an escalating capped start is one of many, and doubling its
4495        // cost to re-run the trajectory the escalation governs is the worse end
4496        // of it.
4497        if matches!(
4498            first_status,
4499            ApplicationReturnStatus::MaximumIterationsExceeded
4500        ) && self.quality_escalations.get() >= 1
4501            && self
4502                .options
4503                .get_bool_value("feral_increase_quality_retry", "")
4504                .map(|(v, _found)| v)
4505                .unwrap_or(true)
4506            && self
4507                .options
4508                .get_bool_value("feral_increase_quality", "")
4509                .map(|(v, _found)| v)
4510                .unwrap_or(true)
4511        {
4512            return first_status;
4513        }
4514        // Flip the strategy for one retry. The parser maps "adaptive" →
4515        // Adaptive and every other value (incl. unset) → Monotone, so the
4516        // opposite of an explicit "adaptive" is "monotone" and the
4517        // opposite of anything else is "adaptive".
4518        let prev = self.options.get_string_value("mu_strategy", "").ok();
4519        let was_adaptive = self.effective_mu_strategy_is_adaptive();
4520        let flipped = if was_adaptive { "monotone" } else { "adaptive" };
4521        // Unwind cover only: the normal-path restore below writes the
4522        // resolved value back as caller-set, deliberately, and the scope must
4523        // not change that. A panic in the retry used to leave the flipped
4524        // strategy in the option table of an application `ffi_guard` keeps.
4525        let mut scope = RetryOptionScope::enter(self, &["mu_strategy"], true);
4526        let _ = scope
4527            .options
4528            .set_string_value("mu_strategy", flipped, true, false);
4529        // Floor the *answer*, not just the status (pounce#870).
4530        //
4531        // The promote-only-on-`Solve_Succeeded` rule below has always floored
4532        // the status. It did not floor the point, and the point is what the
4533        // caller consumes: `optimize_constrained` calls the user TNLP's
4534        // `finalize_solution` once per attempt, so a retry that fails to
4535        // promote still overwrites the answer with its own iterate, and the
4536        // statistics with its own residuals. The result is a status describing
4537        // one attempt attached to a point from another.
4538        //
4539        // Measured on a random corpus of 1200 nonconvex models, 20 of them
4540        // (1.7%) returned a materially worse point under an unchanged status,
4541        // the worst flipping sign: a `Maximum_Iterations_Exceeded` exit went
4542        // from -2.38e7 to +7.89e7, and a `Solved_To_Acceptable_Level` one from
4543        // -3.83e7 to +3.41e5 while its reported `final_kkt_error` rose to
4544        // 2.85e-4 — 285x the `acceptable_tol` its own status names, so the
4545        // report contradicted itself. The known example on record understated
4546        // it by three orders: `autocorr_bern55-06` swapping -2304.0000278 for
4547        // -2320.0000298 is the same defect at 0.07%.
4548        //
4549        // This is the floor idiom the rest of the codebase already uses for a
4550        // bet it might lose — `honour_neg_curv_floor` (gh#797),
4551        // `honour_decline_floor` (gh#534), `honour_best_acceptable_after_dual_
4552        // guard` — applied to the one bet that was only half-floored.
4553        //
4554        // Not extended to `run_with_l1_fallback`, which carries the same
4555        // caveat in its doc comment but is NOT the same call: its retry
4556        // deliberately reports the l1-best least-infeasible point, which the
4557        // option help calls informative in its own right. Changing that needs
4558        // its own measurement.
4559        let solution_floor = scope.last_finalize.borrow().clone();
4560        let certificate_floor = SolutionCertificate::of(&scope.statistics.borrow());
4561        let trace_floor = *scope.last_iter_stats.borrow();
4562        let retry_status = scope.optimize_constrained(Rc::clone(&tnlp));
4563        // Restore the user's original option-table view.
4564        let _ = scope.options.set_string_value(
4565            "mu_strategy",
4566            prev.as_ref()
4567                .filter(|(_, found)| *found)
4568                .map(|(v, _)| v.as_str())
4569                .unwrap_or(if was_adaptive { "adaptive" } else { "monotone" }),
4570            true,
4571            false,
4572        );
4573        drop(scope);
4574        if matches!(retry_status, ApplicationReturnStatus::SolveSucceeded) {
4575            return retry_status;
4576        }
4577        // The bet lost. Put the first attempt's answer back, so the point and
4578        // the statistics describe the same solve the returned status does.
4579        //
4580        // `finalize_solution` therefore runs once more than the number of
4581        // attempts on this path. That is deliberate, and is the cheaper of the
4582        // two corrections: withholding the retry's `finalize_solution` until it
4583        // is known to promote would deprive a caller that watches the callback
4584        // of the retry's progress, and buys nothing, since the retry's payload
4585        // is discarded either way.
4586        if let Some(floor) = solution_floor {
4587            tracing::debug!(target: "pounce::algorithm",
4588                "[POUNCE] the mu_strategy_fallback retry did not promote \
4589                 ({:?} is not Solve_Succeeded); restoring the first attempt's \
4590                 solution and statistics alongside its status (pounce#870).",
4591                retry_status);
4592            floor.replay(&tnlp);
4593            self.answer_restored_from_floor.set(true);
4594            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
4595            // Third sink: the per-iteration trace. Consumers accumulate that
4596            // themselves from `intermediate_callback` — the CasADi plugin
4597            // pushes into its own vectors and clears once per `nlpsol` call —
4598            // so POUNCE cannot rewind it, and both attempts concatenate into
4599            // one trace. Restoring the certificate without touching the trace
4600            // leaves the reported numbers describing attempt 1 while the trace
4601            // ends on the retry, which breaks the invariant
4602            // `casadi/test_parity.py` states outright: "The final numbers and
4603            // the end of the trace are the same quantities, and must not come
4604            // from two different places."
4605            //
4606            // Re-emitting the winning attempt's final row restores it. It is
4607            // the trace analogue of `FinalizeSnapshot::replay` above, and it
4608            // makes the property hold by construction rather than by hoping a
4609            // consumer resets on an attempt boundary — nothing in the callback
4610            // contract marks one, and gh#634 is what happens when a consumer
4611            // has to guess the scope of a trace.
4612            //
4613            // The row is a real iterate that was already sent once, not a
4614            // synthesized one, so a trace still contains only points the solver
4615            // actually visited.
4616            if let Some(stats) = trace_floor {
4617                let _ = tnlp.borrow_mut().intermediate_callback(
4618                    stats,
4619                    &TnlpIpoptData::default(),
4620                    &TnlpIpoptCq::default(),
4621                );
4622            }
4623        }
4624        first_status
4625    }
4626
4627    /// Is the gh#884 biactive dual-divergence retry enabled? Default
4628    /// `yes`; `dual_divergence_retry=no` is the kill switch, and
4629    /// restores the pre-gh#884 behaviour outright (no detector cost, no
4630    /// second solve, and the base attempt's verdict returned unchanged).
4631    fn is_dual_divergence_retry_enabled(&self) -> bool {
4632        self.options
4633            .get_bool_value("dual_divergence_retry", "")
4634            .map(|(v, _found)| v)
4635            .unwrap_or(true)
4636    }
4637
4638    /// gh#884: throw the iterate away and solve again from scratch with
4639    /// `perturb_always_cd` on, when the base solve settled its primal
4640    /// while its multipliers ran away.
4641    ///
4642    /// # The defect
4643    ///
4644    /// On an MPCC lowered through an exact complementarity product
4645    /// `G·H = 0`, a pair that is **biactive** at the solution — both
4646    /// `G` and `H` zero — leaves that row's gradient
4647    /// `H∇G + G∇H` identically zero. The row is still there, so its
4648    /// multiplier is *arbitrary* rather than nonexistent, and the IPM
4649    /// drives it to infinity while the primal iterate sits on the
4650    /// answer. Because the convergence verdict is reached on an
4651    /// `s_d`-normalised aggregate and `s_d` grows with the mean
4652    /// multiplier magnitude, the aggregate reads clean: MacMPEC's
4653    /// `qpec_small` under `ncp_eq`/`prod_eq` reported
4654    /// `Solved_To_Acceptable_Level` at an *unscaled* dual infeasibility
4655    /// of `7.9e+04`.
4656    ///
4657    /// # Why a retry rather than a gate
4658    ///
4659    /// Four other shapes of fix were measured and rejected — a Hessian
4660    /// sparsity hypothesis, engaging `delta_c` *in flight*, flipping
4661    /// `perturb_always_cd` on globally, and putting a dual ceiling on
4662    /// the acceptable-level gate. `dev-notes/mpcc-biactive-dual-
4663    /// divergence.md` records all four with numbers. The short version:
4664    /// by the time the runaway is visible this iterate is unrecoverable,
4665    /// so the only action left is to *stop using it*; and the remedy
4666    /// that works — `perturb_always_cd=yes` — is measured to return a
4667    /// wrong answer reported as success on `ralph1`
4668    /// (`Solve_Succeeded` at `f = -2.71e-5`, below `f* = 0`), so it
4669    /// cannot be turned on for everyone.
4670    ///
4671    /// **The detector is therefore the entire safety barrier**, and the
4672    /// promotion gate below is the second one. `ralph1` is exactly the
4673    /// model the detector must not fire on, and
4674    /// `IpoptAlgorithm`'s scale-relative step floor is what keeps it
4675    /// from doing so: `qpec_small` settles to `4.3e-8` while `ralph1`
4676    /// bottoms out at `7.2e-3`, five orders apart.
4677    ///
4678    /// # The gate
4679    ///
4680    /// The retry's verdict replaces the base one only when **all** of:
4681    ///
4682    /// 1. the base attempt saw the signature (a converged primal, a step
4683    ///    at zero, and an unscaled `‖∇L‖∞` far above `dual_inf_tol`, all
4684    ///    at one iterate — see `IpoptAlgorithm::dual_divergence_signature`);
4685    /// 2. the base status is `Solved_To_Acceptable_Level` or
4686    ///    `Restoration_Failed` — the two verdicts the vanishing-gradient
4687    ///    row produces directly. Generic exhaustion exits are excluded;
4688    ///    `deb7` under L-BFGS is why, and the reason is in the code
4689    ///    below;
4690    /// 3. the retry returns `Solve_Succeeded`;
4691    /// 4. the retry's claimed success is **real in the model's own
4692    ///    units** — unscaled KKT error at or below `tol`-scale, which is
4693    ///    the property the base attempt failed and the whole point of
4694    ///    the issue;
4695    /// 5. the retry's unscaled KKT error is *strictly better* than the
4696    ///    base attempt's.
4697    ///
4698    /// Otherwise the base attempt's status, point and statistics are all
4699    /// put back, by the same three-sink floor
4700    /// [`Self::run_with_mu_strategy_fallback`] uses and for the same
4701    /// reason (pounce#870): a status describing one attempt attached to
4702    /// a point from another is worse than either.
4703    fn run_with_dual_divergence_retry(
4704        &mut self,
4705        tnlp: Rc<RefCell<dyn TNLP>>,
4706    ) -> ApplicationReturnStatus {
4707        let first_status = self.dispatch_standard_solve(Rc::clone(&tnlp));
4708        if !self.dual_divergence_signature.get() {
4709            return first_status;
4710        }
4711        // Which base verdicts this remedy is *for*.
4712        //
4713        // Two, and the narrowing was bought with a measurement. The
4714        // detector is a statement about the iterate; it is not a
4715        // statement that `perturb_always_cd` will help. `deb7` under
4716        // L-BFGS is the corpus case that separates the two: the
4717        // signature is real there — iteration 346, scale-relative step
4718        // `6.5e-6`, `inf_pr` `3.0e-12`, unscaled `inf_du` `9.2e5`,
4719        // which is an order *above* the gh#884 reproducer's `7.9e4`, so
4720        // no dual floor excludes it, and the step conjunct separates the
4721        // two only by fitting the default onto one fixture and spending
4722        // the margin that holds `ralph1` out — and the retry still does
4723        // not work: 3000 iterations to
4724        // `Maximum_Iterations_Exceeded` at an unscaled KKT error of
4725        // `6.7e1` against the base attempt's `9.9e1`. Pure cost, 4x the
4726        // base trajectory, on a fixture whose verdict does not move.
4727        //
4728        // The exclusion is by *status*, so it is only as complete as the
4729        // status is stable, and on this very fixture it is not. `deb7`
4730        // reaches `Error_In_Step_Computation` at default options and is
4731        // out; under `limited_memory_ls_failure_restarts=1` (gh#818's
4732        // rung, off by default) it reaches `Restoration_Failed` instead
4733        // and is therefore *in*. It used to pay exactly the cost above
4734        // there — 6.1 s to 25.2 s wall clock for the same
4735        // `Restoration_Failed` verdict and a declined retry, which is
4736        // gh#887. That is the price of scoping by status rather than by
4737        // model, and it is why the second gate below scopes by the
4738        // *answer* instead: `deb7` now declines before spending
4739        // anything. The status scope is kept because it is cheap and
4740        // reads on the verdict a caller sees, but it is not what is
4741        // being relied on.
4742        //
4743        // What separates them is the *status*, and it separates them
4744        // for a reason rather than by luck:
4745        //
4746        //  * `Solved_To_Acceptable_Level` is gh#884 verbatim — the
4747        //    runaway laundered itself through `s_d` into a success.
4748        //  * `Restoration_Failed` is the same defect one step earlier:
4749        //    the rows whose gradients vanished drive the solve into
4750        //    restoration, and restoration cannot repair a row that has
4751        //    no gradient. It is where the `qpec_small` TNLP fixture
4752        //    lands (unscaled KKT `3.3e11`).
4753        //  * `Error_In_Step_Computation` and
4754        //    `Maximum_Iterations_Exceeded` are generic exhaustion
4755        //    exits. Every hard model reaches them, for every reason.
4756        //    Retrying *those* is not "repair the runaway", it is "try
4757        //    again harder" — which is what `mu_strategy_fallback` and
4758        //    the second-opinion ladder already are, and `deb7` is what
4759        //    that costs.
4760        //
4761        // `Solve_Succeeded` is excluded because it is already the best
4762        // verdict available and its certificate has already been
4763        // checked in the model's own units; there is nothing to buy.
4764        //
4765        // Worst-case cost is therefore one extra solve under the
4766        // caller's own `max_iter` — the same contract
4767        // `run_with_mu_strategy_fallback` already has.
4768        //
4769        // Deliberately **not** deferred to `TERMINATION_POLICY_OPTIONS`
4770        // the way the μ flip's acceptable-level trigger is (gh#757).
4771        // That deferral exists because the μ flip returns a different
4772        // *local solution*, so laundering a caller's deliberate
4773        // downgrade loses a signal they asked for. This retry cannot:
4774        // conjunct 4 requires the promoted answer to satisfy the KKT
4775        // conditions in the model's own units, which a downgrade the
4776        // caller induced on purpose does not. And the gh#884 reproducer
4777        // sets `tol=1e-8` explicitly, so deferring would decline the
4778        // retry on the one case the issue is about.
4779        let retry_worthy = matches!(
4780            first_status,
4781            ApplicationReturnStatus::SolvedToAcceptableLevel
4782                | ApplicationReturnStatus::RestorationFailed
4783        );
4784        if !retry_worthy {
4785            return first_status;
4786        }
4787        let base_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
4788        // The runaway has to be the *whole* residual of the answer being
4789        // reported.
4790        //
4791        // The detector is a statement about an *iterate*, and the iterate
4792        // it fires on need not be the one the solve ends at. A run can
4793        // pass through a settled point with a diverged multiplier, work
4794        // its way back down, and report something ordinary — and then
4795        // there is nothing left here for `perturb_always_cd` to repair,
4796        // whatever the trajectory did in the middle. This is what makes
4797        // "one extra solve" a cost the caller only pays on a run that
4798        // still *exhibits* the defect (gh#887).
4799        //
4800        // The test is `runaway_is_the_whole_residual`, which reads only
4801        // the reported answer and only as a ratio within it; its doc
4802        // comment carries the rule and the measured populations.
4803        let (base_viol, base_compl) = {
4804            let st = self.statistics.borrow();
4805            (st.final_unscaled_constr_viol, st.final_unscaled_compl)
4806        };
4807        let base_dual_inf = self.statistics.borrow().final_unscaled_dual_inf;
4808        if !runaway_is_the_whole_residual(
4809            base_dual_inf,
4810            base_viol,
4811            base_compl,
4812            self.options
4813                .get_numeric_value("dual_divergence_retry_du_floor", "")
4814                .map(|(v, _)| v)
4815                .unwrap_or(DUAL_DIV_RETRY_DU_FLOOR),
4816        ) {
4817            tracing::debug!(target: "pounce::algorithm",
4818                "[POUNCE] gh#884: the signature fired mid-trajectory, but the \
4819                 answer being reported is not a converged point with a runaway \
4820                 multiplier — unscaled dual {:.3e} against viol {:.3e} and \
4821                 complementarity {:.3e}. Nothing here for perturb_always_cd to \
4822                 repair, so no retry (gh#887).",
4823                base_dual_inf, base_viol, base_compl);
4824            return first_status;
4825        }
4826        // Floor all three sinks — solution payload, certificate, and the
4827        // last trace row — exactly as the μ fallback does (pounce#870).
4828        let solution_floor = self.last_finalize.borrow().clone();
4829        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
4830        let trace_floor = *self.last_iter_stats.borrow();
4831        tracing::debug!(target: "pounce::algorithm",
4832            "[POUNCE] gh#884: the primal settled while the multipliers ran away \
4833             (base {:?}, unscaled KKT {:.3e}); re-solving from scratch with \
4834             perturb_always_cd=yes.",
4835            first_status, base_unscaled_kkt);
4836        let prev = self.options.get_string_value("perturb_always_cd", "").ok();
4837        // Unwind cover only, as for the μ-strategy fallback: the restore
4838        // below is the normal path and is left exactly as it was.
4839        let mut scope = RetryOptionScope::enter(self, &["perturb_always_cd"], true);
4840        let _ = scope
4841            .options
4842            .set_string_value("perturb_always_cd", "yes", true, false);
4843        let retry_status = scope.dispatch_standard_solve(Rc::clone(&tnlp));
4844        // Restore the caller's option-table view. Absence is restored as
4845        // absence would be seen: the registered default is `no`.
4846        let _ = scope.options.set_string_value(
4847            "perturb_always_cd",
4848            prev.as_ref()
4849                .filter(|(_, found)| *found)
4850                .map(|(v, _)| v.as_str())
4851                .unwrap_or("no"),
4852            true,
4853            false,
4854        );
4855        drop(scope);
4856        let retry_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
4857        let retry_viol = self.statistics.borrow().final_unscaled_constr_viol;
4858        // Conjuncts 3, 4 and 5. Conjunct 4 is the one that distinguishes
4859        // this gate from every other promote-on-`Solve_Succeeded` retry
4860        // in this file: the base attempt's defect *was* a status that its
4861        // own unscaled residual contradicts, so promoting on the status
4862        // alone would reproduce the bug one attempt later.
4863        let accept_tol = self.dual_divergence_retry_accept_tol();
4864        let claimed_success_is_real = (retry_unscaled_kkt <= accept_tol
4865            && retry_viol <= accept_tol)
4866            || retry_certificate_dominates(
4867                base_unscaled_kkt,
4868                retry_unscaled_kkt,
4869                retry_viol,
4870                accept_tol,
4871            );
4872        // Conjuncts 6 and 7 — see `retry_answer_is_admissible`. Everything
4873        // above this line ranks the two attempts on their *certificates*;
4874        // this ranks them as *answers*, which is what a caller receives.
4875        // Without it a better multiplier is allowed to buy a worse point:
4876        // measured, `-13.0057 -> -1.2072` on a random QPEC, and
4877        // `+1.82e-09 -> -6.61e-05` on `scholtes4`, whose `f*` is exactly 0.
4878        let retry_obj = self.statistics.borrow().final_objective;
4879        // `obj_scaling_factor < 0` is how a maximization is posed, and
4880        // `final_objective` is the user's signed objective, so the
4881        // comparison direction has to follow it (R2).
4882        let sense = if self
4883            .options
4884            .get_numeric_value("obj_scaling_factor", "")
4885            .map(|(v, _)| v)
4886            .unwrap_or(1.0)
4887            < 0.0
4888        {
4889            -1.0
4890        } else {
4891            1.0
4892        };
4893        let answer_is_admissible = retry_answer_is_admissible(
4894            certificate_floor.objective,
4895            certificate_floor.unscaled_constr_viol,
4896            retry_obj,
4897            retry_viol,
4898            self.dual_divergence_retry_accept_tol(),
4899            sense,
4900        );
4901        let promote = matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
4902            && claimed_success_is_real
4903            && retry_unscaled_kkt < base_unscaled_kkt
4904            && answer_is_admissible;
4905        // Say on the console which of the two answers shipped.
4906        //
4907        // The per-attempt end summary cannot: `emit_end_summary` runs
4908        // inside `optimize_constrained`, once per attempt, and the
4909        // promotion is decided after the last of them. So a summary that
4910        // reported the promotion would report `false` on the very run that
4911        // promotes, contradicting the JSON report written from the same
4912        // statistics. The summary reports the *signature*, which is true
4913        // when it prints; this line reports the *outcome*, printed once,
4914        // where it is known.
4915        //
4916        // Gated on `print_level >= 1`, matching `emit_end_summary` — the
4917        // block this line follows.
4918        let console_output = match self.options.get_integer_value("print_level", "") {
4919            Ok((v, true)) => v >= 1,
4920            _ => true,
4921        };
4922        if console_output {
4923            println!();
4924            if promote {
4925                println!(
4926                    "gh#884 dual-divergence retry: promoted — unscaled KKT error \
4927                     {base_unscaled_kkt:.4e} -> {retry_unscaled_kkt:.4e}."
4928                );
4929            } else if !answer_is_admissible {
4930                // A distinct line, because this decline looks like a
4931                // contradiction otherwise: the retry converged, its
4932                // certificate is clean, and it was still refused. Say
4933                // which of the two rules refused it and on what numbers,
4934                // so the reader is not left comparing KKT errors that
4935                // had nothing to do with it.
4936                println!(
4937                    "gh#884 dual-divergence retry: declined on the ANSWER, not the \
4938                     certificate — the retry converged (unscaled KKT error \
4939                     {retry_unscaled_kkt:.4e} against the base attempt's \
4940                     {base_unscaled_kkt:.4e}) but its objective {retry_obj:.8e} at \
4941                     constraint violation {retry_viol:.4e} is not admissible next to \
4942                     the base attempt's {:.8e} at {:.4e}; the base attempt's answer \
4943                     is the one reported.",
4944                    certificate_floor.objective, certificate_floor.unscaled_constr_viol
4945                );
4946            } else {
4947                println!(
4948                    "gh#884 dual-divergence retry: declined ({retry_status:?}, \
4949                     unscaled KKT error {retry_unscaled_kkt:.4e} against the base \
4950                     attempt's {base_unscaled_kkt:.4e}); the base attempt's answer \
4951                     is the one reported."
4952                );
4953            }
4954        }
4955        if promote {
4956            self.dual_divergence_retry_promoted.set(true);
4957            self.statistics.borrow_mut().dual_divergence_retry_promoted = true;
4958            tracing::debug!(target: "pounce::algorithm",
4959                "[POUNCE] gh#884: the retry promoted — unscaled KKT {:.3e} \
4960                 (base {:.3e}).",
4961                retry_unscaled_kkt, base_unscaled_kkt);
4962            return retry_status;
4963        }
4964        if let Some(floor) = solution_floor {
4965            tracing::debug!(target: "pounce::algorithm",
4966                "[POUNCE] gh#884: the retry did not promote ({:?}, unscaled KKT \
4967                 {:.3e} vs base {:.3e}); restoring the first attempt's solution \
4968                 and statistics alongside its status.",
4969                retry_status, retry_unscaled_kkt, base_unscaled_kkt);
4970            floor.replay(&tnlp);
4971            self.answer_restored_from_floor.set(true);
4972            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
4973            // The signature belongs to the attempt whose numbers are now
4974            // reported, and `certificate_floor` does not carry it.
4975            self.statistics.borrow_mut().dual_divergence_signature = true;
4976            if let Some(stats) = trace_floor {
4977                let _ = tnlp.borrow_mut().intermediate_callback(
4978                    stats,
4979                    &TnlpIpoptData::default(),
4980                    &TnlpIpoptCq::default(),
4981                );
4982            }
4983        }
4984        first_status
4985    }
4986
4987    /// Is the gh#983 solve-quality audit enabled? Default `yes`;
4988    /// `solve_quality_audit=no` restores the pre-gh#983 behaviour (no
4989    /// re-scale retry, no `warnings`).
4990    fn is_solve_quality_audit_enabled(&self) -> bool {
4991        self.options
4992            .get_bool_value("solve_quality_audit", "")
4993            .map(|(v, _found)| v)
4994            .unwrap_or(true)
4995    }
4996
4997    /// gh#983 items 2 and 3: audit a success verdict against the *model's
4998    /// own* scale, re-solve once when the scaling is what is wrong, and say
4999    /// so in `statistics.warnings` when it is not fixed.
5000    ///
5001    /// The strict gate judges a scaled aggregate. Gradient-based scaling
5002    /// measures the objective gradient once, at the starting point, and
5003    /// freezes the factor; it also only ever scales *down*. Two failures
5004    /// follow, one on each side, and neither is visible to a gate that reads
5005    /// the scaled space:
5006    ///
5007    /// * **Frozen at a huge-gradient start** (LJ7 from a start whose gradient
5008    ///   is `3e8`): the factor is `3e-7`, the scaled test passes at a point
5009    ///   whose unscaled stationarity residual is `2.9e-2`, and no amount of
5010    ///   continued iteration under that factor improves it
5011    ///   (`obj_scale_certificate_threshold` already tries, and its budget is
5012    ///   spent). The fix is the one the issue names: re-evaluate the scaling
5013    ///   *at the returned point*, where the gradient is small, and solve
5014    ///   again from there.
5015    /// * **Small user objective** (profit in M$/L, gradient `1e-5`): nothing
5016    ///   scales up, so the absolute complementarity floor `~mu` is a
5017    ///   `2.5e-4` fraction of the objective gradient and the answer sits
5018    ///   `4.7e-4` (relative) off the optimum on an active bound. The retry
5019    ///   multiplies the objective by `1/max|grad f|` and solves again from
5020    ///   the returned point.
5021    ///
5022    /// Both retries are *bets that are tested*, floored exactly like the
5023    /// gh#884 and mu-strategy retries: the retry is promoted only when it
5024    /// returns a clean verdict, its unscaled KKT error is no worse, its
5025    /// complementarity (small-objective case) or unscaled KKT error (frozen
5026    /// case) is strictly better, and its answer is admissible next to the
5027    /// base attempt's. Otherwise the base attempt's status, point and
5028    /// statistics are restored and a structured warning is attached.
5029    fn audit_solve_quality(
5030        &mut self,
5031        tnlp: Rc<RefCell<dyn TNLP>>,
5032        first_status: ApplicationReturnStatus,
5033    ) -> ApplicationReturnStatus {
5034        if !self.is_solve_quality_audit_enabled()
5035            || !matches!(
5036                first_status,
5037                ApplicationReturnStatus::SolveSucceeded
5038                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5039            )
5040        {
5041            return first_status;
5042        }
5043        let num = |name: &str, default: Number| -> Number {
5044            self.options
5045                .get_numeric_value(name, "")
5046                .ok()
5047                .and_then(|(v, f)| f.then_some(v))
5048                .unwrap_or(default)
5049        };
5050        let acceptable_tol = num("acceptable_tol", 1e-6);
5051        let masked_threshold = num("obj_scale_certificate_threshold", 1e-4);
5052        // `equilibration-based` is registered but pounce runs it as
5053        // gradient-based (see `algorithm_builder_from_options`), so it gets the
5054        // gradient-based audit.
5055        let gradient_based = self
5056            .options
5057            .get_string_value("nlp_scaling_method", "")
5058            .ok()
5059            .and_then(|(v, f)| f.then_some(v))
5060            .map(|v| v == "gradient-based" || v == "equilibration-based")
5061            .unwrap_or(true);
5062        let base = self.statistics.borrow().clone();
5063        // gh#983 review item 2: measure the objective gradient at the point
5064        // being returned, so the audit asks what re-evaluating the scaling
5065        // *there* would do instead of keying on the start alone.
5066        let final_grad_max = self
5067            .last_finalize
5068            .borrow()
5069            .as_ref()
5070            .and_then(|f| {
5071                let mut g = vec![0.0; f.x.len()];
5072                tnlp.borrow_mut()
5073                    .eval_grad_f(&f.x, true, &mut g)
5074                    .then(|| g.iter().fold(0.0_f64, |m, v| m.max(v.abs())))
5075            })
5076            .unwrap_or(Number::NAN);
5077        let rescaled_obj_scale = if final_grad_max.is_finite() {
5078            pounce_nlp::orig_ipopt_nlp::gradient_obj_scale(
5079                final_grad_max,
5080                num("nlp_scaling_max_gradient", 100.0),
5081                num("nlp_scaling_min_value", 1e-8),
5082                num("nlp_scaling_obj_target_gradient", 0.0),
5083            )
5084        } else {
5085            Number::NAN
5086        };
5087        let input = ScaleAuditInput {
5088            tol: num("tol", 1e-8),
5089            obj_scale: base.final_obj_scaling_factor,
5090            rescaled_obj_scale,
5091            start_grad_max: base.start_obj_grad_max,
5092            final_grad_max,
5093            unscaled_kkt: base.final_unscaled_kkt_error,
5094            unscaled_compl: base.final_unscaled_compl,
5095            acceptable_tol,
5096            masked_threshold,
5097            warm_start: self
5098                .options
5099                .get_bool_value("warm_start_init_point", "")
5100                .map(|(v, _)| v)
5101                .unwrap_or(false),
5102        };
5103        let grad_scale = input.grad_scale();
5104        let trigger = scale_audit_trigger(input);
5105        let mut status = first_status;
5106        match trigger {
5107            Some(ScaleAudit::SmallObjective) => {
5108                self.statistics
5109                    .borrow_mut()
5110                    .warnings
5111                    .push(scale_audit_warning(
5112                        ScaleAudit::SmallObjective,
5113                        &base,
5114                        grad_scale,
5115                        acceptable_tol,
5116                        "",
5117                    ));
5118            }
5119            Some(kind) if gradient_based => {
5120                status = self.run_scale_retry(tnlp, first_status, kind, grad_scale);
5121            }
5122            Some(kind) => {
5123                // The caller owns the scaling (`none` / `user-scaling`): not ours
5124                // to override, but the verdict still deserves its caveat.
5125                self.statistics
5126                    .borrow_mut()
5127                    .warnings
5128                    .push(scale_audit_warning(
5129                        kind,
5130                        &base,
5131                        grad_scale,
5132                        acceptable_tol,
5133                        "was not attempted: nlp_scaling_method is not gradient-based",
5134                    ));
5135            }
5136            None => {}
5137        }
5138        status
5139    }
5140
5141    /// gh#983 review items 1 and 3: the verdict-level half of the audit, run
5142    /// **once**, on the run whose point is being returned -- after every
5143    /// retry and fallback has decided.
5144    ///
5145    /// * The item-5 downgrade (a strict verdict on a run that saw the gh#884
5146    ///   signature and still carries an unscaled dual infeasibility above
5147    ///   `max(acceptable_tol, 1e-3)`) used to run inside each attempt, so it
5148    ///   could turn a base `Solve_Succeeded` into the acceptable level *before*
5149    ///   the gh#884 retry decided, reopening that retry for a case it was
5150    ///   deliberately not widened to; and it read the cumulative signature, so
5151    ///   a promoted mu-fallback run that never showed it was downgraded for its
5152    ///   discarded sibling. It now reads
5153    ///   `returned_run_dual_divergence_signature`, which the certificate floor
5154    ///   saves and restores with the rest of the run's tally.
5155    /// * The model-scale caveats ([`quality_warnings`]) are attached here, and
5156    ///   deduplicated by code, so a code appears at most once.
5157    fn finalize_quality_verdict(
5158        &mut self,
5159        status: ApplicationReturnStatus,
5160    ) -> ApplicationReturnStatus {
5161        if !self.is_solve_quality_audit_enabled() {
5162            return status;
5163        }
5164        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5165        let mut status = status;
5166        if matches!(status, ApplicationReturnStatus::SolveSucceeded) {
5167            let (sig, du, du_scale) = {
5168                let st = self.statistics.borrow();
5169                (
5170                    st.returned_run_dual_divergence_signature,
5171                    st.final_unscaled_dual_inf,
5172                    st.final_unscaled_dual_scale,
5173                )
5174            };
5175            // gh#983 item 5. `1e-3` is `UNSCALED_DUAL_WARN`; the measured
5176            // population behind it is in that constant's doc. A residual at
5177            // the rounding floor of its own terms is not evidence of a miss
5178            // (gh#1000, II.22): see `UNSCALED_DUAL_ROUNDOFF_ULPS`.
5179            if sig
5180                && du.is_finite()
5181                && du > acceptable_tol.max(UNSCALED_DUAL_WARN)
5182                && !unscaled_dual_inf_is_roundoff(du, du_scale)
5183            {
5184                status = ApplicationReturnStatus::SolvedToAcceptableLevel;
5185                push_warning_once(
5186                    &mut self.statistics.borrow_mut().warnings,
5187                    format!(
5188                        "unscaled_dual_inf_above_acceptable: the run saw a settled primal with a \
5189                         runaway multiplier (gh#884) and the returned point's unscaled dual \
5190                         infeasibility is {du:.2e}, above {:.0e}; the status is downgraded from \
5191                         Solve_Succeeded to Solved_To_Acceptable_Level",
5192                        acceptable_tol.max(UNSCALED_DUAL_WARN)
5193                    ),
5194                );
5195            }
5196        }
5197        let st = self.statistics.borrow().clone();
5198        let extra = quality_warnings(
5199            status,
5200            st.final_unscaled_dual_inf,
5201            st.final_unscaled_dual_scale,
5202            self.options
5203                .get_numeric_value("dual_inf_tol", "")
5204                .map(|(v, _)| v)
5205                .unwrap_or(1.0),
5206            acceptable_tol,
5207            self.options
5208                .get_numeric_value("bound_relax_factor", "")
5209                .is_ok_and(|(v, _)| v == 0.0),
5210        );
5211        let mut sm = self.statistics.borrow_mut();
5212        for w in extra {
5213            push_warning_once(&mut sm.warnings, w);
5214        }
5215        status
5216    }
5217
5218    /// The variable box `tnlp` declares, `(x_L, x_U)` in its own (full-x)
5219    /// space -- the space a `finalize_solution` payload is in. `None` if the
5220    /// TNLP declines to say.
5221    fn declared_x_box(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> Option<(Vec<Number>, Vec<Number>)> {
5222        let mut t = tnlp.borrow_mut();
5223        let info = t.get_nlp_info()?;
5224        let (n, m) = (info.n.max(0) as usize, info.m.max(0) as usize);
5225        let (mut x_l, mut x_u) = (vec![0.0; n], vec![0.0; n]);
5226        let (mut g_l, mut g_u) = (vec![0.0; m], vec![0.0; m]);
5227        t.get_bounds_info(BoundsInfo {
5228            x_l: &mut x_l,
5229            x_u: &mut x_u,
5230            g_l: &mut g_l,
5231            g_u: &mut g_u,
5232        })
5233        .then_some((x_l, x_u))
5234    }
5235
5236    /// The re-solve half of [`Self::audit_solve_quality`].
5237    fn run_scale_retry(
5238        &mut self,
5239        tnlp: Rc<RefCell<dyn TNLP>>,
5240        first_status: ApplicationReturnStatus,
5241        kind: ScaleAudit,
5242        grad_scale: Number,
5243    ) -> ApplicationReturnStatus {
5244        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5245        let solution_floor = self.last_finalize.borrow().clone();
5246        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
5247        let trace_floor = *self.last_iter_stats.borrow();
5248        let base = self.statistics.borrow().clone();
5249        let Some(seed) = solution_floor.as_ref().map(|f| f.x.clone()) else {
5250            return first_status;
5251        };
5252        // Budget the re-solve: an iteration cap tied to the base solve
5253        // (`SCALE_AUDIT_RETRY_ITER_FACTOR`), and only the time the caller's
5254        // limits have left. Every solve builds a fresh deadline, so without
5255        // this the re-solve got a second full `max_cpu_time` / `max_wall_time`
5256        // after the run had already succeeded. Restored below, absence as
5257        // absence.
5258        let prev_iter = self.options.get_integer_value("max_iter", "").ok();
5259        let prev_cpu = self.options.get_numeric_value("max_cpu_time", "").ok();
5260        let prev_wall = self.options.get_numeric_value("max_wall_time", "").ok();
5261        let cpu_left = prev_cpu.map(|(v, _)| v - base.total_cpu_time_secs);
5262        let wall_left = prev_wall.map(|(v, _)| v - base.total_wallclock_time_secs);
5263        if cpu_left.is_some_and(|t| t <= 0.0) || wall_left.is_some_and(|t| t <= 0.0) {
5264            return first_status;
5265        }
5266        let retry_iter = (SCALE_AUDIT_RETRY_ITER_FACTOR * base.iteration_count)
5267            .max(SCALE_AUDIT_RETRY_MIN_ITER)
5268            .min(prev_iter.map_or(Index::MAX, |(v, _)| v));
5269        let seeded: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(
5270            pounce_nlp::seeded_tnlp::SeededTnlp::new(Rc::clone(&tnlp), seed),
5271        ));
5272        // gh#983 review item 7: remember whether the caller *named* the
5273        // factor, so the restore puts back absence as absence. Writing the
5274        // default back with `found = true` left `obj_scaling_factor` reading as
5275        // user-set after the audit, which every "did the caller name it" test
5276        // downstream (`TERMINATION_POLICY_OPTIONS`, the gh#884 sense) then
5277        // misread.
5278        let prev_user = self
5279            .options
5280            .get_numeric_value("obj_scaling_factor", "")
5281            .ok()
5282            .and_then(|(v, f)| f.then_some(v));
5283        let prev_user_factor = prev_user.unwrap_or(1.0);
5284        let caller_named_relax = self
5285            .options
5286            .get_numeric_value("bound_relax_factor", "")
5287            .is_ok_and(|(_, found)| found);
5288        // Everything below until the scope drops is this re-solve's own
5289        // configuration; the scope puts every entry back, and clears the box
5290        // flag, however the re-solve exits.
5291        let mut scope = RetryOptionScope::enter(
5292            self,
5293            &[
5294                "obj_scaling_factor",
5295                "max_iter",
5296                "max_cpu_time",
5297                "max_wall_time",
5298            ],
5299            false,
5300        );
5301        if let ScaleAudit::Upscale(k) = kind {
5302            let _ = scope.options.set_numeric_value(
5303                "obj_scaling_factor",
5304                prev_user_factor * k,
5305                true,
5306                false,
5307            );
5308        }
5309        let _ = scope
5310            .options
5311            .set_integer_value("max_iter", retry_iter, true, false);
5312        // Solve the re-solve on the caller's own variable box: the rows are
5313        // widened by `bound_relax_factor` exactly as in the base attempt, the
5314        // box is not -- unless the caller named a widening.
5315        //
5316        // The re-solve exists to drive complementarity down (`Upscale`) or the
5317        // unscaled residual (`Rescale`), and on a bound-active variable that
5318        // is the same motion as driving the point onto its bound: `s · z = mu`
5319        // with `z` multiplied by the objective factor, so the slack to the
5320        // *widened* bound shrinks by that factor and the point lands at
5321        // `x_U + bound_relax_factor · max(1, |x_U|)` -- outside the box the
5322        // caller wrote. The base attempt, less converged, usually sat inside
5323        // it. So every promoted re-solve on a bound-active model shipped a
5324        // point outside its declared bounds: measured with `pounce verify`,
5325        // `ex1_320` `1.0e-8` across thousands of controls, `trainf` `7.0e-8`,
5326        // `reading1` `9.9e-9`, against `0` from the base attempt.
5327        //
5328        // The improvement itself is real, not bought with that slack: solved
5329        // with the declared box the re-solve reaches the same objective
5330        // (`reading1` `-1.604802802e-1` against `-1.604802843e-1` widened, the
5331        // base attempt's `-1.604578481e-1`) with the box held exactly. So the
5332        // box widening is dropped for this one solve rather than the re-solve
5333        // refused: it starts from a point that already satisfies the box, and
5334        // `bound_push` moves the seed off any bound it sits on.
5335        //
5336        // Why the box and not `bound_relax_factor=0`: that also un-widens the
5337        // inequality rows, which makes the re-solve a strictly tighter model
5338        // than the base attempt, and its objective then reads *worse* than
5339        // the base's by the row widening's worth -- measured on
5340        // `masked_certificate_fuzz` case 12, `-3.453863914e7` against
5341        // `-3.453863947e7`, with both points inside their box. The rows are
5342        // what the base attempt's `final_unscaled_constr_viol` and rule 2 of
5343        // `retry_answer_is_admissible` already compare like with like; the box
5344        // is the one thing neither did.
5345        //
5346        // A caller who named the factor defined the model that way and keeps
5347        // it; for that case the declared-box conjunct of the promotion gate
5348        // below is what holds the line.
5349        scope.retry_keeps_declared_box.set(!caller_named_relax);
5350        if let Some(t) = cpu_left {
5351            let _ = scope
5352                .options
5353                .set_numeric_value("max_cpu_time", t, true, false);
5354        }
5355        if let Some(t) = wall_left {
5356            let _ = scope
5357                .options
5358                .set_numeric_value("max_wall_time", t, true, false);
5359        }
5360        tracing::debug!(target: "pounce::algorithm",
5361            "[POUNCE] gh#983: {:?} verdict audited ({:?}); re-solving from the \
5362             returned point (max_iter {retry_iter}).", first_status, kind);
5363        // One IPM solve, without the mu-strategy fallback: the re-solve is
5364        // already a second opinion on a run that succeeded, and when it hit
5365        // its cap the flip spent the same budget again (`meyer3` 768 + 768,
5366        // `brainpc3` 120 + 120, `brainpc9` timing out in the second leg).
5367        // No promoted re-solve in the release sweep needed the flip except
5368        // `robot_b` past the cap, which keeps its `Solve_Succeeded` base.
5369        if match scope.options.get_integer_value("print_level", "") {
5370            Ok((v, true)) => v >= 1,
5371            _ => true,
5372        } {
5373            println!();
5374            println!(
5375                "gh#983 scale audit: re-solving from the returned point ({kind:?}); the \
5376                 summary below is a candidate's, and the line after it says whether it \
5377                 replaced the answer above."
5378            );
5379        }
5380        let retry_status = scope.optimize_constrained(Rc::clone(&seeded));
5381        drop(scope);
5382        let retry = self.statistics.borrow().clone();
5383        let sense = if prev_user_factor < 0.0 { -1.0 } else { 1.0 };
5384        let clean = match first_status {
5385            ApplicationReturnStatus::SolveSucceeded => {
5386                matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
5387            }
5388            _ => matches!(
5389                retry_status,
5390                ApplicationReturnStatus::SolveSucceeded
5391                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5392            ),
5393        };
5394        let better = match kind {
5395            ScaleAudit::Rescale => retry.final_unscaled_kkt_error < base.final_unscaled_kkt_error,
5396            ScaleAudit::Upscale(_) | ScaleAudit::SmallObjective => {
5397                retry.final_unscaled_compl < 0.1 * base.final_unscaled_compl
5398                    && retry.final_unscaled_kkt_error <= base.final_unscaled_kkt_error
5399            }
5400        };
5401        let admissible = retry_answer_is_admissible(
5402            certificate_floor.objective,
5403            certificate_floor.unscaled_constr_viol,
5404            retry.final_objective,
5405            retry.final_unscaled_constr_viol,
5406            acceptable_tol,
5407            sense,
5408        );
5409        // Measured on the two `finalize_solution` payloads -- the points a
5410        // caller would actually receive -- against the box the user TNLP
5411        // declares.
5412        let (base_box_rel, retry_box_rel) = match self.declared_x_box(&tnlp) {
5413            Some((x_l, x_u)) => {
5414                let (lo, up) = (self.nlp_lower_bound_inf(), self.nlp_upper_bound_inf());
5415                let rel = |x: &[Number]| declared_box_relative_violation(x, &x_l, &x_u, lo, up);
5416                (
5417                    solution_floor.as_ref().map_or(Number::NAN, |f| rel(&f.x)),
5418                    self.last_finalize
5419                        .borrow()
5420                        .as_ref()
5421                        .map_or(Number::NAN, |f| rel(&f.x)),
5422                )
5423            }
5424            None => (Number::NAN, Number::NAN),
5425        };
5426        let keeps_box = retry_keeps_declared_box(base_box_rel, retry_box_rel);
5427        let promote = clean && better && admissible && keeps_box;
5428        let console_output = match self.options.get_integer_value("print_level", "") {
5429            Ok((v, true)) => v >= 1,
5430            _ => true,
5431        };
5432        if console_output {
5433            println!();
5434            if clean && better && admissible && !keeps_box {
5435                println!(
5436                    "gh#983 scale audit: declined (the re-solve's point is {:.4e} outside the \
5437                     declared variable bounds, the base attempt's {:.4e}); the base attempt's \
5438                     answer is the one reported.",
5439                    retry.final_declared_box_viol, certificate_floor.declared_box_viol
5440                );
5441            } else if promote {
5442                println!(
5443                    "gh#983 scale audit: promoted -- unscaled KKT error {:.4e} -> {:.4e}, \
5444                     unscaled complementarity {:.4e} -> {:.4e}.",
5445                    base.final_unscaled_kkt_error,
5446                    retry.final_unscaled_kkt_error,
5447                    base.final_unscaled_compl,
5448                    retry.final_unscaled_compl
5449                );
5450            } else {
5451                println!(
5452                    "gh#983 scale audit: declined ({retry_status:?}, unscaled KKT error \
5453                     {:.4e} against the base attempt's {:.4e}); the base attempt's answer \
5454                     is the one reported.",
5455                    retry.final_unscaled_kkt_error, base.final_unscaled_kkt_error
5456                );
5457            }
5458            if !promote {
5459                // The re-solve's own end summary printed above this line, with
5460                // *its* objective and bound violation, before the verdict was
5461                // known (`emit_end_summary` runs inside each attempt). Say
5462                // which block that was and restate the numbers that ship, so
5463                // the console cannot be read as reporting the discarded point.
5464                println!(
5465                    "gh#983 scale audit: the summary block above is the discarded re-solve's; \
5466                     the reported answer is the base attempt's (objective {:.16e}, variable \
5467                     bound violation {:.16e}).",
5468                    certificate_floor.objective, certificate_floor.declared_box_viol
5469                );
5470            }
5471        }
5472        if promote {
5473            return retry_status;
5474        }
5475        if let Some(floor) = solution_floor {
5476            floor.replay(&tnlp);
5477            self.answer_restored_from_floor.set(true);
5478            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5479            self.statistics.borrow_mut().dual_divergence_signature |=
5480                retry.dual_divergence_signature;
5481            if let Some(stats) = trace_floor {
5482                let _ = tnlp.borrow_mut().intermediate_callback(
5483                    stats,
5484                    &TnlpIpoptData::default(),
5485                    &TnlpIpoptCq::default(),
5486                );
5487            }
5488        }
5489        let detail = if keeps_box {
5490            format!(
5491                "was declined: the re-solve returned {retry_status:?} with unscaled KKT error {:.2e}",
5492                retry.final_unscaled_kkt_error
5493            )
5494        } else {
5495            format!(
5496                "was declined: the re-solve returned {retry_status:?} at a point {:.2e} outside \
5497                 the declared variable bounds",
5498                retry.final_declared_box_viol
5499            )
5500        };
5501        self.statistics
5502            .borrow_mut()
5503            .warnings
5504            .push(scale_audit_warning(
5505                kind,
5506                &base,
5507                grad_scale,
5508                acceptable_tol,
5509                &detail,
5510            ));
5511        first_status
5512    }
5513
5514    /// The tolerance conjunct 4 of the dual-divergence promotion gate
5515    /// tests the retry's *unscaled* residuals against.
5516    ///
5517    /// `acceptable_tol`-scale rather than `tol`-scale on purpose: the
5518    /// unscaled residual is the one quantity nothing in the solve is
5519    /// driven against, so holding it to `tol` would decline honest
5520    /// retries on badly scaled models for a reason that has nothing to
5521    /// do with gh#884. `qpec_small`'s honest retry reaches `9.96e-8`,
5522    /// four orders inside it.
5523    fn dual_divergence_retry_accept_tol(&self) -> Number {
5524        self.options
5525            .get_numeric_value("acceptable_tol", "")
5526            .ok()
5527            .and_then(|(v, f)| f.then_some(v))
5528            .unwrap_or(1e-6)
5529    }
5530
5531    /// Phase-3 ℓ₁-exact penalty-barrier outer loop.
5532    ///
5533    /// Builds an [`L1PenaltyBarrierTnlp`] wrapper around the user
5534    /// TNLP, runs the constrained IPM at the current ρ, escalates ρ
5535    /// per Byrd-Nocedal-Waltz steering, and terminates on any of:
5536    ///   - slack sum collapses (`Σ(p+n) ≤ l1_slack_tol`)
5537    ///   - inner solve returns non-Optimal (escalation won't fix
5538    ///     numerical / restoration failure at this ρ)
5539    ///   - ρ already at `l1_penalty_max`
5540    ///   - `l1_penalty_max_outer_iter` reached
5541    ///
5542    /// After the loop, if the inner status is `SolveSucceeded` or
5543    /// `SolvedToAcceptableLevel` but slacks didn't collapse, override
5544    /// to `Infeasible_Problem_Detected` — the returned point is the
5545    /// ℓ₁-best least-infeasible iterate, which is informative even
5546    /// though the original constraints are not satisfied.
5547    ///
5548    /// Returns `Some(status)` if the wrapper ran the solve, `None` if
5549    /// wrapper construction failed (caller should fall through to the
5550    /// standard dispatch path).
5551    fn run_l1_penalty_outer_loop(
5552        &mut self,
5553        tnlp: Rc<RefCell<dyn TNLP>>,
5554    ) -> Option<ApplicationReturnStatus> {
5555        let rho_init = self.l1_penalty_init();
5556        let rho_max = self.l1_penalty_max().max(rho_init);
5557        let factor = self.l1_penalty_increase_factor().max(1.0);
5558        let tau = self.l1_steering_factor();
5559        let slack_tol = self.l1_slack_tol();
5560        let max_outer = self.l1_penalty_max_outer_iter().max(1);
5561
5562        let mut wrapper = pounce_l1penalty::L1PenaltyBarrierTnlp::new(Rc::clone(&tnlp), rho_init)?;
5563        if wrapper.m_eq() == 0 {
5564            // Nothing to slack — let the standard dispatch path handle
5565            // this TNLP unmodified.
5566            return None;
5567        }
5568        wrapper.set_defer_inner_finalize(true);
5569        let wrapper_rc = Rc::new(RefCell::new(wrapper));
5570
5571        let mut rho = rho_init;
5572        let mut last_status = ApplicationReturnStatus::InternalError;
5573        // gh#987 item 6: every pass resets the statistics, so without this the
5574        // report described only the last ρ — `iter_count` 26 for a solve that
5575        // ran 18 + 22 + 22 + 26 iterations. Accumulated here, applied once
5576        // after the loop.
5577        let mut totals = MultiPassTotals::default();
5578        for _outer in 0..max_outer {
5579            wrapper_rc.borrow_mut().set_rho(rho);
5580            let dyn_tnlp: Rc<RefCell<dyn TNLP>> = wrapper_rc.clone();
5581            last_status = self.optimize_constrained(dyn_tnlp);
5582            totals.push_pass(&self.statistics.borrow(), Some(rho), last_status);
5583
5584            let w = wrapper_rc.borrow();
5585            if !w.has_solution() {
5586                // Inner solve aborted before producing an iterate.
5587                drop(w);
5588                break;
5589            }
5590            let slack_sum = w.last_slack_sum();
5591            let y_eq_inf = w.last_y_eq_inf_norm();
5592            let x_here: Vec<Number> = w.last_x_trunc().to_vec();
5593            drop(w);
5594            totals.set_slack_sum(slack_sum);
5595
5596            // Termination decisions.
5597            let inner_ok = matches!(
5598                last_status,
5599                ApplicationReturnStatus::SolveSucceeded
5600                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5601            );
5602            if !inner_ok {
5603                break;
5604            }
5605            // Stop escalating ρ once the **user's** constraints are
5606            // satisfied to the tolerance the caller asked for — not once
5607            // `Σ(p + n)` falls under `l1_slack_tol`, which is a different
5608            // quantity judged by a different number (gh#794 P1). The
5609            // slack sum stays the BNW steering signal below, which is
5610            // the job it is right for. One extra `eval_g` per outer
5611            // iteration buys the difference between stopping at the
5612            // penalty solution and stopping at the model's own.
5613            let feasible_here = {
5614                let m_inner = tnlp
5615                    .borrow_mut()
5616                    .get_nlp_info()
5617                    .map(|i| i.m.max(0) as usize)
5618                    .unwrap_or(0);
5619                let mut g_here = vec![0.0; m_inner];
5620                let evaluated =
5621                    m_inner == 0 || tnlp.borrow_mut().eval_g(&x_here, true, &mut g_here);
5622                evaluated
5623                    .then(|| {
5624                        original_space_feasibility(
5625                            &tnlp,
5626                            &x_here,
5627                            &g_here,
5628                            self.nlp_lower_bound_inf(),
5629                            self.nlp_upper_bound_inf(),
5630                            self.user_tol(),
5631                            self.user_acceptable_tol(),
5632                            self.user_constr_viol_tol(),
5633                            self.user_acceptable_constr_viol_tol(),
5634                            self.user_primal_noise_floor_kappa(),
5635                        )
5636                    })
5637                    .flatten()
5638                    .map(|f| {
5639                        totals.set_violation(f.max_violation);
5640                        f.negligible_at_tol
5641                    })
5642            };
5643            match feasible_here {
5644                Some(true) => break,
5645                Some(false) => {}
5646                // Unmeasurable model: fall back to the historical
5647                // slack-sum test rather than looping to the cap.
5648                None if slack_sum.is_finite() && slack_sum <= slack_tol => break,
5649                None => {}
5650            }
5651            if rho >= rho_max {
5652                break;
5653            }
5654            // BNW steering: ρ_new = max(ρ·factor, τ·‖y_eq‖∞ + ε)
5655            let geom = rho * factor;
5656            let steer = tau * y_eq_inf + 1.0e-12;
5657            rho = geom.max(steer).min(rho_max);
5658        }
5659
5660        // gh#987 item 6: total iterations and the per-pass summary.
5661        totals.apply(&mut self.statistics.borrow_mut());
5662
5663        // Forward to the user's inner.finalize_solution exactly once.
5664        let w = wrapper_rc.borrow();
5665        if w.has_solution() {
5666            let x_trunc: Vec<Number> = w.last_x_trunc().to_vec();
5667            let lambda: Vec<Number> = w.last_lambda().to_vec();
5668            let z_l: Vec<Number> = w.last_z_l_trunc().to_vec();
5669            let z_u: Vec<Number> = w.last_z_u_trunc().to_vec();
5670            let solver_status = w.last_status().unwrap_or(SolverReturn::InternalError);
5671            let slack_sum = w.last_slack_sum();
5672            drop(w);
5673
5674            // Recompute f(x*) and c(x*) on the inner. Both are needed
5675            // before the status is decided, because the status now turns
5676            // on the *original-space* feasibility at this point.
5677            let f_inner = tnlp
5678                .borrow_mut()
5679                .eval_f(&x_trunc, true)
5680                .unwrap_or(Number::NAN);
5681            let m = tnlp
5682                .borrow_mut()
5683                .get_nlp_info()
5684                .map(|i| i.m as usize)
5685                .unwrap_or(0);
5686            // The success flag decides whether `g_inner` is a measurement
5687            // or a zero-filled buffer. Dropping it would let a TNLP whose
5688            // final `eval_g` fails fabricate feasibility: every row would
5689            // read `0`, `original_space_feasibility` would return a
5690            // violation of zero, and that would flow into both the exit
5691            // status and the reported residuals. Gate it exactly as the
5692            // ρ-escalation measurement above does, so an evaluation
5693            // failure produces `None` and follows the documented
5694            // `l1_slack_tol` fallback instead (gh#794 review).
5695            let mut g_inner = vec![0.0; m];
5696            let g_evaluated = m == 0 || tnlp.borrow_mut().eval_g(&x_trunc, false, &mut g_inner);
5697
5698            // gh#794 P1. Everything below used to argue from `Σ(p + n)`,
5699            // the sum of the augmented slacks, judged against
5700            // `l1_slack_tol`. That is not the user's constraint
5701            // violation and it is not judged by the user's tolerance:
5702            //
5703            //   * the violation of equality row `i` is `|p_i − n_i|`,
5704            //     not `p_i + n_i`, and at the barrier's interior both
5705            //     slacks stay positive where their difference is zero,
5706            //     so the sum is an upper bound that is loose in one
5707            //     direction; and
5708            //   * `l1_slack_tol` defaults to `1e-6`, four orders looser
5709            //     than a `tol = 1e-8` solve asked for, so a violation
5710            //     that the solver's own strict gate would refuse on the
5711            //     unwrapped problem read as "the constraints are
5712            //     satisfied".
5713            //
5714            // Measured, not argued: the MPCC benchmark's `ralph1`
5715            // (`benchmarks/mpcc/`) returned `Solve_Succeeded` at a point
5716            // violating its one equality row by `2.5e-07`, with the
5717            // reported `final_constr_viol` — the *augmented* residual —
5718            // at `9.6e-15`, so no field in the result disclosed it. The
5719            // objective came back `5.0e-04` below the true optimum,
5720            // which is reachable only off the feasible set.
5721            //
5722            // So: measure the user's own rows at the returned point, and
5723            // judge them by the tolerances the caller set. The slack sum
5724            // keeps its other job unchanged — it is the BNW steering
5725            // signal for ρ escalation inside the loop above, which is
5726            // what it is the right quantity for.
5727            let feas = g_evaluated
5728                .then(|| {
5729                    original_space_feasibility(
5730                        &tnlp,
5731                        &x_trunc,
5732                        &g_inner,
5733                        self.nlp_lower_bound_inf(),
5734                        self.nlp_upper_bound_inf(),
5735                        self.user_tol(),
5736                        self.user_acceptable_tol(),
5737                        self.user_constr_viol_tol(),
5738                        self.user_acceptable_constr_viol_tol(),
5739                        self.user_primal_noise_floor_kappa(),
5740                    )
5741                })
5742                .flatten();
5743
5744            // The reported constraint violation must be the user's, not
5745            // the augmented problem's. Without this the KKT block of a
5746            // successful ℓ₁ solve describes a problem the caller never
5747            // posed. The aggregate errors take a `max` rather than a
5748            // rewrite: the NLP error's primal term enters undivided, so
5749            // the aggregate is never below the constraint violation, and
5750            // the other two components are unaffected by the wrapper.
5751            //
5752            // `f.max_violation` is measured on the inner TNLP's own rows
5753            // and bounds, so it is in the model's **original units**. That
5754            // decides which field family may carry it. `SolveStatistics`
5755            // documents `final_*` as the max-norms in the internally
5756            // scaled NLP space and `final_unscaled_*` as the same
5757            // residuals with the scaling divided back out — equal only
5758            // when no scaling is active — and `docs/src/python.md` states
5759            // the same contract to Python callers. Writing an
5760            // original-units number into `final_constr_viol` would break
5761            // it on any run with `nlp_scaling_method` engaged (gh#794
5762            // review).
5763            //
5764            // So the unscaled family always takes the measurement, and
5765            // the scaled family mirrors it exactly when per-row scaling
5766            // did not engage — the case in which the contract requires
5767            // the two to agree anyway. Under active row scaling the
5768            // scaled fields keep what the inner solve reported; the
5769            // converted number is not available here, because the
5770            // augmented problem's row-scale factors belong to an NLP that
5771            // `optimize_constrained` has already dropped. The status
5772            // decision below does not read these fields — it reads
5773            // `feas` directly — so an active-scaling run is judged on the
5774            // user's rows either way.
5775            // gh#987 (remaining item b): `final_declared_constr_viol` is the
5776            // violation of the model AS THE USER DECLARED IT. The inner
5777            // solve's value describes the wrapper's augmented rows, where
5778            // the elastic slacks absorb any violation, so it read ~1e-12
5779            // even at an infeasible point. Overwrite it with the measurement
5780            // on the user's own rows and box (original units, the same
5781            // quantity the non-l1 path reports); `NaN` when the model could
5782            // not be evaluated, never the augmented number.
5783            self.statistics.borrow_mut().final_declared_constr_viol =
5784                feas.as_ref().map_or(Number::NAN, |f| f.max_violation);
5785            if let Some(f) = feas.as_ref() {
5786                let scaled_may_mirror = self.row_scaling_active.get() == Some(false);
5787                let mut stats = self.statistics.borrow_mut();
5788                stats.final_unscaled_constr_viol = f.max_violation;
5789                stats.final_unscaled_kkt_error =
5790                    stats.final_unscaled_kkt_error.max(f.max_violation);
5791                if scaled_may_mirror {
5792                    stats.final_constr_viol = f.max_violation;
5793                    stats.final_kkt_error = stats.final_kkt_error.max(f.max_violation);
5794                    stats.final_kkt_error_above_noise =
5795                        stats.final_kkt_error_above_noise.max(f.max_violation);
5796                }
5797            }
5798
5799            let inner_claimed_success = matches!(
5800                last_status,
5801                ApplicationReturnStatus::SolveSucceeded
5802                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5803            );
5804
5805            // Downgrade, not upgrade: a solve that reached the strict
5806            // standard on the user's own rows keeps whatever status the
5807            // inner gave it, and nothing here can turn a failure into a
5808            // success.
5809            let downgrade_to_acceptable = inner_claimed_success
5810                && feas
5811                    .as_ref()
5812                    .is_some_and(|f| !f.negligible_at_tol && f.negligible_at_acceptable);
5813
5814            let infeasible_certificate = inner_claimed_success
5815                && match feas.as_ref() {
5816                    // Measured: the point does not satisfy the user's
5817                    // constraints even to `acceptable_tol`.
5818                    Some(f) => !f.negligible_at_acceptable,
5819                    // Unmeasurable model — fall back to the historical
5820                    // slack-sum argument rather than to silence.
5821                    None => slack_sum.is_finite() && slack_sum > slack_tol,
5822                };
5823
5824            if let Some(f) = feas.as_ref()
5825                && inner_claimed_success
5826                && !f.negligible_at_tol
5827            {
5828                tracing::info!(
5829                    target: "pounce::application",
5830                    "l1 penalty-barrier: the inner solve converged the augmented NLP, \
5831                     but the returned point violates the model's own constraints by \
5832                     {:.3e}, which does not meet tol; reporting {} rather than success \
5833                     (gh#794)",
5834                    f.max_violation,
5835                    if f.negligible_at_acceptable {
5836                        "Solved_To_Acceptable_Level"
5837                    } else {
5838                        "an infeasibility verdict"
5839                    },
5840                );
5841            }
5842            // …unless the model's own starting point satisfies every
5843            // constraint, which disproves the certificate outright (gh #379).
5844            // Same gate as the IPM and SQP paths; see
5845            // `withdraw_infeasibility_if_refuted`.
5846            let refuted = infeasible_certificate
5847                && withdraw_infeasibility_if_refuted(
5848                    &tnlp,
5849                    SolverReturn::LocalInfeasibility,
5850                    self.nlp_lower_bound_inf(),
5851                    self.nlp_upper_bound_inf(),
5852                    self.user_tol(),
5853                ) != SolverReturn::LocalInfeasibility;
5854            let final_solver_status = match (infeasible_certificate, refuted) {
5855                (true, false) => SolverReturn::LocalInfeasibility,
5856                // The point is not feasible, so `Solve_Succeeded` would be
5857                // just as wrong as `Infeasible_Problem_Detected`. Report the
5858                // breakdown.
5859                (true, true) => SolverReturn::ErrorInStepComputation,
5860                (false, _) if downgrade_to_acceptable => SolverReturn::StopAtAcceptablePoint,
5861                (false, _) => solver_status,
5862            };
5863            let final_app_status = match (infeasible_certificate, refuted) {
5864                (true, false) => ApplicationReturnStatus::InfeasibleProblemDetected,
5865                (true, true) => ApplicationReturnStatus::ErrorInStepComputation,
5866                (false, _) if downgrade_to_acceptable => {
5867                    ApplicationReturnStatus::SolvedToAcceptableLevel
5868                }
5869                (false, _) => last_status,
5870            };
5871
5872            tnlp.borrow_mut().finalize_solution(
5873                Solution {
5874                    status: final_solver_status,
5875                    x: &x_trunc,
5876                    z_l: &z_l,
5877                    z_u: &z_u,
5878                    g: &g_inner,
5879                    lambda: &lambda,
5880                    obj_value: f_inner,
5881                },
5882                &TnlpIpoptData::default(),
5883                &TnlpIpoptCq::default(),
5884            );
5885            return Some(final_app_status);
5886        }
5887        // No solution captured at all — pass the inner status through.
5888        Some(last_status)
5889    }
5890
5891    /// Constrained-NLP path: build adapter → OrigIpoptNlp → algorithm
5892    /// bundle, run `optimize`, populate statistics, and call
5893    /// `finalize_solution` on the user's TNLP.
5894    /// Whether an over-determined model (more equality rows than free
5895    /// variables) is *provably* infeasible by linear bound propagation.
5896    ///
5897    /// Consulted only on the `NotEnoughDegreesOfFreedom` failure path, where
5898    /// the solve never runs and therefore can never itself discover the
5899    /// infeasibility (gh#387). Builds a throwaway presolve wrapper with only
5900    /// Phase 1 (bound tightening) enabled and asks it for a certified proof —
5901    /// this inherits the certification safety net wholesale: the crossing must
5902    /// exceed the solver's own acceptance margin at the crossed pair's scale,
5903    /// and a concrete witness point satisfying every constraint withdraws the
5904    /// verdict. A `false` here costs nothing but keeping the DOF error.
5905    ///
5906    /// The witness gate runs under [`pounce_presolve::WitnessRule`]'s
5907    /// `DeclaredRowRelative` form, which is admissible only because the solve
5908    /// cannot run on this path (gh#391) — see the comment on the probe below.
5909    ///
5910    /// Deliberately independent of the `presolve` master switch: this is not a
5911    /// model transformation (the wrapper is dropped without solving through
5912    /// it), it is a last check before reporting a structural error for a
5913    /// problem whose verdict is already decided.
5914    fn overdetermined_model_certified_infeasible(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> bool {
5915        let mut opts = pounce_presolve::PresolveOptions::from_options_list(&self.options)
5916            .unwrap_or_else(|_| pounce_presolve::PresolveOptions::defaults());
5917        opts.enabled = true;
5918        opts.bound_tightening = true;
5919        // Certification needs Phase 1 only; every transformative or
5920        // diagnostic phase is dead weight on a wrapper that is never
5921        // solved through.
5922        opts.auxiliary = false;
5923        opts.fbbt = false;
5924        opts.redundant_constraint_removal = false;
5925        opts.licq_check = false;
5926        opts.warm_z_bounds = false;
5927        // The one place the witness rule is raised off the solver's own
5928        // acceptance test (gh#391). It is sound *here specifically* because the
5929        // gate has already established the solve cannot run: the alternative to
5930        // the proof is the structural 5xx error, never `Solve_Succeeded`, so
5931        // the #380 "two routes, two answers" contradiction the clamp exists to
5932        // prevent has no second route to contradict. See `WitnessRule` for the
5933        // full argument and the homogeneous-row fallback.
5934        let mut probe =
5935            pounce_presolve::PresolveTnlp::new(Rc::clone(tnlp), opts).probing_without_a_solve();
5936        if probe.get_nlp_info().is_none() {
5937            return false;
5938        }
5939        probe.certified_infeasible().is_some()
5940    }
5941
5942    fn optimize_constrained(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
5943        let t_start = Instant::now();
5944
5945        // Invalidate the row-scaling record before anything can read it.
5946        //
5947        // It is written near the end of this function, from the NLP the
5948        // solve actually built, so a solve that bails before that point
5949        // leaves whatever the *previous* one recorded. The ℓ₁ outer loop
5950        // calls this repeatedly and reads the flag after each call, so a
5951        // stale `Some(false)` would let it mirror an original-units
5952        // violation into the scaled family — the exact contract this flag
5953        // exists to protect (gh#794 review round 2). Clearing it here
5954        // makes the failure mode fail-closed: "not recorded" reads as
5955        // "cannot mirror", never as "scaling was off".
5956        self.row_scaling_active.set(None);
5957        // gh#983 review item 1: the structured warnings describe the run whose
5958        // point is returned, so each attempt starts with none. They used to
5959        // accumulate on the application for its lifetime, and a promoted
5960        // gh#884 retry (`Solve_Succeeded` at `du = 1.6e-7`) carried the
5961        // discarded base attempt's `large_dual_scale ... 1.43e9`. A declined
5962        // retry restores the floored attempt's own list via
5963        // `SolutionCertificate`.
5964        self.statistics.borrow_mut().warnings.clear();
5965        self.statistics
5966            .borrow_mut()
5967            .returned_run_dual_divergence_signature = false;
5968
5969        // `print_user_options yes` — dump the OptionsList before the
5970        // solve. Mirrors `IpoptApplication::call_optimize` (upstream
5971        // calls `Jnlst().Printf(.., "%s", options_->PrintUserOptions())`).
5972        let print_opts = self
5973            .options
5974            .get_bool_value("print_user_options", "")
5975            .ok()
5976            .and_then(|(v, f)| f.then_some(v))
5977            .unwrap_or(false);
5978        if print_opts {
5979            print!(
5980                "\nList of user-set options:\n\n{}",
5981                self.options.print_user_options()
5982            );
5983        }
5984
5985        // `print_options_documentation yes` — dump the full registry
5986        // (every option with type, default, valid range/strings, and
5987        // long description) before the solve. Honors
5988        // `print_options_mode` (`text` / `latex` / `doxygen`; only
5989        // `text` is implemented today, the others fall through with a
5990        // one-line note) and `print_advanced_options`. Mirrors
5991        // upstream `IpoptApplication::call_optimize`'s
5992        // `print_options_documentation` branch and `Common/IpRegOptions.cpp`
5993        // `OutputOptionDocumentation`.
5994        let print_doc = self
5995            .options
5996            .get_bool_value("print_options_documentation", "")
5997            .ok()
5998            .and_then(|(v, f)| f.then_some(v))
5999            .unwrap_or(false);
6000        if print_doc {
6001            let mode = self
6002                .options
6003                .get_string_value("print_options_mode", "")
6004                .ok()
6005                .map(|(v, _)| PrintOptionsMode::from_tag(&v))
6006                .unwrap_or(PrintOptionsMode::Text);
6007            let advanced = self
6008                .options
6009                .get_bool_value("print_advanced_options", "")
6010                .ok()
6011                .map(|(v, _)| v)
6012                .unwrap_or(false);
6013            print!(
6014                "\n# Pounce options registry\n\n{}",
6015                self.reg_options.print_options_documentation(mode, advanced)
6016            );
6017        }
6018
6019        // Mint a fresh `TimingStatistics` for this solve — shared (via
6020        // `Rc`) with the data and the NLP below so every `eval_*` and
6021        // every iterate-phase records into the same accumulator. The
6022        // application keeps its own `Rc` so callers can read totals out
6023        // via [`Self::timing_stats`].
6024        let timing = Rc::new(TimingStatistics::new());
6025        *self.timing.borrow_mut() = Rc::clone(&timing);
6026        // gh#606: same lifetime as the timings — a solve that bails out
6027        // before the initializer runs must not report the previous
6028        // solve's warm-start verdict.
6029        *self.warm_start_diag.borrow_mut() = None;
6030        // Gate the *detailed* per-subsystem timers on `timing_statistics`
6031        // (default "no"), matching upstream Ipopt. Without this, every
6032        // timed `eval_*` / phase section pays two `getrusage` syscalls per
6033        // start/end even when statistics are off — 16-20% of busy CPU on
6034        // fast-objective NLPs (issue #190). `print_timing_statistics=yes`
6035        // implies `timing_statistics=yes` (per its option help), so either
6036        // one enables the detailed timers. `overall_alg` is started
6037        // unconditionally below: it feeds the `max_cpu_time` check and is
6038        // reported regardless of the option.
6039        //
6040        // Each name is read as a literal rather than looped over an
6041        // array: the registered-but-unread scan
6042        // (`tests/no_silent_options.rs`) keys on the option name as it
6043        // appears at the accessor, so a loop variable reads as "no key
6044        // here" and hid `timing_statistics` among the silent options
6045        // when it has been wired since #190 (#677, #551).
6046        let read_yes = |key: &str| -> bool {
6047            self.options
6048                .get_bool_value(key, "")
6049                .ok()
6050                .and_then(|(v, f)| f.then_some(v))
6051                .unwrap_or(false)
6052        };
6053        let timing_enabled = read_yes("timing_statistics") || read_yes("print_timing_statistics");
6054        timing.set_detailed_enabled(timing_enabled);
6055        timing.overall_alg.start();
6056
6057        // Reset the linear-solver summary sink so back-to-back solves
6058        // don't bleed factor counters / extremal pivots into each
6059        // other. Surviving the lock failure with a debug-assert keeps
6060        // a poisoned mutex from sinking a release build that doesn't
6061        // even consume the summary.
6062        for sink in [&self.linsol_summary_sink, &self.resto_linsol_summary_sink] {
6063            match sink.lock() {
6064                Ok(mut guard) => {
6065                    *guard = LinearSolverSummary::default();
6066                }
6067                _ => {
6068                    debug_assert!(false, "linsol summary sink mutex poisoned");
6069                }
6070            }
6071        }
6072        // Same reasoning for the quality-escalation tally (gh#857): the
6073        // number belongs to this solve, not to whatever ran before it.
6074        self.quality_escalations.set(0);
6075        // And for the published partition: back-to-back solves on one
6076        // application can differ in which variables are fixed, so last
6077        // solve's labels must not describe this solve's KKT. Cleared here and
6078        // written again below only if this solve resolves one.
6079        if let Ok(mut g) = self.kkt_blocks_published.lock() {
6080            *g = None;
6081        }
6082
6083        // Build adapter + Nlp. Honor `fixed_variable_treatment` (default
6084        // `make_parameter`; pounce additionally implements `relax_bounds`,
6085        // which the adapter also auto-selects as a fallback when
6086        // `make_parameter` would leave `n_x_var < n_c` — mirrors upstream
6087        // `IpTNLPAdapter.cpp:623-633`).
6088        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
6089        let adapter = match TNLPAdapter::new_with_options(
6090            Rc::clone(&tnlp),
6091            lo_inf,
6092            up_inf,
6093            fixed_treatment,
6094        ) {
6095            Ok(a) => Rc::new(RefCell::new(a)),
6096            Err(_) => {
6097                timing.overall_alg.end();
6098                return ApplicationReturnStatus::InvalidProblemDefinition;
6099            }
6100        };
6101        // Carry the user's constant `obj_scaling_factor` (default 1.0;
6102        // negative ⇒ maximize) into the NLP. Until pounce#128's
6103        // follow-up this option was registered but never read, so it
6104        // was silently a no-op — maximization diverged because the
6105        // algorithm minimized the unscaled objective.
6106        let obj_scaling_factor = self
6107            .options
6108            .get_numeric_value("obj_scaling_factor", "")
6109            .ok()
6110            .and_then(|(v, f)| f.then_some(v))
6111            .unwrap_or(1.0);
6112        let mut orig_nlp = match OrigIpoptNlp::new(
6113            Rc::clone(&adapter),
6114            Rc::new(ConstObjScaling(obj_scaling_factor)),
6115        ) {
6116            Ok(n) => n,
6117            Err(_) => {
6118                timing.overall_alg.end();
6119                return ApplicationReturnStatus::InternalError;
6120            }
6121        };
6122        orig_nlp.set_timing_stats(Rc::clone(&timing));
6123        // Q6: decide which derivatives may be reused across iterates,
6124        // before anything is evaluated (gh #588).
6125        self.install_constant_derivative_hints(&mut orig_nlp);
6126
6127        // Mirror upstream `OrigIpoptNLP::InitializeStructures` (IpOrigIpoptNLP.cpp:299):
6128        // bail out with NotEnoughDegreesOfFreedom when there are fewer free
6129        // variables than equality constraints. Without this gate, square /
6130        // over-determined systems push the algorithm into restoration on
6131        // iter 0 and exit Restoration_Failed instead of the cleaner DOF code.
6132        let n_x_var = orig_nlp.x_space().dim();
6133        let n_c = orig_nlp.c_space().dim();
6134        if n_x_var > 0 && n_x_var < n_c {
6135            timing.overall_alg.end();
6136            // An over-determined system can still be *provably* infeasible —
6137            // `x == 0.2` with `x == 0.8` is about as provable as infeasibility
6138            // gets — and for such a model the structural DOF error is the
6139            // strictly weaker answer: it reports "cannot attempt this" for a
6140            // problem whose verdict is already decided (gh#387). The DOF gate
6141            // fires before any iteration runs, so nothing downstream will ever
6142            // get the chance to detect the infeasibility; check for a
6143            // bound-propagation proof here, on the rare failure path only.
6144            // The probe reuses presolve's full certification pipeline
6145            // (crossing margin + witness refutation), so a model the solver
6146            // would accept as feasible at its own tolerance is never upgraded
6147            // to "proved infeasible" — those still report the DOF error.
6148            if self.overdetermined_model_certified_infeasible(&tnlp) {
6149                use pounce_common::journalist::JournalCategory;
6150                self.journalist.print(
6151                    JournalLevel::J_SUMMARY,
6152                    JournalCategory::J_MAIN,
6153                    "\nEXIT: Problem has too few degrees of freedom, and bound \
6154                     propagation proves its constraints inconsistent.\n\
6155                     No feasible point exists; the solve was not run.\n",
6156                );
6157                return ApplicationReturnStatus::InfeasibleProblemDetected;
6158            }
6159            return ApplicationReturnStatus::NotEnoughDegreesOfFreedom;
6160        }
6161
6162        // Relax `x_L / x_U / d_L / d_U` by `bound_relax_factor` (default
6163        // 1e-8), capped by `constr_viol_tol` (default 1e-4). Matches
6164        // `OrigIpoptNLP::InitializeStructures` lines 343-358.
6165        let bound_relax_factor = self
6166            .options
6167            .get_numeric_value("bound_relax_factor", "")
6168            .ok()
6169            .and_then(|(v, f)| f.then_some(v))
6170            .unwrap_or(1e-8);
6171        let constr_viol_tol = self
6172            .options
6173            .get_numeric_value("constr_viol_tol", "")
6174            .ok()
6175            .and_then(|(v, f)| f.then_some(v))
6176            .unwrap_or(1e-4);
6177        if self.retry_keeps_declared_box.get() {
6178            orig_nlp.relax_bounds_keeping_box(bound_relax_factor, constr_viol_tol);
6179        } else {
6180            orig_nlp.relax_bounds(bound_relax_factor, constr_viol_tol);
6181        }
6182
6183        // `honor_original_bounds` (default `no`, matching upstream):
6184        // project the reported point back into the un-relaxed box. Must
6185        // follow `relax_bounds`, which snapshots the bounds to project
6186        // onto. Registered but never read before, so a user asking for
6187        // it still got a bound-pinned solution sitting up to
6188        // `min(bound_relax_factor·max(1,|b|), constr_viol_tol)` outside
6189        // its own bounds (gh#483 follow-up).
6190        let honor_original_bounds = self
6191            .options
6192            .get_bool_value("honor_original_bounds", "")
6193            .ok()
6194            .and_then(|(v, f)| f.then_some(v))
6195            .unwrap_or(false);
6196        orig_nlp.set_honor_original_bounds(honor_original_bounds);
6197
6198        // Apply automatic NLP scaling per `nlp_scaling_method` option
6199        // (port of `OrigIpoptNLP::InitializeStructures` →
6200        // `NLPScalingObject::DetermineScaling`). Default is
6201        // `gradient-based` to match upstream Ipopt 3.14.
6202        let scaling_method = self
6203            .options
6204            .get_string_value("nlp_scaling_method", "")
6205            .ok()
6206            .and_then(|(v, f)| f.then_some(v))
6207            .unwrap_or_else(|| "gradient-based".to_string());
6208        let scaling_method = match scaling_method.as_str() {
6209            "none" => ScalingMethod::None,
6210            "gradient-based" => ScalingMethod::GradientBased,
6211            // `curvature-based` computes the factors from the model's
6212            // quadratic coefficients and hands them back through
6213            // `TNLP::get_scaling_parameters` (gh #703), so from the
6214            // engine's side it *is* user scaling — the only difference is
6215            // who filled the vectors in.
6216            "user-scaling" | "curvature-based" => ScalingMethod::UserScaling,
6217            // `equilibration-based` is registered upstream but not yet
6218            // implemented in pounce; fall back to gradient-based (the
6219            // upstream default) to keep behavior predictable.
6220            _ => ScalingMethod::GradientBased,
6221        };
6222        let max_gradient = self
6223            .options
6224            .get_numeric_value("nlp_scaling_max_gradient", "")
6225            .ok()
6226            .and_then(|(v, f)| f.then_some(v))
6227            .unwrap_or(100.0);
6228        let min_value = self
6229            .options
6230            .get_numeric_value("nlp_scaling_min_value", "")
6231            .ok()
6232            .and_then(|(v, f)| f.then_some(v))
6233            .unwrap_or(1e-8);
6234        let obj_target_gradient = self
6235            .options
6236            .get_numeric_value("nlp_scaling_obj_target_gradient", "")
6237            .ok()
6238            .and_then(|(v, f)| f.then_some(v))
6239            .unwrap_or(0.0);
6240        let constr_target_gradient = self
6241            .options
6242            .get_numeric_value("nlp_scaling_constr_target_gradient", "")
6243            .ok()
6244            .and_then(|(v, f)| f.then_some(v))
6245            .unwrap_or(0.0);
6246        orig_nlp.determine_scaling_from_starting_point(
6247            scaling_method,
6248            max_gradient,
6249            min_value,
6250            obj_target_gradient,
6251            constr_target_gradient,
6252        );
6253
6254        let nlp_handle: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
6255
6256        // Build the algorithm strategy bundle. Read coarse knobs from
6257        // the OptionsList where we have them; fall through to defaults
6258        // otherwise. The full upstream parsing surface (mu_strategy,
6259        // hessian_approximation, line_search_method, ...) is wired by
6260        // `AlgBuilder::RegisterOptions` in upstream — that registry
6261        // hookup lands as a follow-up; default builder is correct for
6262        // HS71-class problems.
6263        let mut builder = self.algorithm_builder_from_options();
6264
6265        // The objective element's support for the partitioned Hessian.
6266        // Every constraint element reads its support off a Jacobian row;
6267        // only the objective has none declared, so without this the
6268        // updater falls back to the first `∇f`'s nonzeros — a
6269        // value-derived pattern. See
6270        // `TNLPAdapter::objective_nonlinear_vars`.
6271        if matches!(
6272            builder.hessian_approximation,
6273            HessianApproxChoice::Partitioned | HessianApproxChoice::FiniteDifference
6274        ) {
6275            builder.objective_nonlinear_vars = adapter.borrow().objective_nonlinear_vars();
6276        }
6277        // gh#989 item 5: the declared Lagrangian Hessian structure splits the
6278        // partitioned elements into the independent blocks they really are.
6279        if matches!(
6280            builder.hessian_approximation,
6281            HessianApproxChoice::Partitioned
6282        ) {
6283            let declared = !matches!(
6284                self.options.get_string_value("partitioned_structure", ""),
6285                Ok((ref v, true)) if v == "jacobian"
6286            );
6287            if declared {
6288                builder.hessian_declared_pattern = adapter.borrow().lagrangian_hessian_pattern();
6289            }
6290        }
6291
6292        // Which variables the limited-memory Hessian should span (gh#624).
6293        // Upstream's precedence: a TNLP that implements
6294        // `get_number_of_nonlinear_variables` wins, and
6295        // `num_linear_variables` is only the contiguous-prefix fallback.
6296        // Exact-Hessian solves never consult either.
6297        if matches!(
6298            builder.hessian_approximation,
6299            HessianApproxChoice::LimitedMemory | HessianApproxChoice::FiniteDifference
6300        ) {
6301            let num_linear_variables = self
6302                .options
6303                .get_integer_value("num_linear_variables", "")
6304                .ok()
6305                .and_then(|(v, f)| f.then_some(v))
6306                .unwrap_or(0);
6307            match adapter
6308                .borrow()
6309                .quasi_newton_nonlinear_vars(num_linear_variables)
6310            {
6311                Ok(mask) => builder.limited_memory_nonlinear_vars = mask,
6312                Err(e) => {
6313                    use pounce_common::journalist::JournalCategory;
6314                    self.journalist.print(
6315                        JournalLevel::J_ERROR,
6316                        JournalCategory::J_MAIN,
6317                        &format!("\nEXIT: Invalid nonlinear-variable list: {}\n", e.message),
6318                    );
6319                    timing.overall_alg.end();
6320                    return ApplicationReturnStatus::InvalidProblemDefinition;
6321                }
6322            }
6323        }
6324
6325        // Linear-solver backend. The default factory is option-aware
6326        // — it reads the `feral_*` extension options off the same
6327        // `OptionsList` that drove the IPM-level builder above so
6328        // per-problem `.opt` files can flip backend knobs without
6329        // rebuilding pounce.
6330        let mut feral_cfg = feral_config_from_options(&self.options);
6331        // Block-triangular / Schur KKT partition (pounce#180 item 2). Configure
6332        // the Schur block solvers from the *base* feral cfg: a full-KKT external
6333        // ordering (item 1) is sized for the whole system and cannot apply to
6334        // the A_FF sub-block, so the Schur path keeps the default sub-block
6335        // ordering. `build_with_backend` honors this only on the IPM + feral +
6336        // exact-Hessian path and falls back to the standard solver otherwise.
6337        if let Some(indices) = &self.kkt_schur_block {
6338            builder.set_kkt_schur(indices.clone(), feral_cfg.clone());
6339            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6340        }
6341        // Block-parallel KKT partition (structured-KKT Phase 5b), explicit or
6342        // detected (`kkt_block_detect`).
6343        let detect = matches!(
6344            self.options.get_string_value("kkt_block_detect", ""),
6345            Ok((ref v, true)) if v.eq_ignore_ascii_case("yes")
6346        );
6347        // A model-space declaration (§45) is mapped to KKT indices here, where
6348        // the NLP layout — which variables survived fixing, how constraints
6349        // split into equalities and inequalities — is known.
6350        {
6351            let a = adapter.borrow();
6352            let cls = a.classification();
6353            self.x_elimination = Some((cls.x_not_fixed_map.clone(), cls.n_full_x as usize));
6354        }
6355        let mapped = self.model_blocks.as_ref().and_then(|(v, c)| {
6356            let cls = adapter.borrow().classification().clone();
6357            match map_block_structure_to_kkt(&cls, v, c) {
6358                Ok(l) => Some(l),
6359                Err(e) => {
6360                    tracing::warn!(
6361                        target: "pounce::kkt",
6362                        error = %e,
6363                        "declared block structure does not fit this problem; using the standard solver"
6364                    );
6365                    None
6366                }
6367            }
6368        });
6369        if let Some(labels) = mapped
6370            .or_else(|| self.kkt_blocks.clone())
6371            .or(detect.then(Vec::new))
6372        {
6373            builder.set_kkt_blocks(labels.clone(), feral_cfg.clone());
6374            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6375            // And to the restoration sub-IPM, whose builder was minted before
6376            // this mapping existed. Its reduced system is this one, so the
6377            // same labels apply; see `kkt_blocks_published`. Off with
6378            // `kkt_block_restoration no`, which is how restoration's own
6379            // contribution is measured.
6380            let resto_blocks = !matches!(
6381                self.options.get_string_value("kkt_block_restoration", ""),
6382                Ok((ref v, _)) if v.eq_ignore_ascii_case("no")
6383            );
6384            if resto_blocks {
6385                if let Ok(mut g) = self.kkt_blocks_published.lock() {
6386                    *g = Some((labels, feral_cfg.clone()));
6387                }
6388            }
6389        }
6390        // A caller-supplied KKT permutation (pounce#180 item 1) overrides
6391        // the string-option / env ordering: `OrderingMethod::External`
6392        // can't be expressed through the OptionsList (it carries a
6393        // vector), so it is injected here from the side-channel field.
6394        // Only applies to the workspace-default FERAL backend below; a
6395        // custom `linear_backend_factory` owns its own config.
6396        if let Some(perm) = &self.external_ordering {
6397            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
6398        }
6399        // MA57's knobs come off the same `OptionsList`, at the main-IPM
6400        // prefix. The restoration sub-IPM reads them again under
6401        // `"resto."` when its caller mints the inner backend factory —
6402        // see `ma57_config_from_options`.
6403        let ma57_cfg = ma57_config_from_options(&self.options, "");
6404        // gh#987 item 3: publish the unperturbed trials' inertia next to the
6405        // backend's own per-factorization record.
6406        builder.inertia_sink = Some(Arc::clone(&self.linsol_summary_sink));
6407        let factory = self.linear_backend_factory.take().unwrap_or_else(|| {
6408            default_backend_factory_with_sink(
6409                feral_cfg,
6410                ma57_cfg,
6411                Arc::clone(&self.linsol_summary_sink),
6412            )
6413        });
6414        let bundle = builder.build_with_backend(factory);
6415
6416        // Wire the data / cq pair around the NLP. Install the shared
6417        // `TimingStatistics` so the algorithm's iterate phases
6418        // (output, convergence, hessian, μ, search-direction,
6419        // line-search, accept) all record into the same accumulator
6420        // the application exposes via `timing_stats()`.
6421        let data: crate::ipopt_data::IpoptDataHandle = Rc::new(RefCell::new(AlgIpoptData::new()));
6422        data.borrow_mut().timing = Rc::clone(&timing);
6423        // Install a shared wall/CPU-time deadline (pounce#242) so the time
6424        // budget is honored at the granularity of the expensive inner
6425        // steps — the main loop's KKT factorization / line search and the
6426        // restoration inner IPM — instead of only between outer iterations.
6427        // The `Deadline` starts its clock now (right after `overall_alg`),
6428        // and the restoration sub-solve reuses this same instance, so the
6429        // caller's budget bounds the whole solve rather than each nested
6430        // level independently. The convergence check treats it as
6431        // authoritative when present (see `conv_check::opt_error`).
6432        data.borrow_mut().deadline = Some(pounce_common::timing::Deadline::new(
6433            builder.conv_check.max_wall_time,
6434            builder.conv_check.max_cpu_time,
6435        ));
6436        let cq: crate::ipopt_cq::IpoptCqHandle = Rc::new(RefCell::new(
6437            IpoptCalculatedQuantities::new(Rc::clone(&data), Rc::clone(&nlp_handle)),
6438        ));
6439        // Correction size for very small slacks (default mach_eps^{3/4});
6440        // drives the safe-slack bound-adjustment mechanism.
6441        if let Ok((v, true)) = self.options.get_numeric_value("slack_move", "") {
6442            cq.borrow_mut().slack_move = v;
6443        }
6444        // `kappa_d` — weight of the linear damping term added to the
6445        // barrier objective/gradient to handle one-sided bounds
6446        // (`IpIpoptCalculatedQuantities.cpp`). Registered (default 1e-5)
6447        // but previously never read, so a user override was silently
6448        // ignored (#191). Routed through the builder for parity with the
6449        // other numeric knobs; the default matches the registered
6450        // default, so only explicit overrides change behavior.
6451        cq.borrow_mut().kappa_d = builder.kappa_d;
6452        // `s_max` — cap on the average multiplier magnitude in the
6453        // `(s_d, s_c)` scaling of the KKT error test. Same shape as
6454        // `kappa_d`: registered (default 100) and previously never read,
6455        // so an override was silently ignored (#551 / #677).
6456        cq.borrow_mut().s_max = builder.s_max;
6457
6458        // Seed `data.curr` with a zero-valued iterate of the correct
6459        // dimensions. The `IterateInitializer` consumes these as its
6460        // template (it overwrites `x`, `s`, multipliers in place); we
6461        // just need the dim metadata.
6462        {
6463            let nlp_borrow = nlp_handle.borrow();
6464            let n_x = nlp_borrow.n();
6465            let n_s = nlp_borrow.m_ineq();
6466            let n_yc = nlp_borrow.m_eq();
6467            let n_yd = nlp_borrow.m_ineq();
6468            let n_zl = nlp_borrow.x_l().dim();
6469            let n_zu = nlp_borrow.x_u().dim();
6470            let n_vl = nlp_borrow.d_l().dim();
6471            let n_vu = nlp_borrow.d_u().dim();
6472            drop(nlp_borrow);
6473            let iv = IteratesVector::new(
6474                Rc::new(DenseVectorSpace::new(n_x).make_new_dense()),
6475                Rc::new(DenseVectorSpace::new(n_s).make_new_dense()),
6476                Rc::new(DenseVectorSpace::new(n_yc).make_new_dense()),
6477                Rc::new(DenseVectorSpace::new(n_yd).make_new_dense()),
6478                Rc::new(DenseVectorSpace::new(n_zl).make_new_dense()),
6479                Rc::new(DenseVectorSpace::new(n_zu).make_new_dense()),
6480                Rc::new(DenseVectorSpace::new(n_vl).make_new_dense()),
6481                Rc::new(DenseVectorSpace::new(n_vu).make_new_dense()),
6482            );
6483            data.borrow_mut().set_curr(iv);
6484        }
6485
6486        // Full primal-dual warm restart (debugger `resolve`): if a
6487        // captured iterate is queued, install it onto `data.curr` over
6488        // the placeholder so the `WarmStartIterateInitializer`'s
6489        // re-optimize branch (x already initialized) keeps it and only
6490        // clamps multipliers / sets target_mu — no cold re-seed from the
6491        // NLP. Skipped (with a warning) if the dimensions don't line up,
6492        // e.g. an option changed the problem structure between solves.
6493        if let Some(snap) = self.warm_start_iterate.take() {
6494            let dims_match = {
6495                let borrow = data.borrow();
6496                borrow
6497                    .curr
6498                    .as_ref()
6499                    .map(|c| iterates_dims(c) == iterates_dims(snap.iterates()))
6500                    .unwrap_or(false)
6501            };
6502            if dims_match {
6503                data.borrow_mut().set_curr(snap.iterates().clone());
6504                data.borrow_mut().curr_mu = snap.mu();
6505            } else {
6506                tracing::warn!(
6507                    target: "pounce::warm_start",
6508                    "debugger warm-restart iterate dimensions differ from the fresh \
6509                     solve; ignoring the captured iterate and seeding normally"
6510                );
6511            }
6512        }
6513
6514        let max_iter = self
6515            .options
6516            .get_integer_value("max_iter", "")
6517            .ok()
6518            .and_then(|(v, f)| f.then_some(v))
6519            .unwrap_or(3000);
6520        let tol = self
6521            .options
6522            .get_numeric_value("tol", "")
6523            .ok()
6524            .and_then(|(v, f)| f.then_some(v))
6525            .unwrap_or(1e-8);
6526        data.borrow_mut().tol = tol;
6527
6528        let mut alg = IpoptAlgorithm::new(data, cq, bundle)
6529            .with_nlp(Rc::clone(&nlp_handle))
6530            .with_tnlp(Rc::clone(&tnlp));
6531        alg.last_iter_stats_sink = Some(Rc::clone(&self.last_iter_stats));
6532        alg.live_iterate_fixed_var_duals = self.reports_fixed_var_duals();
6533        // Mint a fresh restoration factory per inner solve if a
6534        // provider is configured (pounce#10 Phase 3). Falls back to
6535        // the legacy one-shot `restoration_factory` slot when no
6536        // provider is set, preserving single-shot caller behavior.
6537        if let Some(provider) = self.restoration_factory_provider.as_mut() {
6538            self.restoration_factory = Some(provider());
6539        }
6540        if let Some(factory) = self.restoration_factory.as_mut() {
6541            alg = alg.with_restoration(factory());
6542        }
6543        if let Some(diag) = self.diagnostics.as_ref() {
6544            alg = alg.with_diagnostics(Rc::clone(diag));
6545        }
6546        // Move the interactive debugger hook (if any) into the main
6547        // algorithm. Taken — not cloned — so it drives exactly this
6548        // solve; a subsequent solve must reinstall it.
6549        if let Some(hook) = self.debug_hook.take() {
6550            alg = alg.with_debug_hook(hook);
6551        }
6552        alg.max_iter = max_iter;
6553        // `kappa_sigma` — factor bounding how far the bound multipliers
6554        // may deviate from their primal estimates; the clamp runs after
6555        // every accepted step (`IpIpoptAlg.cpp`, Eqn. (16)). Registered
6556        // (default 1e10) but previously never read, so a user override —
6557        // including the documented `< 1` "disable the correction" — was
6558        // silently ignored (#191). Routed through the builder; the struct
6559        // default matches the registered default, so default runs are
6560        // unchanged.
6561        alg.kappa_sigma = builder.kappa_sigma;
6562        // `recalc_y` (#677) — see the read site above for why the
6563        // limited-memory path defaults it on.
6564        // `linear_system_scaling=slack-based` (#677) — the only scaling
6565        // choice whose factors depend on the iterate, so the main loop
6566        // has to refresh them. See `IpoptAlgorithm::push_slack_scaling`.
6567        alg.slack_based_scaling = matches!(
6568            builder.linear_system_scaling,
6569            crate::alg_builder::LinearSystemScalingChoice::SlackBased
6570        );
6571        alg.recalc_y = builder.recalc_y;
6572        alg.recalc_y_feas_tol = builder.recalc_y_feas_tol;
6573        // `start_with_resto` — the outer loop is what acts on it. It was
6574        // previously copied only into the restoration sub-solver's own
6575        // builder, which has no first outer iteration to force, so
6576        // setting the option did nothing at all.
6577        alg.start_with_resto = builder.resto.start_with_resto;
6578        // Tiny-step and divergence guards (#191): registered but
6579        // previously never read. Struct defaults match the registered
6580        // defaults, so default runs are unchanged.
6581        alg.tiny_step_tol = builder.tiny_step_tol;
6582        alg.tiny_step_y_tol = builder.tiny_step_y_tol;
6583        alg.diverging_iterates_tol = builder.diverging_iterates_tol;
6584        alg.dual_diverging_streak = builder.dual_diverging_streak.max(0) as usize;
6585        alg.dual_divergence_retry_step_tol = builder.dual_divergence_retry_step_tol;
6586        alg.dual_divergence_retry_du_floor = builder.dual_divergence_retry_du_floor;
6587        alg.resto_decline_deferrals = builder.resto_decline_deferrals.max(0) as usize;
6588        alg.resto_decline_progress_ratio = builder.resto_decline_progress_ratio;
6589        alg.neg_curv_escapes = builder.neg_curv_escapes.max(0) as usize;
6590        alg.lbfgs_ls_failure_restarts = builder.limited_memory_ls_failure_restarts.max(0) as usize;
6591        alg.kkt_fidelity_tol = builder.kkt_fidelity_tol;
6592        // Honor `print_level == 0`: silence the algorithm's direct-to-stdout
6593        // output — the per-iteration table and, new in #206, the
6594        // problem-statistics and end-of-run summary blocks the engine now
6595        // emits itself. Default (unset) or any positive level shows them; the
6596        // CLI's JSON mode forces print_level 0, so structured output stays
6597        // clean. (The Phase-7 journalist surface respects print_level already;
6598        // this is the legacy direct-print site that needs the same gate.)
6599        let console_output = match self.options.get_integer_value("print_level", "") {
6600            Ok((v, true)) => v >= 1,
6601            _ => true,
6602        };
6603        if !console_output {
6604            alg.print_iter_output = false;
6605            // The nested restoration IPM is built inside the restoration
6606            // driver, not by `IpoptAlgorithm::new`, so it never sees this
6607            // gate unless we forward it.
6608            if let Some(resto) = alg.restoration.as_mut() {
6609                resto.set_print_iter_output(false);
6610            }
6611        }
6612
6613        // Problem statistics, Ipopt-style, emitted before the iteration table
6614        // from the engine's own reduced problem (#206). Built from the same
6615        // collect_stats inputs the CLI used, so the block is byte-identical;
6616        // emitting it here means every frontend (CLI, Python, C) and every
6617        // algorithm (IPM, SQP) gets it.
6618        self.emit_problem_stats(&tnlp, console_output);
6619
6620        // Per-iteration history (pounce#71): when requested, capture the
6621        // `pounce::iteration` events emitted during the solve into an
6622        // `IterRecord` trajectory via the observability collector layer.
6623        // This replaces the old in-loop `iter_history` accumulation; it
6624        // requires the collector to be installed in the active
6625        // subscriber (the CLI / Python / C frontends install it via
6626        // `pounce_observability::init_subscriber`; tests call
6627        // `init_for_tests`). The collector scopes out restoration
6628        // sub-solve iterations via the `restoration` span, so the
6629        // trajectory matches the previous behavior (outer iters only).
6630        let iter_capture = self
6631            .record_iter_history
6632            .then(pounce_observability::IterCaptureGuard::start);
6633
6634        let solver_status = alg.optimize();
6635        // Keep the initializer's feasibility diagnostics reachable
6636        // after the algorithm goes out of scope (gh#605).
6637        self.least_square_init_report = alg.least_square_init_report();
6638
6639        let captured_iters = iter_capture.map(|g| g.finish()).unwrap_or_default();
6640        // Propagate to any enclosing capture (e.g. `with_iter_capture`
6641        // wrapped around a solve with iteration history enabled), whose
6642        // buffer this inner guard would otherwise leave empty.
6643        pounce_observability::extend_active_capture(&captured_iters);
6644        // Close the overall-algorithm timer on the success path. The
6645        // early-return arms above end it themselves before bailing out;
6646        // this one matches upstream `IpoptApplication::call_optimize`
6647        // (which calls `EndCpuTime()` on overall_alg right after
6648        // `Optimize` returns, regardless of solver_status).
6649        timing.overall_alg.end();
6650
6651        // gh#612: opt-in crossover. Runs here — after the algorithm is done
6652        // but BEFORE the statistics drain, the status gates, the
6653        // `on_converged` hook and `finalize_via_orig_nlp` — so that when it
6654        // accepts, every one of those describes the point actually returned.
6655        // Placing it later would mean reporting residuals for an iterate the
6656        // user is not given, and would hide the exact active set from the
6657        // post-optimal sensitivity hook, which is the first of the three
6658        // consumers this exists for.
6659        self.maybe_crossover(&mut alg, &nlp_handle, solver_status);
6660
6661        // Drain counters / iter count off the algorithm.
6662        {
6663            let mut stats = self.statistics.borrow_mut();
6664            {
6665                let d = alg.data.borrow();
6666                stats.iteration_count = d.iter_count;
6667                // Converged barrier parameter μ — threaded forward into a
6668                // warm-started corrector's `mu_init` / `warm_start_target_mu`
6669                // for predictor–corrector path following (pounce#86).
6670                stats.final_mu = d.curr_mu;
6671            }
6672            // gh#606: the warm-start initializer's verdict on what the
6673            // caller supplied. Lifted off the (solve-local) data handle
6674            // so it outlives the solve; `None` on a cold start.
6675            *self.warm_start_diag.borrow_mut() = alg.data.borrow().warm_start_diagnostics.clone();
6676            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
6677            // Restoration-phase audit counters (pounce#12). Zero on
6678            // problems where restoration never fires; populated by
6679            // `IpoptAlgorithm::invoke_restoration`.
6680            // Finite-difference Hessian census (gh#823 review). `None` on
6681            // every other updater, which leaves the `-1` sentinel in
6682            // place and says "this mode did not run" rather than "it ran
6683            // and found nothing".
6684            if let Some(fd) = alg.bundle.hess.fd_hessian_stats() {
6685                use crate::hess::fd_hessian::FdPatternSource;
6686                stats.fd_hessian_pattern_used = match fd.pattern_used {
6687                    Some(FdPatternSource::Declared) => 0,
6688                    Some(FdPatternSource::Jacobian) => 1,
6689                    None => -1,
6690                };
6691                stats.fd_hessian_nnz = fd.nnz as Index;
6692                stats.fd_hessian_n = fd.n as Index;
6693                stats.fd_hessian_groups = fd.groups as Index;
6694                stats.fd_hessian_rho_max = fd.rho_max as Index;
6695                stats.fd_hessian_coloring_fell_back = fd.coloring_fell_back;
6696                stats.fd_hessian_objective_clique_widened = fd.objective_clique_widened;
6697            }
6698            stats.restoration_calls = alg.resto_calls;
6699            stats.restoration_inner_iters = alg.resto_inner_iters;
6700            stats.restoration_outer_iters = alg.resto_outer_iters;
6701            stats.restoration_wall_secs = alg.resto_wall_secs;
6702            // gh#857. Read off the shared cell rather than the algorithm's
6703            // own `PdFullSpaceSolver`, so restoration sub-solves — which
6704            // run their own solver instance — are included.
6705            stats.quality_escalations = self.quality_escalations.get() as Index;
6706            // gh#884. Read off the algorithm that just ran, so
6707            // `run_with_dual_divergence_retry` — which sits above this
6708            // call — can see what it observed.
6709            self.dual_divergence_signature
6710                .set(self.dual_divergence_signature.get() || alg.dual_divergence_signature());
6711            stats.dual_divergence_signature = self.dual_divergence_signature.get();
6712            stats.returned_run_dual_divergence_signature = alg.dual_divergence_signature();
6713            stats.dual_divergence_retry_promoted = self.dual_divergence_retry_promoted.get();
6714            stats.derivative_check = self.derivative_check.borrow().clone();
6715            let (rs, ra) = self.obj_scale_refused.get();
6716            self.obj_scale_refused.set((
6717                rs || alg.obj_scale_certificate_refused(),
6718                ra || alg.obj_scale_acceptable_refused(),
6719            ));
6720            stats.obj_scale_certificate_refused = self.obj_scale_refused.get().0;
6721            stats.obj_scale_acceptable_refused = self.obj_scale_refused.get().1;
6722            stats.iterations = captured_iters;
6723            // A refused starting point does not produce a valid iterate.
6724            // Leave final objective/residual fields at their NaN defaults.
6725            // Capture the final *scaled* objective at the algorithm's
6726            // (compressed `x_var`-space) iterate via the NLP: the
6727            // algorithm-side `eval_f` returns `f * obj_scale_factor`.
6728            // `final_objective` is seeded with it only as a best-effort
6729            // fallback; the success path below overwrites it with the
6730            // true unscaled objective from `finalize_via_orig_nlp`
6731            // (which evaluates the user TNLP directly).
6732            if solver_status != SolverReturn::InvalidProblemDefinition {
6733                let curr_x = alg.data.borrow().curr.as_ref().map(|c| c.x.clone());
6734                if let Some(x) = curr_x {
6735                    if let Ok(f) = try_eval_curr_f(&nlp_handle, &x) {
6736                        stats.final_objective = f;
6737                        stats.final_scaled_objective = f;
6738                    }
6739                }
6740                // Final residuals straight off the cq cache. These mirror
6741                // the values upstream prints in its end-of-run summary
6742                // ("Dual infeasibility / Constraint violation /
6743                // Complementarity / Overall NLP error").
6744                let cq = alg.cq.borrow();
6745                stats.final_dual_inf = cq.curr_dual_infeasibility_max();
6746                // Stays on the *internal* measure deliberately: the summary's
6747                // "Overall NLP error" is `curr_nlp_error`, and it is built from
6748                // this same `max(||c||, ||d - s||)`. Switching the violation line
6749                // alone to the original-NLP measure
6750                // (`curr_unscaled_nlp_constraint_violation_max`, now used by the
6751                // `inf_pr` column) would leave the block self-inconsistent —
6752                // an error larger than the max of its own components. Making
6753                // them agree means deciding whether *convergence* should be
6754                // judged on the original NLP, which is a behaviour change for
6755                // every model, not a reporting fix. See pounce#476.
6756                //
6757                // NOTE (gh #528): "Overall NLP error" is no longer the number
6758                // the strict gate tests. That gate judges
6759                // `curr_nlp_error_above_primal_noise` — the same aggregate with
6760                // each row's residual counted only above what it can represent
6761                // in floating point — so on a model whose constraint values run
6762                // to `~1e8` the summary can report an error above `tol` beside
6763                // `EXIT: Optimal Solution Found`. The gap is exactly the part
6764                // of the residual that is quantisation noise, and it is bounded
6765                // by `constr_viol_tol`, which is still tested here on the full
6766                // unfloored residual. Reporting is deliberately left on the raw
6767                // value: it is the honest measurement, and at these magnitudes
6768                // the default `bound_relax_factor = 1e-8` has already moved
6769                // every bound by orders of magnitude more than the floor
6770                // forgives, so the raw number was never an exact statement
6771                // about the original NLP either.
6772                stats.final_constr_viol = cq.curr_primal_infeasibility_max();
6773                // How far outside the model AS DECLARED the returned point
6774                // sits. The line above is the internal slack measure the
6775                // convergence test reads, on the `bound_relax_factor`-widened
6776                // model this arm genuinely solves; the widening stays here
6777                // because a feasible-iterate log-barrier needs `x` strictly
6778                // inside its bounds (the convex arm's does not -- see
6779                // `qp_extract::BoundRelax`). The two can differ by orders and
6780                // nothing used to say so: on netlib `wood1p` this reports
6781                // `1.71e-14` at a point `7.96e-09` outside the declared rows
6782                // and `9.84e-09` outside the declared box. Reported on
6783                // every solve (see gh#987 below).
6784                //
6785                // gh#987: computed on every solve, not only a widened one.
6786                // `final_constr_viol` is documented as the internal scaled
6787                // residual, so under row scaling with `bound_relax_factor=0`
6788                // the user-unit violation was reported nowhere (the field read
6789                // NaN). Without a widening the declared and live models
6790                // coincide, but the *units* do not, and this is the one field
6791                // that is always in the caller's.
6792                stats.final_declared_constr_viol = cq.curr_declared_primal_violation_max();
6793                // The box half of the same measurement, unconditionally: this
6794                // one is a *summary line* (Ipopt's `Variable bound
6795                // violation`), not an extra warning, so it has to carry a real
6796                // number on every solve rather than only on a widened one. At
6797                // `bound_relax_factor = 0` the honest number is `0` and the
6798                // accessor returns it by measurement, not by assumption.
6799                stats.final_declared_box_viol = cq.curr_declared_box_violation_max();
6800                // Infinity-norm complementarity, max over all four bound
6801                // blocks (s_xl·z_l, s_xu·z_u, s_sl·v_l, s_su·v_u). The
6802                // empty-bound blocks return `0` from amax(), so the max is
6803                // safe even when only one side has bounds.
6804                let compl = cq
6805                    .curr_compl_x_l()
6806                    .amax()
6807                    .max(cq.curr_compl_x_u().amax())
6808                    .max(cq.curr_compl_s_l().amax())
6809                    .max(cq.curr_compl_s_u().amax());
6810                stats.final_compl = compl;
6811                stats.final_kkt_error = cq.curr_nlp_error();
6812                // The aggregate the strict gate tested (gh #528). Reported
6813                // alongside the raw one so a summary can account for the gap
6814                // between them; equal to it on every `O(1)` model, and on any
6815                // run with `primal_noise_floor_kappa = 0`.
6816                stats.final_kkt_error_above_noise = cq
6817                    .curr_nlp_error_above_primal_noise(builder.conv_check.primal_noise_floor_kappa);
6818                // Unscaled (user-space) counterparts — divide the nlp_scaling
6819                // back out so a consumer can verify the certificate in its own
6820                // units (pounce#173). Identical to the scaled fields when no
6821                // scaling is active.
6822                stats.final_unscaled_dual_inf = cq.curr_unscaled_dual_infeasibility_max();
6823                stats.final_unscaled_dual_scale = cq.curr_unscaled_dual_infeasibility_scale_max();
6824                stats.final_obj_scaling_factor = cq.computed_obj_scaling_factor();
6825                stats.final_total_obj_scaling_factor = cq.obj_scaling_factor().abs();
6826                stats.start_obj_grad_max = cq.start_obj_gradient_max();
6827                stats.final_unscaled_constr_viol = cq.curr_unscaled_primal_infeasibility_max();
6828                // Record whether per-row scaling actually engaged, so a
6829                // wrapper that measures the user's rows in the model's own
6830                // units knows which field family may carry that number.
6831                // `curr_unscaled_primal_infeasibility_max` treats both
6832                // vectors absent as "scaled == unscaled"; the ℓ₁ outer loop
6833                // relies on the same equivalence (gh#794 review).
6834                {
6835                    let nlp_ref = nlp_handle.borrow();
6836                    self.row_scaling_active.set(Some(
6837                        nlp_ref.c_scale_vec().is_some() || nlp_ref.d_scale_vec().is_some(),
6838                    ));
6839                }
6840                stats.final_unscaled_compl = cq.curr_unscaled_complementarity_max();
6841                stats.final_unscaled_kkt_error = cq.curr_unscaled_nlp_error();
6842
6843                // Report an accepted crossover in the frame it solved in
6844                // (#646). Everything above measures against the bounds the
6845                // interior iteration ran against, which `bound_relax_factor`
6846                // widened by `δ` before the solve. That is the right frame
6847                // for an interior iterate — it never touches a bound — but a
6848                // crossed-over point sits *exactly* on the constraints of the
6849                // problem as declared, i.e. `δ` inside the relaxed ones, so
6850                // the four `s·z` blocks above read `|multiplier| · δ`. For a
6851                // unit multiplier and the default `δ = 1e-8` that is `1e-8`,
6852                // which is `tol`: a strictly better point printed an `Overall
6853                // NLP error` above tolerance, and the opt-in
6854                // `kkt_fidelity_tol` gate below downgraded it.
6855                //
6856                // Only complementarity moves. Stationarity involves no
6857                // bounds, and the crossed-over point is *interior* to the
6858                // relaxed box, so its violation is zero under either reading.
6859                //
6860                // The substitution is confined to reporting. Crossover runs
6861                // after the status is decided, and it only ever installs a
6862                // point the never-regress gate accepted on the declared-bound
6863                // residuals, so this cannot dress up a worse iterate — the
6864                // measurement it replaces is the artifact.
6865                if let Some(report) = self.crossover_report.as_ref()
6866                    && report.accepted()
6867                    && report.compl_after.is_finite()
6868                {
6869                    let compl_declared = report.compl_after;
6870                    stats.final_compl = compl_declared;
6871                    stats.final_kkt_error =
6872                        cq.curr_nlp_error_with_complementarity(compl_declared, 0.0);
6873                    stats.final_kkt_error_above_noise = cq.curr_nlp_error_with_complementarity(
6874                        compl_declared,
6875                        builder.conv_check.primal_noise_floor_kappa,
6876                    );
6877                    // Same unscaling as `curr_unscaled_complementarity_max`:
6878                    // the slack's row factor and the multiplier's cancel in
6879                    // the product, leaving the objective factor. Magnitude —
6880                    // `obj_scaling_factor` is signed, `-1` being the
6881                    // documented way to pose a maximization.
6882                    let df = cq.obj_scaling_factor().abs();
6883                    stats.final_unscaled_compl = if df == 0.0 || df == 1.0 {
6884                        compl_declared
6885                    } else {
6886                        compl_declared / df
6887                    };
6888                    stats.final_unscaled_kkt_error = stats
6889                        .final_unscaled_dual_inf
6890                        .max(stats.final_unscaled_constr_viol)
6891                        .max(stats.final_unscaled_compl);
6892                }
6893            }
6894        }
6895
6896        // Never report `Infeasible_Problem_Detected` while holding a point that
6897        // satisfies every constraint. The gates that produce this verdict argue
6898        // from a stalled feasibility sub-problem, and gh #379 is what that looks
6899        // like when the argument is wrong — a model whose own starting point is
6900        // exactly feasible, reported infeasible. See
6901        // `withdraw_infeasibility_if_refuted`.
6902        let solver_status =
6903            withdraw_infeasibility_if_refuted(&tnlp, solver_status, lo_inf, up_inf, tol);
6904
6905        // Map SolverReturn → ApplicationReturnStatus per
6906        // MAIN_LOOP.md's exception table, then apply the opt-in
6907        // status-fidelity gate (pounce#173).
6908        let app_status = self.apply_kkt_fidelity_gate(solver_return_to_app_status(solver_status));
6909        // gh#986 item 5: `mehrotra_algorithm=yes` runs with no line search
6910        // (every trial step is accepted), which is sound on LP / convex QP and
6911        // not on a general NLP — there an unglobalized step can walk the
6912        // iterate into an infeasible region that restoration then cannot
6913        // leave. (A *feasible* iterate is no longer sent to restoration by the
6914        // probing guard: it is recentred, gh#986 item 5, so this no longer
6915        // fires on the guard's own account.) Say so when it happens.
6916        if app_status == ApplicationReturnStatus::RestorationFailed
6917            && matches!(
6918                self.options.get_string_value("mehrotra_algorithm", ""),
6919                Ok((ref v, true)) if v == "yes"
6920            )
6921        {
6922            tracing::warn!(
6923                target: "pounce::algorithm",
6924                "pounce: restoration failed under mehrotra_algorithm=yes. That option \
6925                 disables the line search and is intended for LPs and convex QPs; on a \
6926                 general NLP every trial step is accepted, so the iterate can leave the \
6927                 region restoration can repair, and a successful run may stop at a \
6928                 different local solution than the default algorithm finds. Retry with \
6929                 the default (mehrotra_algorithm=no)."
6930            );
6931        }
6932
6933        // On convergence, fire the user-supplied callback (post-optimal
6934        // sensitivity hook, pounce#16) before flowing back through
6935        // `finalize_via_orig_nlp`. Borrowed handles into the converged
6936        // KKT state stay alive for the duration of the closure.
6937        if matches!(
6938            app_status,
6939            ApplicationReturnStatus::SolveSucceeded
6940                | ApplicationReturnStatus::SolvedToAcceptableLevel
6941        ) {
6942            if let Some(cb) = self.on_converged.as_mut() {
6943                if let Some(sd) = alg.search_dir.as_mut() {
6944                    let pd = sd.pd_solver_rc();
6945                    cb(&alg.data, &alg.cq, &nlp_handle, pd);
6946                }
6947            }
6948        }
6949
6950        // Finalize: forward the final iterate to the user's TNLP. The
6951        // returned objective is evaluated on the *user* TNLP at the
6952        // unscaled iterate, so it overrides the scaled best-effort
6953        // value stashed in `final_objective` above (the algorithm-side
6954        // `eval_f` returns `f * obj_scale_factor`).
6955        if solver_status != SolverReturn::InvalidProblemDefinition {
6956            match finalize_via_orig_nlp(
6957                &nlp_handle,
6958                &alg,
6959                solver_status,
6960                app_status,
6961                &tnlp,
6962                &self.last_finalize,
6963                self.reports_fixed_var_duals(),
6964            ) {
6965                Ok(f_unscaled) => {
6966                    self.statistics.borrow_mut().final_objective = f_unscaled;
6967                }
6968                Err(()) => {}
6969            }
6970        }
6971
6972        // End-of-solve timing report. Gated on `print_timing_statistics`
6973        // (default "no"); mirrors upstream's
6974        // `IpoptApplication::call_optimize` →
6975        // `IpTimingStatistics::PrintAllValues` call site. The report
6976        // goes to stdout (for parity with the banner / iter-row output
6977        // path) and is also fanned out to the journalist so an
6978        // `output_file` attached via `Initialize` picks it up.
6979        let print_timing = self
6980            .options
6981            .get_bool_value("print_timing_statistics", "")
6982            .ok()
6983            .and_then(|(v, f)| f.then_some(v))
6984            .unwrap_or(false);
6985        if print_timing {
6986            let report = timing.report();
6987            print!("{}", report);
6988            use pounce_common::journalist::{JournalCategory, JournalLevel};
6989            self.journalist.print(
6990                JournalLevel::J_SUMMARY,
6991                JournalCategory::J_TIMING_STATISTICS,
6992                &report,
6993            );
6994        }
6995
6996        // End-of-run summary, Ipopt-style, emitted last (after any timing
6997        // report) from the engine's own statistics (#206). Drains the eval
6998        // tallies into SolveStatistics (read AFTER finalize so the final
6999        // solution evaluation is included) and prints the summary, gated on
7000        // the same print_level as the rest of the console.
7001        self.emit_end_summary(app_status, &nlp_handle, console_output);
7002
7003        app_status
7004    }
7005
7006    /// Build an [`AlgorithmBuilder`] populated from the app's
7007    /// [`OptionsList`]. Public so callers wiring the restoration
7008    /// factory can hand the *inner* IPM a builder that mirrors the
7009    /// outer's `mu_strategy`/`mu_oracle`/line-search choices —
7010    /// matching upstream `IpAlgBuilder::BuildRestoIpoptAlgorithm`,
7011    /// which reads the same `mu_strategy` option with prefix `"resto."
7012    /// + prefix` and falls back to the outer setting.
7013    pub fn algorithm_builder_from_options(&self) -> AlgorithmBuilder {
7014        let mut builder = AlgorithmBuilder::new();
7015        // gh#857: share this application's escalation tally. Every
7016        // frontend builds the restoration provider's inner builder from
7017        // this method, so restoration escalations aggregate here too.
7018        builder.quality_escalation_counter = Some(Rc::clone(&self.quality_escalations));
7019        // Structured-KKT Phase 5b: the same reasoning, one solve later. The
7020        // partition this solve resolves is not known yet — it is derived from
7021        // a KKT layout that does not exist until `optimize` builds it — so the
7022        // builder takes the cell rather than the labels, and reads it when
7023        // restoration actually runs. Block-path factorizations record into the
7024        // restoration sink, so `linear_solver.restoration` reports them where
7025        // the rest of restoration's linear algebra is reported.
7026        if let Ok((v, _)) = self.options.get_integer_value("kkt_block_min_size", "") {
7027            builder.kkt_block_min_size = v.max(0) as usize;
7028        }
7029        builder.set_kkt_blocks_cell(Arc::clone(&self.kkt_blocks_published));
7030        builder.set_kkt_schur_summary_sink(Arc::clone(&self.resto_linsol_summary_sink));
7031
7032        // `mehrotra_algorithm` is parsed first so its cascading
7033        // defaults (mu_strategy=adaptive, mu_oracle=probing) can be
7034        // overridden by an explicit user setting of those keys
7035        // below. Mirrors `IpAlgBuilder.cpp:Mehrotra`.
7036        // `fast_step_computation` — skip the search-direction residual
7037        // check and allow an inexact linear solve. `PdSearchDirCalc` has
7038        // consumed this flag since it landed, hard-coded to `false`; the
7039        // option's read site was simply missing, so setting it did
7040        // nothing at all (gh#483 follow-up, #191 round 2).
7041        if let Ok((v, true)) = self.options.get_string_value("fast_step_computation", "") {
7042            builder.fast_step_computation = v.eq_ignore_ascii_case("yes");
7043        }
7044
7045        let mut mehrotra_on = false;
7046        if let Ok((v, found)) = self.options.get_string_value("mehrotra_algorithm", "") {
7047            if found && v == "yes" {
7048                mehrotra_on = true;
7049                builder.mehrotra_algorithm = true;
7050                builder.mu_strategy = MuStrategyChoice::Adaptive;
7051                builder.mu_oracle = crate::mu::adaptive::MuOracleKind::Probing;
7052                // `accept_every_trial_step` short-circuits the alpha
7053                // loop / filter — Mehrotra steps would otherwise be
7054                // rejected by the filter on LP-shaped problems because
7055                // the barrier objective is non-monotone along the
7056                // corrector. Mirrors upstream `IpAlgBuilder.cpp:Mehrotra`.
7057                builder.line_search.accept_every_trial_step = true;
7058                // Aggressive iterate-push defaults (`SetNumericValueIfUnset`
7059                // in upstream). The explicit user parses below will
7060                // overwrite these if the user set them explicitly.
7061                builder.init.bound_push = 10.0;
7062                builder.init.bound_frac = 0.2;
7063                builder.init.slack_bound_push = 10.0;
7064                builder.init.slack_bound_frac = 0.2;
7065                builder.init.bound_mult_init_val = 10.0;
7066                builder.init.constr_mult_init_max = 0.0;
7067                // `alpha_for_y=bound-mult` — Mehrotra wants the
7068                // equality multipliers to advance with the dual
7069                // alpha so they stay in step with z/v. Mirrors
7070                // upstream `IpIpoptAlg.cpp:InitializeImpl`.
7071                builder.line_search.alpha_for_y =
7072                    crate::line_search::backtracking::AlphaForY::BoundMult;
7073                // `adaptive_mu_globalization=never-monotone-mode` —
7074                // upstream `IpIpoptAlg.cpp:148-154` enforces this:
7075                // Mehrotra disables the globalization switch entirely
7076                // (no fallback to monotone mode when convergence
7077                // stalls). Required for the unsafeguarded Mehrotra
7078                // path to function.
7079                builder.mu.adaptive_mu_globalization =
7080                    crate::mu::adaptive::AdaptiveMuGlobalization::NeverMonotoneMode;
7081                // `least_square_init_primal=yes` — upstream
7082                // `IpIpoptAlg.cpp:182` enables this for the Mehrotra
7083                // cascade. Replaces the user's starting `x` with the
7084                // min-norm primal that satisfies the linearized
7085                // equality+inequality constraints. Critical on
7086                // LP-shaped problems where the user's starting point
7087                // can be wildly infeasible (e.g. nuffield2_trap).
7088                builder.init.least_square_init_primal = true;
7089            }
7090        }
7091
7092        if let Ok((v, found)) = self.options.get_string_value("mu_strategy", "") {
7093            if found {
7094                let parsed = match v.as_str() {
7095                    "adaptive" => MuStrategyChoice::Adaptive,
7096                    _ => MuStrategyChoice::Monotone,
7097                };
7098                if mehrotra_on && matches!(parsed, MuStrategyChoice::Monotone) {
7099                    // Upstream Ipopt refuses this combination: Mehrotra
7100                    // needs an affine step every iter, which only the
7101                    // adaptive path computes. Keep adaptive and warn.
7102                    tracing::warn!(target: "pounce::algorithm",
7103                        "pounce: mehrotra_algorithm=yes requires \
7104                         mu_strategy=adaptive; ignoring \
7105                         mu_strategy=monotone."
7106                    );
7107                } else {
7108                    builder.mu_strategy = parsed;
7109                }
7110            }
7111        }
7112        if let Ok((v, found)) = self.options.get_string_value("mu_oracle", "") {
7113            if found {
7114                builder.mu_oracle = match v.as_str() {
7115                    "loqo" => crate::mu::adaptive::MuOracleKind::Loqo,
7116                    "probing" => crate::mu::adaptive::MuOracleKind::Probing,
7117                    _ => crate::mu::adaptive::MuOracleKind::QualityFunction,
7118                };
7119            }
7120        }
7121        if let Ok((v, found)) = self
7122            .options
7123            .get_string_value("adaptive_mu_globalization", "")
7124        {
7125            if found {
7126                use crate::mu::adaptive::AdaptiveMuGlobalization;
7127                builder.mu.adaptive_mu_globalization = match v.as_str() {
7128                    "kkt-error" => AdaptiveMuGlobalization::KktError,
7129                    "never-monotone-mode" => AdaptiveMuGlobalization::NeverMonotoneMode,
7130                    _ => AdaptiveMuGlobalization::ObjConstrFilter,
7131                };
7132            }
7133        }
7134        if let Ok((v, found)) = self.options.get_string_value("hessian_approximation", "") {
7135            if found {
7136                builder.hessian_approximation = match v.as_str() {
7137                    "limited-memory" => HessianApproxChoice::LimitedMemory,
7138                    "partitioned" => HessianApproxChoice::Partitioned,
7139                    "finite-difference" => HessianApproxChoice::FiniteDifference,
7140                    _ => HessianApproxChoice::Exact,
7141                };
7142            }
7143        }
7144        // **Upstream changes the `mu_strategy` default for a
7145        // limited-memory Hessian.** `IpAlgBuilder.cpp:1059`:
7146        //
7147        //     if( !options.GetStringValue("mu_strategy", smuupdate, prefix) )
7148        //     {
7149        //        // Change default for quasi-Newton option (then we use adaptive)
7150        //        ... if( hessian_approximation == LIMITED_MEMORY )
7151        //               smuupdate = "adaptive";
7152        //     }
7153        //
7154        // and again at `:920` for the restoration-phase algorithm.
7155        // Registered default is `monotone`; the quasi-Newton path takes
7156        // `adaptive` unless the caller says otherwise. pounce read the
7157        // registered default unconditionally, so every L-BFGS solve ran
7158        // a barrier schedule Ipopt does not use on that path — a
7159        // trajectory divergence on the arm the Python frontend and the
7160        // CasADi plugin select automatically (gh#746).
7161        //
7162        // The restoration sub-IPM inherits this: `run_inner_resto`
7163        // clones the configured `inner_alg_builder`, so the flag set
7164        // here is what the resto algorithm gets, matching `:920`.
7165        //
7166        // Only when unset — an explicit `mu_strategy` still wins, and
7167        // `mehrotra_algorithm` (parsed above) has already forced
7168        // adaptive on its own terms.
7169        if builder.hessian_approximation == HessianApproxChoice::LimitedMemory
7170            && !self.mu_strategy_was_set()
7171        {
7172            builder.mu_strategy = MuStrategyChoice::Adaptive;
7173        }
7174        // Limited-memory quasi-Newton update formula. Registered upstream
7175        // (`limited_memory_update_type`, IpLimMemQuasiNewtonUpdater.cpp) but
7176        // until now read nowhere on the IPM path — the updater was hard-wired
7177        // to Powell-damped BFGS. SR1 is honored too (the updater and the
7178        // low-rank/inertia path already handle its indefinite models).
7179        // Partitioned quasi-Newton knobs. `partitioned_update_type`
7180        // defaults to SR1 rather than BFGS — see
7181        // `crates::hess::partitioned_quasi_newton` for why damping is
7182        // the wrong choice on a per-constraint element.
7183        if let Ok((v, found)) = self.options.get_string_value("partitioned_update_type", "") {
7184            if found {
7185                builder.partitioned_update_type = match v.as_str() {
7186                    "bfgs" => UpdateType::Bfgs,
7187                    _ => UpdateType::Sr1,
7188                };
7189                builder.partitioned_update_type_was_set = true;
7190            }
7191        }
7192        if let Ok((v, found)) = self
7193            .options
7194            .get_integer_value("partitioned_max_element", "")
7195        {
7196            if found && v > 0 {
7197                builder.partitioned_max_element = v as usize;
7198            }
7199        }
7200        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_pattern", "") {
7201            if found {
7202                builder.fd_hessian_pattern = match v.as_str() {
7203                    "jacobian" => crate::hess::fd_hessian::FdPatternSource::Jacobian,
7204                    _ => crate::hess::fd_hessian::FdPatternSource::Declared,
7205                };
7206            }
7207        }
7208        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_coloring", "") {
7209            if found {
7210                builder.fd_hessian_coloring = match v.as_str() {
7211                    "cpr" => crate::hess::fd_hessian::FdColoring::Cpr,
7212                    _ => crate::hess::fd_hessian::FdColoring::Star,
7213                };
7214            }
7215        }
7216        if let Ok((v, found)) = self.options.get_numeric_value("fd_hessian_reuse_tol", "") {
7217            if found && v >= 0.0 {
7218                builder.fd_hessian_reuse_tol = v;
7219            }
7220        }
7221        if let Ok((v, found)) = self.options.get_string_value("partitioned_elements", "") {
7222            if found {
7223                builder.partitioned_elements = match v.as_str() {
7224                    "blocks" => crate::hess::partitioned_quasi_newton::ElementMode::PrimalBlock,
7225                    _ => crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
7226                };
7227            }
7228        }
7229        if let Ok((v, found)) = self.options.get_integer_value("partitioned_block_size", "") {
7230            if found && v > 0 {
7231                builder.partitioned_block_size = v as usize;
7232            }
7233        }
7234        if let Ok((v, found)) = self
7235            .options
7236            .get_numeric_value("partitioned_curvature_cap", "")
7237        {
7238            if found && v > 0.0 {
7239                builder.partitioned_curvature_cap = v;
7240            }
7241        }
7242        if let Ok((v, found)) = self
7243            .options
7244            .get_string_value("limited_memory_update_type", "")
7245        {
7246            if found {
7247                builder.limited_memory_update_type = match v.as_str() {
7248                    "sr1" => UpdateType::Sr1,
7249                    _ => UpdateType::Bfgs,
7250                };
7251            }
7252        }
7253        // Limited-memory history length (`limited_memory_max_history`).
7254        if let Ok((v, found)) = self
7255            .options
7256            .get_integer_value("limited_memory_max_history", "")
7257        {
7258            if found && v >= 0 {
7259                builder.limited_memory_max_history = v as Index;
7260            }
7261        }
7262        // `limited_memory_initialization` — which formula picks the
7263        // initial Hessian scalar σ. Registered since the option port with
7264        // upstream's `scalar1` default and read nowhere until #677, so
7265        // the updater's own `Scalar2` default was the only value any
7266        // solve ever used: setting the option did nothing, and it warned
7267        // nothing. Same miss as gh#483 / #191 round 2 (which wired
7268        // `limited_memory_init_val_max`/`_min`) — this is the third
7269        // argument to that same `initial_hessian_scalar` call.
7270        //
7271        // The effective default now follows the registry (`scalar1`),
7272        // matching Ipopt. σ_scalar2/σ_scalar1 = (yᵀy·sᵀs)/(sᵀy)² ≥ 1 and
7273        // is unbounded as the curvature pair degrades, so on an
7274        // ill-conditioned problem `scalar2` inflates `B0 = σI` until it
7275        // swamps the rank-2 corrections and the step collapses.
7276        if let Ok((v, found)) = self
7277            .options
7278            .get_string_value("limited_memory_initialization", "")
7279        {
7280            if found {
7281                use crate::hess::lim_mem_quasi_newton::InitialApprox;
7282                // Every registered value is named explicitly. #551 §3
7283                // held this option back precisely because wiring only
7284                // the values that mapped would leave the rest falling
7285                // back silently — a new no-op created by the fix — so a
7286                // catch-all standing in for a real value is the one
7287                // shape to avoid here. `OptionsList` rejects any
7288                // unregistered value before this runs (`options_list.rs`
7289                // `OPTION_INVALID`), so the final arm is unreachable
7290                // rather than a fallback.
7291                builder.limited_memory_initialization = match v.as_str() {
7292                    "scalar1" => InitialApprox::Scalar1,
7293                    "scalar2" => InitialApprox::Scalar2,
7294                    "scalar3" => InitialApprox::Scalar3,
7295                    "scalar4" => InitialApprox::Scalar4,
7296                    "constant" => InitialApprox::Constant,
7297                    "history-max" => InitialApprox::HistoryMax,
7298                    _ => InitialApprox::Scalar2,
7299                };
7300            }
7301        }
7302        // `recalc_y` / `recalc_y_feas_tol` — least-square re-estimation
7303        // of the equality multipliers once feasible (#677).
7304        //
7305        // Upstream registers `recalc_y` as `no`, but its own option text
7306        // ends "If a limited memory quasi-Newton option is chosen, this
7307        // is used by default", so upstream's effective default is
7308        // conditional on the Hessian approximation.
7309        //
7310        // **pounce does not follow that, and the discrepancy is
7311        // deliberate.** Auto-enabling it for the limited-memory path was
7312        // implemented and measured against the fixture corpus first: it
7313        // moved 16 of 57 fixtures on the L-BFGS leg and took **7 from
7314        // solved to not solved, with nothing moving the other way** —
7315        // `airport` 56 it → `SearchDirectionBecomesTooSmall` at 541,
7316        // `pooling_rt2stp` 413 it → the same at 1775, all three `jit1`
7317        // variants, `linear_eq_collapsed_box`, and `hs13_bigstart` to
7318        // the iteration cap. The signature is consistent: re-estimating
7319        // `y` on every feasible iteration overwrites Newton multipliers
7320        // that were converging, the dual never settles, and the step
7321        // vanishes short of the certificate.
7322        //
7323        // So the feature is available and off by default. That still
7324        // closes the gap that mattered — until #677 the option was
7325        // refused outright as unimplemented, so an L-BFGS user could not
7326        // reach Ipopt's behaviour at all. They can now, by asking.
7327        //
7328        // Why it is worth having: a quasi-Newton model's dual step is
7329        // computed from an approximate `W`, so L-BFGS can settle a
7330        // feasible primal and still not drive `inf_du` to tolerance —
7331        // the failure a 59,939-variable CasADi model hit, oscillating
7332        // `inf_du` between 3.6e-3 and 1.8e+01 for 300 iterations with
7333        // the objective already settled. On that shape it is the fix;
7334        // on a corpus of small well-conditioned models it is a
7335        // pessimisation. Matching upstream's conditional default needs
7336        // to explain the 7 regressions first.
7337        if let Ok((v, true)) = self.options.get_string_value("recalc_y", "") {
7338            builder.recalc_y = v == "yes";
7339        }
7340        if let Ok((v, true)) = self.options.get_numeric_value("recalc_y_feas_tol", "") {
7341            builder.recalc_y_feas_tol = v;
7342        }
7343        // `limited_memory_init_val` — σ before any curvature pair exists,
7344        // and every iteration under `constant`. Also unread until #677;
7345        // the empty-history branch hard-coded the same `1.0`.
7346        if let Ok((v, true)) = self
7347            .options
7348            .get_numeric_value("limited_memory_init_val", "")
7349        {
7350            builder.limited_memory_init_val = v;
7351        }
7352        // `limited_memory_max_skipping` (#686) — registered and unread,
7353        // and the feature behind it did not exist either: the updater
7354        // counted nothing and never discarded its history.
7355        if let Ok((v, true)) = self
7356            .options
7357            .get_integer_value("limited_memory_max_skipping", "")
7358        {
7359            if v >= 0 {
7360                builder.limited_memory_max_skipping = v as Index;
7361            }
7362        }
7363        if let Ok((v, found)) = self.options.get_string_value("line_search_method", "") {
7364            if found {
7365                builder.line_search_method = match v.as_str() {
7366                    // Unreachable from a real solve since gh#981:
7367                    // `cg-penalty` is refused by
7368                    // `unimplemented_options::UNIMPLEMENTED_VALUES`
7369                    // before the builder is configured, because the
7370                    // variant assembles the plain penalty acceptor.
7371                    "cg-penalty" => LineSearchChoice::CgPenalty,
7372                    "penalty" => LineSearchChoice::Penalty,
7373                    _ => LineSearchChoice::Filter,
7374                };
7375            }
7376        }
7377        // `accept_every_trial_step` — direct user override. Parsed
7378        // after the Mehrotra cascade so an explicit `no` still wins.
7379        if let Ok((v, found)) = self.options.get_string_value("accept_every_trial_step", "") {
7380            if found {
7381                builder.line_search.accept_every_trial_step = v == "yes";
7382            }
7383        }
7384        // `alpha_for_y` — direct user override. Parsed after the
7385        // Mehrotra cascade so an explicit value still wins.
7386        if let Ok((v, found)) = self.options.get_string_value("alpha_for_y", "") {
7387            if found {
7388                use crate::line_search::backtracking::AlphaForY;
7389                builder.line_search.alpha_for_y = match v.as_str() {
7390                    "primal" => AlphaForY::Primal,
7391                    "bound-mult" | "bound_mult" => AlphaForY::BoundMult,
7392                    "full" => AlphaForY::Full,
7393                    "min" => AlphaForY::Min,
7394                    "max" => AlphaForY::Max,
7395                    "primal-and-full" | "dual-and-full" => AlphaForY::Primal,
7396                    _ => AlphaForY::Primal,
7397                };
7398            }
7399        }
7400        // `nlp_scaling_method` is consumed NLP-side in
7401        // `OrigIpoptNlp::determine_scaling_from_starting_point` (see the
7402        // `determine_scaling_from_starting_point` call earlier in this
7403        // method); there is no algorithm-side scaling strategy to wire.
7404        // `limited_memory_init_val_max` / `_min` — the clamp on the
7405        // initial Hessian scalar. `LimMemQuasiNewtonUpdater` consumes
7406        // both in `initial_hessian_scalar`; only the read sites were
7407        // missing, so setting either did nothing (gh#483, #191 round 2).
7408        if let Ok((v, true)) = self
7409            .options
7410            .get_numeric_value("limited_memory_init_val_max", "")
7411        {
7412            builder.limited_memory_init_val_max = v;
7413        }
7414        if let Ok((v, true)) = self
7415            .options
7416            .get_numeric_value("limited_memory_init_val_min", "")
7417        {
7418            builder.limited_memory_init_val_min = v;
7419        }
7420
7421        // Unlike the other options here, we always honor the registry
7422        // value (not just when the user set it explicitly): the option
7423        // registry default is "ma57" but `AlgorithmBuilder::default`
7424        // has `linear_solver: Feral`, so gating on `found` would
7425        // silently route default runs through Feral while the banner
7426        // (and ipopt-compatible behavior) advertises MA57.
7427        //
7428        // Record the **effective** backend, not the requested one. MA57 lives
7429        // behind the optional `ma57` cargo feature (HSL is licensed and needs a
7430        // Fortran toolchain); without it `default_backend_factory` silently
7431        // substitutes FERAL. Storing `Ma57` here therefore made
7432        // `builder.linear_solver` disagree with the backend actually built, and
7433        // consumers acted on the lie: the Schur KKT gate in
7434        // `alg_builder::build_with_backend` tests `== Feral`, so on the
7435        // pure-Rust default build — where the registry default (then upstream's
7436        // "ma57") resolved to FERAL anyway — `set_kkt_schur_block()` silently
7437        // never engaged for ANY user. Resolving here keeps the field truthful
7438        // for every consumer.
7439        //
7440        // The `_ =>` arm is now only reachable for `feral`: every other name
7441        // is refused up front by `unimplemented_linear_solver`. It used to
7442        // swallow `mumps`, `pardiso`, `ma97`, … and run FERAL instead.
7443        if let Ok((v, _found)) = self.options.get_string_value("linear_solver", "") {
7444            let requested = if v.eq_ignore_ascii_case("ma57") {
7445                LinearSolverChoice::Ma57
7446            } else {
7447                LinearSolverChoice::Feral
7448            };
7449            builder.linear_solver =
7450                if matches!(requested, LinearSolverChoice::Ma57) && !cfg!(feature = "ma57") {
7451                    LinearSolverChoice::Feral
7452                } else {
7453                    requested
7454                };
7455        }
7456
7457        // `linear_system_scaling` — symmetric scaling of the augmented
7458        // KKT matrix before factorization. Port of
7459        // `IpTSymLinearSolver.cpp:RegisterOptions` plumbing. Default
7460        // "none"; "ruiz" invokes the Ruiz-2001 symmetric ∞-norm
7461        // equilibration in `RuizTSymScalingMethod`. "mc19" and
7462        // "slack-based" are accepted by the registry but not yet
7463        // implemented at this layer; they fall back to no scaling
7464        // with a one-line notice.
7465        //
7466        // `slack-based` is implemented as of #677. It used to reach the
7467        // no-scaling fallback through the catch-all arm, which meant it
7468        // fell back **silently** — the comment above promised a notice
7469        // that only `mc19` actually emitted. It is not a hypothetical
7470        // value: it is what Ipopt's own recommended configuration for
7471        // large collocation NLPs uses, so the users most likely to set
7472        // it were the least likely to be told it did nothing. The
7473        // catch-all is left for genuinely unreachable input —
7474        // `OptionsList` rejects anything the registry does not list.
7475        if let Ok((v, found)) = self.options.get_string_value("linear_system_scaling", "") {
7476            if found {
7477                builder.linear_system_scaling = match v.as_str() {
7478                    "ruiz" => crate::alg_builder::LinearSystemScalingChoice::Ruiz,
7479                    "mc19" => crate::alg_builder::LinearSystemScalingChoice::Mc19,
7480                    "slack-based" => crate::alg_builder::LinearSystemScalingChoice::SlackBased,
7481                    _ => crate::alg_builder::LinearSystemScalingChoice::None,
7482                };
7483            }
7484        }
7485        if let Ok((v, found)) = self.options.get_bool_value("linear_scaling_on_demand", "") {
7486            if found {
7487                builder.linear_scaling_on_demand = v;
7488            }
7489        }
7490
7491        // Convergence tolerances (port of `IpOptErrorConvCheck.cpp`'s
7492        // `RegisterOptions` consumers). Defaults already match upstream
7493        // — only override when the user set the key explicitly.
7494        let read_num = |key: &str| -> Option<f64> {
7495            self.options
7496                .get_numeric_value(key, "")
7497                .ok()
7498                .and_then(|(v, f)| f.then_some(v))
7499        };
7500        let read_int = |key: &str| -> Option<i32> {
7501            self.options
7502                .get_integer_value(key, "")
7503                .ok()
7504                .and_then(|(v, f)| f.then_some(v))
7505        };
7506        if let Some(v) = read_num("tol") {
7507            builder.conv_check.tol = v;
7508        }
7509        if let Some(v) = read_num("obj_scale_certificate_threshold") {
7510            builder.conv_check.obj_scale_certificate_threshold = v;
7511        }
7512        if let Some(v) = read_num("primal_noise_floor_kappa") {
7513            builder.conv_check.primal_noise_floor_kappa = v;
7514        }
7515        if let Some(v) = read_num("acceptable_progress_kappa") {
7516            builder.conv_check.acceptable_progress_kappa = v;
7517        }
7518        if let Some(v) = read_num("dual_inf_scale_kappa") {
7519            builder.conv_check.dual_inf_scale_kappa = v;
7520        }
7521        if let Some(v) = read_num("kkt_fidelity_tol") {
7522            builder.kkt_fidelity_tol = v;
7523        }
7524        if let Some(v) = read_num("dual_inf_tol") {
7525            builder.conv_check.dual_inf_tol = v;
7526            // gh#983 item 1: a caller who names `dual_inf_tol` has asked for
7527            // that absolute standard. The scale-relative floor (gh#532) is a
7528            // default for a caller who has not, and it let `1e-6` certify a
7529            // point with `‖∇L‖∞ = 0.144` because the multipliers were 3.5e9
7530            // (a failed constraint qualification, which is not a reason to
7531            // loosen the test). Naming `dual_inf_scale_kappa` as well opts the
7532            // floor back in.
7533            //
7534            // gh#983 review: a value equal to the registered default is read
7535            // as "not named". Front ends that echo every default (option
7536            // files copied from Ipopt's documentation, wrappers that pass the
7537            // full table) would otherwise lose the gh#532 floor without asking
7538            // for anything. That is safe because the floor with the default
7539            // tolerance IS the default behaviour; a caller who wants the
7540            // absolute standard at `1` names `dual_inf_scale_kappa 0`, which
7541            // the option help documents.
7542            let default_tol = crate::alg_builder::ConvCheckOptions::default().dual_inf_tol;
7543            if read_num("dual_inf_scale_kappa").is_none() && v != default_tol {
7544                builder.conv_check.dual_inf_scale_kappa = 0.0;
7545            }
7546        }
7547        if let Some(v) = read_num("constr_viol_tol") {
7548            builder.conv_check.constr_viol_tol = v;
7549        }
7550        if let Some(v) = read_num("compl_inf_tol") {
7551            builder.conv_check.compl_inf_tol = v;
7552        }
7553        if let Some(v) = read_int("max_iter") {
7554            builder.conv_check.max_iter = v;
7555        }
7556        if let Some(v) = read_num("max_cpu_time") {
7557            builder.conv_check.max_cpu_time = v;
7558        }
7559        if let Some(v) = read_num("max_wall_time") {
7560            builder.conv_check.max_wall_time = v;
7561        }
7562        if let Some(v) = read_num("acceptable_tol") {
7563            builder.conv_check.acceptable_tol = v;
7564        }
7565        if let Some(v) = read_num("acceptable_dual_inf_tol") {
7566            builder.conv_check.acceptable_dual_inf_tol = v;
7567        }
7568        if let Some(v) = read_num("acceptable_constr_viol_tol") {
7569            builder.conv_check.acceptable_constr_viol_tol = v;
7570        }
7571        if let Some(v) = read_num("acceptable_compl_inf_tol") {
7572            builder.conv_check.acceptable_compl_inf_tol = v;
7573        }
7574        if let Some(v) = read_num("acceptable_obj_change_tol") {
7575            builder.conv_check.acceptable_obj_change_tol = v;
7576        }
7577        if let Some(v) = read_int("acceptable_iter") {
7578            builder.conv_check.acceptable_iter = v;
7579        }
7580        if let Some(v) = read_num("infeas_stationarity_tol") {
7581            builder.conv_check.infeas_stationarity_tol = v;
7582        }
7583        if let Some(v) = read_num("infeas_viol_kappa") {
7584            builder.conv_check.infeas_viol_kappa = v;
7585        }
7586        if let Some(v) = read_int("infeas_max_streak") {
7587            builder.conv_check.infeas_max_streak = v;
7588        }
7589
7590        // Bound-multiplier / barrier damping constants (#191). Both were
7591        // registered but never read, so user overrides were silently
7592        // dropped; the algorithm ran with the hard-coded struct defaults.
7593        // Defaults equal the registered defaults, so this changes nothing
7594        // for a run that doesn't set them.
7595        if let Some(v) = read_num("kappa_sigma") {
7596            builder.kappa_sigma = v;
7597        }
7598        if let Some(v) = read_num("kappa_d") {
7599            builder.kappa_d = v;
7600        }
7601        // `s_max` — the cap in the `(s_d, s_c)` scaling of the KKT error
7602        // test (#551 / #677). `IpoptCalculatedQuantities` carried it as a
7603        // hard-coded 100 (the registered default) and nothing read the
7604        // option; a run that does not set it is unaffected.
7605        if let Some(v) = read_num("s_max") {
7606            builder.s_max = v;
7607        }
7608        if let Some(v) = read_num("tiny_step_tol") {
7609            builder.tiny_step_tol = v;
7610        }
7611        if let Some(v) = read_num("tiny_step_y_tol") {
7612            builder.tiny_step_y_tol = v;
7613        }
7614        if let Some(v) = read_num("diverging_iterates_tol") {
7615            builder.diverging_iterates_tol = v;
7616        }
7617        if let Some(v) = read_int("dual_diverging_streak") {
7618            builder.dual_diverging_streak = v;
7619        }
7620        if let Some(v) = read_num("dual_divergence_retry_step_tol") {
7621            builder.dual_divergence_retry_step_tol = v;
7622        }
7623        if let Some(v) = read_num("dual_divergence_retry_du_floor") {
7624            builder.dual_divergence_retry_du_floor = v;
7625        }
7626        if let Some(v) = read_int("resto_decline_deferrals") {
7627            builder.resto_decline_deferrals = v;
7628        }
7629        if let Some(v) = read_num("resto_decline_progress_ratio") {
7630            builder.resto_decline_progress_ratio = v;
7631        }
7632        if let Some(v) = read_int("neg_curv_escapes") {
7633            builder.neg_curv_escapes = v;
7634        }
7635        if let Some(v) = read_int("limited_memory_ls_failure_restarts") {
7636            builder.limited_memory_ls_failure_restarts = v;
7637        }
7638
7639        // Barrier-parameter (μ) options — consumers in
7640        // `IpMonotoneMuUpdate.cpp` / `IpAdaptiveMuUpdate.cpp`. Both
7641        // updaters share the same option names; the builder forwards
7642        // each into whichever strategy is assembled.
7643        if let Some(v) = read_num("mu_init") {
7644            builder.mu.mu_init = v;
7645        }
7646        if let Some(v) = read_num("mu_max") {
7647            builder.mu.mu_max = v;
7648        }
7649        if let Some(v) = read_num("mu_max_fact") {
7650            builder.mu.mu_max_fact = v;
7651        }
7652        if let Some(v) = read_num("mu_min") {
7653            builder.mu.mu_min = v;
7654        }
7655        if let Some(v) = read_num("mu_target") {
7656            builder.mu.mu_target = v;
7657        }
7658        if let Some(v) = read_num("mu_linear_decrease_factor") {
7659            builder.mu.mu_linear_decrease_factor = v;
7660        }
7661        if let Some(v) = read_num("mu_superlinear_decrease_power") {
7662            builder.mu.mu_superlinear_decrease_power = v;
7663        }
7664        if let Ok((v, found)) = self
7665            .options
7666            .get_string_value("mu_allow_fast_monotone_decrease", "")
7667        {
7668            if found {
7669                builder.mu.mu_allow_fast_monotone_decrease = v == "yes";
7670            }
7671        }
7672        if let Some(v) = read_num("barrier_tol_factor") {
7673            builder.mu.barrier_tol_factor = v;
7674        }
7675        // `tau_min` — floor on the fraction-to-the-boundary parameter
7676        // (#551 / #677). Both `MonotoneMuUpdate` and `AdaptiveMuUpdate`
7677        // carried the field with upstream's 0.99 default and nothing
7678        // read the option, so an override was silently dropped. The
7679        // default equals the registered default, so this changes
7680        // nothing for a run that does not set it.
7681        if let Some(v) = read_num("tau_min") {
7682            builder.mu.tau_min = v;
7683        }
7684        if let Some(v) = read_num("sigma_max") {
7685            builder.mu.sigma_max = v;
7686        }
7687        if let Some(v) = read_num("sigma_min") {
7688            builder.mu.sigma_min = v;
7689        }
7690
7691        // Quality-function oracle knobs — consumers in
7692        // `IpQualityFunctionMuOracle.cpp:RegisterOptions`. Forwarded
7693        // to the oracle on every free-mode call.
7694        if let Ok((v, found)) = self
7695            .options
7696            .get_string_value("quality_function_norm_type", "")
7697        {
7698            if found {
7699                use crate::mu::oracle::quality_function::NormType;
7700                builder.mu.quality_function_norm_type = match v.as_str() {
7701                    "1-norm" => NormType::OneNorm,
7702                    "2-norm" => NormType::TwoNorm,
7703                    "max-norm" => NormType::MaxNorm,
7704                    _ => NormType::TwoNormSquared,
7705                };
7706            }
7707        }
7708        if let Ok((v, found)) = self
7709            .options
7710            .get_string_value("quality_function_centrality", "")
7711        {
7712            if found {
7713                use crate::mu::oracle::quality_function::CentralityType;
7714                builder.mu.quality_function_centrality = match v.as_str() {
7715                    "log" => CentralityType::LogCenter,
7716                    "reciprocal" => CentralityType::ReciprocalCenter,
7717                    "cubed-reciprocal" => CentralityType::CubedReciprocalCenter,
7718                    _ => CentralityType::None,
7719                };
7720            }
7721        }
7722        if let Ok((v, found)) = self
7723            .options
7724            .get_string_value("quality_function_balancing_term", "")
7725        {
7726            if found {
7727                use crate::mu::oracle::quality_function::BalancingTermType;
7728                builder.mu.quality_function_balancing_term = match v.as_str() {
7729                    "cubic" => BalancingTermType::CubicTerm,
7730                    _ => BalancingTermType::None,
7731                };
7732            }
7733        }
7734        if let Some(v) = read_int("quality_function_max_section_steps") {
7735            builder.mu.quality_function_max_section_steps = v;
7736        }
7737        if let Some(v) = read_num("quality_function_section_sigma_tol") {
7738            builder.mu.quality_function_section_sigma_tol = v;
7739        }
7740        if let Some(v) = read_num("quality_function_section_qf_tol") {
7741            builder.mu.quality_function_section_qf_tol = v;
7742        }
7743
7744        // `probing_iterate_quality_factor` — pounce-specific guard
7745        // (pounce#58) on the probing μ-oracle's input iterate. When
7746        // `curr_avrg_compl / curr_mu` exceeds this factor, the
7747        // μ-update layer signals restoration via
7748        // `IpoptData::request_resto` instead of letting probing
7749        // return `σ · mu_curr` ≫ previous μ. Default 1e4; set to ≤ 0
7750        // to disable. No upstream Ipopt counterpart.
7751        if let Some(v) = read_num("probing_iterate_quality_factor") {
7752            builder.mu.probing_iterate_quality_factor = v;
7753        }
7754
7755        // Adaptive-μ extras — consumers in
7756        // `IpAdaptiveMuUpdate.cpp:RegisterOptions`. Only active when
7757        // `mu_strategy=adaptive`.
7758        if let Some(v) = read_num("adaptive_mu_safeguard_factor") {
7759            builder.mu.adaptive_mu_safeguard_factor = v;
7760        }
7761        if let Some(v) = read_num("adaptive_mu_monotone_init_factor") {
7762            builder.mu.adaptive_mu_monotone_init_factor = v;
7763        }
7764        if let Ok((v, found)) = self
7765            .options
7766            .get_bool_value("adaptive_mu_restore_previous_iterate", "")
7767        {
7768            if found {
7769                builder.mu.adaptive_mu_restore_previous_iterate = v;
7770            }
7771        }
7772        if let Some(v) = read_int("adaptive_mu_max_free_returns") {
7773            builder.mu.adaptive_mu_max_free_returns = v;
7774        }
7775        if let Some(v) = read_num("adaptive_mu_budget_pin_fraction") {
7776            builder.mu.adaptive_mu_budget_pin_fraction = v;
7777        }
7778        if let Some(v) = read_int("adaptive_mu_kkterror_red_iters") {
7779            if v >= 0 {
7780                builder.mu.adaptive_mu_kkterror_red_iters = v as usize;
7781            }
7782        }
7783        if let Some(v) = read_num("adaptive_mu_kkterror_red_fact") {
7784            builder.mu.adaptive_mu_kkterror_red_fact = v;
7785        }
7786        // `filter_margin_fact` / `filter_max_margin` (#551) — the margin
7787        // an entry must clear in the `obj-constr-filter` globalization
7788        // test. `AdaptiveMuUpdate` computes
7789        // `filter_margin_fact * min(filter_max_margin, err)` and has
7790        // always done so; only these two read sites were missing, so
7791        // setting either did nothing. Defaults equal the registered
7792        // defaults (1e-5 / 1.0), so an unset run is unchanged.
7793        if let Some(v) = read_num("filter_margin_fact") {
7794            builder.mu.filter_margin_fact = v;
7795        }
7796        if let Some(v) = read_num("filter_max_margin") {
7797            builder.mu.filter_max_margin = v;
7798        }
7799        if let Ok((v, found)) = self
7800            .options
7801            .get_string_value("adaptive_mu_kkt_norm_type", "")
7802        {
7803            if found {
7804                use crate::mu::adaptive::AdaptiveMuKktNorm;
7805                builder.mu.adaptive_mu_kkt_norm_type = match v.as_str() {
7806                    "1-norm" => AdaptiveMuKktNorm::OneNorm,
7807                    "2-norm" => AdaptiveMuKktNorm::TwoNorm,
7808                    "max-norm" => AdaptiveMuKktNorm::MaxNorm,
7809                    _ => AdaptiveMuKktNorm::TwoNormSquared,
7810                };
7811            }
7812        }
7813
7814        // Watchdog options — consumers in
7815        // `IpBacktrackingLineSearch.cpp:RegisterOptions`. Baked into
7816        // the `BacktrackingLineSearch` at build time.
7817        if let Some(v) = read_int("watchdog_shortened_iter_trigger") {
7818            builder.line_search.watchdog_shortened_iter_trigger = v;
7819        }
7820        if let Some(v) = read_int("watchdog_trial_iter_max") {
7821            builder.line_search.watchdog_trial_iter_max = v;
7822        }
7823        if let Some(v) = read_num("soft_resto_pderror_reduction_factor") {
7824            builder.line_search.soft_resto_pderror_reduction_factor = v;
7825        }
7826        if let Some(v) = read_int("max_soft_resto_iters") {
7827            builder.line_search.max_soft_resto_iters = v;
7828        }
7829        // `alpha_red_factor` (#678) and `accept_after_max_steps` (#551)
7830        // — both consumed by the α-loop in `BacktrackingLineSearch`,
7831        // both registered without a read site until those issues.
7832        // `alpha_red_factor`'s default (0.5) equals the registered one,
7833        // and `accept_after_max_steps` defaults to `-1`, which disables
7834        // the escape hatch, so neither moves a solve that leaves them
7835        // alone.
7836        if let Some(v) = read_num("alpha_red_factor") {
7837            builder.line_search.alpha_red_factor = v;
7838        }
7839        if let Some(v) = read_num("alpha_red_factor_min") {
7840            builder.line_search.alpha_red_factor_min = Some(v);
7841        }
7842        if let Some(v) = read_int("accept_after_max_steps") {
7843            builder.line_search.accept_after_max_steps = v;
7844        }
7845
7846        // Filter switching / Armijo / margin constants (#191). Consumed
7847        // by `FilterLsAcceptor` (only on the `Filter` line-search path);
7848        // registered but never read, so overrides were silently dropped.
7849        // Defaults equal the registered defaults.
7850        if let Some(v) = read_num("eta_phi") {
7851            builder.line_search.eta_phi = v;
7852        }
7853        // `delta` (#551) — the switching rule's multiplier on the
7854        // constraint violation (Eqn. (19)); `FilterLsAcceptor` has
7855        // always used it as `delta_armijo`, only the read site was
7856        // missing. Default 1.0 equals the registered default.
7857        if let Some(v) = read_num("delta") {
7858            builder.line_search.delta = v;
7859        }
7860        if let Some(v) = read_num("theta_min_fact") {
7861            builder.line_search.theta_min_fact = v;
7862        }
7863        if let Some(v) = read_num("theta_max_row_scale_kappa") {
7864            builder.line_search.theta_max_row_scale_kappa = v;
7865        }
7866        if let Some(v) = read_int("theta_max_adaptive_trigger") {
7867            builder.line_search.theta_max_adaptive_trigger = v.max(0) as u32;
7868        }
7869        if let Some(v) = read_num("theta_max_adaptive_factor") {
7870            builder.line_search.theta_max_adaptive_factor = v;
7871        }
7872        if let Some(v) = read_int("theta_max_adaptive_max_raises") {
7873            builder.line_search.theta_max_adaptive_max_raises = v.max(0) as u32;
7874        }
7875        if let Some(v) = read_num("theta_max_fact") {
7876            builder.line_search.theta_max_fact = v;
7877        }
7878        if let Some(v) = read_num("gamma_phi") {
7879            builder.line_search.gamma_phi = v;
7880        }
7881        if let Some(v) = read_num("gamma_theta") {
7882            builder.line_search.gamma_theta = v;
7883        }
7884        if let Some(v) = read_num("s_phi") {
7885            builder.line_search.s_phi = v;
7886        }
7887        if let Some(v) = read_num("s_theta") {
7888            builder.line_search.s_theta = v;
7889        }
7890        if let Some(v) = read_num("alpha_min_frac") {
7891            builder.line_search.alpha_min_frac = v;
7892        }
7893        if let Some(v) = read_num("obj_max_inc") {
7894            builder.line_search.obj_max_inc = v;
7895        }
7896        if let Some(v) = read_int("max_filter_resets") {
7897            builder.line_search.max_filter_resets = v;
7898        }
7899        if let Some(v) = read_int("filter_reset_trigger") {
7900            builder.line_search.filter_reset_trigger = v;
7901        }
7902        // `filter_theta_roundoff_retry` (gh#945).
7903        if let Ok((v, true)) = self
7904            .options
7905            .get_bool_value("filter_theta_roundoff_retry", "")
7906        {
7907            builder.line_search.filter_theta_roundoff_retry = v;
7908        }
7909        // `objective_noise_wolfe` (gh#1016).
7910        if let Ok((v, true)) = self.options.get_bool_value("objective_noise_wolfe", "") {
7911            builder.line_search.objective_noise_wolfe = v;
7912        }
7913        // Penalty line-search constants (#551), consumed by
7914        // `PenaltyLsAcceptor` (only on the `line_search_method=penalty`
7915        // / `cg-penalty` paths). The acceptor implements ν and the
7916        // Armijo test on the penalty merit function already; these four
7917        // were registered with no read site, so tuning the penalty
7918        // update did nothing. Defaults equal the registered defaults.
7919        if let Some(v) = read_num("nu_init") {
7920            builder.line_search.nu_init = v;
7921        }
7922        if let Some(v) = read_num("nu_inc") {
7923            builder.line_search.nu_inc = v;
7924        }
7925        if let Some(v) = read_num("rho") {
7926            builder.line_search.rho = v;
7927        }
7928        if let Some(v) = read_num("eta_penalty") {
7929            builder.line_search.eta_penalty = v;
7930        }
7931
7932        // Second-order-correction constants (#191), consumed by
7933        // `BacktrackingLineSearch`. `max_soc = 0` disables SOC.
7934        if let Some(v) = read_int("max_soc") {
7935            builder.line_search.max_soc = v;
7936        }
7937        if let Some(v) = read_num("kappa_soc") {
7938            builder.line_search.kappa_soc = v;
7939        }
7940        if let Some(v) = read_int("soc_method") {
7941            builder.line_search.soc_method = v;
7942        }
7943
7944        // Inertia-correction / Jacobian-regularization constants (#191),
7945        // consumed by `PdPerturbationHandler`. Registered but never read.
7946        if let Some(v) = read_num("max_hessian_perturbation") {
7947            builder.perturbation.max_hessian_perturbation = v;
7948        }
7949        if let Some(v) = read_num("min_hessian_perturbation") {
7950            builder.perturbation.min_hessian_perturbation = v;
7951        }
7952        if let Some(v) = read_num("perturb_inc_fact_first") {
7953            builder.perturbation.perturb_inc_fact_first = v;
7954        }
7955        if let Some(v) = read_num("perturb_inc_fact") {
7956            builder.perturbation.perturb_inc_fact = v;
7957        }
7958        if let Some(v) = read_num("perturb_dec_fact") {
7959            builder.perturbation.perturb_dec_fact = v;
7960        }
7961        if let Some(v) = read_num("first_hessian_perturbation") {
7962            builder.perturbation.first_hessian_perturbation = v;
7963        }
7964        if let Some(v) = read_num("jacobian_regularization_value") {
7965            builder.perturbation.jacobian_regularization_value = v;
7966        }
7967        if let Some(v) = read_num("jacobian_regularization_exponent") {
7968            builder.perturbation.jacobian_regularization_exponent = v;
7969        }
7970        if let Ok((v, true)) = self.options.get_bool_value("perturb_always_cd", "") {
7971            builder.perturbation.perturb_always_cd = v;
7972        }
7973        if let Some(v) = read_int("perturb_delta_c_max_rungs") {
7974            builder.perturbation.perturb_delta_c_max_rungs = v;
7975        }
7976
7977        // Iterative-refinement constants (#191), consumed by
7978        // `PdFullSpaceSolver`. Registered but never read.
7979        if let Some(v) = read_int("min_refinement_steps") {
7980            builder.refinement.min_refinement_steps = v;
7981        }
7982        if let Some(v) = read_int("max_refinement_steps") {
7983            builder.refinement.max_refinement_steps = v;
7984        }
7985        if let Some(v) = read_num("residual_ratio_max") {
7986            builder.refinement.residual_ratio_max = v;
7987        }
7988        if let Some(v) = read_num("residual_ratio_singular") {
7989            builder.refinement.residual_ratio_singular = v;
7990        }
7991        if let Some(v) = read_num("residual_improvement_factor") {
7992            builder.refinement.residual_improvement_factor = v;
7993        }
7994
7995        // Inertia-free curvature test (#551 / #677), also consumed by
7996        // `PdFullSpaceSolver`. `neg_curv_test_tol` had a field that only
7997        // ever held its 0.0 default, and `neg_curv_test_reg` had none at
7998        // all; both are now read, and the curvature test they configure
7999        // is implemented in `PdFullSpaceSolver::solve_once`. At the
8000        // registered default (`0.0`) the heuristic is off and the
8001        // inertia check runs as before.
8002        if let Some(v) = read_num("neg_curv_test_tol") {
8003            builder.refinement.neg_curv_test_tol = v;
8004        }
8005        if let Ok((v, true)) = self.options.get_bool_value("neg_curv_test_reg", "") {
8006            builder.refinement.neg_curv_test_reg = v;
8007        }
8008
8009        // Restoration-phase constants (#191). Carried on the outer builder
8010        // and copied into the `RestoAlgorithmBuilder` when the restoration
8011        // factory is minted (the frontends pass this builder in). The
8012        // restoration builder was never options-configured, so these were
8013        // registered but never read. Defaults equal the registered
8014        // defaults.
8015        if let Some(v) = read_num("bound_mult_reset_threshold") {
8016            builder.resto.bound_mult_reset_threshold = v;
8017        }
8018        if let Some(v) = read_num("constr_mult_reset_threshold") {
8019            builder.resto.constr_mult_reset_threshold = v;
8020        }
8021        if let Some(v) = read_num("resto_penalty_parameter") {
8022            builder.resto.resto_penalty_parameter = v;
8023        }
8024        if let Some(v) = read_num("resto_proximity_weight") {
8025            builder.resto.resto_proximity_weight = v;
8026        }
8027        // `required_infeasibility_reduction` (#439) — the κ_resto guard the
8028        // restoration sub-solve exits on. Registered since #191 but the
8029        // value was hardcoded at the callsite, so setting it was a silent
8030        // no-op.
8031        if let Some(v) = read_num("required_infeasibility_reduction") {
8032            builder.resto.required_infeasibility_reduction = v;
8033        }
8034        // gh#483 / #191 round 2: three restoration switches whose fields
8035        // `RestoAlgorithmBuilder` has consumed all along — the read site
8036        // was the only missing piece, so setting them did nothing.
8037        let read_yes = |key: &str| -> Option<bool> {
8038            match self.options.get_string_value(key, "") {
8039                Ok((v, true)) => Some(v.eq_ignore_ascii_case("yes")),
8040                _ => None,
8041            }
8042        };
8043        if let Some(v) = read_yes("evaluate_orig_obj_at_resto_trial") {
8044            builder.resto.evaluate_orig_obj_at_resto_trial = v;
8045        }
8046        if let Some(v) = read_yes("expect_infeasible_problem") {
8047            builder.resto.expect_infeasible_problem = v;
8048        }
8049        if let Some(v) = read_yes("start_with_resto") {
8050            builder.resto.start_with_resto = v;
8051        }
8052        // `max_resto_iter` (#551 / #677) — the cap on *successive*
8053        // restoration iterations. `RestoConvCheckAdapter` has enforced a cap
8054        // all along (returning `MaxIterExceeded` at the limit); the number
8055        // it enforced was a hard-coded constant in `resto_inner_solver.rs`,
8056        // so setting the option did nothing. The consumer's field is
8057        // `maximum_resto_iters`, not the option name — grepping for
8058        // `max_resto_iter` found only the registry (#551 caution 2).
8059        //
8060        // DEFAULT MISMATCH, LEFT AS IT IS ON PURPOSE: the registry declares
8061        // upstream's 3000000, pounce's effective cap is 3000
8062        // (`RestoOptions::default`). `read_int` fires only when the user set
8063        // the key, so an unset `max_resto_iter` still means 3000 and this
8064        // wiring is trajectory-neutral. Adopting upstream's number would let
8065        // restorations pounce currently truncates run on, which is a
8066        // trajectory change and needs its own measurement.
8067        if let Some(v) = read_int("max_resto_iter") {
8068            builder.resto.max_resto_iter = v;
8069        }
8070
8071        // Iteration-output options — consumed by `OrigIterationOutput`.
8072        if let Some(v) = read_int("print_frequency_iter") {
8073            builder.output.print_frequency_iter = v;
8074        }
8075        if let Some(v) = read_num("print_frequency_time") {
8076            builder.output.print_frequency_time = v;
8077        }
8078        if let Ok((v, found)) = self.options.get_bool_value("print_info_string", "") {
8079            if found {
8080                builder.output.print_info_string = v;
8081            }
8082        }
8083        if let Ok((v, found)) = self.options.get_string_value("inf_pr_output", "") {
8084            if found {
8085                builder.output.inf_pr_output_internal = v == "internal";
8086            }
8087        }
8088
8089        // Warm-start options — consumed by `WarmStartIterateInitializer`
8090        // (port of `IpWarmStartIterateInitializer.cpp:RegisterOptions`).
8091        // `warm_start_init_point` is the toggle that picks between the
8092        // default (cold) and warm-start initializers; the remaining
8093        // knobs are baked onto the chosen initializer at build time.
8094        if let Ok((v, found)) = self.options.get_bool_value("warm_start_init_point", "") {
8095            if found {
8096                builder.warm_start_init_point = v;
8097            }
8098        }
8099        if let Some(v) = read_num("warm_start_bound_push") {
8100            builder.warm.bound_push = v;
8101        }
8102        if let Some(v) = read_num("warm_start_bound_frac") {
8103            builder.warm.bound_frac = v;
8104        }
8105        if let Some(v) = read_num("warm_start_slack_bound_push") {
8106            builder.warm.slack_bound_push = v;
8107        }
8108        if let Some(v) = read_num("warm_start_slack_bound_frac") {
8109            builder.warm.slack_bound_frac = v;
8110        }
8111        if let Some(v) = read_num("warm_start_mult_bound_push") {
8112            builder.warm.mult_bound_push = v;
8113        }
8114        if let Some(v) = read_num("warm_start_mult_init_max") {
8115            builder.warm.mult_init_max = v;
8116        }
8117        if let Some(v) = read_num("warm_start_target_mu") {
8118            builder.warm.target_mu = v;
8119        }
8120        // gh#606: residual-adaptive recentering. `warm_start_entire_iterate`
8121        // and `warm_start_same_structure` used to be parsed here into
8122        // fields nothing read; they are refused by
8123        // `unimplemented_options` instead (they name the
8124        // `GetWarmStartIterate` TNLP surface pounce does not expose).
8125        if let Ok((v, found)) = self.options.get_string_value("warm_start_recentering", "") {
8126            if found {
8127                builder.warm.recentering = if v.eq_ignore_ascii_case("none") {
8128                    crate::alg_builder::WarmStartRecentering::None
8129                } else {
8130                    crate::alg_builder::WarmStartRecentering::Residual
8131                };
8132            }
8133        }
8134
8135        // `DefaultIterateInitializer` knobs — parsed after the Mehrotra
8136        // cascade so explicit user values win
8137        // (mirrors upstream's `SetNumericValueIfUnset` semantics).
8138        if let Some(v) = read_num("bound_push") {
8139            builder.init.bound_push = v;
8140        }
8141        if let Some(v) = read_num("bound_frac") {
8142            builder.init.bound_frac = v;
8143        }
8144        if let Some(v) = read_num("slack_bound_push") {
8145            builder.init.slack_bound_push = v;
8146        }
8147        if let Some(v) = read_num("slack_bound_frac") {
8148            builder.init.slack_bound_frac = v;
8149        }
8150        if let Some(v) = read_num("constr_mult_init_max") {
8151            builder.init.constr_mult_init_max = v;
8152        }
8153        if let Some(v) = read_num("bound_mult_init_val") {
8154            builder.init.bound_mult_init_val = v;
8155        }
8156        if let Ok((v, found)) = self.options.get_string_value("bound_mult_init_method", "") {
8157            if found {
8158                builder.init.bound_mult_init_method = v;
8159            }
8160        }
8161        if let Ok((v, found)) = self
8162            .options
8163            .get_string_value("least_square_init_primal", "")
8164        {
8165            if found {
8166                builder.init.least_square_init_primal = v == "yes";
8167            }
8168        }
8169        builder
8170    }
8171}
8172
8173/// Map the integer `print_level` / `file_print_level` option to the
8174/// matching [`JournalLevel`] variant. Mirrors upstream's
8175/// `static_cast<EJournalLevel>(int_value)` with clamping.
8176/// The eight block dimensions of an iterate, in canonical order
8177/// (x, s, y_c, y_d, z_l, z_u, v_l, v_u). Used to guard the debugger's
8178/// warm-restart install against a structural mismatch between solves.
8179fn iterates_dims(c: &IteratesVector) -> [i32; 8] {
8180    [
8181        c.x.dim(),
8182        c.s.dim(),
8183        c.y_c.dim(),
8184        c.y_d.dim(),
8185        c.z_l.dim(),
8186        c.z_u.dim(),
8187        c.v_l.dim(),
8188        c.v_u.dim(),
8189    ]
8190}
8191
8192fn journal_level_from_int(v: i32) -> JournalLevel {
8193    match v.clamp(0, 12) {
8194        0 => JournalLevel::J_NONE,
8195        1 => JournalLevel::J_ERROR,
8196        2 => JournalLevel::J_STRONGWARNING,
8197        3 => JournalLevel::J_SUMMARY,
8198        4 => JournalLevel::J_WARNING,
8199        5 => JournalLevel::J_ITERSUMMARY,
8200        6 => JournalLevel::J_DETAILED,
8201        7 => JournalLevel::J_MOREDETAILED,
8202        8 => JournalLevel::J_VECTOR,
8203        9 => JournalLevel::J_MOREVECTOR,
8204        10 => JournalLevel::J_MATRIX,
8205        11 => JournalLevel::J_MOREMATRIX,
8206        _ => JournalLevel::J_ALL,
8207    }
8208}
8209
8210/// MA57 backend knobs snapshotted off an `OptionsList`, ready to be
8211/// handed to a backend factory.
8212///
8213/// The type exists — rather than passing `pounce_hsl::Ma57Options`
8214/// directly — so that the factory signature is the same shape whether or
8215/// not the `ma57` cargo feature is on. `pounce-py`, `pounce-cinterface`
8216/// and `pounce-restoration` all call [`default_backend_factory`] and none
8217/// of them can name a `pounce-hsl` type; without the feature this struct
8218/// carries nothing and costs nothing.
8219///
8220/// Build it with [`ma57_config_from_options`]. It is the MA57 half of
8221/// what [`feral_config_from_options`] does for FERAL, and the asymmetry
8222/// between the two was the root cause of gh#825: FERAL's knobs were
8223/// threaded into the factory and MA57's were not, so the factory had
8224/// nothing to give MA57 and called `Ma57SolverInterface::new()` — which
8225/// hard-codes the defaults. Every `ma57_*` option was registered,
8226/// documented, accepted, and then silently discarded.
8227#[derive(Debug, Clone, Default)]
8228pub struct Ma57Config {
8229    #[cfg(feature = "ma57")]
8230    opts: pounce_hsl::Ma57Options,
8231}
8232
8233impl Ma57Config {
8234    /// The wrapped MA57 settings.
8235    #[cfg(feature = "ma57")]
8236    pub fn options(&self) -> &pounce_hsl::Ma57Options {
8237        &self.opts
8238    }
8239}
8240
8241/// Read the `ma57_*` options off `options` under `prefix`, for handing
8242/// to [`default_backend_factory`] / [`default_backend_factory_with_sink`].
8243///
8244/// `prefix` is `""` for the main IPM and `"resto."` for the restoration
8245/// sub-IPM, mirroring upstream's
8246/// `Ma57TSolverInterface::InitializeImpl(options, prefix)`. The
8247/// restoration sub-IPM builds its own backend through its own
8248/// `InnerBackendFactoryFactory` (see
8249/// `pounce_restoration::resto_inner_solver`), so the two really are
8250/// separately configurable — before gh#825 neither was.
8251///
8252/// Without the `ma57` cargo feature this returns an empty config and
8253/// does not touch `options`; nothing downstream can consume MA57
8254/// settings in that build.
8255pub fn ma57_config_from_options(
8256    options: &pounce_common::options_list::OptionsList,
8257    prefix: &str,
8258) -> Ma57Config {
8259    #[cfg(feature = "ma57")]
8260    {
8261        Ma57Config {
8262            opts: pounce_hsl::Ma57Options::from_options_list(options, prefix),
8263        }
8264    }
8265    #[cfg(not(feature = "ma57"))]
8266    {
8267        let _ = (options, prefix);
8268        Ma57Config::default()
8269    }
8270}
8271
8272/// Construct the MA57 backend for a factory, or fall back to FERAL when
8273/// the `ma57` cargo feature is off.
8274///
8275/// Factored out of the two factories below so there is exactly one place
8276/// that decides how an MA57 backend is built from a [`Ma57Config`]. Both
8277/// factories used to inline `Ma57SolverInterface::new()`, and the
8278/// duplication is half of why gh#825 was easy to miss.
8279fn make_ma57_backend(
8280    ma57_cfg: &Ma57Config,
8281    feral_fallback: impl FnOnce() -> Box<dyn SparseSymLinearSolverInterface>,
8282) -> Box<dyn SparseSymLinearSolverInterface> {
8283    #[cfg(feature = "ma57")]
8284    {
8285        let _ = feral_fallback;
8286        Box::new(pounce_hsl::Ma57SolverInterface::with_options(
8287            *ma57_cfg.options(),
8288        ))
8289    }
8290    #[cfg(not(feature = "ma57"))]
8291    {
8292        // ma57 feature not compiled in — fall back to FERAL.
8293        let _ = ma57_cfg;
8294        feral_fallback()
8295    }
8296}
8297
8298/// Default symmetric linear-solver factory, parameterized by the
8299/// pounce-extension FERAL knobs and the `ma57_*` knobs read off the
8300/// application's `OptionsList`.
8301///
8302/// FERAL (pure-Rust) is the shipping default. The HSL MA57 backend is
8303/// available when the `ma57` cargo feature is enabled; without it,
8304/// requesting `linear_solver = ma57` falls back to FERAL with a
8305/// warning printed by the journalist (see [`AlgorithmBuilder`]).
8306///
8307/// Both configs are snapshots, not live views: take them with
8308/// [`feral_config_from_options`] and [`ma57_config_from_options`] at the
8309/// point the application's options are fully populated. The factory is
8310/// called more than once per solve (the main KKT solver and, under
8311/// limited memory, the Hessian-free bypass solver), so each call gets a
8312/// fresh backend built from the same snapshot.
8313pub fn default_backend_factory(
8314    feral_cfg: pounce_feral::FeralConfig,
8315    ma57_cfg: Ma57Config,
8316) -> LinearBackendFactory {
8317    Box::new(
8318        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8319            match choice {
8320                LinearSolverChoice::Feral => Box::new(
8321                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone()),
8322                ),
8323                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8324                    Box::new(pounce_feral::FeralSolverInterface::with_config(
8325                        feral_cfg.clone(),
8326                    ))
8327                }),
8328            }
8329        },
8330    )
8331}
8332
8333/// Turn a model-space block declaration into the KKT-space labels the block
8334/// solver takes (structured-KKT Phase 5b's mapper, plan §63.6).
8335///
8336/// The KKT is laid out `[x | slacks | equality duals | inequality duals]`, so
8337/// each part inherits a label from what it belongs to:
8338///
8339/// * an `x` column takes its variable's label — skipping variables fixed out
8340///   by `fixed_variable_treatment`, which are not in the KKT at all;
8341/// * a slack and its inequality dual take their constraint's label;
8342/// * an equality dual takes its constraint's label.
8343///
8344/// `var_blocks` / `con_blocks` are in the model's own indexing (`n_full_x`,
8345/// `n_full_g`); negative means shared. Returns the label per KKT index, or an
8346/// error naming the mismatch — the caller then falls back rather than
8347/// mislabel, because a label that is off by one row silently declares a
8348/// structure the matrix does not have.
8349pub fn map_block_structure_to_kkt(
8350    cls: &pounce_nlp::tnlp_adapter::BoundClassification,
8351    var_blocks: &[i32],
8352    con_blocks: &[i32],
8353) -> Result<Vec<i32>, String> {
8354    if var_blocks.len() != cls.n_full_x as usize {
8355        return Err(format!(
8356            "block structure has {} variable labels, the problem has {} variables",
8357            var_blocks.len(),
8358            cls.n_full_x
8359        ));
8360    }
8361    if con_blocks.len() != cls.n_full_g as usize {
8362        return Err(format!(
8363            "block structure has {} constraint labels, the problem has {} constraints",
8364            con_blocks.len(),
8365            cls.n_full_g
8366        ));
8367    }
8368    let n_x = cls.x_not_fixed_map.len();
8369    let n_c = cls.c_map.len();
8370    let n_d = cls.d_map.len();
8371    let mut labels = Vec::with_capacity(n_x + 2 * n_d + n_c);
8372    for &full in &cls.x_not_fixed_map {
8373        labels.push(var_blocks[full as usize]);
8374    }
8375    for &full in &cls.d_map {
8376        labels.push(con_blocks[full as usize]); // slack
8377    }
8378    for &full in &cls.c_map {
8379        labels.push(con_blocks[full as usize]); // equality dual
8380    }
8381    for &full in &cls.d_map {
8382        labels.push(con_blocks[full as usize]); // inequality dual
8383    }
8384    Ok(labels)
8385}
8386
8387/// Sink-aware variant of [`default_backend_factory`]. Identical
8388/// dispatch, but the FERAL backend is constructed with a
8389/// `LinearSolverSummary` sink so [`IpoptApplication`] can read out
8390/// aggregate post-mortem stats (factor counts, fill ratio, extremal
8391/// pivots, final inertia) after the solve returns. MA57 ignores the
8392/// sink — the HSL backend doesn't carry the same instrumentation yet.
8393pub fn default_backend_factory_with_sink(
8394    feral_cfg: pounce_feral::FeralConfig,
8395    ma57_cfg: Ma57Config,
8396    sink: Arc<Mutex<LinearSolverSummary>>,
8397) -> LinearBackendFactory {
8398    Box::new(
8399        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8400            match choice {
8401                LinearSolverChoice::Feral => Box::new(
8402                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8403                        .with_summary_sink(Arc::clone(&sink)),
8404                ),
8405                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8406                    Box::new(
8407                        pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8408                            .with_summary_sink(Arc::clone(&sink)),
8409                    )
8410                }),
8411            }
8412        },
8413    )
8414}
8415
8416/// Read the `feral_*` extension options off `options`, falling
8417/// back to the env-var defaults baked into [`pounce_feral::FeralConfig::from_env`]
8418/// for any knob the caller did not set explicitly. The returned
8419/// config is what every default-factory invocation (main IPM and
8420/// restoration sub-IPM) consumes.
8421pub fn feral_config_from_options(
8422    options: &pounce_common::options_list::OptionsList,
8423) -> pounce_feral::FeralConfig {
8424    feral_config_from_options_scoped(options, RefineCarveOut::InteriorPoint)
8425}
8426
8427/// Whether [`feral_config_from_options_scoped`] applies the interior-point
8428/// arm's limited-memory `feral_refine` carve-out.
8429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8430pub enum RefineCarveOut {
8431    /// Apply it: under `hessian_approximation=limited-memory`, force
8432    /// `refine = false` unless the user said otherwise. This is the shipped
8433    /// interior-point behaviour and what [`feral_config_from_options`] does.
8434    InteriorPoint,
8435    /// Skip it. For arms that do not refine the unreduced system themselves,
8436    /// where the backend loop is the only refinement in the stack.
8437    None,
8438}
8439
8440/// [`feral_config_from_options`] with the limited-memory `refine` carve-out
8441/// made explicit.
8442///
8443/// The carve-out is interior-point-specific in both of its premises, and
8444/// neither holds on the active-set SQP arm. It is justified by
8445/// `PdFullSpaceSolver::compute_residuals` already refining the *unreduced*
8446/// Newton system — the SQP arm has no such host loop, so
8447/// `pounce_qp::factor::LinearSolver` relies on the backend's own refinement
8448/// ("refinement is *implicit* in this layer", that module's docs) and turning
8449/// it off removes refinement from the stack entirely. And it keys off
8450/// `hessian_approximation`, which is not that arm's Hessian selector at all:
8451/// `sqp_hessian` is.
8452///
8453/// Measured, and this is why the parameter exists rather than the SQP path
8454/// just calling the plain function: inheriting the carve-out moved 10 of 97
8455/// fixtures on the sweep's L-BFGS leg under `algorithm=active-set-sqp`, while
8456/// the exact leg did not move at all. Some of that movement looked like a win
8457/// (`mu_fallback_point_floor` MaximumIterationsExceeded/200 ->
8458/// SolveSucceeded/8), but it was a win bought by disabling refinement for a
8459/// reason that does not apply here, and it came with `hs13_bigstart` landing
8460/// on a different point (objective 1 -> 1.0018) and `eigena2` and
8461/// `mpcc_scholtes4_biactive` likewise. Turning refinement off on this arm may
8462/// well be worth measuring on its own merits; it should not arrive as a side
8463/// effect of honouring `linear_solver`.
8464pub fn feral_config_from_options_scoped(
8465    options: &pounce_common::options_list::OptionsList,
8466    carve_out: RefineCarveOut,
8467) -> pounce_feral::FeralConfig {
8468    let mut cfg = pounce_feral::FeralConfig::from_env();
8469    // Tri-state: the `(_, true)` arm only fires when the user set the
8470    // option explicitly. Leaving it unset keeps `cfg.cascade_break` at
8471    // `None`, which inherits FERAL's `NumericParams::default()` (CB on
8472    // as of FERAL Phase B / pounce#55). `Some(false)` explicitly
8473    // disarms (reproduces pre-Phase-B behaviour, surfaces FERAL's
8474    // `DelayBudgetExceeded` on non-root cascade victims).
8475    if let Ok((v, true)) = options.get_bool_value("feral_cascade_break", "") {
8476        cfg.cascade_break = Some(v);
8477    }
8478    if let Ok((v, true)) = options.get_bool_value("feral_fma", "") {
8479        cfg.fma = v;
8480    }
8481    // Not tri-state, and deliberately not: on the limited-memory path
8482    // the IPM's default is the opposite of the library's (gh#710,
8483    // gh#698 obs 5). `FeralConfig` ships `refine = true` because a
8484    // caller that only refines its own system needs the backend loop.
8485    //
8486    // Scoped to limited-memory, because that is where the win was
8487    // measured and where it comes from. Under L-BFGS the Hessian-free
8488    // bypass batches the low-rank SMW correction into one multi-RHS
8489    // back-solve, and the backend loop refines per right-hand side, so
8490    // its cost scales with the memory depth — while what it polishes is
8491    // the *condensed* system, which is not where Waechter-Biegler 3.10
8492    // puts refinement. Turning it off takes `laptime` under
8493    // limited-memory from 1397 s to 394 s.
8494    //
8495    // The same switch is a net loss on the exact path, so it is not
8496    // applied there. It costs `NARX_CFy` 230 iterations (400 -> 630,
8497    // 173 s -> 250 s) to buy back 34 on `laptime` (380 -> 346). And the
8498    // exact path has no rung left to stand in for it: the
8499    // `increase_quality` escalation that once argued for dropping the
8500    // backend loop here proved inert and was itself removed, so with
8501    // `refine` off the host loop in `PdFullSpaceSolver` is the only
8502    // refinement in the stack — and it stops the moment it crosses
8503    // `residual_ratio_max` (1e-10), three orders looser than the ~1e-16
8504    // the backend-refined solves reach.
8505    //
8506    // Tightening that threshold instead is not the fix, and was measured
8507    // rather than assumed: it is chaotic on this corpus, flipping `deb7`
8508    // to `Error_In_Step_Computation` at 1e-12 and swinging
8509    // `pooling_rt2stp` between 107 and 199 iterations across 1e-11 to
8510    // 1e-13. Forcing extra passes via `min_refinement_steps` behaves the
8511    // same way (both fixtures break at 2). Restoring the backend loop is
8512    // trajectory-neutral next to either (`deb7` 146 -> 147,
8513    // `pooling_rt2stp` 107 -> 109).
8514    //
8515    // Ordered env-then-registry-then-option so `POUNCE_FERAL_REFINE`
8516    // still reaches this path and an explicit `feral_refine` still beats
8517    // both.
8518    //
8519    // gh#909: the registry read below takes the value and IGNORES the
8520    // found flag, which is the whole point. Reading it as `Ok((v, true))`
8521    // — the tri-state shape every other option in this function uses —
8522    // consults the user's setting and never the *registered default*, so
8523    // an unset option left `cfg.refine` at `FeralConfig::default()`'s
8524    // `true` while `pounce --print-options` reported the registry's.
8525    // Registered `no`, ran `yes`: the gh#677 shape, one option family
8526    // over. It is fixed by making the registry authoritative here rather
8527    // than by changing what runs — see below for why — so the registered
8528    // default moved to `yes` in the same commit and this read is what
8529    // keeps the two from drifting apart again.
8530    //
8531    // The scoping stays. There is no single default that is right on both
8532    // paths, and this is a two-sided trade of the same shape as
8533    // `feral_increase_quality` above: the option is the lever, and the
8534    // default is a choice rather than a fact. Measured on `e5f5830b`,
8535    // one binary, `feral_refine=no` against the default:
8536    //
8537    //   fixture corpus, exact leg: 10 legs move, NO status flips, and
8538    //     the net is favourable -- `issue_508_infeasible_gap_1em4`
8539    //     441 -> 245, `square_flowsheet_resto` 54 -> 47 (tot 185 -> 176),
8540    //     `issue_508_infeasible_gap_1em2` 114 -> 112, `deb7` 147 -> 146,
8541    //     `pooling_rt2stp` 109 -> 107, against one loss
8542    //     (`mu_fallback_point_floor` 31 -> 32).
8543    //   fixture corpus, lbfgs leg: identical, refine is already off there.
8544    //   `NARX_CFy` (Mittelmann): 400 -> 630 iterations, 208.7 s -> 254.2 s.
8545    //   `eigena2` final dual infeasibility: 3.43e-10 -> 5.20e-09, both
8546    //     inside `tol`, and see `issue_540_eigena2_superlinear_tail.rs`.
8547    //   AC-OPF (PGLib), gh#909: 10-18% faster, iteration counts
8548    //     unchanged, solution identical to ~13 significant figures.
8549    //
8550    // So the corpus and the AC-OPF benchmarks both prefer `no` and
8551    // `NARX_CFy` pays 57% more iterations for it. Nothing here separates
8552    // those, which is why the default is scoped rather than flipped.
8553    let limited_memory = carve_out == RefineCarveOut::InteriorPoint
8554        && matches!(
8555            options.get_string_value("hessian_approximation", ""),
8556            Ok((ref s, true)) if s == "limited-memory"
8557        );
8558    if std::env::var_os("POUNCE_FERAL_REFINE").is_none() {
8559        // Deliberately `_`, not `true`: see above.
8560        if let Ok((v, _)) = options.get_bool_value("feral_refine", "") {
8561            cfg.refine = v;
8562        }
8563        if limited_memory {
8564            cfg.refine = false;
8565        }
8566    }
8567    // An explicit setting beats both the carve-out and the environment.
8568    if let Ok((v, true)) = options.get_bool_value("feral_refine", "") {
8569        cfg.refine = v;
8570    }
8571    // gh #850: `feral_increase_quality` exists because this rung is a genuine
8572    // two-sided trade, and the option is the lever — the default is left ON,
8573    // which is the 0.11 behaviour.
8574    //
8575    // Ipopt's `IncreaseQuality` contract assumes a *monotone* escalation: MA57
8576    // raises `pivtol` toward `pivtolmax`, strictly more conservative each time,
8577    // so keeping it raised for the rest of the solve can only make the
8578    // factorization safer. FERAL's ladder changes which pivots are taken, which
8579    // is lateral in trajectory terms, and it persists the same way. So it
8580    // reroutes solves, and the reroute goes both ways:
8581    //
8582    //   it COSTS two whole solves, both `square_flowsheet_resto`:
8583    //     exact  Optimal/99  -> RestorationFailed/131 (a second-opinion rung
8584    //                          rescues it, at 185 iterations total)
8585    //     lbfgs  Optimal/178 -> 3000 iterations at the cap, rescued by nothing
8586    //   it BUYS accuracy where nothing else does:
8587    //     `watchdog_trial_is_not_a_divergence_verdict`'s 12-variable model ends
8588    //     `SolvedToAcceptableLevel` at obj 3.7e-6 with the rung and at obj 3.42
8589    //     against `f* = 0` without it — a wrong-ish answer under a
8590    //     success-shaped status, which is worse than an honest failure.
8591    //   and it buys iterations on five more fixture-legs (15-25%).
8592    //
8593    // There is no scoping that separates those. Measured with a process-global
8594    // firing cap on `square_flowsheet_resto`: the rung fires twice, once in the
8595    // main solve at iteration 25 and once inside restoration at `76r`, and
8596    // allowing only the first still loses the leg — so declining it just for
8597    // the restoration sub-solve would not help. Nor does a count separate them:
8598    // `deb7` and `square_flowsheet_resto` each fire it exactly twice on their
8599    // exact legs, one gaining 16% of its iterations and the other losing its
8600    // verdict.
8601    //
8602    // So the default stands, and the losing direction now recovers itself:
8603    // `feral_increase_quality_retry` (gh#857) re-solves once with this off when
8604    // a solve that actually escalated ends `Restoration_Failed` or
8605    // `Maximum_Iterations_Exceeded`.
8606    //
8607    // It is a re-solve rather than a *revertible* escalation because the
8608    // revertible one was tried. jkitchin/feral#192 landed as `reset_quality`,
8609    // was plumbed here and instrumented (376 escalations, 376 matching resets
8610    // on one solve), and recovers neither leg at either re-baselining boundary
8611    // -- the harm is the destination, not the duration. See
8612    // `dev-notes/second-opinion-promotions-in-the-sweep.md`.
8613    if let Ok((v, true)) = options.get_bool_value("feral_increase_quality", "") {
8614        cfg.increase_quality = v;
8615    }
8616    // Only consulted when `refine` is on; see `FeralConfig::refine_max_steps`
8617    // (gh#710). Registered as an integer option with lower bound 0, so the
8618    // cast cannot go negative.
8619    if let Ok((v, true)) = options.get_integer_value("feral_refine_steps", "") {
8620        cfg.refine_max_steps = v.max(0) as usize;
8621    }
8622    // Also only consulted when `refine` is on. Registered with lower bound
8623    // 0, and 0 disables the pre-check; see `FeralConfig::refine_target`.
8624    if let Ok((v, true)) = options.get_numeric_value("feral_refine_target", "") {
8625        cfg.refine_target = v.max(0.0);
8626    }
8627    // Explicit static-pivoting opt-in (feral#8 cascade breaker, pounce#254).
8628    // Same tri-state discipline: unset leaves `cfg.static_pivoting` at
8629    // whatever `from_env` resolved (`None` → inherit feral's delayed-pivot
8630    // default), so the default numeric path is unchanged.
8631    if let Ok((v, true)) = options.get_bool_value("feral_static_pivoting", "") {
8632        cfg.static_pivoting = Some(v);
8633    }
8634    if let Ok((v, true)) = options.get_numeric_value("feral_singular_pivot_floor", "") {
8635        cfg.singular_pivot_floor = v;
8636    }
8637    // Explicitly set pins an absolute floor for every dimension (`0`
8638    // disables the trigger); left unset, `None` keeps the dimension-aware
8639    // `n * eps` default (pounce gh#592).
8640    if let Ok((v, true)) = options.get_numeric_value("feral_inertia_pivot_floor", "") {
8641        cfg.inertia_pivot_floor = Some(v);
8642    }
8643    // Number option (not integer): the gate is a u64 and Index is i32, too
8644    // narrow for large flop counts or the u64::MAX reject-all sentinel. The
8645    // lower bound (0.0) rules out negatives; `as u64` then saturates a very
8646    // large finite value to u64::MAX (reject all tree-level parallelism).
8647    if let Ok((v, true)) = options.get_numeric_value("feral_min_par_flops", "") {
8648        cfg.min_par_flops = Some(v as u64);
8649    }
8650    if let Ok((v, true)) = options.get_numeric_value("feral_pivtol", "") {
8651        cfg.pivtol = v;
8652    }
8653    // Only override on explicit set so `from_env` (which itself
8654    // defaults to OrderingMethod::Auto) keeps governing unset cases.
8655    // Unrecognized tags are silently ignored — the registered enum
8656    // restricts inputs at the OptionsList layer.
8657    if let Ok((v, true)) = options.get_string_value("feral_ordering", "") {
8658        if let Some(m) = pounce_feral::parse_ordering_method(&v) {
8659            cfg.ordering = m;
8660        }
8661    }
8662    if let Ok((v, true)) = options.get_string_value("feral_ordering_preprocess", "") {
8663        if let Some(p) = pounce_feral::parse_ordering_preprocess(&v) {
8664            cfg.ordering_preprocess = p;
8665        }
8666    }
8667    // Same explicit-set discipline as `feral_ordering`: `from_env`
8668    // defaults to ScalingStrategy::Auto (FERAL's current default), so
8669    // leaving the option unset preserves existing behaviour exactly.
8670    if let Ok((v, true)) = options.get_string_value("feral_scaling", "") {
8671        if let Some(s) = pounce_feral::parse_scaling_strategy(&v) {
8672            cfg.scaling = s;
8673        }
8674    }
8675    cfg
8676}
8677
8678/// Withdraw a numerical infeasibility verdict the model's own starting point
8679/// disproves.
8680///
8681/// Applied at every site in this file that can return
8682/// `Infeasible_Problem_Detected` from a *numerical* argument — the IPM path's
8683/// restoration / cycle gates, the SQP path's infeasible-subproblem exit, and the
8684/// ℓ₁ wrapper's uncollapsed-slack certificate. Deliberately one gate rather than
8685/// three: the two preceding safeguards in this area (gh #376, gh #380) were each
8686/// added to one path and not its twin, and a hole survived both times.
8687///
8688/// Not applied to a presolve *certificate*
8689/// (`TNLP::presolve_infeasibility_proof`), which carries its own, tighter
8690/// refutation
8691/// (`pounce_presolve::witness_refutes_infeasibility`) and is a proof rather than
8692/// a numerical inference.
8693///
8694/// The replacement is `Error_In_Step_Computation`, the status this codebase
8695/// already uses for "the solve broke down and we are **not** claiming
8696/// infeasibility" — see the `cycle_exit` fallback in
8697/// [`crate::ipopt_alg::IpoptAlgorithm::invoke_restoration`], which picks between
8698/// exactly these two on exactly this question. It maps to AMPL 500, an honest
8699/// failure the caller can see, instead of AMPL 200, a wrong answer they cannot.
8700///
8701/// gh #379.
8702fn withdraw_infeasibility_if_refuted(
8703    tnlp: &Rc<RefCell<dyn TNLP>>,
8704    solver_status: SolverReturn,
8705    lo_inf: Number,
8706    up_inf: Number,
8707    tol: Number,
8708) -> SolverReturn {
8709    if solver_status != SolverReturn::LocalInfeasibility {
8710        return solver_status;
8711    }
8712    // A presolve proof is not a numerical inference; it does its own refutation.
8713    if tnlp.borrow().presolve_infeasibility_proof().is_some() {
8714        return solver_status;
8715    }
8716    match crate::infeasibility_refutation::starting_point_refutes_infeasibility(
8717        tnlp, lo_inf, up_inf, tol,
8718    ) {
8719        Some(w) => {
8720            tracing::debug!(
8721                target: "pounce::application",
8722                "[PN_INFEAS_REFUTED] the model's starting point satisfies every constraint \
8723                 (max violation {:.3e}) — withdrawing Infeasible_Problem_Detected",
8724                w.max_violation
8725            );
8726            SolverReturn::ErrorInStepComputation
8727        }
8728        None => solver_status,
8729    }
8730}
8731
8732/// How well a point satisfies the **user's own** rows and bounds.
8733///
8734/// Computed from `g = c(x)` and the inner TNLP's declared bounds, in the
8735/// user's units, with no reference to whatever problem the algorithm
8736/// actually iterated on. That distinction is the whole reason this
8737/// exists: on the ℓ₁ path the IPM converges the *augmented* NLP
8738/// `c(x) − p + n = target`, whose equality rows the slacks satisfy to
8739/// machine precision by construction, and reporting that residual as
8740/// the solve's constraint violation says nothing about `c(x) − target`
8741/// (gh#794 finding P1).
8742struct OriginalSpaceFeasibility {
8743    /// Largest absolute violation of any row or bound, in the user's units.
8744    max_violation: Number,
8745    /// Every row and bound negligible at `tol`, judged scale-relative.
8746    negligible_at_tol: bool,
8747    /// The same at `acceptable_tol`.
8748    negligible_at_acceptable: bool,
8749}
8750
8751/// Measure [`OriginalSpaceFeasibility`] at `x`, given `g = c(x)`.
8752///
8753/// `is_negligible` rather than `!is_significant`, deliberately, and for
8754/// the reason that function's own documentation gives: the question here
8755/// is "did the solve converge well enough to call this point feasible",
8756/// which must never demand more precision than the solver promised, so
8757/// the threshold is clamped at `tol` from below (`tol · max(|scale|, 1)`).
8758/// The refutation path next door asks the opposite question — "is this
8759/// residual real at this row's scale" — and correctly uses the pure
8760/// relative form.
8761///
8762/// Returns `None` when the model cannot be measured (bounds unreadable, a
8763/// non-finite value). `None` means "not measured", never "feasible": the
8764/// caller keeps whatever verdict it already had.
8765fn original_space_feasibility(
8766    tnlp: &Rc<RefCell<dyn TNLP>>,
8767    x: &[Number],
8768    g: &[Number],
8769    lower_bound_inf: Number,
8770    upper_bound_inf: Number,
8771    tol: Number,
8772    acceptable_tol: Number,
8773    constr_viol_tol: Number,
8774    acceptable_constr_viol_tol: Number,
8775    noise_floor_kappa: Number,
8776) -> Option<OriginalSpaceFeasibility> {
8777    use pounce_common::tolerance::is_negligible;
8778
8779    let info = tnlp.borrow_mut().get_nlp_info()?;
8780    let n = info.n.max(0) as usize;
8781    let m = info.m.max(0) as usize;
8782    if x.len() < n || g.len() < m {
8783        return None;
8784    }
8785
8786    let mut x_l = vec![0.0; n];
8787    let mut x_u = vec![0.0; n];
8788    let mut g_l = vec![0.0; m];
8789    let mut g_u = vec![0.0; m];
8790    if !tnlp.borrow_mut().get_bounds_info(BoundsInfo {
8791        x_l: &mut x_l,
8792        x_u: &mut x_u,
8793        g_l: &mut g_l,
8794        g_u: &mut g_u,
8795    }) {
8796        return None;
8797    }
8798
8799    let mut max_violation: Number = 0.0;
8800    let mut ok_tol = true;
8801    let mut ok_acceptable = true;
8802
8803    // Only *finite, present* bounds inform a row's magnitude: letting the
8804    // `±1e19` sentinel set the scale would make every row look satisfied,
8805    // the same trap `infeasibility_refutation` documents.
8806    let present = |b: Number, is_lower: bool| -> Option<Number> {
8807        let absent = if is_lower {
8808            b <= lower_bound_inf
8809        } else {
8810            b >= upper_bound_inf
8811        };
8812        (b.is_finite() && !absent).then_some(b)
8813    };
8814
8815    // Accumulates into `max_violation` / `ok_tol` / `ok_acceptable`; a
8816    // non-positive `viol` means the side is satisfied and contributes
8817    // nothing. Returns nothing — every caller is a statement.
8818    let mut judge = |viol: Number, scale: Number| {
8819        if viol <= 0.0 {
8820            return;
8821        }
8822        max_violation = max_violation.max(viol);
8823        // The scale-relative test alone is not a feasibility standard, and
8824        // on a large-magnitude row it is not even close to one: it accepts
8825        // anything up to `tol · |row|`, which on a row near `1e10` is `1e2`
8826        // at the default `tol`. An adversary probe on this branch built a
8827        // model infeasible by exactly `50` with its row at `1e10` and got
8828        // `Solve_Succeeded` — a *worse* verdict than this branch's own
8829        // parent, which refused the same point (the old `Σ(p+n)` argument
8830        // was crude but absolute). So the wrapper has to judge feasibility
8831        // the way the rest of the solver does.
8832        //
8833        // `OptErrorConvCheck::primal_component_passes` is that standard:
8834        // an absolute `constr_viol <= constr_viol_tol`, with scale-awareness
8835        // supplied by an abstention when every row sits at its own
8836        // floating-point noise floor (gh#528/gh#590) rather than by
8837        // multiplying the tolerance by the row's magnitude. That
8838        // abstention "cannot fabricate a success on a genuinely infeasible
8839        // model: such a model's violation is pinned at its infeasibility
8840        // gap, orders above `eps ·` the row's own magnitude" — which is
8841        // exactly the property `is_negligible` lacks and the probe
8842        // exploited (`50` is `~2e7 ×` this row's floor).
8843        //
8844        // The strict gate's `primal_resolvable` cannot be reused verbatim:
8845        // it is computed by the CQ on the *augmented* NLP, whose rows the
8846        // slacks satisfy to machine precision, so it would abstain always
8847        // and accept everything. The floor is therefore recomputed here on
8848        // the user's own row, from the same `kappa · eps · magnitude` the
8849        // option documents. `primal_noise_floor_kappa = 0` opts out, as it
8850        // does for the strict gate.
8851        //
8852        // Both arms are conjoined rather than substituted: the relative
8853        // test still catches a violation that is small in absolute terms
8854        // but large for its row, which is the gh#794 P1 case itself
8855        // (`ralph1` at `2.5e-7` under a `2.5e-11` tol).
8856        let noise = noise_floor_kappa * Number::EPSILON * scale.abs();
8857        let absolute_ok = |bound: Number| viol <= bound || viol <= noise;
8858        ok_tol &= is_negligible(viol, scale, tol) && absolute_ok(constr_viol_tol);
8859        ok_acceptable &=
8860            is_negligible(viol, scale, acceptable_tol) && absolute_ok(acceptable_constr_viol_tol);
8861    };
8862
8863    for i in 0..m {
8864        let v = g[i];
8865        if !v.is_finite() {
8866            return None;
8867        }
8868        let lo = present(g_l[i], true);
8869        let hi = present(g_u[i], false);
8870        let scale = v
8871            .abs()
8872            .max(lo.map_or(0.0, Number::abs))
8873            .max(hi.map_or(0.0, Number::abs));
8874        judge(lo.map_or(0.0, |b| b - v), scale);
8875        judge(hi.map_or(0.0, |b| v - b), scale);
8876    }
8877    for j in 0..n {
8878        let v = x[j];
8879        if !v.is_finite() {
8880            return None;
8881        }
8882        let lo = present(x_l[j], true);
8883        let hi = present(x_u[j], false);
8884        let scale = v
8885            .abs()
8886            .max(lo.map_or(0.0, Number::abs))
8887            .max(hi.map_or(0.0, Number::abs));
8888        judge(lo.map_or(0.0, |b| b - v), scale);
8889        judge(hi.map_or(0.0, |b| v - b), scale);
8890    }
8891
8892    Some(OriginalSpaceFeasibility {
8893        max_violation,
8894        negligible_at_tol: ok_tol,
8895        negligible_at_acceptable: ok_acceptable,
8896    })
8897}
8898
8899/// Map upstream `SolverReturn` codes to `ApplicationReturnStatus`.
8900/// Mirrors the table in
8901/// `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception → SolverReturn
8902/// map") and the corresponding switch in
8903/// `IpIpoptApplication.cpp:call_optimize`.
8904fn solver_return_to_app_status(s: SolverReturn) -> ApplicationReturnStatus {
8905    match s {
8906        SolverReturn::Success => ApplicationReturnStatus::SolveSucceeded,
8907        SolverReturn::StopAtAcceptablePoint => ApplicationReturnStatus::SolvedToAcceptableLevel,
8908        SolverReturn::FeasiblePointFound => ApplicationReturnStatus::FeasiblePointFound,
8909        SolverReturn::MaxiterExceeded => ApplicationReturnStatus::MaximumIterationsExceeded,
8910        SolverReturn::CpuTimeExceeded => ApplicationReturnStatus::MaximumCpuTimeExceeded,
8911        SolverReturn::WallTimeExceeded => ApplicationReturnStatus::MaximumWallTimeExceeded,
8912        SolverReturn::StopAtTinyStep => ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
8913        SolverReturn::LocalInfeasibility => ApplicationReturnStatus::InfeasibleProblemDetected,
8914        SolverReturn::UserRequestedStop => ApplicationReturnStatus::UserRequestedStop,
8915        SolverReturn::DivergingIterates => ApplicationReturnStatus::DivergingIterates,
8916        SolverReturn::RestorationFailure => ApplicationReturnStatus::RestorationFailed,
8917        SolverReturn::ErrorInStepComputation => ApplicationReturnStatus::ErrorInStepComputation,
8918        SolverReturn::InvalidNumberDetected => ApplicationReturnStatus::InvalidNumberDetected,
8919        SolverReturn::TooFewDegreesOfFreedom => ApplicationReturnStatus::NotEnoughDegreesOfFreedom,
8920        SolverReturn::InvalidProblemDefinition => ApplicationReturnStatus::InvalidProblemDefinition,
8921        SolverReturn::InvalidOption => ApplicationReturnStatus::InvalidOption,
8922        SolverReturn::OutOfMemory => ApplicationReturnStatus::InsufficientMemory,
8923        SolverReturn::InternalError | SolverReturn::Unassigned => {
8924            ApplicationReturnStatus::InternalError
8925        }
8926    }
8927}
8928
8929/// Best-effort evaluation of the objective at the algorithm's final
8930/// `x`. Returns the *scaled* objective (`f * obj_scale_factor`); used
8931/// to populate `SolveStatistics::final_scaled_objective`.
8932fn try_eval_curr_f(
8933    nlp: &Rc<RefCell<dyn IpoptNlp>>,
8934    x: &Rc<dyn pounce_linalg::Vector>,
8935) -> Result<Number, ()> {
8936    let mut nlp_mut = nlp.borrow_mut();
8937    Ok(nlp_mut.eval_f(&**x))
8938}
8939
8940/// Trigger predicate for the Phase-3.5 ℓ₁ auto-fallback path. Returns
8941/// `true` when a status warrants a retry through the wrapper. Mirrors
8942/// ripopt#23's trigger set, extended per the audit's Refinement B
8943/// (pounce-side `Not_Enough_Degrees_Of_Freedom` is added because
8944/// pounce's DOF early-exit blocks NE-suffix problems that ripopt's
8945/// equivalent would let pass to the wrapper).
8946fn is_l1_fallback_trigger(status: ApplicationReturnStatus) -> bool {
8947    matches!(
8948        status,
8949        ApplicationReturnStatus::RestorationFailed
8950            | ApplicationReturnStatus::InfeasibleProblemDetected
8951            | ApplicationReturnStatus::SolvedToAcceptableLevel
8952            | ApplicationReturnStatus::MaximumIterationsExceeded
8953            | ApplicationReturnStatus::NotEnoughDegreesOfFreedom
8954    )
8955}
8956
8957/// Forward the final iterate back to the user's `TNLP::finalize_solution`.
8958/// We pull `x` (compressed in `x_var`-space) off the algorithm's
8959/// `data.curr`, lift it back to full TNLP indexing, and pass empty
8960/// multipliers for now (the algorithm's `y_c`, `y_d`, `z_l`, `z_u` are
8961/// in compressed split form — re-assembling them into the user's
8962/// `lambda` / `z_l` / `z_u` is mechanical but lives behind a
8963/// `OrigIpoptNlp::finalize_solution_*` accessor that's still being
8964/// fleshed out). On success returns the unscaled objective evaluated
8965/// on the user TNLP at the final iterate; returns `Err` if the final
8966/// iterate is missing.
8967/// Read a `dyn Vector`'s entries. Empty for a non-dense backing; POUNCE is
8968/// dense-only, so that is defensive rather than a supported case.
8969fn dense_values(v: &dyn pounce_linalg::Vector) -> Vec<Number> {
8970    v.as_any()
8971        .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
8972        .map(|d| d.expanded_values())
8973        .unwrap_or_default()
8974}
8975
8976/// Overwrite a `dyn Vector`'s entries. Returns false — writing nothing —
8977/// when the backing is not dense or the lengths disagree, so a caller
8978/// updating several components together can abandon the whole update rather
8979/// than leave a half-written iterate.
8980fn set_dense(v: &mut dyn pounce_linalg::Vector, vals: &[Number]) -> bool {
8981    match v
8982        .as_any_mut()
8983        .downcast_mut::<pounce_linalg::dense_vector::DenseVector>()
8984    {
8985        Some(d) if pounce_linalg::Vector::dim(d) as usize == vals.len() => {
8986            d.set_values(vals);
8987            true
8988        }
8989        _ => false,
8990    }
8991}
8992
8993/// An owned copy of a [`Solution`] payload already delivered to the user's
8994/// TNLP, enough to deliver it again.
8995///
8996/// Exists because a losing second-opinion retry has to be undoable. The status
8997/// a retry earns is already floored — `run_with_mu_strategy_fallback` returns
8998/// `first_status` unless the retry promotes — but the *point* was not, and the
8999/// user consumes the point. See that function for what went wrong without this.
9000#[derive(Debug, Clone)]
9001struct FinalizeSnapshot {
9002    status: SolverReturn,
9003    x: Vec<Number>,
9004    z_l: Vec<Number>,
9005    z_u: Vec<Number>,
9006    g: Vec<Number>,
9007    lambda: Vec<Number>,
9008    obj_value: Number,
9009}
9010
9011/// The option-table overrides (and the box flag) one retry applies for its
9012/// own solve, put back when the scope ends -- on **every** exit, unwinding
9013/// included.
9014///
9015/// The retries used to restore by hand after `optimize_constrained`
9016/// returned, so a panic inside it left the overrides in place. That is not
9017/// hypothetical for an embedder: `pounce-cinterface`'s `ffi_guard` catches the
9018/// panic and keeps the `IpoptApplication`, so the next `IpoptSolve` on that
9019/// handle ran with the scale audit's `max_iter` (`3x` the base solve's),
9020/// `obj_scaling_factor` multiplied by `k`, a CPU / wall budget shrunk to what
9021/// the audited run had left -- and, since gh#983's declared-box fix, the
9022/// variable box un-widened.
9023///
9024/// Derefs to the application, so the retry runs *through* the scope:
9025/// `scope.optimize_constrained(..)`. Each entry is restored with
9026/// [`OptionsList::restore_entry`], i.e. exactly as it stood, absence as
9027/// absence.
9028///
9029/// `on_unwind_only` is for the two retries (μ-strategy fallback, gh#884)
9030/// whose normal-path restore is deliberately *not* "as it stood" -- both
9031/// write the resolved value back with `found = true` -- and whose behaviour
9032/// on that path this guard must not change: there it only covers the unwind.
9033struct RetryOptionScope<'a> {
9034    app: &'a mut IpoptApplication,
9035    saved: Vec<(
9036        &'static str,
9037        pounce_common::options_list::OptionEntrySnapshot,
9038    )>,
9039    on_unwind_only: bool,
9040}
9041
9042impl<'a> RetryOptionScope<'a> {
9043    fn enter(app: &'a mut IpoptApplication, tags: &[&'static str], on_unwind_only: bool) -> Self {
9044        let saved = tags
9045            .iter()
9046            .map(|&t| (t, app.options.snapshot_entry(t)))
9047            .collect();
9048        Self {
9049            app,
9050            saved,
9051            on_unwind_only,
9052        }
9053    }
9054}
9055
9056impl std::ops::Deref for RetryOptionScope<'_> {
9057    type Target = IpoptApplication;
9058    fn deref(&self) -> &IpoptApplication {
9059        self.app
9060    }
9061}
9062
9063impl std::ops::DerefMut for RetryOptionScope<'_> {
9064    fn deref_mut(&mut self) -> &mut IpoptApplication {
9065        self.app
9066    }
9067}
9068
9069impl Drop for RetryOptionScope<'_> {
9070    fn drop(&mut self) {
9071        if self.on_unwind_only && !std::thread::panicking() {
9072            return;
9073        }
9074        for (tag, snap) in self.saved.drain(..) {
9075            self.app.options.restore_entry(tag, snap);
9076        }
9077        self.app.retry_keeps_declared_box.set(false);
9078    }
9079}
9080
9081/// The `final_*` half of [`SolveStatistics`] — the numbers that describe the
9082/// answer and the certificate attached to it.
9083///
9084/// Deliberately **not** the whole struct. `SolveStatistics` mixes two kinds of
9085/// number and they float back differently when a second-opinion retry loses:
9086///
9087/// * the `final_*` fields describe *the point being reported*, so they have to
9088///   agree with the status reported beside them. A `Solved_To_Acceptable_Level`
9089///   carrying a `final_kkt_error` two orders above `acceptable_tol` is
9090///   self-contradictory, and that is pounce#870.
9091/// * the wall clock (`total_wallclock_time_secs`) and the cumulative
9092///   dual-divergence flags describe *what the invocation did*: both attempts
9093///   really ran, so rewinding them would under-report the work actually
9094///   spent.
9095///
9096/// Everything else a solve report reads beside the final residuals describes
9097/// the *run that produced the returned point* (gh#983 item 5): the iteration
9098/// count and rows, the evaluation counts, the restoration tallies and
9099/// `quality_escalations`. Before that fix `deb7` at `max_iter=100` reported the
9100/// declined retry's 100 iterations beside the first attempt's objective and
9101/// point, and `eigenb2` (limited memory) 86 objective evaluations beside the
9102/// first attempt's 47 iterations and 159 evaluations. The first attempt's own
9103/// counts (`deb7`: 84 outer + 32 restoration = 116) are the ones that belong
9104/// with its point. The console's per-attempt summaries still show each
9105/// attempt's own tally.
9106///
9107/// So the certificate and the run it came from are floored together; only the
9108/// wall clock is the invocation's.
9109#[derive(Debug, Clone)]
9110struct SolutionCertificate {
9111    objective: Number,
9112    scaled_objective: Number,
9113    dual_inf: Number,
9114    constr_viol: Number,
9115    compl: Number,
9116    kkt_error: Number,
9117    unscaled_dual_inf: Number,
9118    unscaled_constr_viol: Number,
9119    unscaled_compl: Number,
9120    unscaled_kkt_error: Number,
9121    kkt_error_above_noise: Number,
9122    mu: Number,
9123    /// How far the attempt's point sits outside the model as declared --
9124    /// rows and box. Both are read off the statistics beside the residuals
9125    /// above, and both describe the *point*; leaving them out meant a
9126    /// declined retry's measurement was reported beside the base attempt's
9127    /// point (`Variable bound violation` and `final_declared_box_viol` naming
9128    /// the discarded re-solve's `9.9e-9` next to a point that sits inside
9129    /// its box).
9130    declared_constr_viol: Number,
9131    declared_box_viol: Number,
9132    /// gh#983 item 5: the iteration count and per-iteration rows of the
9133    /// attempt being floored. A solve report reads both from the statistics,
9134    /// so restoring the certificate without them left a report whose
9135    /// numbers describe the returned point and whose iteration table
9136    /// describes the declined retry.
9137    iteration_count: Index,
9138    iterations: Vec<pounce_nlp::solve_statistics::IterRecord>,
9139    /// The per-run evaluation and restoration tallies of the attempt, for the
9140    /// same reason as the iteration table: they are read off the statistics
9141    /// beside the final residuals, and a declined retry used to leave its own
9142    /// (`eigenb2` limited-memory: 86 objective evaluations reported beside the
9143    /// base attempt's 47 iterations and 159 evaluations).
9144    evals: [Index; 5],
9145    restoration: (Index, Index, Index, Number),
9146    quality_escalations: Index,
9147    /// gh#983: the scale the stationarity residual is judged against, the
9148    /// objective scale the run ended with, and the warnings raised about the
9149    /// attempt. All three describe the *point being reported*.
9150    unscaled_dual_scale: Number,
9151    obj_scaling_factor: Number,
9152    total_obj_scaling_factor: Number,
9153    start_obj_grad_max: Number,
9154    warnings: Vec<String>,
9155    /// gh#983 review item 3: the detector's verdict on this run alone.
9156    returned_run_signature: bool,
9157}
9158
9159impl SolutionCertificate {
9160    fn of(s: &pounce_nlp::solve_statistics::SolveStatistics) -> Self {
9161        Self {
9162            objective: s.final_objective,
9163            scaled_objective: s.final_scaled_objective,
9164            dual_inf: s.final_dual_inf,
9165            constr_viol: s.final_constr_viol,
9166            compl: s.final_compl,
9167            kkt_error: s.final_kkt_error,
9168            unscaled_dual_inf: s.final_unscaled_dual_inf,
9169            unscaled_constr_viol: s.final_unscaled_constr_viol,
9170            unscaled_compl: s.final_unscaled_compl,
9171            unscaled_kkt_error: s.final_unscaled_kkt_error,
9172            kkt_error_above_noise: s.final_kkt_error_above_noise,
9173            mu: s.final_mu,
9174            declared_constr_viol: s.final_declared_constr_viol,
9175            declared_box_viol: s.final_declared_box_viol,
9176            iteration_count: s.iteration_count,
9177            iterations: s.iterations.clone(),
9178            evals: [
9179                s.num_obj_evals,
9180                s.num_constr_evals,
9181                s.num_obj_grad_evals,
9182                s.num_constr_jac_evals,
9183                s.num_hess_evals,
9184            ],
9185            restoration: (
9186                s.restoration_calls,
9187                s.restoration_inner_iters,
9188                s.restoration_outer_iters,
9189                s.restoration_wall_secs,
9190            ),
9191            quality_escalations: s.quality_escalations,
9192            unscaled_dual_scale: s.final_unscaled_dual_scale,
9193            obj_scaling_factor: s.final_obj_scaling_factor,
9194            total_obj_scaling_factor: s.final_total_obj_scaling_factor,
9195            start_obj_grad_max: s.start_obj_grad_max,
9196            warnings: s.warnings.clone(),
9197            returned_run_signature: s.returned_run_dual_divergence_signature,
9198        }
9199    }
9200
9201    fn restore_into(&self, s: &mut pounce_nlp::solve_statistics::SolveStatistics) {
9202        s.final_objective = self.objective;
9203        s.final_scaled_objective = self.scaled_objective;
9204        s.final_dual_inf = self.dual_inf;
9205        s.final_constr_viol = self.constr_viol;
9206        s.final_compl = self.compl;
9207        s.final_kkt_error = self.kkt_error;
9208        s.final_unscaled_dual_inf = self.unscaled_dual_inf;
9209        s.final_unscaled_constr_viol = self.unscaled_constr_viol;
9210        s.final_unscaled_compl = self.unscaled_compl;
9211        s.final_unscaled_kkt_error = self.unscaled_kkt_error;
9212        s.final_kkt_error_above_noise = self.kkt_error_above_noise;
9213        s.final_mu = self.mu;
9214        s.final_declared_constr_viol = self.declared_constr_viol;
9215        s.final_declared_box_viol = self.declared_box_viol;
9216        s.iteration_count = self.iteration_count;
9217        s.iterations = self.iterations.clone();
9218        s.num_obj_evals = self.evals[0];
9219        s.num_constr_evals = self.evals[1];
9220        s.num_obj_grad_evals = self.evals[2];
9221        s.num_constr_jac_evals = self.evals[3];
9222        s.num_hess_evals = self.evals[4];
9223        s.restoration_calls = self.restoration.0;
9224        s.restoration_inner_iters = self.restoration.1;
9225        s.restoration_outer_iters = self.restoration.2;
9226        s.restoration_wall_secs = self.restoration.3;
9227        s.quality_escalations = self.quality_escalations;
9228        s.final_unscaled_dual_scale = self.unscaled_dual_scale;
9229        s.final_obj_scaling_factor = self.obj_scaling_factor;
9230        s.final_total_obj_scaling_factor = self.total_obj_scaling_factor;
9231        s.start_obj_grad_max = self.start_obj_grad_max;
9232        s.warnings = self.warnings.clone();
9233        s.returned_run_dual_divergence_signature = self.returned_run_signature;
9234    }
9235}
9236
9237impl FinalizeSnapshot {
9238    /// Re-deliver this payload to `tnlp`, overwriting whatever a later attempt
9239    /// captured there.
9240    fn replay(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
9241        tnlp.borrow_mut().finalize_solution(
9242            Solution {
9243                status: self.status,
9244                x: &self.x,
9245                z_l: &self.z_l,
9246                z_u: &self.z_u,
9247                g: &self.g,
9248                lambda: &self.lambda,
9249                obj_value: self.obj_value,
9250            },
9251            &TnlpIpoptData::default(),
9252            &TnlpIpoptCq::default(),
9253        );
9254    }
9255}
9256
9257fn finalize_via_orig_nlp(
9258    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9259    alg: &IpoptAlgorithm,
9260    solver_status: SolverReturn,
9261    _app_status: ApplicationReturnStatus,
9262    tnlp: &Rc<RefCell<dyn TNLP>>,
9263    sink: &RefCell<Option<FinalizeSnapshot>>,
9264    fixed_var_duals: bool,
9265) -> Result<Number, ()> {
9266    let curr = alg.data.borrow().curr.clone().ok_or(())?;
9267    // Lift compressed x_var → full-x (length `info.n`) so the user
9268    // TNLP receives the same shape it provided. With `make_parameter`
9269    // the fixed components are spliced back in by the IpoptNlp.
9270    let nlp_borrow = nlp.borrow();
9271    // `finalize_solution_x`, not `lift_x_to_full`: the reported point also
9272    // owes the user the `honor_original_bounds` projection. `f` and `g`
9273    // below are then evaluated at the point actually reported, so x/f/g
9274    // agree with each other.
9275    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&*curr.x);
9276    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
9277    let n = info.n as usize;
9278    let m = info.m as usize;
9279    debug_assert_eq!(x_vec.len(), n);
9280    // Lift algorithm-side multipliers back into user-space (pounce#11).
9281    // Use the `finalize_solution_*` family (not the `pack_*` family): the
9282    // final solution duals must be reported in the user's *unscaled-
9283    // Lagrangian* convention `∇f + λ·∇g + z = 0`, which divides out the
9284    // `obj_scale_factor` the algorithm threads through `eval_h`. The `pack_*`
9285    // family deliberately omits that division because it feeds the scaled
9286    // `eval_h`; calling it here left every dual scaled by `obj_scale_factor`
9287    // whenever gradient-based scaling triggered (pounce#11 F1).
9288    // Backends without overrides return empty; fall back to zero stubs so the
9289    // user sees a length-consistent vector.
9290    let mut z_l = nlp_borrow.finalize_solution_z_l(&*curr.z_l);
9291    if z_l.is_empty() {
9292        z_l = vec![0.0; n];
9293    }
9294    let mut z_u = nlp_borrow.finalize_solution_z_u(&*curr.z_u);
9295    if z_u.is_empty() {
9296        z_u = vec![0.0; n];
9297    }
9298    let mut lambda = nlp_borrow.finalize_solution_lambda(&*curr.y_c, &*curr.y_d);
9299    if lambda.is_empty() {
9300        lambda = vec![0.0; m];
9301    }
9302    if fixed_var_duals {
9303        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
9304    }
9305    drop(nlp_borrow);
9306    // Compute g(x) via the user TNLP so the final residual is
9307    // populated for the user.
9308    let mut g_final = vec![0.0; m];
9309    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
9310    let f_final = tnlp
9311        .borrow_mut()
9312        .eval_f(&x_vec, true)
9313        .unwrap_or(Number::NAN);
9314    let snap = FinalizeSnapshot {
9315        status: solver_status,
9316        x: x_vec,
9317        z_l,
9318        z_u,
9319        g: g_final,
9320        lambda,
9321        obj_value: f_final,
9322    };
9323    snap.replay(tnlp);
9324    *sink.borrow_mut() = Some(snap);
9325    Ok(f_final)
9326}
9327
9328/// Bind SQP suboptions registered in `upstream_options.rs`
9329/// (`sqp_globalization`, `sqp_hessian`, `sqp_max_iter`, `sqp_tol`,
9330/// `sqp_constr_viol_tol`, `sqp_dual_inf_tol`, `sqp_l1_penalty`,
9331/// `sqp_bt_reduction`, `sqp_bt_min_alpha`, `sqp_print_level`,
9332/// `sqp_lbfgs_max_history`) onto
9333/// `opts`. Used by [`IpoptApplication::algorithm_builder_snapshot`]
9334/// before constructing an SQP algorithm.
9335fn apply_sqp_options(options: &OptionsList, opts: &mut crate::sqp::SqpOptions) {
9336    use crate::sqp::{SqpGlobalization, SqpHessianSource};
9337
9338    if let Ok((s, true)) = options.get_string_value("sqp_globalization", "") {
9339        opts.globalization = match s.as_str() {
9340            "filter" => SqpGlobalization::Filter,
9341            "l1-elastic" => SqpGlobalization::L1Elastic,
9342            _ => opts.globalization,
9343        };
9344    }
9345    // `hessian_approximation` is the upstream Ipopt option a frontend sets
9346    // when the caller supplies no second derivatives -- `pounce.minimize` does
9347    // it automatically, and warns that it is doing so. It was only ever read
9348    // on the IPM path, so an SQP solve ignored it and fell back to the
9349    // `Exact` default, asking the NLP for a Lagrangian Hessian that was never
9350    // provided. A zero Hessian turns the QP subproblem into an LP, which is
9351    // unbounded whenever the objective gradient has a component in the null
9352    // space of the active constraints -- so the solve died with
9353    // `Internal_Error` on problems the IPM handles without complaint:
9354    //
9355    //     min (x0-3)^2 + (x1-2)^2  s.t.  4 - x0 - x1 >= 0
9356    //
9357    // (IPM: x = [2.5, 1.5]. Active-set SQP before this: Internal_Error, or
9358    // with variable bounds, a run to the box corner along the null-space
9359    // direction.)
9360    //
9361    // The quasi-Newton source picked here is the *dense Powell-damped BFGS*,
9362    // not the limited-memory one, even though the requesting option is spelled
9363    // `limited-memory`. On this active-set-SQP path L-BFGS buys nothing: its
9364    // `as_triplet` materializes a full dense `n×n` Hessian for the QP
9365    // subproblem exactly as `DampedBfgs` does (the matrix-free product
9366    // interface that would make L-BFGS cheaper is not implemented yet), and it
9367    // is markedly less robust -- it stalls with
9368    // `Search_Direction_Becomes_Too_Small` (or reports the QP subproblem
9369    // `unbounded`) on easy, well-conditioned convex QPs whenever a general
9370    // inequality is active at the optimum, returning `success=False` with a
9371    // wrong `x` (issue #358). `DampedBfgs` solves those. So the automatic
9372    // approximation the facade injects when no analytic Hessian is available
9373    // maps to the robust dense update; a caller who genuinely wants
9374    // limited-memory storage can still request it explicitly with
9375    // `sqp_hessian = "lbfgs"` below (read after this, so it wins).
9376    //
9377    // Read this before `sqp_hessian` so an explicit setting still wins.
9378    if let Ok((s, true)) = options.get_string_value("hessian_approximation", "") {
9379        if s == "limited-memory" {
9380            opts.hessian = SqpHessianSource::DampedBfgs;
9381        }
9382    }
9383    if let Ok((s, true)) = options.get_string_value("sqp_hessian", "") {
9384        opts.hessian = match s.as_str() {
9385            "exact" => SqpHessianSource::Exact,
9386            "damped-bfgs" => SqpHessianSource::DampedBfgs,
9387            "lbfgs" => SqpHessianSource::Lbfgs,
9388            _ => opts.hessian,
9389        };
9390    }
9391    if let Ok((v, true)) = options.get_integer_value("sqp_max_iter", "") {
9392        if v >= 0 {
9393            opts.max_iter = v as u32;
9394        }
9395    }
9396    if let Ok((v, true)) = options.get_numeric_value("sqp_tol", "") {
9397        opts.tol = v;
9398    }
9399    if let Ok((v, true)) = options.get_numeric_value("sqp_constr_viol_tol", "") {
9400        opts.constr_viol_tol = v;
9401    }
9402    if let Ok((v, true)) = options.get_numeric_value("sqp_dual_inf_tol", "") {
9403        opts.dual_inf_tol = v;
9404    }
9405    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty", "") {
9406        opts.l1_penalty = v;
9407    }
9408    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_safety", "") {
9409        opts.l1_penalty_safety = v;
9410    }
9411    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_max", "") {
9412        opts.l1_penalty_max = v;
9413    }
9414    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_reduction", "") {
9415        opts.bt_reduction = v;
9416    }
9417    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_min_alpha", "") {
9418        opts.bt_min_alpha = v;
9419    }
9420    if let Ok((v, true)) = options.get_integer_value("sqp_print_level", "") {
9421        opts.print_level = v.clamp(0, u8::MAX as i32) as u8;
9422    }
9423    if let Ok((v, true)) = options.get_integer_value("sqp_lbfgs_max_history", "") {
9424        if v >= 1 {
9425            opts.lbfgs_max_history = v as u32;
9426        }
9427    }
9428}
9429
9430/// Populate the active-set SQP **QP-subproblem** options
9431/// ([`pounce_qp::QpOptions`]) from the `sqp_qp_*` option family.
9432///
9433/// Sister to [`apply_sqp_options`], which handles the SQP *outer-loop*
9434/// options ([`crate::sqp::SqpOptions`]); this one feeds the inner QP
9435/// solver that `SqpAlgorithm` delegates each subproblem to. Consulted
9436/// only on the `ActiveSetSqp` path. Each knob is forwarded only when
9437/// the user explicitly set it, so the `pounce_qp` defaults stand
9438/// otherwise.
9439///
9440/// The reading itself is [`pounce_qp::ActiveSetOverrides`], shared with
9441/// `pounce_convex`'s direct active-set driver, which overlays the same
9442/// eight names onto the same `QpOptions` type. This function had its own
9443/// copy until then, and the two had drifted: this one silently ignored a
9444/// `sqp_qp_max_iter` of 0 and an unknown `sqp_qp_anti_cycling` value where
9445/// the other rejected them. Neither divergence was reachable — the
9446/// registry bounds `sqp_qp_max_iter` at 1 and restricts `anti_cycling` to
9447/// three values — but two readers of one option family is how a
9448/// reachable one starts.
9449fn apply_qp_subproblem_options(options: &OptionsList, opts: &mut pounce_qp::QpOptions) {
9450    match pounce_qp::ActiveSetOverrides::try_from_options_list(options) {
9451        Ok(overrides) => overrides.apply(opts),
9452        // Unreachable from here: this runs after `initialize()`, so every
9453        // value present has already been validated against the registered
9454        // bound that the reader re-checks. Say so out loud anyway rather
9455        // than solving with a configuration the user did not ask for —
9456        // silently dropping the whole family is exactly the failure mode
9457        // `tests/no_silent_options.rs` exists to prevent.
9458        Err(error) => tracing::error!(
9459            target: "pounce::options",
9460            %error,
9461            "sqp_qp_* options were rejected after the registry accepted them; \
9462             the QP subproblem is running on pounce-qp defaults"
9463        ),
9464    }
9465}
9466
9467/// The TNLP's own starting point as an SQP warm start, in algorithm space,
9468/// through the projections the IPM's warm initializer reads
9469/// (`prepare_warm_start`, `get_starting_x/y/z`). `None` when the NLP
9470/// declines. An unseeded bound multiplier (NaN, gh#622) counts as zero: the
9471/// SQP has no `bound_mult_init_val` of its own to resolve it to.
9472fn sqp_tnlp_warm_start(nlp_rc: &Rc<RefCell<dyn IpoptNlp>>) -> Option<crate::sqp::SqpIterates> {
9473    use pounce_linalg::dense_vector::DenseVectorSpace;
9474    let dense = |v: &dyn pounce_linalg::Vector| -> Vec<Number> {
9475        v.as_any()
9476            .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
9477            .map(|d| d.expanded_values().to_vec())
9478            .unwrap_or_default()
9479    };
9480    let (z_l, z_u, x, lambda_g) = {
9481        let mut nlp = nlp_rc.borrow_mut();
9482        if !nlp.prepare_warm_start() {
9483            return None;
9484        }
9485        let (n, m_eq, m_ineq) = (nlp.n(), nlp.m_eq(), nlp.m_ineq());
9486        let (n_xl, n_xu) = (nlp.x_l().dim(), nlp.x_u().dim());
9487        let (n_dl, n_du) = (nlp.d_l().dim(), nlp.d_u().dim());
9488        let mut x = DenseVectorSpace::new(n).make_new_dense();
9489        let mut y_c = DenseVectorSpace::new(m_eq).make_new_dense();
9490        let mut y_d = DenseVectorSpace::new(m_ineq).make_new_dense();
9491        let mut z_l = DenseVectorSpace::new(n_xl).make_new_dense();
9492        let mut z_u = DenseVectorSpace::new(n_xu).make_new_dense();
9493        let mut v_l = DenseVectorSpace::new(n_dl).make_new_dense();
9494        let mut v_u = DenseVectorSpace::new(n_du).make_new_dense();
9495        let ok = nlp.get_starting_x(&mut x)
9496            && nlp.get_starting_y(&mut y_c, &mut y_d)
9497            && nlp.get_starting_z(&mut z_l, &mut z_u, &mut v_l, &mut v_u);
9498        nlp.finish_warm_start();
9499        if !ok {
9500            return None;
9501        }
9502        let finite = |v: Vec<Number>| -> Vec<Number> {
9503            v.into_iter()
9504                .map(|a| if a.is_finite() { a } else { 0.0 })
9505                .collect()
9506        };
9507        let mut lambda_g = finite(dense(&y_c));
9508        lambda_g.extend(finite(dense(&y_d)));
9509        (
9510            finite(dense(&z_l)),
9511            finite(dense(&z_u)),
9512            dense(&x),
9513            lambda_g,
9514        )
9515    };
9516    let lambda_x = crate::sqp::ipopt_adapter::pack_bound_multipliers(nlp_rc, &z_l, &z_u);
9517    Some(crate::sqp::SqpIterates {
9518        x,
9519        lambda_g,
9520        lambda_x,
9521        working: None,
9522    })
9523}
9524
9525/// Map a staged SQP warm start from the caller's space into the algorithm's:
9526/// the exact inverse of what [`finalize_via_sqp`] / [`sqp_user_iterate`] do on
9527/// the way out, so that the multipliers a solve reports, fed back unchanged,
9528/// are the iterate the next solve starts from.
9529///
9530/// | field | user space (what callers stage) | algorithm space |
9531/// |---|---|---|
9532/// | `x` | full `n`, model units | fixed columns dropped, `x̃ = d ⊙ x` |
9533/// | `lambda_x` | full `n`, `z_L − z_U` | fixed dropped, `· obj_scal ⊘ d` |
9534/// | `lambda_g` | `m`, in `g` order | `[y_c; y_d]`, `y = λ · obj_scal / {c,d}_scale` |
9535/// | `working.constraints` | `m`, in `g` order | `[c; d]` order |
9536///
9537/// (`working.bounds` goes from full `n` to the reduced columns in the
9538/// caller, which also knows which elimination an already-reduced set came
9539/// from.)
9540///
9541/// `d` is the per-variable factor of a `ScalingTnlp` below the NLP (gh#486;
9542/// `z̃ = z ⊘ d`, its `get_starting_point` rule) and `obj_scal` includes the
9543/// sign of a maximize. The `λ` rule is `OrigIpoptNlp::initialize_starting_point`'s,
9544/// the IPM's inbound half of the same inverse.
9545///
9546/// Every frontend stages user space — the C API and `pounce-py` pass the
9547/// caller's `x` / `mult_g` / `z_L − z_U` through untouched. Before this they
9548/// went in as-is: on a model whose equality is not the first row, the two
9549/// constraint multipliers landed on each other's rows, and any
9550/// `obj_scaling_factor` ≠ 1 left them off by that factor.
9551///
9552/// An `x` / `lambda_x` already of the reduced length (a problem with fixed
9553/// variables) is taken as user-unit values of the surviving columns, in
9554/// order; any other length is left alone for the dimension check to reject.
9555fn sqp_warm_start_to_algorithm(nlp: &dyn IpoptNlp, w: &mut crate::sqp::SqpIterates) {
9556    let n_alg = nlp.n() as usize;
9557    let n_full = nlp.n_full_x() as usize;
9558    let m_full = nlp.n_full_g() as usize;
9559    let m_eq = nlp.m_eq() as usize;
9560    let obj_scal = nlp.obj_scaling_factor();
9561    let d = nlp.variable_scaling();
9562    // Algorithm column -> (user column, its x-scaling factor).
9563    let cols: Vec<(usize, Number)> = (0..n_alg)
9564        .map(|k| {
9565            let j = nlp.var_x_to_full_x(k as Index) as usize;
9566            let dj = d.as_ref().and_then(|d| d.get(j).copied()).unwrap_or(1.0);
9567            (j, dj)
9568        })
9569        .collect();
9570    let to_alg = |v: &[Number], f: &dyn Fn(Number, Number) -> Number| -> Option<Vec<Number>> {
9571        if v.len() == n_full {
9572            Some(cols.iter().map(|&(j, dj)| f(v[j], dj)).collect())
9573        } else if v.len() == n_alg {
9574            Some(cols.iter().zip(v).map(|(&(_, dj), &x)| f(x, dj)).collect())
9575        } else {
9576            None
9577        }
9578    };
9579    if let Some(x) = to_alg(&w.x, &|x, dj| x * dj) {
9580        w.x = x;
9581    }
9582    if let Some(lx) = to_alg(&w.lambda_x, &|z, dj| z * obj_scal / dj) {
9583        w.lambda_x = lx;
9584    }
9585    if w.lambda_g.len() == m_full {
9586        let cs = nlp.c_scale_vec();
9587        let ds = nlp.d_scale_vec();
9588        let mut y = vec![0.0; m_full];
9589        for (i, &lam) in w.lambda_g.iter().enumerate() {
9590            let i = i as Index;
9591            if let Some(k) = nlp.full_g_to_c_block(i) {
9592                let k = k as usize;
9593                let s = cs.as_ref().map_or(1.0, |v| v[k]);
9594                y[k] = lam / s * obj_scal;
9595            } else if let Some(k) = nlp.full_g_to_d_block(i) {
9596                let k = k as usize;
9597                let s = ds.as_ref().map_or(1.0, |v| v[k]);
9598                y[m_eq + k] = lam / s * obj_scal;
9599            }
9600        }
9601        w.lambda_g = y;
9602    }
9603    if let Some(ws) = w.working.as_mut() {
9604        ws.constraints = working_set_rows_to_algorithm(nlp, std::mem::take(&mut ws.constraints));
9605    }
9606}
9607
9608/// Algorithm row `k` of the `[c; d]` constraint vector → user `g` row, or
9609/// `None` when the NLP's row count does not describe a full split.
9610fn algorithm_rows_to_user(nlp: &dyn IpoptNlp) -> Option<Vec<usize>> {
9611    let m_full = nlp.n_full_g() as usize;
9612    let m_eq = nlp.m_eq() as usize;
9613    let m_alg = m_eq + nlp.m_ineq() as usize;
9614    if m_full != m_alg {
9615        return None;
9616    }
9617    let mut map = vec![usize::MAX; m_alg];
9618    for i in 0..m_full {
9619        let k = if let Some(k) = nlp.full_g_to_c_block(i as Index) {
9620            k as usize
9621        } else if let Some(k) = nlp.full_g_to_d_block(i as Index) {
9622            m_eq + k as usize
9623        } else {
9624            return None;
9625        };
9626        if k >= m_alg || map[k] != usize::MAX {
9627            return None;
9628        }
9629        map[k] = i;
9630    }
9631    Some(map)
9632}
9633
9634/// Constraint statuses of a working set, algorithm `[c; d]` order → user
9635/// `g` order. The SQP stacks equalities first, so on a model whose first
9636/// row is an inequality the statuses published positionally landed on the
9637/// wrong rows (`[Equality, AtUpper]` for `g = [ineq, eq]`). A vector of
9638/// any other length is returned unchanged for the dimension check to judge.
9639fn working_set_rows_to_user(
9640    nlp: &dyn IpoptNlp,
9641    rows: Vec<pounce_qp::ConsStatus>,
9642) -> Vec<pounce_qp::ConsStatus> {
9643    match algorithm_rows_to_user(nlp) {
9644        Some(map) if map.len() == rows.len() => {
9645            let mut user = vec![pounce_qp::ConsStatus::Inactive; rows.len()];
9646            for (k, &i) in map.iter().enumerate() {
9647                user[i] = rows[k];
9648            }
9649            user
9650        }
9651        _ => rows,
9652    }
9653}
9654
9655/// Inverse of [`working_set_rows_to_user`]: user `g` order → `[c; d]`.
9656fn working_set_rows_to_algorithm(
9657    nlp: &dyn IpoptNlp,
9658    rows: Vec<pounce_qp::ConsStatus>,
9659) -> Vec<pounce_qp::ConsStatus> {
9660    match algorithm_rows_to_user(nlp) {
9661        Some(map) if map.len() == rows.len() => map.iter().map(|&i| rows[i]).collect(),
9662        _ => rows,
9663    }
9664}
9665
9666/// The SQP iterate in the user's index spaces, for the live-inspector window
9667/// (gh#1015). Same conversions as [`finalize_via_sqp`] — `λ_x` is packed
9668/// signed (`z_L − z_U`) and is split by sign — minus the user-callback
9669/// evaluations: `g` comes from the loop's own `[c; d]` values.
9670fn sqp_user_iterate(
9671    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9672    x: &[Number],
9673    lambda_g: &[Number],
9674    lambda_x: &[Number],
9675    c_vals: &[Number],
9676    grad_lag_x: &[Number],
9677    fixed_var_duals: bool,
9678) -> crate::intermediate::UserIterate {
9679    use pounce_linalg::dense_vector::DenseVectorSpace;
9680
9681    // `finalize_solution_z_*` read the compressed x_l / x_u spaces (one
9682    // entry per finite bound, via `x_l_map`), not one entry per variable;
9683    // `split_bound_multipliers` does that split, as crossover does.
9684    let (zl, zu) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, lambda_x);
9685    let nlp = nlp.borrow();
9686    let n_alg = nlp.n() as usize;
9687    let m_eq = nlp.m_eq() as usize;
9688    let m_ineq = nlp.m_ineq() as usize;
9689    let n_user = nlp.n_full_x() as usize;
9690    let m_user = nlp.n_full_g() as usize;
9691
9692    let x_space = DenseVectorSpace::new(n_alg as Index);
9693    let c_space = DenseVectorSpace::new(m_eq as Index);
9694    let d_space = DenseVectorSpace::new(m_ineq as Index);
9695    let dv = |space: &Rc<DenseVectorSpace>, v: &[Number]| {
9696        let mut d = space.make_new_dense();
9697        if !v.is_empty() {
9698            d.set_values(v);
9699        }
9700        d
9701    };
9702
9703    let x_full = nlp.finalize_solution_x(&dv(&x_space, x));
9704    let mut z_l = nlp.finalize_solution_z_l(&dv(&DenseVectorSpace::new(zl.len() as Index), &zl));
9705    if z_l.is_empty() {
9706        z_l = vec![0.0; n_user];
9707    }
9708    let mut z_u = nlp.finalize_solution_z_u(&dv(&DenseVectorSpace::new(zu.len() as Index), &zu));
9709    if z_u.is_empty() {
9710        z_u = vec![0.0; n_user];
9711    }
9712    let (y_c, y_d) = lambda_g.split_at(m_eq.min(lambda_g.len()));
9713    let mut lambda = nlp.finalize_solution_lambda(&dv(&c_space, y_c), &dv(&d_space, y_d));
9714    if lambda.is_empty() {
9715        lambda = vec![0.0; m_user];
9716    }
9717    if fixed_var_duals {
9718        nlp.complete_fixed_var_bound_multipliers(&x_full, &lambda, &mut z_l, &mut z_u);
9719    }
9720    // Everything here is in the space of the TNLP the NLP wraps, which
9721    // under per-variable `user-scaling` is a `ScalingTnlp` seeing
9722    // `x̃ = d ⊙ x`; that wrapper undoes the substitution on the iterate's
9723    // way through its `intermediate_callback`, by its `finalize_solution`'s
9724    // rule (`x = x̃ ⊘ d`, `z = d ⊙ z̃`).
9725    let (c, d) = c_vals.split_at(m_eq.min(c_vals.len()));
9726    let g = nlp.pack_g_for_user(&dv(&c_space, c), &dv(&d_space, d));
9727    // The SQP iterates against the same live bounds (widened only when
9728    // `bound_relax_factor` is set by name on this arm).
9729    let (x_l_alg, x_u_alg) = crate::intermediate::algorithm_x_bounds(&*nlp, &x_full);
9730    crate::intermediate::UserIterate {
9731        x: x_full,
9732        z_l,
9733        z_u,
9734        g,
9735        lambda,
9736        scaling: Some(crate::intermediate::iterate_scaling(&*nlp)),
9737        x_l_alg,
9738        x_u_alg,
9739        grad_lag_x: crate::intermediate::user_grad_lag(&*nlp, grad_lag_x),
9740    }
9741}
9742
9743/// SQP-side analog of [`finalize_via_orig_nlp`]. Hands the SQP
9744/// solution iterate to the user TNLP via the standard
9745/// `finalize_solution` callback. Multiplier lifting goes through
9746/// the same OrigIpoptNlp hooks so the user sees the same shape
9747/// regardless of which algorithm produced the iterate.
9748///
9749/// Returns the user-space objective value on success.
9750fn finalize_via_sqp(
9751    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9752    res: &crate::sqp::SqpResult,
9753    solver_status: pounce_nlp::SolverReturn,
9754    tnlp: &Rc<RefCell<dyn TNLP>>,
9755    sink: &RefCell<Option<FinalizeSnapshot>>,
9756    fixed_var_duals: bool,
9757) -> Result<Number, ()> {
9758    use pounce_linalg::dense_vector::DenseVectorSpace;
9759
9760    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
9761    let n = info.n as usize;
9762    let m = info.m as usize;
9763
9764    // Wrap SQP slices in DenseVectors so we can pass them through
9765    // the OrigIpoptNlp lift_x_to_full / pack_*_for_user hooks.
9766    let nlp_borrow = nlp.borrow();
9767    let n_alg = nlp_borrow.n() as usize;
9768    let m_eq = nlp_borrow.m_eq() as usize;
9769    let m_ineq = nlp_borrow.m_ineq() as usize;
9770    debug_assert_eq!(res.x.len(), n_alg);
9771    debug_assert_eq!(res.lambda_g.len(), m_eq + m_ineq);
9772    debug_assert_eq!(res.lambda_x.len(), n_alg);
9773
9774    let x_space = DenseVectorSpace::new(n_alg as Index);
9775    let c_space = DenseVectorSpace::new(m_eq as Index);
9776    let d_space = DenseVectorSpace::new(m_ineq as Index);
9777
9778    let mut x_dv = x_space.make_new_dense();
9779    x_dv.set_values(&res.x);
9780    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&x_dv);
9781    debug_assert_eq!(x_vec.len(), n);
9782
9783    // λ_x is packed signed (z_l − z_u), one entry per variable. Split it
9784    // into the compressed x_l / x_u spaces `finalize_solution_z_*` read
9785    // (one entry per finite bound): splitting per variable put each
9786    // multiplier on the wrong variable whenever an unbounded one came
9787    // first, as crossover's `split_bound_multipliers` call already avoids.
9788    let (zl_vals, zu_vals) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, &res.lambda_x);
9789    let mut z_l_compressed = DenseVectorSpace::new(zl_vals.len() as Index).make_new_dense();
9790    let mut z_u_compressed = DenseVectorSpace::new(zu_vals.len() as Index).make_new_dense();
9791    if !zl_vals.is_empty() {
9792        z_l_compressed.set_values(&zl_vals);
9793    }
9794    if !zu_vals.is_empty() {
9795        z_u_compressed.set_values(&zu_vals);
9796    }
9797    // `finalize_solution_*` (not `pack_*`): report unscaled-Lagrangian duals,
9798    // dividing out `obj_scale_factor` — see `finalize_via_orig_nlp` (F1).
9799    let mut z_l = nlp_borrow.finalize_solution_z_l(&z_l_compressed);
9800    if z_l.is_empty() {
9801        z_l = vec![0.0; n];
9802    }
9803    let mut z_u = nlp_borrow.finalize_solution_z_u(&z_u_compressed);
9804    if z_u.is_empty() {
9805        z_u = vec![0.0; n];
9806    }
9807
9808    // λ_g is [y_c; y_d]; split into the c/d blocks for lift.
9809    let mut y_c_dv = c_space.make_new_dense();
9810    let mut y_d_dv = d_space.make_new_dense();
9811    if m_eq > 0 {
9812        y_c_dv.set_values(&res.lambda_g[..m_eq]);
9813    }
9814    if m_ineq > 0 {
9815        y_d_dv.set_values(&res.lambda_g[m_eq..]);
9816    }
9817    let mut lambda = nlp_borrow.finalize_solution_lambda(&y_c_dv, &y_d_dv);
9818    if lambda.is_empty() {
9819        lambda = vec![0.0; m];
9820    }
9821    if fixed_var_duals {
9822        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
9823    }
9824    drop(nlp_borrow);
9825
9826    let mut g_final = vec![0.0; m];
9827    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
9828    let f_final = tnlp
9829        .borrow_mut()
9830        .eval_f(&x_vec, true)
9831        .unwrap_or(Number::NAN);
9832    let snap = FinalizeSnapshot {
9833        status: solver_status,
9834        x: x_vec,
9835        z_l,
9836        z_u,
9837        g: g_final,
9838        lambda,
9839        obj_value: f_final,
9840    };
9841    snap.replay(tnlp);
9842    *sink.borrow_mut() = Some(snap);
9843    Ok(f_final)
9844}
9845
9846#[cfg(test)]
9847mod block_structure_tests {
9848    use super::map_block_structure_to_kkt;
9849    use pounce_nlp::tnlp_adapter::BoundClassification;
9850
9851    /// Three variables (the middle one fixed out) and four constraints: two
9852    /// equalities (rows 0 and 3) and two inequalities (rows 1 and 2).
9853    fn classification() -> BoundClassification {
9854        BoundClassification {
9855            n_full_x: 3,
9856            n_full_g: 4,
9857            n_x_fixed: 1,
9858            x_not_fixed_map: vec![0, 2],
9859            x_fixed_map: vec![1],
9860            x_fixed_vals: vec![0.0],
9861            full_to_var: vec![0, -1, 1],
9862            x_l_map: vec![],
9863            x_u_map: vec![],
9864            n_c: 2,
9865            c_map: vec![0, 3],
9866            n_d: 2,
9867            d_map: vec![1, 2],
9868            d_l_map: vec![],
9869            d_u_map: vec![],
9870            full_to_c: vec![0, -1, -1, 1],
9871            full_to_d: vec![-1, 0, 1, -1],
9872        }
9873    }
9874
9875    /// The KKT is `[x | slacks | equality duals | inequality duals]`, so a
9876    /// declaration in the model's terms lands as: the surviving variables'
9877    /// labels, then each inequality's label twice (slack and dual) around the
9878    /// equalities' labels. A variable fixed out of the problem contributes
9879    /// nothing — reading its label anyway would shift every later one.
9880    #[test]
9881    fn model_labels_map_onto_the_kkt_layout() {
9882        let cls = classification();
9883        let var_blocks = vec![7, 99, -1]; // x0 -> block 7, x1 fixed, x2 shared
9884        let con_blocks = vec![5, 6, -1, 8]; // eq 5, ineq 6, ineq shared, eq 8
9885        let labels = map_block_structure_to_kkt(&cls, &var_blocks, &con_blocks).unwrap();
9886        assert_eq!(
9887            labels,
9888            vec![
9889                7, -1, // x: the two unfixed variables
9890                6, -1, // slacks, in d order (rows 1 and 2)
9891                5, 8, // equality duals, in c order (rows 0 and 3)
9892                6, -1, // inequality duals, same order as their slacks
9893            ]
9894        );
9895    }
9896
9897    /// A length that does not match the problem is refused rather than
9898    /// truncated: a structure off by one row declares blocks the matrix does
9899    /// not have, and the solver would only notice as a wrong answer or a
9900    /// rejected partition.
9901    #[test]
9902    fn a_mismatched_declaration_is_refused() {
9903        let cls = classification();
9904        assert!(map_block_structure_to_kkt(&cls, &[1, 2], &[1, 2, 3, 4]).is_err());
9905        assert!(map_block_structure_to_kkt(&cls, &[1, 2, 3], &[1, 2, 3]).is_err());
9906    }
9907}
9908
9909#[cfg(test)]
9910mod tests {
9911    use super::*;
9912
9913    /// pounce#748 — the flipped default is conditional on the caller not
9914    /// having named a `mu_strategy`. All four combinations, because the
9915    /// point of the condition is that an explicit strategy suppresses the
9916    /// automatic retry while an explicit `mu_strategy_fallback` does not.
9917    #[test]
9918    fn mu_strategy_fallback_default_defers_to_an_explicit_strategy() {
9919        // Nothing set: the retry is on.
9920        let app = IpoptApplication::new();
9921        assert!(app.is_mu_strategy_fallback_enabled());
9922
9923        // Caller named a strategy: the automatic retry stands down.
9924        let mut app = IpoptApplication::new();
9925        app.options_mut()
9926            .set_string_value("mu_strategy", "monotone", true, false)
9927            .unwrap();
9928        assert!(!app.is_mu_strategy_fallback_enabled());
9929
9930        // ... unless they also asked for the retry explicitly.
9931        app.options_mut()
9932            .set_string_value("mu_strategy_fallback", "yes", true, false)
9933            .unwrap();
9934        assert!(app.is_mu_strategy_fallback_enabled());
9935
9936        // An explicit "no" is honoured with no strategy set.
9937        let mut app = IpoptApplication::new();
9938        app.options_mut()
9939            .set_string_value("mu_strategy_fallback", "no", true, false)
9940            .unwrap();
9941        assert!(!app.is_mu_strategy_fallback_enabled());
9942    }
9943
9944    /// gh#990: a `mu_strategy` a POUNCE frontend pinned (the Python
9945    /// no-`hessian` path's `monotone`) is not the caller naming a strategy,
9946    /// so the default-on stall retry stays on; an explicit `no` still wins.
9947    #[test]
9948    fn a_pounce_chosen_mu_strategy_keeps_the_fallback_on() {
9949        let mut app = IpoptApplication::new();
9950        app.options_mut()
9951            .set_string_value("hessian_approximation", "limited-memory", true, false)
9952            .unwrap();
9953        app.options_mut()
9954            .set_string_value("mu_strategy", "monotone", true, false)
9955            .unwrap();
9956        assert!(!app.is_mu_strategy_fallback_enabled());
9957        app.mark_mu_strategy_pounce_chosen();
9958        assert!(app.is_mu_strategy_fallback_enabled());
9959        // The pin still decides the schedule: no limited-memory -> adaptive.
9960        assert!(!app.effective_mu_strategy_is_adaptive());
9961        app.options_mut()
9962            .set_string_value("mu_strategy_fallback", "no", true, false)
9963            .unwrap();
9964        assert!(!app.is_mu_strategy_fallback_enabled());
9965    }
9966
9967    use pounce_nlp::tnlp::{
9968        BoundsInfo, IndexStyle, IpoptCq, IpoptData, NlpInfo, ScalingRequest, Solution,
9969        SparsityRequest, StartingPoint,
9970    };
9971
9972    struct Hs071Stub;
9973    impl TNLP for Hs071Stub {
9974        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
9975            // HS071 dimensions: n=4, m=2, dense Jacobian (8 nz),
9976            // dense lower-triangular Hessian (10 nz).
9977            Some(NlpInfo {
9978                n: 4,
9979                m: 2,
9980                nnz_jac_g: 8,
9981                nnz_h_lag: 10,
9982                index_style: IndexStyle::C,
9983            })
9984        }
9985        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
9986            b.x_l.copy_from_slice(&[1.0; 4]);
9987            b.x_u.copy_from_slice(&[5.0; 4]);
9988            b.g_l.copy_from_slice(&[25.0, 40.0]);
9989            b.g_u.copy_from_slice(&[2.0e19, 40.0]);
9990            true
9991        }
9992        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
9993            sp.x.copy_from_slice(&[1.0, 5.0, 5.0, 1.0]);
9994            true
9995        }
9996        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
9997            Some(x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2])
9998        }
9999        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10000            grad.fill(0.0);
10001            true
10002        }
10003        fn eval_g(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10004            g.fill(0.0);
10005            true
10006        }
10007        fn eval_jac_g(
10008            &mut self,
10009            _x: Option<&[Number]>,
10010            _new_x: bool,
10011            mode: SparsityRequest<'_>,
10012        ) -> bool {
10013            if let SparsityRequest::Structure { irow, jcol } = mode {
10014                irow.copy_from_slice(&[0, 0, 0, 0, 1, 1, 1, 1]);
10015                jcol.copy_from_slice(&[0, 1, 2, 3, 0, 1, 2, 3]);
10016            }
10017            true
10018        }
10019        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
10020    }
10021
10022    #[test]
10023    fn application_default_does_not_select_sqp() {
10024        let mut app = IpoptApplication::new();
10025        app.initialize().unwrap();
10026        assert!(!app.is_sqp_algorithm_selected());
10027    }
10028
10029    #[test]
10030    fn application_routes_to_sqp_when_algorithm_option_set() {
10031        let mut app = IpoptApplication::new();
10032        app.initialize().unwrap();
10033        app.initialize_with_options_str("algorithm active-set-sqp\n")
10034            .unwrap();
10035        assert!(app.is_sqp_algorithm_selected());
10036    }
10037
10038    #[test]
10039    fn feral_min_par_flops_option_reaches_config() {
10040        let mut app = IpoptApplication::new();
10041        app.initialize().unwrap();
10042        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10043        // which leaves it None (inherit feral's built-in default) when the
10044        // POUNCE_FERAL_MIN_PAR_FLOPS env var is also absent.
10045        assert_eq!(
10046            feral_config_from_options(app.options()).min_par_flops,
10047            None,
10048            "unset feral_min_par_flops should not force an override"
10049        );
10050        // Explicit set is mapped through, cast to u64. `0` is the "dispatch
10051        // on every eligible tree" setting and must survive the cast.
10052        app.initialize_with_options_str("feral_min_par_flops 0\n")
10053            .unwrap();
10054        assert_eq!(
10055            feral_config_from_options(app.options()).min_par_flops,
10056            Some(0)
10057        );
10058        // A large finite value passes through intact (5e8 > i32::MAX, which
10059        // is why this is a number option, not an integer one).
10060        app.initialize_with_options_str("feral_min_par_flops 5e8\n")
10061            .unwrap();
10062        assert_eq!(
10063            feral_config_from_options(app.options()).min_par_flops,
10064            Some(500_000_000)
10065        );
10066    }
10067
10068    #[test]
10069    fn feral_refine_steps_option_reaches_config() {
10070        let mut app = IpoptApplication::new();
10071        app.initialize().unwrap();
10072        // Unset: falls through to FeralConfig::from_env, which resolves to
10073        // feral's own DEFAULT_REFINE_MAX_STEPS. The bump to feral 0.17.0 is
10074        // deliberately behaviour-preserving here — the cap that gh#710 wants
10075        // to measure (1) is not yet the default.
10076        assert_eq!(
10077            feral_config_from_options(app.options()).refine_max_steps,
10078            pounce_feral::FeralConfig::default().refine_max_steps,
10079            "unset feral_refine_steps must keep feral's own default"
10080        );
10081        // The setting gh#710 exists to evaluate.
10082        app.initialize_with_options_str("feral_refine_steps 1\n")
10083            .unwrap();
10084        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 1);
10085        // `0` is a legal cap (zero corrections, refined entry point still
10086        // taken) and must not be read as "unset".
10087        app.initialize_with_options_str("feral_refine_steps 0\n")
10088            .unwrap();
10089        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 0);
10090    }
10091
10092    #[test]
10093    fn feral_static_pivoting_option_reaches_config() {
10094        let mut app = IpoptApplication::new();
10095        app.initialize().unwrap();
10096        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10097        // which leaves it None (inherit feral's delayed-pivot default) when
10098        // the POUNCE_FERAL_STATIC_PIVOTING env var is also absent — so the
10099        // default numeric path is unchanged.
10100        assert_eq!(
10101            feral_config_from_options(app.options()).static_pivoting,
10102            None,
10103            "unset feral_static_pivoting must not force a numeric override"
10104        );
10105        // Explicit `yes` maps to Some(true): every supernode factors with
10106        // delayed pivoting disabled (feral#8 cascade breaker).
10107        app.initialize_with_options_str("feral_static_pivoting yes\n")
10108            .unwrap();
10109        assert_eq!(
10110            feral_config_from_options(app.options()).static_pivoting,
10111            Some(true)
10112        );
10113        // Explicit `no` maps to Some(false): keep delayed pivoting on
10114        // (distinct from unset, which merely inherits the default).
10115        app.initialize_with_options_str("feral_static_pivoting no\n")
10116            .unwrap();
10117        assert_eq!(
10118            feral_config_from_options(app.options()).static_pivoting,
10119            Some(false)
10120        );
10121    }
10122
10123    /// Convex equality NLP fixture for end-to-end SQP testing
10124    /// through `IpoptApplication`:
10125    ///
10126    ///     min ½(x₁² + x₂²) − x₁ − 2x₂  s.t.  x₁ + x₂ = 1
10127    ///
10128    /// Closed form: x* = (0, 1), obj = -1.5, λ_g = 1.
10129    struct ConvexEqTnlp {
10130        finalize_called: std::rc::Rc<std::cell::RefCell<Option<(Vec<Number>, Number)>>>,
10131    }
10132    impl TNLP for ConvexEqTnlp {
10133        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10134            Some(NlpInfo {
10135                n: 2,
10136                m: 1,
10137                nnz_jac_g: 2,
10138                nnz_h_lag: 2,
10139                index_style: IndexStyle::C,
10140            })
10141        }
10142        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10143            b.x_l.copy_from_slice(&[-2.0e19; 2]);
10144            b.x_u.copy_from_slice(&[2.0e19; 2]);
10145            b.g_l.copy_from_slice(&[1.0]);
10146            b.g_u.copy_from_slice(&[1.0]);
10147            true
10148        }
10149        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10150            sp.x.copy_from_slice(&[0.0, 0.0]);
10151            true
10152        }
10153        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
10154            Some(0.5 * (x[0] * x[0] + x[1] * x[1]) - x[0] - 2.0 * x[1])
10155        }
10156        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10157            grad[0] = x[0] - 1.0;
10158            grad[1] = x[1] - 2.0;
10159            true
10160        }
10161        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10162            g[0] = x[0] + x[1];
10163            true
10164        }
10165        fn eval_jac_g(
10166            &mut self,
10167            _x: Option<&[Number]>,
10168            _new_x: bool,
10169            mode: SparsityRequest<'_>,
10170        ) -> bool {
10171            match mode {
10172                SparsityRequest::Structure { irow, jcol } => {
10173                    irow.copy_from_slice(&[0, 0]);
10174                    jcol.copy_from_slice(&[0, 1]);
10175                }
10176                SparsityRequest::Values { values, .. } => {
10177                    values.copy_from_slice(&[1.0, 1.0]);
10178                }
10179            }
10180            true
10181        }
10182        fn eval_h(
10183            &mut self,
10184            _x: Option<&[Number]>,
10185            _new_x: bool,
10186            _obj_factor: Number,
10187            _lambda: Option<&[Number]>,
10188            _new_lambda: bool,
10189            mode: SparsityRequest<'_>,
10190        ) -> bool {
10191            match mode {
10192                SparsityRequest::Structure { irow, jcol } => {
10193                    irow.copy_from_slice(&[0, 1]);
10194                    jcol.copy_from_slice(&[0, 1]);
10195                }
10196                SparsityRequest::Values { values, .. } => {
10197                    values.copy_from_slice(&[1.0, 1.0]);
10198                }
10199            }
10200            true
10201        }
10202        fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
10203            *self.finalize_called.borrow_mut() = Some((sol.x.to_vec(), sol.obj_value));
10204        }
10205    }
10206
10207    /// A TNLP that solves normally once, then declines to supply bounds.
10208    ///
10209    /// The second `optimize_constrained` therefore bails long before the
10210    /// statistics block that records `row_scaling_active`, which is the
10211    /// path the fail-closed reset exists for.
10212    struct DescribesItselfOnce {
10213        /// Flipped by the test between the two solves. A call counter
10214        /// would not work: these hooks are called more than once per
10215        /// solve, so it would trip inside the first one.
10216        refuse: std::rc::Rc<std::cell::Cell<bool>>,
10217        inner: ExactQuadratic,
10218    }
10219    impl TNLP for DescribesItselfOnce {
10220        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10221            self.inner.get_nlp_info()
10222        }
10223        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10224            // Declining here is a documented TNLP outcome and unwinds
10225            // cleanly; declining `get_nlp_info` mid-flight panics instead,
10226            // which would test the panic path rather than the reset.
10227            if self.refuse.get() {
10228                return false;
10229            }
10230            self.inner.get_bounds_info(b)
10231        }
10232        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10233            self.inner.get_starting_point(sp)
10234        }
10235        fn eval_f(&mut self, x: &[Number], n: bool) -> Option<Number> {
10236            self.inner.eval_f(x, n)
10237        }
10238        fn eval_grad_f(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10239            self.inner.eval_grad_f(x, n, g)
10240        }
10241        fn eval_g(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10242            self.inner.eval_g(x, n, g)
10243        }
10244        fn eval_jac_g(&mut self, x: Option<&[Number]>, n: bool, mode: SparsityRequest<'_>) -> bool {
10245            self.inner.eval_jac_g(x, n, mode)
10246        }
10247        fn eval_h(
10248            &mut self,
10249            x: Option<&[Number]>,
10250            n: bool,
10251            o: Number,
10252            l: Option<&[Number]>,
10253            nl: bool,
10254            mode: SparsityRequest<'_>,
10255        ) -> bool {
10256            self.inner.eval_h(x, n, o, l, nl, mode)
10257        }
10258        fn finalize_solution(&mut self, s: Solution<'_>, d: &IpoptData, c: &IpoptCq) {
10259            self.inner.finalize_solution(s, d, c)
10260        }
10261    }
10262
10263    /// gh#794 review round 2: `row_scaling_active` must be fail-closed.
10264    ///
10265    /// It is written near the end of `optimize_constrained`, from the NLP
10266    /// that solve built. A solve that bails before that point used to
10267    /// leave the *previous* solve's value in place — and the ℓ₁ outer
10268    /// loop calls `optimize_constrained` repeatedly and reads the flag
10269    /// after each call, so a stale `Some(false)` would let it mirror an
10270    /// original-units violation into the scaled family. That is exactly
10271    /// the units contract the flag was added to protect.
10272    ///
10273    /// The two solves here are the shape that matters: the first records
10274    /// a verdict, the second never gets far enough to record one.
10275    /// Removing the reset at the top of `optimize_constrained` makes this
10276    /// fail with `Some(false)` where `None` is required — checked, not
10277    /// assumed.
10278    #[test]
10279    fn row_scaling_active_is_cleared_when_a_later_solve_bails_early() {
10280        let mut app = IpoptApplication::new();
10281        app.initialize().unwrap();
10282
10283        // Solve 1: reaches the statistics block and records a verdict.
10284        // `ExactQuadratic` supplies `eval_h`, so the solve stays on the
10285        // exact-Hessian NLP path that writes this flag; a fixture without
10286        // one lands on L-BFGS instead.
10287        let refuse = std::rc::Rc::new(std::cell::Cell::new(false));
10288        let first = std::rc::Rc::new(std::cell::RefCell::new(DescribesItselfOnce {
10289            refuse: std::rc::Rc::clone(&refuse),
10290            inner: ExactQuadratic,
10291        }));
10292        let _ = app
10293            .optimize_tnlp(std::rc::Rc::clone(&first) as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
10294        assert!(
10295            app.row_scaling_active.get().is_some(),
10296            "the first solve did not record a row-scaling verdict, so this \
10297             test cannot show the second one clearing it",
10298        );
10299
10300        // Solve 2, same application: bails before recording anything.
10301        refuse.set(true);
10302        let _ = app.optimize_tnlp(first as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
10303
10304        assert_eq!(
10305            app.row_scaling_active.get(),
10306            None,
10307            "a solve that bailed before recording row scaling left the \
10308             previous solve's verdict in place; the ℓ₁ outer loop would \
10309             read it as fact and mirror an original-units violation into \
10310             the scaled family (gh#794 review round 2)",
10311        );
10312    }
10313
10314    #[test]
10315    fn application_sqp_path_solves_convex_eq_nlp_and_finalizes() {
10316        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
10317        let tnlp = std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
10318            finalize_called: std::rc::Rc::clone(&finalize_slot),
10319        }));
10320
10321        let mut app = IpoptApplication::new();
10322        app.initialize().unwrap();
10323        app.initialize_with_options_str("algorithm active-set-sqp\n")
10324            .unwrap();
10325        let status = app.optimize_tnlp(tnlp);
10326        assert_eq!(status, ApplicationReturnStatus::SolveSucceeded);
10327
10328        // The TNLP's finalize_solution must have been invoked.
10329        let recv = finalize_slot.borrow().clone();
10330        let (x_recv, obj_recv) = recv.expect("finalize_solution was not called");
10331        assert_eq!(x_recv.len(), 2);
10332        assert!((x_recv[0] - 0.0).abs() < 1e-6, "x[0] = {}", x_recv[0]);
10333        assert!((x_recv[1] - 1.0).abs() < 1e-6, "x[1] = {}", x_recv[1]);
10334        assert!(
10335            (obj_recv - (-1.5)).abs() < 1e-6,
10336            "obj = {} but expected -1.5",
10337            obj_recv
10338        );
10339    }
10340
10341    #[test]
10342    fn application_routes_to_sqp_case_insensitively() {
10343        let mut app = IpoptApplication::new();
10344        app.initialize().unwrap();
10345        app.initialize_with_options_str("algorithm Active-Set-SQP\n")
10346            .unwrap();
10347        // get_string_value may return the value as-stored (no
10348        // normalization); the dispatch must handle case
10349        // insensitively per the c11 design choice.
10350        assert!(app.is_sqp_algorithm_selected());
10351    }
10352
10353    #[test]
10354    fn application_constructs_and_loads_options() {
10355        let mut app = IpoptApplication::new();
10356        app.initialize().unwrap();
10357        // ipopt.opt-style file: an integer-typed option registered by
10358        // the Interfaces layer.
10359        app.initialize_with_options_str("print_level 5\nfile_print_level 7\n")
10360            .unwrap();
10361        let (level, found) = app.options().get_integer_value("print_level", "").unwrap();
10362        assert!(found);
10363        assert_eq!(level, 5);
10364    }
10365
10366    #[test]
10367    fn application_sqp_suboptions_propagate_to_builder() {
10368        // All SQP suboptions are read by algorithm_builder_snapshot
10369        // and baked into the builder's `sqp` field.
10370        let mut app = IpoptApplication::new();
10371        app.initialize().unwrap();
10372        app.initialize_with_options_str(
10373            "algorithm active-set-sqp\n\
10374             sqp_globalization l1-elastic\n\
10375             sqp_hessian lbfgs\n\
10376             sqp_max_iter 17\n\
10377             sqp_tol 1e-7\n\
10378             sqp_constr_viol_tol 1e-5\n\
10379             sqp_dual_inf_tol 1e-3\n\
10380             sqp_l1_penalty 2.5\n\
10381             sqp_bt_reduction 0.25\n\
10382             sqp_bt_min_alpha 1e-10\n\
10383             sqp_print_level 2\n\
10384             sqp_lbfgs_max_history 12\n",
10385        )
10386        .unwrap();
10387        let snap = app.algorithm_builder_snapshot();
10388        assert_eq!(
10389            snap.sqp.globalization,
10390            crate::sqp::SqpGlobalization::L1Elastic
10391        );
10392        assert_eq!(snap.sqp.hessian, crate::sqp::SqpHessianSource::Lbfgs);
10393        assert_eq!(snap.sqp.max_iter, 17);
10394        assert!((snap.sqp.tol - 1e-7).abs() < 1e-18);
10395        assert!((snap.sqp.constr_viol_tol - 1e-5).abs() < 1e-18);
10396        assert!((snap.sqp.dual_inf_tol - 1e-3).abs() < 1e-18);
10397        assert!((snap.sqp.l1_penalty - 2.5).abs() < 1e-18);
10398        assert!((snap.sqp.bt_reduction - 0.25).abs() < 1e-18);
10399        assert!((snap.sqp.bt_min_alpha - 1e-10).abs() < 1e-18);
10400        assert_eq!(snap.sqp.print_level, 2);
10401        assert_eq!(snap.sqp.lbfgs_max_history, 12);
10402    }
10403
10404    /// Every `sqp_qp_*` key that [`apply_qp_subproblem_options`] reads must
10405    /// actually be *registered*, and must reach `pounce_qp::QpOptions`.
10406    ///
10407    /// The whole family was readable-but-unregistered (gh #360): the options
10408    /// registry rejected each one with OPTION_INVALID, so the reader was
10409    /// unreachable and the documented knobs were unusable. This is the guard
10410    /// that class of omission needs — it fails both if a key stops being
10411    /// registered and if a newly-read key is never registered at all.
10412    #[test]
10413    fn application_sqp_qp_subproblem_options_are_registered_and_propagate() {
10414        use pounce_qp::AntiCyclingChoice;
10415
10416        // Source of truth: the keys `apply_qp_subproblem_options` reads.
10417        // Kept in step with that function by the round-trip assertions below.
10418        let mut app = IpoptApplication::new();
10419        app.initialize().unwrap();
10420        app.initialize_with_options_str(
10421            "algorithm active-set-sqp\n\
10422             sqp_qp_max_iter 37\n\
10423             sqp_qp_feas_tol 1e-7\n\
10424             sqp_qp_opt_tol 2e-7\n\
10425             sqp_qp_elastic_gamma 1e4\n\
10426             sqp_qp_anti_cycling bland\n\
10427             sqp_qp_use_schur_updates yes\n\
10428             sqp_qp_max_schur_updates_before_refactor 12\n\
10429             sqp_qp_use_homotopy yes\n\
10430             sqp_qp_certify_second_order yes\n",
10431        )
10432        .expect("every sqp_qp_* option must be registered (gh #360)");
10433
10434        let qp = &app.algorithm_builder_snapshot().sqp_qp;
10435        assert_eq!(qp.max_iter, 37);
10436        assert!((qp.feas_tol - 1e-7).abs() < 1e-20);
10437        assert!((qp.opt_tol - 2e-7).abs() < 1e-20);
10438        assert!((qp.elastic_gamma - 1e4).abs() < 1e-9);
10439        assert_eq!(qp.anti_cycling, AntiCyclingChoice::Bland);
10440        // The Schur update path was implemented but reachable only through
10441        // `SqpAlgorithm::with_qp_options`, so no CLI/library user could turn
10442        // it on — the same unreachable-knob defect gh #360 fixed for the rest
10443        // of this family.
10444        assert!(qp.use_schur_updates);
10445        assert_eq!(qp.max_schur_updates_before_refactor, 12);
10446        assert!(qp.use_homotopy);
10447        // gh #848. Off by default on this path (see
10448        // `QpOptions::sqp_subproblem`), so the value that proves the wire is
10449        // live is `yes` — asserting the default would pass on a reader that
10450        // never ran.
10451        assert!(qp.certify_second_order);
10452
10453        // Untouched options must keep the SQP subproblem base, not be
10454        // overwritten with zeros by the "explicitly set" gate. That base is
10455        // `QpOptions::default()` in every field but one; the exception is
10456        // asserted below.
10457        let mut app = IpoptApplication::new();
10458        app.initialize().unwrap();
10459        app.initialize_with_options_str("algorithm active-set-sqp\n")
10460            .unwrap();
10461        let defaults = pounce_qp::QpOptions::default();
10462        let qp = &app.algorithm_builder_snapshot().sqp_qp;
10463        assert_eq!(qp.max_iter, defaults.max_iter);
10464        assert!((qp.feas_tol - defaults.feas_tol).abs() < 1e-20);
10465        assert!((qp.opt_tol - defaults.opt_tol).abs() < 1e-20);
10466        assert_eq!(qp.anti_cycling, defaults.anti_cycling);
10467        // Default stays OFF, and that is a measured choice: enabling it breaks
10468        // 9 of the 46 Maros-Meszaros instances the default path solves
10469        // correctly. Do not flip this without re-running that comparison.
10470        assert!(!qp.use_schur_updates);
10471        assert_eq!(
10472            qp.max_schur_updates_before_refactor,
10473            defaults.max_schur_updates_before_refactor
10474        );
10475        // Off by default *on the SQP path*, and deliberately different from
10476        // `QpOptions::default()` — which is what a standalone `solve_qp`
10477        // gets, and where it is on. gh #848 / gh #856.
10478        assert!(!qp.certify_second_order);
10479        assert!(pounce_qp::QpOptions::default().certify_second_order);
10480    }
10481
10482    /// The other direction of the gh #360 guard: every **registered**
10483    /// `sqp_qp_*` option must be one `apply_qp_subproblem_options` actually
10484    /// reads.
10485    ///
10486    /// The sister test above checks read-keys-are-registered. It cannot catch
10487    /// the inverse, and the inverse happened: `sqp_qp_use_homotopy` was
10488    /// registered with the homotopy work and never wired into the reader, so
10489    /// setting it on the SQP path silently did nothing while the option's own
10490    /// documentation described what it would do. A registered knob that no
10491    /// code reads is worse than a missing one — it validates, it accepts a
10492    /// value, and it lies.
10493    ///
10494    /// Adding a new `sqp_qp_*` option therefore fails here until it is both
10495    /// read by `apply_qp_subproblem_options` and asserted in the round-trip
10496    /// test above.
10497    #[test]
10498    fn application_every_registered_sqp_qp_option_is_read_by_the_subproblem_reader() {
10499        let mut app = IpoptApplication::new();
10500        app.initialize().unwrap();
10501
10502        let mut registered: Vec<String> = app
10503            .registered_options()
10504            .registered_options_in_order()
10505            .iter()
10506            .map(|o| o.name.clone())
10507            .filter(|n| n.starts_with("sqp_qp_"))
10508            .collect();
10509        registered.sort();
10510
10511        // Kept in step by hand with the `options.get_*_value("sqp_qp_…")`
10512        // calls in `apply_qp_subproblem_options`, and cross-checked by the
10513        // round-trip assertions in the sister test.
10514        let mut read_by_the_reader = vec![
10515            "sqp_qp_anti_cycling".to_string(),
10516            "sqp_qp_certify_second_order".to_string(),
10517            "sqp_qp_elastic_gamma".to_string(),
10518            "sqp_qp_feas_tol".to_string(),
10519            "sqp_qp_max_iter".to_string(),
10520            "sqp_qp_max_schur_updates_before_refactor".to_string(),
10521            "sqp_qp_opt_tol".to_string(),
10522            "sqp_qp_use_homotopy".to_string(),
10523            "sqp_qp_use_schur_updates".to_string(),
10524        ];
10525        read_by_the_reader.sort();
10526
10527        assert_eq!(
10528            registered, read_by_the_reader,
10529            "registered sqp_qp_* options and the ones \
10530             `apply_qp_subproblem_options` reads have diverged. A key that is \
10531             registered but unread is a no-op knob with working documentation \
10532             (that is how `sqp_qp_use_homotopy` shipped); a key read but not \
10533             registered is gh #360. Wire it up in both places, assert it in \
10534             `application_sqp_qp_subproblem_options_are_registered_and_propagate`, \
10535             then add it here."
10536        );
10537    }
10538
10539    #[test]
10540    fn application_sqp_hessian_approximation_maps_to_damped_bfgs() {
10541        // The frontend sets `hessian_approximation = limited-memory` when no
10542        // exact Lagrangian Hessian is available (e.g. `pounce.minimize` with
10543        // no `hess`). On the active-set-SQP path that must resolve to the
10544        // dense Powell-damped BFGS, NOT the limited-memory update: L-BFGS
10545        // materializes the same dense Hessian for the QP subproblem yet stalls
10546        // (`Search_Direction_Becomes_Too_Small` / wrong `x`) on convex QPs with
10547        // an active inequality (issue #358); damped-BFGS solves them.
10548        let mut app = IpoptApplication::new();
10549        app.initialize().unwrap();
10550        app.initialize_with_options_str(
10551            "algorithm active-set-sqp\n\
10552             hessian_approximation limited-memory\n",
10553        )
10554        .unwrap();
10555        assert_eq!(
10556            app.algorithm_builder_snapshot().sqp.hessian,
10557            crate::sqp::SqpHessianSource::DampedBfgs
10558        );
10559
10560        // An explicit `sqp_hessian = lbfgs` is still honored (it is read after
10561        // `hessian_approximation`, so it wins): callers who genuinely want the
10562        // limited-memory update can still ask for it.
10563        let mut app = IpoptApplication::new();
10564        app.initialize().unwrap();
10565        app.initialize_with_options_str(
10566            "algorithm active-set-sqp\n\
10567             hessian_approximation limited-memory\n\
10568             sqp_hessian lbfgs\n",
10569        )
10570        .unwrap();
10571        assert_eq!(
10572            app.algorithm_builder_snapshot().sqp.hessian,
10573            crate::sqp::SqpHessianSource::Lbfgs
10574        );
10575    }
10576
10577    /// `builder.linear_solver` must name the backend that will actually be
10578    /// built, not the one the option string asked for.
10579    ///
10580    /// MA57 is behind the optional `ma57` cargo feature; without it
10581    /// `default_backend_factory` silently substitutes FERAL. Recording `Ma57`
10582    /// anyway made the field disagree with reality, and the Schur KKT gate in
10583    /// `alg_builder::build_with_backend` (which tests `== Feral`) consumed that
10584    /// disagreement — so `set_kkt_schur_block()` never engaged on the default
10585    /// pure-Rust build for any user, while the transparent fallback kept every
10586    /// answer correct and every test green.
10587    #[test]
10588    fn application_linear_solver_records_the_effective_backend() {
10589        // Default options resolve to FERAL in *every* build. The registry
10590        // used to default to upstream's "ma57", which meant an HSL build
10591        // silently ran MA57 without being asked and a pure-Rust build
10592        // advertised a backend it did not contain; the default now names
10593        // pounce's own solver and HSL is opt-in (gh#483 follow-up).
10594        let mut app = IpoptApplication::new();
10595        app.initialize().unwrap();
10596        assert_eq!(
10597            app.algorithm_builder_from_options().linear_solver,
10598            LinearSolverChoice::Feral,
10599            "the registered default is `feral`, in an ma57 build too"
10600        );
10601
10602        // An explicit ma57 request resolves the same way.
10603        let mut app = IpoptApplication::new();
10604        app.initialize().unwrap();
10605        app.initialize_with_options_str("linear_solver ma57\n")
10606            .unwrap();
10607        let got = app.algorithm_builder_from_options().linear_solver;
10608        if cfg!(feature = "ma57") {
10609            assert_eq!(got, LinearSolverChoice::Ma57);
10610        } else {
10611            assert_eq!(got, LinearSolverChoice::Feral);
10612        }
10613
10614        // An explicit feral request is honored in every build.
10615        let mut app = IpoptApplication::new();
10616        app.initialize().unwrap();
10617        app.initialize_with_options_str("linear_solver feral\n")
10618            .unwrap();
10619        assert_eq!(
10620            app.algorithm_builder_from_options().linear_solver,
10621            LinearSolverChoice::Feral
10622        );
10623    }
10624
10625    /// gh#746. `IpAlgBuilder.cpp:1059` substitutes `adaptive` for the
10626    /// registered `monotone` when `hessian_approximation` is
10627    /// limited-memory and the caller left `mu_strategy` alone. pounce
10628    /// read the registered default unconditionally, which is a
10629    /// different barrier schedule on the whole quasi-Newton arm.
10630    #[test]
10631    fn limited_memory_defaults_mu_strategy_to_adaptive() {
10632        // Exact Hessian, nothing set: monotone, as registered.
10633        let mut app = IpoptApplication::new();
10634        app.initialize().unwrap();
10635        assert_eq!(
10636            app.algorithm_builder_from_options().mu_strategy,
10637            MuStrategyChoice::Monotone,
10638            "the exact arm must keep the registered default"
10639        );
10640
10641        // Limited memory, nothing set: adaptive.
10642        let mut app = IpoptApplication::new();
10643        app.initialize().unwrap();
10644        app.initialize_with_options_str("hessian_approximation limited-memory\n")
10645            .unwrap();
10646        assert_eq!(
10647            app.algorithm_builder_from_options().mu_strategy,
10648            MuStrategyChoice::Adaptive,
10649            "limited-memory must take upstream's quasi-Newton default"
10650        );
10651
10652        // An explicit `monotone` still wins — the substitution is only
10653        // for an absent option.
10654        let mut app = IpoptApplication::new();
10655        app.initialize().unwrap();
10656        app.initialize_with_options_str(
10657            "hessian_approximation limited-memory\n\
10658             mu_strategy monotone\n",
10659        )
10660        .unwrap();
10661        assert_eq!(
10662            app.algorithm_builder_from_options().mu_strategy,
10663            MuStrategyChoice::Monotone,
10664            "an explicit mu_strategy must not be overridden"
10665        );
10666    }
10667
10668    /// The μ-strategy auto-fallback retries with the *other* strategy.
10669    /// Under limited-memory the first attempt is adaptive, so the flip
10670    /// has to be monotone — reading the registered default there would
10671    /// re-run the strategy that just stalled (gh#746).
10672    #[test]
10673    fn fallback_flip_follows_the_resolved_mu_strategy() {
10674        let mut app = IpoptApplication::new();
10675        app.initialize().unwrap();
10676        assert!(
10677            !app.effective_mu_strategy_is_adaptive(),
10678            "unset + exact resolves to monotone"
10679        );
10680
10681        let mut app = IpoptApplication::new();
10682        app.initialize().unwrap();
10683        app.initialize_with_options_str("hessian_approximation limited-memory\n")
10684            .unwrap();
10685        assert!(
10686            app.effective_mu_strategy_is_adaptive(),
10687            "unset + limited-memory resolves to adaptive"
10688        );
10689
10690        let mut app = IpoptApplication::new();
10691        app.initialize().unwrap();
10692        app.initialize_with_options_str(
10693            "hessian_approximation limited-memory\n\
10694             mu_strategy monotone\n",
10695        )
10696        .unwrap();
10697        assert!(
10698            !app.effective_mu_strategy_is_adaptive(),
10699            "an explicit monotone under limited-memory resolves to monotone"
10700        );
10701    }
10702
10703    #[test]
10704    fn application_limited_memory_options_propagate_to_builder() {
10705        use crate::hess::lim_mem_quasi_newton::UpdateType;
10706
10707        // Default: no options set -> bit-exact with Ipopt's default
10708        // (bfgs, history 6). This is what the IPM path runs unless the
10709        // user opts in, so it must not drift.
10710        let mut app = IpoptApplication::new();
10711        app.initialize().unwrap();
10712        let def = app.algorithm_builder_from_options();
10713        assert_eq!(def.limited_memory_update_type, UpdateType::Bfgs);
10714        assert_eq!(def.limited_memory_max_history, 6);
10715
10716        // `limited_memory_update_type=sr1` and a custom history length
10717        // must reach the builder (these were registered upstream but
10718        // read nowhere on the IPM path before — see #131). Honoring
10719        // them is what lets SR1 break the monotone L-BFGS stall.
10720        let mut app = IpoptApplication::new();
10721        app.initialize().unwrap();
10722        app.initialize_with_options_str(
10723            "hessian_approximation limited-memory\n\
10724             limited_memory_update_type sr1\n\
10725             limited_memory_max_history 9\n",
10726        )
10727        .unwrap();
10728        let snap = app.algorithm_builder_from_options();
10729        assert_eq!(snap.limited_memory_update_type, UpdateType::Sr1);
10730        assert_eq!(snap.limited_memory_max_history, 9);
10731    }
10732
10733    #[test]
10734    fn application_recalc_y_is_wired_and_defaults_off() {
10735        // #677. Upstream registers `recalc_y` as `no`, but its option
10736        // text ends "If a limited memory quasi-Newton option is chosen,
10737        // this is used by default" — the effective default is
10738        // conditional on the Hessian approximation. pounce refused the
10739        // option outright before this, so an L-BFGS user had no way to
10740        // reach Ipopt's behaviour.
10741
10742        // Exact Hessian: off, matching the registered default.
10743        let mut app = IpoptApplication::new();
10744        app.initialize().unwrap();
10745        let b = app.algorithm_builder_from_options();
10746        assert!(!b.recalc_y, "exact-Hessian default must stay off");
10747        assert_eq!(b.recalc_y_feas_tol, 1e-6, "default changed");
10748
10749        // Limited memory: also off. Upstream's option text says it is
10750        // used by default there; pounce deliberately does not, because
10751        // auto-enabling took 7 of 57 fixtures from solved to not solved
10752        // on the L-BFGS leg with nothing moving the other way. See the
10753        // read site in `algorithm_builder_from_options`. If this
10754        // assertion is what fails, the auto-enable is being restored —
10755        // re-run `scripts/sweep-fixtures.sh` and explain those 7 first.
10756        let mut app = IpoptApplication::new();
10757        app.initialize().unwrap();
10758        app.initialize_with_options_str("hessian_approximation limited-memory\n")
10759            .unwrap();
10760        assert!(
10761            !app.algorithm_builder_from_options().recalc_y,
10762            "limited-memory must not silently enable recalc_y"
10763        );
10764
10765        // An explicit `yes` reaches the exact-Hessian path, which
10766        // used to be refused as unimplemented.
10767        let mut app = IpoptApplication::new();
10768        app.initialize().unwrap();
10769        app.initialize_with_options_str("recalc_y yes\nrecalc_y_feas_tol 1e-3\n")
10770            .unwrap();
10771        let b = app.algorithm_builder_from_options();
10772        assert!(b.recalc_y);
10773        assert_eq!(b.recalc_y_feas_tol, 1e-3);
10774    }
10775
10776    #[test]
10777    fn application_limited_memory_initialization_propagates_to_builder() {
10778        use crate::hess::lim_mem_quasi_newton::InitialApprox;
10779
10780        // #677: registered with upstream's `scalar1` default and read
10781        // nowhere, so every limited-memory solve ran `scalar2` and
10782        // setting the option was a silent no-op. Each keyword must now
10783        // reach the builder.
10784        for (kw, want) in [
10785            ("scalar1", InitialApprox::Scalar1),
10786            ("scalar2", InitialApprox::Scalar2),
10787            ("scalar3", InitialApprox::Scalar3),
10788            ("scalar4", InitialApprox::Scalar4),
10789            ("constant", InitialApprox::Constant),
10790            ("history-max", InitialApprox::HistoryMax),
10791        ] {
10792            let mut app = IpoptApplication::new();
10793            app.initialize().unwrap();
10794            app.initialize_with_options_str(&format!(
10795                "hessian_approximation limited-memory\n\
10796                 limited_memory_initialization {kw}\n"
10797            ))
10798            .unwrap();
10799            assert_eq!(
10800                app.algorithm_builder_from_options()
10801                    .limited_memory_initialization,
10802                want,
10803                "limited_memory_initialization={kw} did not reach the builder"
10804            );
10805        }
10806
10807        // `limited_memory_init_val` was unread too — the empty-history
10808        // branch hard-coded the same 1.0, so the miss was invisible.
10809        let mut app = IpoptApplication::new();
10810        app.initialize().unwrap();
10811        app.initialize_with_options_str(
10812            "hessian_approximation limited-memory\n\
10813             limited_memory_init_val 4.5\n",
10814        )
10815        .unwrap();
10816        assert_eq!(
10817            app.algorithm_builder_from_options().limited_memory_init_val,
10818            4.5
10819        );
10820
10821        // The effective default matches the registry and Ipopt
10822        // (`scalar1`). This is the assertion that would have caught #677
10823        // when the option was first registered: it pins the *selection*,
10824        // which the per-formula tests in `lim_mem_quasi_newton` cannot
10825        // see. Do not relax it to make an unrelated change pass.
10826        let mut app = IpoptApplication::new();
10827        app.initialize().unwrap();
10828        let def = app.algorithm_builder_from_options();
10829        assert_eq!(def.limited_memory_initialization, InitialApprox::Scalar1);
10830        assert_eq!(def.limited_memory_init_val, 1.0);
10831    }
10832
10833    #[test]
10834    fn application_sqp_warm_start_round_trip() {
10835        // Drive the convex-equality TNLP through the SQP path
10836        // twice. The first solve produces a working set; the
10837        // second is warm-started from it. The second must converge
10838        // with zero QP solves (the first KKT check declares
10839        // optimality immediately).
10840        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
10841        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
10842            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
10843                finalize_called: std::rc::Rc::clone(&finalize_slot),
10844            }));
10845
10846        let mut app = IpoptApplication::new();
10847        app.initialize().unwrap();
10848        app.initialize_with_options_str("algorithm active-set-sqp\n")
10849            .unwrap();
10850
10851        // Cold solve.
10852        let status_a = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
10853        assert_eq!(status_a, ApplicationReturnStatus::SolveSucceeded);
10854        let ws = app.last_sqp_working_set().cloned();
10855        assert!(ws.is_some(), "cold solve must yield a working set");
10856
10857        // Build the warm-start iterate from the converged finalize
10858        // payload (just x; pad multipliers to 0 since the test
10859        // problem is convex).
10860        let (x_recv, _) = finalize_slot.borrow().clone().unwrap();
10861        let warm = crate::sqp::SqpIterates {
10862            x: x_recv,
10863            lambda_g: vec![1.0],
10864            lambda_x: vec![0.0, 0.0],
10865            working: ws,
10866        };
10867        app.set_sqp_warm_start(warm);
10868
10869        // Warm solve.
10870        let status_b = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
10871        assert_eq!(status_b, ApplicationReturnStatus::SolveSucceeded);
10872        assert!(app.last_sqp_working_set().is_some());
10873    }
10874
10875    #[test]
10876    fn application_sqp_warm_start_auto_clears_after_use() {
10877        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
10878        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
10879            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
10880                finalize_called: std::rc::Rc::clone(&finalize_slot),
10881            }));
10882        let mut app = IpoptApplication::new();
10883        app.initialize().unwrap();
10884        app.initialize_with_options_str("algorithm active-set-sqp\n")
10885            .unwrap();
10886        app.set_sqp_warm_start(crate::sqp::SqpIterates {
10887            x: vec![0.0, 1.0],
10888            lambda_g: vec![1.0],
10889            lambda_x: vec![0.0, 0.0],
10890            working: None,
10891        });
10892        assert!(app.sqp_warm_start.is_some());
10893        let _ = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
10894        assert!(
10895            app.sqp_warm_start.is_none(),
10896            "warm-start input must be auto-cleared after use"
10897        );
10898    }
10899
10900    #[test]
10901    fn application_sqp_suboptions_default_when_unset() {
10902        // Without any sqp_* settings, the snapshot should equal
10903        // SqpOptions::default().
10904        let mut app = IpoptApplication::new();
10905        app.initialize().unwrap();
10906        let snap = app.algorithm_builder_snapshot();
10907        let d = crate::sqp::SqpOptions::default();
10908        assert_eq!(snap.sqp.globalization, d.globalization);
10909        assert_eq!(snap.sqp.hessian, d.hessian);
10910        assert_eq!(snap.sqp.max_iter, d.max_iter);
10911        assert!((snap.sqp.tol - d.tol).abs() < 1e-18);
10912        assert!((snap.sqp.constr_viol_tol - d.constr_viol_tol).abs() < 1e-18);
10913        assert!((snap.sqp.dual_inf_tol - d.dual_inf_tol).abs() < 1e-18);
10914        assert!((snap.sqp.l1_penalty - d.l1_penalty).abs() < 1e-18);
10915        assert!((snap.sqp.bt_reduction - d.bt_reduction).abs() < 1e-18);
10916        assert!((snap.sqp.bt_min_alpha - d.bt_min_alpha).abs() < 1e-18);
10917        assert_eq!(snap.sqp.print_level, d.print_level);
10918        assert_eq!(snap.sqp.lbfgs_max_history, d.lbfgs_max_history);
10919    }
10920
10921    #[test]
10922    fn application_reports_problem_dimensions() {
10923        let app = IpoptApplication::new();
10924        let mut tnlp = Hs071Stub;
10925        let info = app.problem_dimensions(&mut tnlp).unwrap();
10926        assert_eq!(info.n, 4);
10927        assert_eq!(info.m, 2);
10928        assert_eq!(info.nnz_jac_g, 8);
10929        assert_eq!(info.nnz_h_lag, 10);
10930    }
10931
10932    /// Each of the four constant-derivative hints reaches the algorithm,
10933    /// and reaches its *own* slot (#551 / #677).
10934    ///
10935    /// All four were wired and consumed — gh#588 Q6 made pounce exploit
10936    /// them — but the read site looped over
10937    /// `constant_derivatives::HINT_OPTIONS`, so the registered-but-unread
10938    /// scan saw a loop variable where it needs a literal key and reported
10939    /// all four as silent no-ops. They are literals now, and this pins
10940    /// what a literal-per-name rewrite can get wrong that a loop could
10941    /// not: setting one hint must light up that hint's slot and no other,
10942    /// because `reconcile` pairs `asserted[k]` with the model's proof for
10943    /// `HINT_OPTIONS[k]` and a transposed pair would reuse the wrong
10944    /// derivative.
10945    #[test]
10946    fn each_constant_derivative_hint_lights_up_its_own_slot() {
10947        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
10948
10949        let app = IpoptApplication::new();
10950        assert_eq!(
10951            app.asserted_constant_derivative_hints(),
10952            [false; 4],
10953            "no hint is asserted on a fresh options list",
10954        );
10955
10956        for (k, name) in HINT_OPTIONS.iter().enumerate() {
10957            let mut app = IpoptApplication::new();
10958            app.initialize().unwrap();
10959            app.initialize_with_options_str(&format!("{name} yes\n"))
10960                .unwrap();
10961            let mut expected = [false; 4];
10962            expected[k] = true;
10963            assert_eq!(
10964                app.asserted_constant_derivative_hints(),
10965                expected,
10966                "`{name}=yes` must set slot {k} and nothing else",
10967            );
10968
10969            // …and the registered default asks for nothing, so an
10970            // `ipopt.opt` that spells it out changes no derivative reuse.
10971            let mut app = IpoptApplication::new();
10972            app.initialize().unwrap();
10973            app.initialize_with_options_str(&format!("{name} no\n"))
10974                .unwrap();
10975            assert_eq!(
10976                app.asserted_constant_derivative_hints(),
10977                [false; 4],
10978                "`{name}=no` is the registered default and asserts nothing",
10979            );
10980        }
10981    }
10982
10983    /// `min x²` on `[-10, 10]` from `x = 1`, with an *exactly correct*
10984    /// gradient `2x`. Unconstrained and one-dimensional so the only
10985    /// thing the derivative checker can react to is its own step size
10986    /// and threshold.
10987    ///
10988    /// The forward difference at step `h` is `((1+h)² − 1)/h = 2 + h`,
10989    /// so the deviation from the analytic `2` is exactly `h`, and the
10990    /// relative test flags it when `h > tol·(2 + h)`. That makes the
10991    /// verdict a closed-form function of the two knobs under test.
10992    struct ExactQuadratic;
10993    impl TNLP for ExactQuadratic {
10994        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10995            Some(NlpInfo {
10996                n: 1,
10997                m: 0,
10998                nnz_jac_g: 0,
10999                nnz_h_lag: 0,
11000                index_style: IndexStyle::C,
11001            })
11002        }
11003        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
11004            b.x_l.copy_from_slice(&[-10.0]);
11005            b.x_u.copy_from_slice(&[10.0]);
11006            true
11007        }
11008        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
11009            sp.x.copy_from_slice(&[1.0]);
11010            true
11011        }
11012        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
11013            Some(x[0] * x[0])
11014        }
11015        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11016            grad[0] = 2.0 * x[0];
11017            true
11018        }
11019        fn eval_g(&mut self, _x: &[Number], _new_x: bool, _g: &mut [Number]) -> bool {
11020            true
11021        }
11022        fn eval_jac_g(
11023            &mut self,
11024            _x: Option<&[Number]>,
11025            _new_x: bool,
11026            _mode: SparsityRequest<'_>,
11027        ) -> bool {
11028            true
11029        }
11030        fn eval_h(
11031            &mut self,
11032            _x: Option<&[Number]>,
11033            _new_x: bool,
11034            _obj_factor: Number,
11035            _lambda: Option<&[Number]>,
11036            _new_lambda: bool,
11037            _mode: SparsityRequest<'_>,
11038        ) -> bool {
11039            true
11040        }
11041        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11042    }
11043
11044    struct RecordingQuadratic {
11045        gradient_points: Rc<RefCell<Vec<Number>>>,
11046        objective_points: Rc<RefCell<Vec<Number>>>,
11047        x_scaling: Number,
11048    }
11049
11050    impl TNLP for RecordingQuadratic {
11051        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
11052            ExactQuadratic.get_nlp_info()
11053        }
11054
11055        fn get_bounds_info(&mut self, bounds: BoundsInfo<'_>) -> bool {
11056            ExactQuadratic.get_bounds_info(bounds)
11057        }
11058
11059        fn get_starting_point(&mut self, start: StartingPoint<'_>) -> bool {
11060            ExactQuadratic.get_starting_point(start)
11061        }
11062
11063        fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
11064            self.objective_points.borrow_mut().push(x[0]);
11065            ExactQuadratic.eval_f(x, new_x)
11066        }
11067
11068        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11069            self.gradient_points.borrow_mut().push(x[0]);
11070            grad[0] = 2.0 * x[0];
11071            true
11072        }
11073
11074        fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
11075            ExactQuadratic.eval_g(x, new_x, g)
11076        }
11077
11078        fn eval_jac_g(
11079            &mut self,
11080            x: Option<&[Number]>,
11081            new_x: bool,
11082            mode: SparsityRequest<'_>,
11083        ) -> bool {
11084            ExactQuadratic.eval_jac_g(x, new_x, mode)
11085        }
11086
11087        fn get_scaling_parameters(&mut self, req: ScalingRequest<'_>) -> bool {
11088            *req.obj_scaling = 1.0;
11089            *req.use_x_scaling = true;
11090            req.x_scaling[0] = self.x_scaling;
11091            *req.use_g_scaling = false;
11092            true
11093        }
11094
11095        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11096    }
11097
11098    fn derivative_test_verdict(extra: &str) -> pounce_nlp::derivative_test::DerivativeTestReport {
11099        let mut app = IpoptApplication::new();
11100        app.initialize().unwrap();
11101        app.initialize_with_options_str(&format!("derivative_test first-order\n{extra}"))
11102            .unwrap();
11103        let opts = app.derivative_test_options();
11104        pounce_nlp::derivative_test::run(&mut ExactQuadratic, &opts).expect("a report")
11105    }
11106
11107    /// `derivative_test_perturbation` and `derivative_test_tol` were
11108    /// registered, read into [`DerivativeTestOptions`], and consumed by
11109    /// the checker — but nothing proved a *set value* reached it, which
11110    /// is the only assertion that distinguishes a read site from a
11111    /// parse-and-discard (#677, #551).
11112    ///
11113    /// Each of the three verdicts below differs from the one above it by
11114    /// exactly one option, so a knob that stopped reaching the checker
11115    /// would collapse two of them together and fail here.
11116    #[test]
11117    fn the_derivative_checker_knobs_change_the_verdict() {
11118        // Registered defaults (1e-8 / 1e-4), which are also the read
11119        // site's fallbacks: a correct gradient looks correct.
11120        let clean = derivative_test_verdict("");
11121        assert_eq!(clean.checked, 1);
11122        assert_eq!(clean.suspicious, 0, "{:#?}", clean.lines);
11123
11124        // A coarse step makes the *same correct gradient* look wrong:
11125        // deviation 0.5 > 1e-4·2.5. Only `derivative_test_perturbation`
11126        // changed, so this is that option and nothing else.
11127        let coarse = derivative_test_verdict("derivative_test_perturbation 0.5\n");
11128        assert_eq!(coarse.checked, 1);
11129        assert_eq!(
11130            coarse.suspicious, 1,
11131            "derivative_test_perturbation never reached the checker: {:#?}",
11132            coarse.lines,
11133        );
11134
11135        // …and loosening the threshold at that same coarse step clears
11136        // it again: 0.5 < 0.5·2.5. Only `derivative_test_tol` changed.
11137        let tolerant =
11138            derivative_test_verdict("derivative_test_perturbation 0.5\nderivative_test_tol 0.5\n");
11139        assert_eq!(tolerant.checked, 1);
11140        assert_eq!(
11141            tolerant.suspicious, 0,
11142            "derivative_test_tol never reached the checker: {:#?}",
11143            tolerant.lines,
11144        );
11145
11146        // The report also prints what it used, so a user reading the
11147        // output can tell which step and threshold produced the verdict.
11148        assert!(
11149            tolerant.lines[0].contains("5.0e-1"),
11150            "{:#?}",
11151            tolerant.lines,
11152        );
11153    }
11154
11155    #[test]
11156    fn ordinary_derivative_test_keeps_the_conditioned_start() {
11157        let gradient_points = Rc::new(RefCell::new(Vec::new()));
11158        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11159            gradient_points: Rc::clone(&gradient_points),
11160            objective_points: Rc::new(RefCell::new(Vec::new())),
11161            x_scaling: 1.0,
11162        })) as Rc<RefCell<dyn TNLP>>;
11163        let mut app = IpoptApplication::new();
11164        app.initialize().unwrap();
11165        app.initialize_with_options_str(
11166            "derivative_test first-order\n\
11167             start_point_perturbation 0.5\n\
11168             hessian_approximation limited-memory\n\
11169             max_iter 0\n\
11170             print_level 0\n",
11171        )
11172        .unwrap();
11173
11174        let _ = app.optimize_tnlp(tnlp);
11175
11176        let first = gradient_points.borrow()[0];
11177        assert!((first - 1.7666216164272852).abs() < 1e-12, "{first}");
11178    }
11179
11180    #[test]
11181    fn ordinary_derivative_test_keeps_variable_scaling() {
11182        let objective_points = Rc::new(RefCell::new(Vec::new()));
11183        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11184            gradient_points: Rc::new(RefCell::new(Vec::new())),
11185            objective_points: Rc::clone(&objective_points),
11186            x_scaling: 0.5,
11187        })) as Rc<RefCell<dyn TNLP>>;
11188        let mut app = IpoptApplication::new();
11189        app.initialize().unwrap();
11190        app.initialize_with_options_str(
11191            "derivative_test first-order\n\
11192             derivative_test_perturbation 0.5\n\
11193             nlp_scaling_method user-scaling\n\
11194             hessian_approximation limited-memory\n\
11195             max_iter 0\n\
11196             print_level 0\n",
11197        )
11198        .unwrap();
11199
11200        let _ = app.optimize_tnlp(tnlp);
11201
11202        assert_eq!(&objective_points.borrow()[..2], &[1.0, 2.0]);
11203    }
11204
11205    // ---- gh#887: the dominance gate ------------------------------------
11206    //
11207    // These pin the rule directly, on numbers measured off real runs,
11208    // because the fixture that motivated the gate turned out not to be a
11209    // portable witness for it. `deb7` on the L-BFGS leg with
11210    // `limited_memory_ls_failure_restarts=1` reaches a *materially
11211    // different answer* on macOS and on Linux -- different objective
11212    // (99.677 vs 99.651) and, decisively, a different shape:
11213    //
11214    //   | run                 | unscaled dual | viol    | compl   | ratio   |
11215    //   | reproducer, .nl     | 7.90e4        | 1.1e-16 | 1.1e-9  | 1.5e-14 |
11216    //   | reproducer, TNLP    | 3.25e11       | 2.5e-16 | 2.8e-3  | 8.7e-15 |
11217    //   | deb7 + rung, macOS  | 9.90e1        | 8.0e-13 | 4.65e0  | 4.7e-2  |
11218    //   | deb7 + rung, Linux  | 5.5743e3      | 5.6e-14 | 2.08e-5 | 3.7e-9  |
11219    //
11220    // The Linux row is the one worth reading twice: that answer really is
11221    // gh#884's shape (scaled overall error 5.28e-1 against unscaled
11222    // 5.57e3, which is the `s_d` normalisation hiding a runaway exactly
11223    // as it did on `qpec_small`), so the retry there is the designed cost
11224    // and not the waste gh#887 filed. A CLI assertion of "deb7 declines"
11225    // is therefore false on Linux no matter what the threshold is, which
11226    // is why the pin lives here instead.
11227
11228    /// The dominance rule on its own, with the absolute floor switched
11229    /// off (`du_floor = 0`), so each of these tests is about one rule.
11230    fn ratio_only(dual_inf: Number, viol: Number, compl: Number) -> bool {
11231        runaway_is_the_whole_residual(dual_inf, viol, compl, 0.0)
11232    }
11233
11234    /// The gate as it actually runs: dominance *and* the detector's own
11235    /// absolute floor.
11236    fn runaway(dual_inf: Number, viol: Number, compl: Number) -> bool {
11237        runaway_is_the_whole_residual(dual_inf, viol, compl, DUAL_DIV_RETRY_DU_FLOOR)
11238    }
11239
11240    #[test]
11241    fn a_converged_point_with_a_runaway_multiplier_opens_the_retry() {
11242        // The gh#884 reproducer, both routes it reaches the gate by.
11243        assert!(runaway(7.90e4, 1.1e-16, 1.1e-9));
11244        assert!(runaway(3.25e11, 2.5e-16, 2.8e-3));
11245        // deb7 under the rung on Linux: primal exact, complementarity
11246        // eight orders under its own dual residual. Same shape.
11247        assert!(runaway(5.5743e3, 5.6e-14, 2.08e-5));
11248    }
11249
11250    #[test]
11251    fn an_unconverged_point_does_not_open_the_retry() {
11252        // deb7 under the rung on macOS: complementarity 4.65, five
11253        // percent of its own KKT error. Not a runaway multiplier on an
11254        // otherwise-converged point -- just an unconverged point.
11255        assert!(!ratio_only(9.90e1, 8.0e-13, 4.65e0));
11256        // Either residual alone is enough to close it: the gate takes the
11257        // max, so a clean complementarity does not excuse a violated
11258        // constraint. (`1.0e1` against `1.0e6` is a ratio of `1e-5`; note
11259        // that `1.0e0` there would be `1e-6` exactly, i.e. inside.)
11260        assert!(!ratio_only(1.0e6, 1.0e1, 1.0e-16));
11261        assert!(!ratio_only(1.0e6, 1.0e-16, 1.0e1));
11262    }
11263
11264    /// The dominance ratio is scale-free, and that is exactly why it
11265    /// cannot be the whole gate: a point converged to `1e-30` primal with
11266    /// a dual residual of `4.4e-1` satisfies it as comfortably as
11267    /// gh#884's `7.9e+04` does, and `4.4e-1` is not a runaway by any
11268    /// reading of the issue. Measured on the 400-model QPEC family, the
11269    /// floor alone removes 7 of 68 promotions, every one of them on an
11270    /// answer whose reported dual residual was below `1e2`.
11271    ///
11272    /// The floor is the *detector's*, so this is the answer-level gate
11273    /// asking about the same magnitude the iterate-level one did rather
11274    /// than being a strictly looser copy of it.
11275    #[test]
11276    fn a_small_dual_residual_is_not_a_runaway_however_dominant() {
11277        // Passes the ratio comfortably (1e-30 / 4.4e-1 = 2.3e-30) ...
11278        assert!(ratio_only(4.4e-1, 1.0e-30, 1.0e-30));
11279        // ... and is still refused, because it is not a runaway.
11280        assert!(!runaway(4.4e-1, 1.0e-30, 1.0e-30));
11281        // The two real `r`-family answers that reached the gate this way.
11282        assert!(!runaway(4.397e-1, 1.0e-16, 1.0e-16));
11283        assert!(!runaway(2.026e1, 1.0e-16, 1.0e-16));
11284        // Exactly at the floor is inside; a hair under is outside.
11285        assert!(runaway(DUAL_DIV_RETRY_DU_FLOOR, 0.0, 0.0));
11286        assert!(!runaway(DUAL_DIV_RETRY_DU_FLOOR * 0.999, 0.0, 0.0));
11287    }
11288
11289    #[test]
11290    fn the_threshold_is_where_the_constant_says_it_is() {
11291        // Exactly at the ratio is inside; a hair past it is outside.
11292        assert!(ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE, 0.0));
11293        assert!(!ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE * 1.001, 0.0));
11294    }
11295
11296    #[test]
11297    fn what_we_cannot_measure_does_not_buy_a_retry() {
11298        // A NaN compares false everywhere, so the condition is written so
11299        // that "we cannot tell" declines rather than retries. Each
11300        // argument in turn.
11301        assert!(!ratio_only(Number::NAN, 0.0, 0.0));
11302        assert!(!ratio_only(1.0e6, Number::NAN, 0.0));
11303        assert!(!ratio_only(1.0e6, 0.0, Number::NAN));
11304        assert!(!ratio_only(Number::INFINITY, 0.0, 0.0));
11305        // And a dual residual that is not a runaway at all: the ratio
11306        // would be meaningless, and a zero-dual point is not gh#884.
11307        assert!(!ratio_only(0.0, 0.0, 0.0));
11308        assert!(!ratio_only(-1.0, 0.0, 0.0));
11309    }
11310
11311    // ---- the promotion gate reads the ANSWER, not only the certificate --
11312    //
11313    // gh#884 ranked the two attempts on unscaled KKT error alone and
11314    // argued that this could not return a different local solution,
11315    // because "conjunct 4 requires the promoted answer to satisfy the KKT
11316    // conditions in the model's own units". Any other KKT point does too.
11317    // Measured on 400 random QPECs under the `prod_eq` lowering
11318    // (`bound_relax_factor=0 mu_strategy_fallback=no tol=1e-8`): 68
11319    // promotions, 42 of which moved the objective materially, and three
11320    // of which returned a strictly worse *feasible* point.
11321    //
11322    // Every number below is off a real run, and the two branches are
11323    // separated on purpose -- a rule that branches needs a case on each
11324    // side or the untaken one stays broken while the test is green.
11325    //
11326    //   | model      | base f      | base viol | retry f     | retry viol | branch |
11327    //   |------------|-------------|-----------|-------------|------------|--------|
11328    //   | qpec_small | +3.586e-28  | 1.11e-16  | +5.835e-11  | 5.47e-12   | admit  |
11329    //   | r116       | -1.3006e+01 | 2.22e-16  | -1.2072e+00 | 4.55e-13   | rule 1 |
11330    //   | r261       | -4.7919e+00 | 1.07e-14  | -9.8563e-01 | 7.99e-14   | rule 1 |
11331    //   | r201       | -2.9559e-01 | 6.25e-17  | -9.7321e-02 | 6.21e-13   | rule 1 |
11332    //   | scholtes4  | +1.8176e-09 | 2.07e-25  | -6.6088e-05 | 1.09e-09   | rule 2 |
11333
11334    const ACCEPT: Number = 1e-6;
11335    /// Minimization, which is every row of the table above.
11336    const MIN: Number = 1.0;
11337    /// Maximization, i.e. `obj_scaling_factor < 0`.
11338    const MAX: Number = -1.0;
11339
11340    fn admissible(bo: Number, bv: Number, ro: Number, rv: Number) -> bool {
11341        retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN)
11342    }
11343
11344    #[test]
11345    fn the_reproducers_promotion_is_still_admissible() {
11346        // `qpec_small`: the retry's objective is *worse*, by 5.8e-11 --
11347        // deliberately, since it buys nine orders of unscaled dual
11348        // residual. Five orders inside the tolerance, so rule 1 admits
11349        // it, which is the whole point of having a tolerance at all.
11350        assert!(admissible(3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12));
11351    }
11352
11353    /// Rule 1: a strictly worse feasible point is never an upgrade.
11354    #[test]
11355    fn a_worse_feasible_objective_is_refused_however_clean_the_certificate() {
11356        // r116: -13.0057 -> -1.2072, both independently verified feasible
11357        // by `pounce verify`. The retry's unscaled KKT error is 2.9e-11
11358        // against the base attempt's 3.0e+03, so every certificate
11359        // conjunct passes and only this one refuses it.
11360        assert!(!admissible(
11361            -1.3005680756e1,
11362            2.22e-16,
11363            -1.2072337962e0,
11364            4.55e-13
11365        ));
11366        assert!(!admissible(
11367            -4.7919265770e0,
11368            1.07e-14,
11369            -9.8562977711e-1,
11370            7.99e-14
11371        ));
11372        assert!(!admissible(
11373            -2.9558632401e-1,
11374            6.25e-17,
11375            -9.7321185691e-2,
11376            6.21e-13
11377        ));
11378    }
11379
11380    /// The declared-box conjunct is scale-safe: at a bound of `1e6`, two
11381    /// points pinned to the same widened bound differ by an ulp (`1.2e-10`),
11382    /// which an absolute `1e-12` floor read as the re-solve using more of the
11383    /// widening; relative to the bound it is rounding. A genuine excess at
11384    /// that magnitude -- the bound-magnitude probe's `2.5e-6`, i.e. `2.5e-12`
11385    /// relative -- is still refused, and at a unit bound `1e-8` is.
11386    #[test]
11387    fn the_declared_box_conjunct_is_relative_to_each_bounds_magnitude() {
11388        let (lo, up) = (-1e19, 1e19);
11389        let rel = |x: &[Number], l: &[Number], u: &[Number]| {
11390            declared_box_relative_violation(x, l, u, lo, up)
11391        };
11392        let ub: Number = 1e6;
11393        let pinned: Number = ub + 1e-4; // on the widened bound (`constr_viol_tol` cap)
11394        let one_ulp_out = f64::from_bits(pinned.to_bits() + 1);
11395        assert!(
11396            one_ulp_out - pinned > 1e-12,
11397            "premise: an ulp of 1e6 exceeds 1e-12"
11398        );
11399        let (l, u) = (vec![0.0], vec![ub]);
11400        let base = rel(&[pinned], &l, &u);
11401        assert!(retry_keeps_declared_box(base, rel(&[one_ulp_out], &l, &u)));
11402        // The absolute rule this replaces declined exactly that pair.
11403        assert!(one_ulp_out - ub > (pinned - ub) + 1e-12);
11404        let genuine = rel(&[ub + 9.9995e-5], &l, &u);
11405        let base_genuine = rel(&[ub + 9.7494e-5], &l, &u);
11406        assert!(!retry_keeps_declared_box(base_genuine, genuine));
11407        // Unit bound: the widening's own size is refused, rounding is not.
11408        let (l1, u1) = (vec![0.0], vec![1.0]);
11409        assert!(!retry_keeps_declared_box(0.0, rel(&[1.0 + 1e-8], &l1, &u1)));
11410        assert!(retry_keeps_declared_box(
11411            0.0,
11412            rel(&[f64::from_bits(1.0f64.to_bits() + 1)], &l1, &u1)
11413        ));
11414        // Lower bounds, sentinels, and single-point boxes.
11415        assert_eq!(rel(&[-2e-4], &[-1e4], &[1e19]), 0.0);
11416        assert!(rel(&[-1e4 - 1e-4], &[-1e4], &[1e19]) > 0.0);
11417        assert_eq!(rel(&[5.0], &[-1e19], &[1e19]), 0.0);
11418        assert_eq!(rel(&[0.5 + 1e-8], &[0.5], &[0.5]), 0.0);
11419        assert!(rel(&[1.0], &[0.0, 0.0], &[1.0, 1.0]).is_nan());
11420        // `NaN` is "not measured".
11421        assert!(retry_keeps_declared_box(Number::NAN, Number::NAN));
11422        assert!(!retry_keeps_declared_box(0.0, Number::NAN));
11423    }
11424
11425    /// Rule 2: an objective *improvement* bought with primal slack.
11426    ///
11427    /// `scholtes4` (`benchmarks/mpcc/cases.py`, and now a CLI fixture) has
11428    /// `f* = 0` exactly -- for the MPCC and for the smooth lowering alike,
11429    /// since `x1*x2 = 0` forces one of them to zero, hence `x3 <= 0`, hence
11430    /// `f = x1 - x3 >= 0`. The retry reports `-6.61e-05`, which no feasible
11431    /// point reaches, by moving the complementarity row 16 orders further
11432    /// out. Rule 1 cannot see it: the objective got *better*.
11433    #[test]
11434    fn an_improvement_bought_with_primal_slack_is_refused() {
11435        assert!(!admissible(
11436            1.8175997416e-9,
11437            2.07e-25,
11438            -6.6088333055e-5,
11439            1.09e-9
11440        ));
11441        // The same numbers with the primal *held* would be admissible --
11442        // this is the conjunct that refuses it, not the objective move.
11443        assert!(admissible(
11444            1.8175997416e-9,
11445            2.07e-25,
11446            -6.6088333055e-5,
11447            2.07e-25
11448        ));
11449    }
11450
11451    /// The window the tolerance sits in, from both sides, so it is a
11452    /// checkable claim rather than a fitted constant: the smallest move
11453    /// that must be admitted is `qpec_small`'s `5.8e-11` and the smallest
11454    /// that must be refused is `r201`'s `0.198`, four and five orders
11455    /// away from `acceptable_tol` on either side.
11456    #[test]
11457    fn the_objective_tolerance_is_not_fitted_to_one_model() {
11458        let admit = 5.835e-11;
11459        let refuse = 0.198;
11460        assert!(admit < ACCEPT / 1.0e4, "{admit} is not well inside");
11461        assert!(refuse > ACCEPT * 1.0e4, "{refuse} is not well outside");
11462        // Scale-relative above 1, absolute below it -- the same
11463        // convention `sigma_forward_error_is_small` uses for `norm(x)`.
11464        assert!(admissible(1.0e6, 0.0, 1.0e6 + 0.5, 0.0));
11465        assert!(!admissible(1.0e6, 0.0, 1.0e6 + 5.0, 0.0));
11466    }
11467
11468    /// gh#983 item 4: `x*y == 0` from `(0.3, 0.3)`. The base attempt sits at
11469    /// `f = 2` with a violation of `3e-38` and an unscaled dual infeasibility
11470    /// of `1.4e9`; the retry reaches `f = 1` at `1.96e-13`, six orders inside
11471    /// `constr_viol_tol`. Rule 2 compared the two violations bare and refused
11472    /// it. The floor admits arithmetic noise and nothing above it: the
11473    /// scholtes4 row (`1.09e-9`) is refused in the same breath.
11474    #[test]
11475    fn a_retry_violation_at_the_noise_floor_does_not_block_an_improvement() {
11476        assert!(retry_answer_is_admissible(
11477            2.0, 3.037e-38, 1.0, 1.9584e-13, ACCEPT, MIN
11478        ));
11479        assert!(retry_answer_is_admissible(
11480            -2.0, 3.037e-38, -1.0, 1.9584e-13, ACCEPT, MAX
11481        ));
11482        // Just above the floor is still slack.
11483        assert!(!retry_answer_is_admissible(
11484            2.0,
11485            3.037e-38,
11486            1.0,
11487            RETRY_VIOL_NOISE_FLOOR * 10.0,
11488            ACCEPT,
11489            MIN
11490        ));
11491        // ... and rule 1 is untouched by the floor.
11492        assert!(!retry_answer_is_admissible(
11493            1.0, 3.037e-38, 2.0, 1.0e-13, ACCEPT, MIN
11494        ));
11495    }
11496
11497    /// The audit input with every measurement given and the defaults for
11498    /// the rest (`tol 1e-8`, `acceptable_tol 1e-6`, threshold `1e-4`).
11499    #[allow(clippy::too_many_arguments)]
11500    fn audit_in(
11501        tol: Number,
11502        obj_scale: Number,
11503        rescaled: Number,
11504        start_grad: Number,
11505        final_grad: Number,
11506        kkt: Number,
11507        compl: Number,
11508        th: Number,
11509    ) -> ScaleAuditInput {
11510        ScaleAuditInput {
11511            tol,
11512            obj_scale,
11513            rescaled_obj_scale: rescaled,
11514            start_grad_max: start_grad,
11515            final_grad_max: final_grad,
11516            unscaled_kkt: kkt,
11517            unscaled_compl: compl,
11518            acceptable_tol: 1e-6,
11519            masked_threshold: th,
11520            warm_start: false,
11521        }
11522    }
11523
11524    /// `audit_in` for a warm start (`warm_start_init_point=yes`).
11525    #[allow(clippy::too_many_arguments)]
11526    fn audit_in_warm(
11527        tol: Number,
11528        obj_scale: Number,
11529        rescaled: Number,
11530        start_grad: Number,
11531        final_grad: Number,
11532        kkt: Number,
11533        compl: Number,
11534        th: Number,
11535    ) -> ScaleAuditInput {
11536        ScaleAuditInput {
11537            warm_start: true,
11538            ..audit_in(
11539                tol, obj_scale, rescaled, start_grad, final_grad, kkt, compl, th,
11540            )
11541        }
11542    }
11543
11544    /// gh#983 / CI: a warm start is an answer, so its gradient -- and the
11545    /// returned point's -- carry the model's scale only above the barrier
11546    /// level. Both branches of the warm rule need a row: the session's
11547    /// interior optimum (gradient at the complementarity) stays out, and the
11548    /// reactor warm-started at its answer (gradient `4e3` times it) is still
11549    /// up-scaled.
11550    #[test]
11551    fn a_warm_start_at_an_answer_is_not_read_as_a_tiny_objective() {
11552        let th = 1e-4;
11553        let t = |inp| scale_audit_trigger(inp);
11554        // `cold_then_warm_through_presolve`'s warm re-solve, measured.
11555        assert_eq!(
11556            t(audit_in_warm(
11557                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
11558            )),
11559            None
11560        );
11561        // The same numbers on a cold start are the tiny-objective signature:
11562        // the rule is the warm start's, not a change to the cold branch.
11563        assert!(matches!(
11564            t(audit_in(
11565                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
11566            )),
11567            Some(ScaleAudit::Upscale(_))
11568        ));
11569        // The reactor (fs = 1e-6) warm-started from its answer: the active
11570        // bound's multiplier keeps the gradient at 1e-5, the model's scale.
11571        match t(audit_in_warm(
11572            1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th,
11573        )) {
11574            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
11575            other => panic!("{other:?}"),
11576        }
11577        // A barrier-level seed does not mask an answer that carries scale.
11578        assert!(matches!(
11579            t(audit_in_warm(
11580                1e-8, 1.0, 1.0, 1e-11, 1e-5, 2.5e-9, 2.5e-9, th
11581            )),
11582            Some(ScaleAudit::Upscale(_))
11583        ));
11584        // The re-scale branch does not read the gradient scale at all.
11585        assert_eq!(
11586            t(audit_in_warm(
11587                1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th
11588            )),
11589            Some(ScaleAudit::Rescale)
11590        );
11591    }
11592
11593    /// gh#983: the audit's trigger branches on *which* scaling defect shows,
11594    /// and each branch needs its own row.
11595    #[test]
11596    fn the_scale_audit_trigger_takes_each_branch_and_neither_by_default() {
11597        let th = 1e-4;
11598        let t = |inp| scale_audit_trigger(inp);
11599        // Frozen factor, non-stationary in the model's own units, and the
11600        // factor re-evaluated at the returned point (gradient 2.9e-2 -> 1) is
11601        // seven orders from the frozen one: re-scale.
11602        assert_eq!(
11603            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th)),
11604            Some(ScaleAudit::Rescale)
11605        );
11606        // gh#983 review item 2(b): the same masked certificate on a
11607        // legitimately large objective (`hs71 x 1e8`) re-evaluates to the
11608        // factor it already has -- the re-solve would be the same solve.
11609        assert_eq!(
11610            t(audit_in(1e-8, 2.2e-7, 2.4e-7, 4.6e8, 4.2e8, 3e-6, 1e-9, th)),
11611            None
11612        );
11613        // Tiny gradient, complementarity 2.5e-4 of it (the reactor, fs = 1e-6).
11614        match t(audit_in(1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th)) {
11615            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
11616            other => panic!("{other:?}"),
11617        }
11618        // gh#983 review item 4: no band without a signal. fs = 3e-5 (gradient
11619        // 3e-4, relative complementarity 8.4e-6) and fs = 1e-3 (2.5e-7) are
11620        // both re-solved now; fs = 1 is left alone.
11621        assert!(matches!(
11622            t(audit_in(1e-8, 1.0, 1.0, 3e-4, 3e-4, 2.5e-9, 2.5e-9, th)),
11623            Some(ScaleAudit::Upscale(_))
11624        ));
11625        assert!(matches!(
11626            t(audit_in(1e-8, 1.0, 1.0, 1e-2, 1e-2, 2.5e-9, 2.5e-9, th)),
11627            Some(ScaleAudit::Upscale(_))
11628        ));
11629        assert_eq!(
11630            t(audit_in(1e-8, 1.0, 1.0, 10.0, 10.0, 2.5e-9, 2.5e-9, th)),
11631            None
11632        );
11633        // A gradient in [0.1, 1): the signature, but an up-scale below the
11634        // material factor -- warn, do not re-solve.
11635        assert_eq!(
11636            t(audit_in(1e-8, 1.0, 1.0, 0.5, 0.5, 1e-6, 1e-6, th)),
11637            Some(ScaleAudit::SmallObjective)
11638        );
11639        // gh#983 review item 2(a): a start near a stationary point
11640        // (`grad f(x0) = 2e-7`) is not a tiny objective when the gradient at
11641        // the answer is 1.
11642        assert_eq!(
11643            t(audit_in(1e-8, 1.0, 1.0, 2e-7, 1.0, 2.5e-9, 2.5e-9, th)),
11644            None
11645        );
11646        // A start measured at a stationary point (gradient exactly 0) carries
11647        // no scale: the audit stays out however small the answer's gradient.
11648        assert_eq!(
11649            t(audit_in(1e-8, 1.0, 1.0, 0.0, 2e-4, 6e-3, 2.5e-9, th)),
11650            None
11651        );
11652        // An unmeasured start (caller-owned scaling) defers to the answer.
11653        assert!(matches!(
11654            t(audit_in(
11655                1e-8,
11656                f64::NAN,
11657                f64::NAN,
11658                f64::NAN,
11659                1e-5,
11660                2.5e-9,
11661                2.5e-9,
11662                th
11663            )),
11664            Some(ScaleAudit::Upscale(_))
11665        ));
11666        // A big gradient never up-scales, whatever the complementarity.
11667        assert_eq!(
11668            t(audit_in(1e-8, 1.0, 1.0, 50.0, 50.0, 1e-3, 1e-3, th)),
11669            None
11670        );
11671        // An extreme factor at a stationary point is the honest case.
11672        assert_eq!(
11673            t(audit_in(1e-8, 1e-8, 1e-8, 1e9, 1e9, 1e-9, 1e-12, th)),
11674            None
11675        );
11676        // The masked opt-out (threshold 0) disables the re-scale branch.
11677        assert_eq!(
11678            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, 0.0)),
11679            None
11680        );
11681        // A caller who loosened tol asked for the complementarity they got.
11682        assert_eq!(
11683            t(audit_in(5e-2, 1.0, 1.0, 1e-5, 1e-5, 1e-2, 1e-2, th)),
11684            None
11685        );
11686        // NaN stays quiet.
11687        let nan = f64::NAN;
11688        assert_eq!(t(audit_in(1e-8, nan, nan, nan, nan, nan, nan, th)), None);
11689        // The upscale is capped.
11690        match t(audit_in(1e-8, 1.0, 1.0, 1e-14, 1e-14, 1.0, 1.0, th)) {
11691            Some(ScaleAudit::Upscale(k)) => assert_eq!(k, SCALE_AUDIT_MAX_UPSCALE),
11692            other => panic!("{other:?}"),
11693        }
11694    }
11695
11696    /// gh#1000 (II.22): the roundoff exemption, on the measured population
11697    /// named in `UNSCALED_DUAL_ROUNDOFF_ULPS`'s doc.
11698    #[test]
11699    fn a_residual_at_the_roundoff_floor_of_its_terms_is_not_a_miss() {
11700        // Pump network at H0_max 148: 1.6 ulps of its terms.
11701        assert!(unscaled_dual_inf_is_roundoff(5.54e-3, 1.57e13));
11702        assert!(unscaled_dual_inf_is_roundoff(7.39e-3, 2.66e13));
11703        // The downgrades that are right keep it: Haverly, the process
11704        // network's T2 and S2+T2 subproblems, the eps-perspective root, and
11705        // the gh#983 cusp.
11706        assert!(!unscaled_dual_inf_is_roundoff(1.33e-2, 6.6e10));
11707        assert!(!unscaled_dual_inf_is_roundoff(0.5, 7.55e11));
11708        assert!(!unscaled_dual_inf_is_roundoff(6.25e-2, 3.21e11));
11709        assert!(!unscaled_dual_inf_is_roundoff(3.92e-3, 5.03e9));
11710        assert!(!unscaled_dual_inf_is_roundoff(0.144, 3.55e9));
11711        // No scale measured: keep the downgrade.
11712        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, f64::NAN));
11713        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, 0.0));
11714        assert!(!unscaled_dual_inf_is_roundoff(f64::NAN, 1e13));
11715    }
11716
11717    /// gh#983 review item 7: one warning per code.
11718    #[test]
11719    fn a_warning_code_is_attached_at_most_once() {
11720        let mut w = vec!["unscaled_dual_inf_above_acceptable: downgraded".to_string()];
11721        push_warning_once(
11722            &mut w,
11723            "unscaled_dual_inf_above_acceptable: verify in your units".to_string(),
11724        );
11725        push_warning_once(&mut w, "large_dual_scale: terms of 1e9".to_string());
11726        assert_eq!(w.len(), 2, "{w:?}");
11727        assert!(w[0].ends_with("downgraded"));
11728    }
11729
11730    /// gh#983: the structured warnings, by code, on success verdicts only.
11731    #[test]
11732    fn quality_warnings_carry_a_code_and_only_on_success_verdicts() {
11733        use ApplicationReturnStatus::*;
11734        // The cusp: multipliers 3.5e9, residual 0.144.
11735        let w = quality_warnings(SolveSucceeded, 0.144, 3.55e9, 1.0, 1e-6, false);
11736        assert!(
11737            w.iter().any(|m| m.starts_with("large_dual_scale:")),
11738            "{w:?}"
11739        );
11740        assert!(
11741            w.iter()
11742                .any(|m| m.starts_with("unscaled_dual_inf_above_acceptable:")),
11743            "{w:?}"
11744        );
11745        // orthrds2-like: scale 1.6e10, residual 89.7 -> only the scale caveat
11746        // and the absolute one; never a status change (the function returns
11747        // text, not a verdict).
11748        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, false);
11749        assert!(w.iter().any(|m| m.starts_with("large_dual_scale:")));
11750        assert!(!w.iter().any(|m| m.contains("bound_relax_factor")), "{w:?}");
11751        // gh#1000: under bound_relax_factor = 0 the caveat names the option.
11752        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, true);
11753        assert!(
11754            w.iter()
11755                .any(|m| m.starts_with("large_dual_scale:") && m.contains("bound_relax_factor = 0")),
11756            "{w:?}"
11757        );
11758        // A clean point has none.
11759        assert!(quality_warnings(SolveSucceeded, 1e-9, 5.0, 1.0, 1e-6, false).is_empty());
11760        // A large objective with a stationary residual is not a failed CQ.
11761        assert!(quality_warnings(SolveSucceeded, 2.9e-7, 1.46e9, 1.0, 1e-6, false).is_empty());
11762        // 5e-4 is below the warning bar even though it exceeds acceptable_tol.
11763        assert!(quality_warnings(SolveSucceeded, 5e-4, 5.0, 1.0, 1e-6, false).is_empty());
11764        // Failures carry no success caveat.
11765        assert!(quality_warnings(RestorationFailed, 0.144, 3.55e9, 1.0, 1e-6, false).is_empty());
11766        assert!(quality_warnings(SolveSucceeded, f64::NAN, f64::NAN, 1.0, 1e-6, false).is_empty());
11767    }
11768
11769    /// gh#983 item 5: flooring an attempt must floor everything a solve
11770    /// report reads off the statistics, the iteration count and the row table
11771    /// included, or the report describes the declined retry.
11772    #[test]
11773    fn the_certificate_floor_carries_the_iteration_trace() {
11774        use pounce_nlp::solve_statistics::{IterRecord, SolveStatistics};
11775        let mut base = SolveStatistics::new();
11776        base.iteration_count = 64;
11777        base.iterations = vec![IterRecord::default(); 3];
11778        base.num_obj_evals = 159;
11779        base.restoration_calls = 2;
11780        let floor = SolutionCertificate::of(&base);
11781        let mut retry = SolveStatistics::new();
11782        retry.iteration_count = 15;
11783        retry.iterations = vec![IterRecord::default(); 15];
11784        retry.num_obj_evals = 86;
11785        floor.restore_into(&mut retry);
11786        assert_eq!(retry.num_obj_evals, 159);
11787        assert_eq!(retry.restoration_calls, 2);
11788        assert_eq!(retry.iteration_count, 64);
11789        assert_eq!(retry.iterations.len(), 3);
11790    }
11791
11792    /// An infeasible base attempt is not a point worth protecting, so
11793    /// both rules stand down and the certificate conjuncts decide alone.
11794    /// R2: `obj_scaling_factor < 0` poses a maximization, and
11795    /// `final_objective` is the user's **signed** objective, so both rules
11796    /// have to follow the sense. This is the table above with every
11797    /// objective negated: the same three answers must be refused and the
11798    /// same one admitted, with `MAX` instead of `MIN`.
11799    ///
11800    /// Without the normalization each row flips — rule 1 starts refusing
11801    /// genuine improvements (a regression against the behaviour before the
11802    /// conjunct existed) and rule 2 starts admitting strictly worse
11803    /// answers, which is the class it was added to block.
11804    #[test]
11805    fn the_rules_follow_the_objective_sense() {
11806        // qpec_small, mirrored: the retry is worse by 5.8e-11, well inside
11807        // the tolerance, so it is still admitted.
11808        assert!(retry_answer_is_admissible(
11809            -3.586e-28, 1.11e-16, -5.835e-11, 5.47e-12, ACCEPT, MAX
11810        ));
11811        // r116, mirrored: +13.0057 given up for +1.2072 is now a *worse*
11812        // maximum, and rule 1 must still refuse it.
11813        assert!(!retry_answer_is_admissible(
11814            1.3005680756e1,
11815            2.22e-16,
11816            1.2072337962e0,
11817            4.55e-13,
11818            ACCEPT,
11819            MAX
11820        ));
11821        // scholtes4, mirrored: +6.6088e-05 is now an improvement bought
11822        // with primal slack, and rule 2 must still refuse it.
11823        assert!(!retry_answer_is_admissible(
11824            -1.8175997416e-9,
11825            2.07e-25,
11826            6.6088333055e-5,
11827            1.09e-9,
11828            ACCEPT,
11829            MAX
11830        ));
11831        // ... and the same improvement with the primal held is admitted.
11832        assert!(retry_answer_is_admissible(
11833            -1.8175997416e-9,
11834            2.07e-25,
11835            6.6088333055e-5,
11836            2.07e-25,
11837            ACCEPT,
11838            MAX
11839        ));
11840    }
11841
11842    /// The mirror of the above, stated as the property rather than the
11843    /// rows: negating both objectives and flipping the sense must leave
11844    /// every verdict unchanged.
11845    #[test]
11846    fn negating_the_objective_and_the_sense_is_inert() {
11847        for &(bo, bv, ro, rv) in &[
11848            (3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12),
11849            (-1.3005680756e1, 2.22e-16, -1.2072337962e0, 4.55e-13),
11850            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 1.09e-9),
11851            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 2.07e-25),
11852            (-1.0e3, 1.0e-2, 0.0, 1.0e-12),
11853        ] {
11854            assert_eq!(
11855                retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN),
11856                retry_answer_is_admissible(-bo, bv, -ro, rv, ACCEPT, MAX),
11857                "verdict moved under (obj, sense) -> (-obj, -sense) at {bo:e}/{ro:e}"
11858            );
11859        }
11860    }
11861
11862    #[test]
11863    fn an_infeasible_base_attempt_protects_nothing() {
11864        assert!(admissible(-1.0e3, 1.0e-2, 0.0, 1.0e-12));
11865        // ... and what cannot be measured is refused, not admitted, the
11866        // same way `runaway_is_the_whole_residual` treats a NaN.
11867        assert!(admissible(Number::NAN, 0.0, 0.0, 0.0));
11868        assert!(!admissible(0.0, 0.0, Number::NAN, 0.0));
11869        assert!(!admissible(0.0, 0.0, -1.0, Number::NAN));
11870    }
11871}