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 case rule 2 exists for,
507/// `scholtes4`, buys `6.6e-05` of objective with a violation of `1.09e-09`, an
508/// order above this floor, so it is still refused. The floor was `1e-12` until
509/// MacMPEC `pack-comp1p-32` (complementarity driver review): the retry reached
510/// the published optimum, `0.652997` against the base's `0.704` (whose own
511/// unscaled dual residual was `7.2e7`), at a violation of `2.6e-11` -- three
512/// orders inside `tol` and four inside `constr_viol_tol` -- and was refused
513/// because the base sat at `2.5e-12`. Two orders below the default `tol` is
514/// still far below any violation that changes which point a model accepts.
515const RETRY_VIOL_NOISE_FLOOR: Number = 1e-10;
516
517/// gh#983 review item 5: how many orders a retry's unscaled KKT error must sit
518/// below the base attempt's before it may be promoted without reaching
519/// `acceptable_tol` itself.
520const RETRY_DOMINANCE_ORDERS: Number = 1e-6;
521
522/// gh#983 review item 5: the second way conjunct 4 of the gh#884 promotion
523/// gate can hold.
524///
525/// Conjunct 4 demanded the retry's unscaled KKT error be at or below
526/// `acceptable_tol`. On the toll-pricing MPCC at `bound_relax_factor = 0` the
527/// base attempt returns `Solved_To_Acceptable_Level` at an unscaled dual
528/// infeasibility of `1.03e5` and the retry `Solve_Succeeded` at `1.69e-5`:
529/// ten orders better, and refused because `1.69e-5 > 1e-6`. That is a
530/// certificate an ordinary first solve would ship as `Solve_Succeeded`
531/// without a second look (it is under `1e-3`, the bar
532/// `finalize_quality_verdict` holds strict verdicts to), held to a stricter
533/// standard only because it was a retry, while the answer reported instead is
534/// one whose residual is the runaway itself.
535///
536/// So the retry's certificate also counts as real when **all** of:
537/// * it is at least six orders below the base attempt's
538///   (`RETRY_DOMINANCE_ORDERS`) -- not "better", *categorically* better;
539/// * it is at or below `UNSCALED_DUAL_WARN` (`1e-3`) in absolute terms, the
540///   same bar a strict verdict is held to everywhere else, so no promotion
541///   ships a residual the audit would flag on a first solve;
542/// * the retry's unscaled constraint violation is within `acceptable_tol`
543///   (the primal half is not relaxed at all).
544///
545/// The answer rules ([`retry_answer_is_admissible`]) and the `Solve_Succeeded`
546/// conjunct are unchanged and still apply. Why this does not let `ralph1`
547/// through: `ralph1`'s defect is that `perturb_always_cd` returns a wrong
548/// answer reported as success, and what keeps it out is that the retry is
549/// never *opened* there -- the detector's scale-relative step conjunct and
550/// the `1e2` dual floor on the reported answer
551/// (`runaway_is_the_whole_residual`), neither of which this touches. Within an
552/// opened retry the base residual is at least that floor, so the dominance
553/// conjunct alone would admit `1e-4`; the absolute `1e-3` cap and the
554/// unchanged answer rules are what bound it, and `issue884_*` pins both
555/// barriers (`ralph1` is in that corpus).
556fn retry_certificate_dominates(
557    base_unscaled_kkt: Number,
558    retry_unscaled_kkt: Number,
559    retry_viol: Number,
560    accept_tol: Number,
561) -> bool {
562    base_unscaled_kkt.is_finite()
563        && retry_unscaled_kkt.is_finite()
564        && retry_viol.is_finite()
565        && retry_unscaled_kkt <= RETRY_DOMINANCE_ORDERS * base_unscaled_kkt
566        && retry_unscaled_kkt <= UNSCALED_DUAL_WARN
567        && retry_viol <= accept_tol
568}
569
570/// Is the retry's answer admissible *as an answer*, next to the base
571/// attempt's — independent of which has the better multiplier?
572///
573/// gh#884's promotion gate ranked the two attempts on unscaled KKT error
574/// alone. That is a statement about the **certificate**, and it was
575/// allowed to decide which **point** shipped, on the argument that
576/// "conjunct 4 requires the promoted answer to satisfy the KKT conditions
577/// in the model's own units" — so, unlike the μ flip, this retry could not
578/// return a different local solution. The inference does not hold: *any*
579/// other KKT point satisfies the KKT conditions in the model's own units
580/// too. Measured on 400 random QPECs (`prod_eq` lowering), 42 of 68
581/// promotions moved the objective materially, i.e. returned a different
582/// local solution, and three returned a **worse feasible point** — worst
583/// case `-13.0057 → -1.2072`, both independently verified feasible.
584///
585/// Two rules, and both are about the *answer* rather than its certificate:
586///
587/// 1. **Never hand back a feasible point whose objective is worse than one
588///    this run already computed.** The base attempt's point is feasible
589///    and in hand; returning a worse one is a regression no certificate
590///    buys back.
591/// 2. **An objective *improvement* may not be bought with primal slack.**
592///    Two costs this carries, named rather than hidden (R3). It is an exact
593///    non-increase with **no noise floor**, so it fires the same on
594///    `2.07e-25 -> 1.09e-09` (where the move is the whole defect) as on
595///    `1e-17 -> 1.1e-17` (where which side a retry lands on is arithmetic):
596///    of the 45 promotions this PR removes, ~35 are improvements refused
597///    because the violation ticked up somewhere far below any tolerance. The
598///    direction is conservative — the base answer is feasible and in hand —
599///    but "refuses purchases, not improvements" is only true above the noise.
600///    And the rule detects *the primal moved*, not *below the optimum*: had
601///    `scholtes4`'s retry **held** its violation, `f = -6.6088e-05` would have
602///    been admitted, which the second assertion of
603///    `an_improvement_bought_with_primal_slack_is_refused` states outright.
604///    On that model the two coincided.
605///    The remedy is for a *dual* defect — the premise is that the primal
606///    has settled — so a retry that lands further outside the constraints
607///    *and* reports a better objective has not repaired the runaway, it
608///    has moved somewhere the model does not reach. This is what
609///    `scholtes4` does: from a base at `f = +1.82e-09` with a constraint
610///    violation of `2.07e-25` it promotes `f = -6.61e-05` at `1.09e-09`,
611///    below the model's exactly-known `f* = 0`, and reports
612///    `Optimal Solution Found`.
613///
614/// Both comparisons are skipped when the base attempt is not itself
615/// feasible within [`IpoptApplication::dual_divergence_retry_accept_tol`]:
616/// there is then no admissible point to protect, and the retry's is
617/// strictly better information.
618///
619/// `tol` is that same acceptable tolerance, scaled by
620/// `max(1, |base_obj|)` so the comparison is relative on a large
621/// objective and absolute on a small one — the convention
622/// `sigma_forward_error_is_small` uses for `‖x‖` and for the same reason.
623/// It is not a fitted constant: the objective moves this has to admit
624/// (`qpec_small`, `5.8e-11`) and the ones it has to refuse (`r201`,
625/// `0.198`; `scholtes4`, `6.6e-05`) sit four and five orders away from it
626/// on either side.
627///
628/// `sense` is `+1` for a minimization and `-1` for a maximization, and both
629/// objectives are multiplied by it before either rule looks at them.
630/// [`SolveStatistics::final_objective`] is the objective evaluated on the
631/// **user** TNLP — signed, and *not* premultiplied by `obj_scaling_factor` —
632/// and a negative `obj_scaling_factor` is the documented way to pose a
633/// maximization. Without the normalization both rules invert under it: rule 1
634/// would refuse genuine *improvements* (a regression against the behaviour
635/// before this conjunct existed) and rule 2 would admit strictly worse
636/// answers, re-arming the exact class the conjunct was added to block. The
637/// repo has shipped one defect from this sign already —
638/// `masked_certificate_fuzz.rs::the_veto_is_not_disabled_by_a_negative_objective_scaling_factor`,
639/// whose fix took `.abs()` in the residual accessors, which is also what keeps
640/// the detector firing under maximization and so keeps this path reachable.
641fn retry_answer_is_admissible(
642    base_obj: Number,
643    base_viol: Number,
644    retry_obj: Number,
645    retry_viol: Number,
646    accept_tol: Number,
647    sense: Number,
648) -> bool {
649    // Nothing to compare against: a non-finite or infeasible base answer
650    // is not a point worth protecting.
651    if !base_obj.is_finite() || !base_viol.is_finite() || base_viol > accept_tol {
652        return true;
653    }
654    // A non-finite retry objective is refused rather than admitted, for
655    // the same reason `runaway_is_the_whole_residual` refuses a NaN.
656    if !retry_obj.is_finite() {
657        return false;
658    }
659    // Both into a minimization frame, so "lower is better" below is true
660    // whichever sense the caller posed.
661    let base_obj = sense * base_obj;
662    let retry_obj = sense * retry_obj;
663    let tol = accept_tol * base_obj.abs().max(1.0);
664    if retry_obj > base_obj + tol {
665        return false; // rule 1: strictly worse feasible point
666    }
667    if retry_obj < base_obj - tol {
668        // Rule 2: an improvement is admissible only if the retry did not
669        // give up primal accuracy to get it.
670        return retry_viol.is_finite() && retry_viol <= base_viol.max(RETRY_VIOL_NOISE_FLOOR);
671    }
672    true
673}
674
675/// How far `x` sits outside the declared box, **relative to each bound's own
676/// magnitude**: `max_i viol_i / max(1, |b_i|)`, where `b_i` is the bound
677/// `x_i` crosses and bounds at or beyond the infinity sentinels are absent.
678///
679/// Relative because the quantity it is compared on is: `bound_relax_factor`
680/// widens bound `b` by `factor · max(1, |b|)` (capped at `constr_viol_tol`),
681/// so a point pinned to the widened bound sits a *relative* distance from the
682/// box that does not depend on `|b|`, while its rounding is one ulp of `|b|`
683/// -- `1.2e-10` at `|b| = 1e6`, two orders above any absolute floor that
684/// still separates `1e-8` from noise on a unit bound.
685///
686/// A variable fixed by its declared box (`x_L == x_U`) is skipped. Under
687/// `fixed_variable_treatment=relax_bounds` it stays in the iterate with its
688/// point widened into a band -- in the base attempt and the re-solve alike,
689/// since a barrier needs an interior -- so where it lands inside that band is
690/// barrier noise, not a choice to use the widening: on a fixed `z = 0.5`
691/// beside three bound-active controls the base attempt returned it `1.2e-11`
692/// off and the re-solve `2.0e-11`, and counting it declined a re-solve whose
693/// controls were all inside their box. Under the default `make_parameter` it
694/// is spliced in at its exact value and reads `0` either way.
695///
696/// `NaN` when the lengths disagree (nothing to measure against).
697fn declared_box_relative_violation(
698    x: &[Number],
699    x_l: &[Number],
700    x_u: &[Number],
701    lower_inf: Number,
702    upper_inf: Number,
703) -> Number {
704    if x.len() != x_l.len() || x.len() != x_u.len() {
705        return Number::NAN;
706    }
707    let mut worst = 0.0_f64;
708    for i in 0..x.len() {
709        let (l, u) = (x_l[i], x_u[i]);
710        if l == u {
711            continue;
712        }
713        if l > lower_inf && x[i] < l {
714            worst = worst.max((l - x[i]) / l.abs().max(1.0));
715        }
716        if u < upper_inf && x[i] > u {
717            worst = worst.max((x[i] - u) / u.abs().max(1.0));
718        }
719    }
720    worst
721}
722
723/// A relative declared-box violation at or below this is rounding, not use of
724/// the widening: four ulps of the bound's magnitude (`4 · ε ≈ 8.9e-16`).
725///
726/// Measured populations on either side of it. Rounding: a point pinned to a
727/// bound reads at most one ulp off it, `ε/2 .. ε` relative at any magnitude.
728/// Genuine use of the widening, from the bound-magnitude probe (the
729/// `scale_audit_bound_active` model with `x_U` in `{1, 10, 1e2, 1e3, 1e4,
730/// 1e6}`, each with the box at `[0, x_U]` and at `[x_U − 1, x_U]`, under a
731/// named `bound_relax_factor=1e-8`): the re-solve's excess over the base
732/// attempt is `4.97e-9` relative at `x_U = 1`, `9.5e-9` at `10`, `9.9e-9` at
733/// `1e2`, `2.5e-9` at `1e3`, `2.5e-10` at `1e4` and `2.5e-12` at `1e6` (the
734/// last three are where `constr_viol_tol = 1e-4` caps the widening). The
735/// smallest of those is three and a half orders above this floor, the
736/// largest rounding three times below it.
737const RETRY_BOX_REL_NOISE: Number = 4.0 * Number::EPSILON;
738
739/// May a retry's point ship, as far as the box the caller *declared* goes?
740///
741/// Only when it sits no further outside that box than the base attempt's
742/// point does, measured relative to each bound's magnitude
743/// ([`declared_box_relative_violation`]) and up to [`RETRY_BOX_REL_NOISE`].
744/// Every interior-point solve runs on bounds widened by `bound_relax_factor`,
745/// so "outside the declared box" is something any converged point can be, by
746/// up to the widening; what this refuses is a retry that *uses more of it*
747/// than the answer already in hand. That is the gh#983 scale audit's failure
748/// mode exactly: its re-solve drives complementarity down, which on a
749/// bound-active variable is the same as driving the point onto the widened
750/// bound, so `ex1_320`'s re-solve shipped `1.0e-8` outside the box its base
751/// attempt satisfied exactly.
752///
753/// Unconditional, unlike rule 2 of [`retry_answer_is_admissible`]: a point
754/// outside the box is the defect whatever the objective did, and a re-solve
755/// whose objective move is under that rule's tolerance shipped it all the
756/// same. When the caller left `bound_relax_factor` alone the scale audit's
757/// re-solve keeps the variable box as declared (its inequality rows are
758/// still widened, as in the base attempt), so there this conjunct is a
759/// backstop. It bites when the caller named a widening: both attempts then
760/// solve the widened box, and the re-solve may not exploit it further.
761///
762/// `NaN` means "not measured". A retry that cannot be measured is refused
763/// unless the base could not be either: there is then nothing to compare and
764/// the rule has no opinion.
765fn retry_keeps_declared_box(base_rel_viol: Number, retry_rel_viol: Number) -> bool {
766    if retry_rel_viol.is_nan() {
767        return base_rel_viol.is_nan();
768    }
769    let base = if base_rel_viol.is_nan() {
770        0.0
771    } else {
772        base_rel_viol.max(0.0)
773    };
774    retry_rel_viol <= base + RETRY_BOX_REL_NOISE
775}
776
777/// What [`IpoptApplication::initialize_with_option_file`] did — enough
778/// for a caller to tell the user which file (if any) configured the run.
779#[derive(Debug, Default, Clone)]
780pub struct OptionFileLoad {
781    /// The file actually read. `None` means no options file was read:
782    /// nobody named one and neither default was present.
783    pub path: Option<PathBuf>,
784    /// Whether [`Self::path`] was named by the caller rather than found
785    /// by probing the working directory.
786    pub explicit: bool,
787    /// Non-fatal notes about option-file settings that did *not* take
788    /// effect. Nothing here stops a solve; the point is that it not
789    /// happen silently.
790    pub warnings: Vec<String>,
791}
792
793/// Opaque snapshot of an application's linear-solver summaries; see
794/// [`IpoptApplication::linear_solver_summary_state`].
795#[derive(Debug, Clone)]
796pub struct LinearSolverSummaryState {
797    main: LinearSolverSummary,
798    restoration: LinearSolverSummary,
799}
800
801/// Factory that constructs a fresh restoration-phase strategy on
802/// demand. The outer algorithm owns at most one restoration object,
803/// so the factory is invoked once per `optimize_tnlp` call. The
804/// factory is `FnMut` to allow callers to capture a builder that
805/// internally reuses caches across builds.
806pub type RestorationFactory = Box<dyn FnMut() -> Box<dyn RestorationPhase>>;
807
808/// Provider that mints fresh [`RestorationFactory`] instances on
809/// demand. Used by drivers that need to run the inner IPM more than
810/// once per `optimize_tnlp` call — notably the Phase-3 ℓ₁-exact
811/// penalty-barrier outer loop (pounce#10), which the existing
812/// `RestorationFactory` cannot support because pounce's default
813/// `make_default_restoration_factory` is a one-shot. Callers wire
814/// this via [`IpoptApplication::set_restoration_factory_provider`].
815pub type RestorationFactoryProvider = Box<dyn FnMut() -> RestorationFactory>;
816
817/// Running totals over the passes of a multi-pass solve (the ℓ₁ exact-penalty
818/// ρ loop, and the plain attempt that precedes it under
819/// `l1_fallback_on_restoration_failure`). Every pass starts from reset
820/// statistics, so the passes are summed here and written back once, after
821/// the last, as the **total** `iteration_count` plus a `passes` summary
822/// (gh#987 item 6). Everything else in the statistics keeps describing the
823/// last pass — the one that produced the returned point.
824#[derive(Default)]
825struct MultiPassTotals {
826    iterations: Index,
827    rows: Vec<pounce_nlp::solve_statistics::IterRecord>,
828    obj_evals: Index,
829    constr_evals: Index,
830    grad_evals: Index,
831    jac_evals: Index,
832    hess_evals: Index,
833    restoration_calls: Index,
834    restoration_inner_iters: Index,
835    restoration_outer_iters: Index,
836    passes: Vec<pounce_nlp::SolvePassRecord>,
837}
838
839impl MultiPassTotals {
840    fn push_pass(
841        &mut self,
842        st: &SolveStatistics,
843        rho: Option<Number>,
844        status: ApplicationReturnStatus,
845    ) {
846        self.passes.push(pounce_nlp::SolvePassRecord {
847            rho,
848            iterations: st.iteration_count,
849            first_row: self.rows.len(),
850            slack_sum: None,
851            constraint_violation: None,
852            status: format!("{status:?}"),
853        });
854        self.iterations += st.iteration_count;
855        self.rows.extend(st.iterations.iter().cloned());
856        self.obj_evals += st.num_obj_evals;
857        self.constr_evals += st.num_constr_evals;
858        self.grad_evals += st.num_obj_grad_evals;
859        self.jac_evals += st.num_constr_jac_evals;
860        self.hess_evals += st.num_hess_evals;
861        self.restoration_calls += st.restoration_calls;
862        self.restoration_inner_iters += st.restoration_inner_iters;
863        self.restoration_outer_iters += st.restoration_outer_iters;
864    }
865
866    fn set_slack_sum(&mut self, v: Number) {
867        if let Some(p) = self.passes.last_mut() {
868            p.slack_sum = v.is_finite().then_some(v);
869        }
870    }
871
872    fn set_violation(&mut self, v: Number) {
873        if let Some(p) = self.passes.last_mut() {
874            p.constraint_violation = v.is_finite().then_some(v);
875        }
876    }
877
878    fn apply(&self, st: &mut SolveStatistics) {
879        if self.passes.is_empty() {
880            return;
881        }
882        st.iteration_count = self.iterations;
883        st.iterations = self.rows.clone();
884        st.num_obj_evals = self.obj_evals;
885        st.num_constr_evals = self.constr_evals;
886        st.num_obj_grad_evals = self.grad_evals;
887        st.num_constr_jac_evals = self.jac_evals;
888        st.num_hess_evals = self.hess_evals;
889        st.restoration_calls = self.restoration_calls;
890        st.restoration_inner_iters = self.restoration_inner_iters;
891        st.restoration_outer_iters = self.restoration_outer_iters;
892        st.passes = self.passes.clone();
893    }
894}
895
896/// Callback fired by [`IpoptApplication::optimize_constrained`] once
897/// the IPM has converged (status `SolveSucceeded` or
898/// `SolvedToAcceptableLevel`) and before the user TNLP's
899/// `finalize_solution` runs. Receives borrowed handles into the
900/// algorithm's converged state.
901///
902/// **Use case**: post-optimal sensitivity analysis (pounce#7 /
903/// `pounce-sensitivity`). The callback receives a shared handle to
904/// the PD solver so a `SensBacksolver` adapter can run backsolves
905/// against the converged KKT factor — and so that handle may outlive
906/// the call frame (e.g. the public `Solver` session API retains the
907/// factor for repeated `parametric_step` / `kkt_solve` calls);
908/// receives the data / cq / nlp handles so the adapter can reproduce
909/// the augmented-system coefficient layout the IPM converged at.
910///
911/// **Not** the same as `set_intermediate_callback` (per-iteration
912/// progress notification) — this fires exactly once per `optimize_*`
913/// call, only on success.
914pub type ConvergedCallback = Box<
915    dyn FnMut(
916        &crate::ipopt_data::IpoptDataHandle,
917        &crate::ipopt_cq::IpoptCqHandle,
918        &Rc<RefCell<dyn pounce_nlp::ipopt_nlp::IpoptNlp>>,
919        Rc<RefCell<crate::kkt::pd_full_space_solver::PdFullSpaceSolver>>,
920    ),
921>;
922use pounce_common::diagnostics::DiagnosticsState;
923use pounce_common::exception::{ExceptionKind, SolverException};
924use pounce_common::journalist::{JournalLevel, Journalist};
925use pounce_common::options_list::OptionsList;
926use pounce_common::reg_options::{PrintOptionsMode, RegisteredOptions};
927use pounce_common::timing::TimingStatistics;
928use pounce_common::types::{Index, Number};
929use pounce_linalg::dense_vector::DenseVectorSpace;
930use pounce_linsol::SparseSymLinearSolverInterface;
931use pounce_linsol::summary::LinearSolverSummary;
932use pounce_nlp::alg_types::SolverReturn;
933use pounce_nlp::derivative_test::{DerivativeTest, DerivativeTestOptions};
934use pounce_nlp::orig_ipopt_nlp::{ConstObjScaling, OrigIpoptNlp, ScalingMethod};
935use pounce_nlp::return_codes::ApplicationReturnStatus;
936use pounce_nlp::solve_statistics::SolveStatistics;
937use pounce_nlp::tnlp::{
938    BoundsInfo, IpoptCq as TnlpIpoptCq, IpoptData as TnlpIpoptData, NlpInfo, Solution, TNLP,
939};
940use pounce_nlp::tnlp_adapter::{
941    DEFAULT_NLP_LOWER_BOUND_INF, DEFAULT_NLP_UPPER_BOUND_INF, FixedVarTreatment, TNLPAdapter,
942};
943use std::cell::RefCell;
944use std::fmt;
945use std::path::{Path, PathBuf};
946use std::rc::Rc;
947use std::sync::{Arc, Mutex};
948use std::time::Instant;
949
950/// Smallest `n + m` at which `algorithm=active-set-sqp` starts from the
951/// interior point; see [`IpoptApplication::sqp_auto_handover`]. The fixture
952/// corpus (largest model 813 variables) sits far below it.
953pub const AUTO_HANDOVER_MIN_DIM: usize = 5_000;
954
955pub struct IpoptApplication {
956    options: OptionsList,
957    /// Diagnostics from the safeguarded `least_square_init_primal`
958    /// initializer step of the most recent solve (gh#605). `None` when
959    /// the step was not run. Read with
960    /// [`Self::least_square_init_report`].
961    least_square_init_report: Option<crate::init::default::LeastSquareInitReport>,
962    /// Per-variable scaling factors applied by the wrapper installed in
963    /// [`Self::optimize_tnlp`] (gh#486). Recorded so consumers that read
964    /// the algorithm's own iterate rather than the `finalize_solution`
965    /// payload — the CLI's `on_converged` hook feeding the `.sol` and
966    /// the JSON report — can undo the substitution. `None` when no
967    /// variable scaling was applied.
968    variable_scaling: RefCell<Option<Vec<Number>>>,
969    /// Whether the most recent `optimize_constrained` ran with per-row
970    /// constraint scaling active (`c_scale_vec`/`d_scale_vec` present).
971    ///
972    /// Read by [`Self::run_l1_penalty_outer_loop`], which measures the
973    /// user's rows in the model's own units and so may only write that
974    /// number into the `final_unscaled_*` family. `SolveStatistics`
975    /// documents `final_*` as the internally-scaled residuals and
976    /// `final_unscaled_*` as the same quantities in original units,
977    /// *equal when no scaling is active* — so the measurement may be
978    /// mirrored into the scaled family exactly when this is `false`
979    /// (gh#794 review). `None` when no solve has run.
980    row_scaling_active: std::cell::Cell<Option<bool>>,
981    /// Whether the submitted TNLP has already been explicitly wrapped by the
982    /// caller's presolve layer.
983    presolve_already_applied: bool,
984    reg_options: Rc<RegisteredOptions>,
985    journalist: Rc<Journalist>,
986    statistics: RefCell<SolveStatistics>,
987    /// Shared per-subsystem timing accumulator. Re-created at the top of
988    /// every solve (so back-to-back `optimize_tnlp` calls don't bleed
989    /// timings across invocations) and handed to the data, the NLP, and
990    /// any other consumer via `Rc`. Reported by [`Self::timing_stats`]
991    /// after the solve completes.
992    timing: RefCell<Rc<TimingStatistics>>,
993    /// Optional override factory for the symmetric linear-solver
994    /// backend. When `None`, we ship the workspace default (MA57 via
995    /// `pounce-hsl`). Tests can plug a stub via [`Self::set_linear_backend_factory`].
996    linear_backend_factory: Option<LinearBackendFactory>,
997    /// Optional factory for the restoration phase. Lives outside this
998    /// crate because `pounce-algorithm` cannot depend on
999    /// `pounce-restoration` (the dep edge is the other way). Callers
1000    /// that need restoration plug a factory via
1001    /// [`Self::set_restoration_factory`]; when unset, the outer
1002    /// algorithm runs without a restoration fallback and surfaces
1003    /// `RestorationFailure` as soon as the line-search would otherwise
1004    /// jump into restoration.
1005    restoration_factory: Option<RestorationFactory>,
1006    /// Shared diagnostic-dump state, installed by the CLI when the
1007    /// user passes `--dump <cat>:<spec>`. When set, the application
1008    /// propagates an `Rc<DiagnosticsState>` into [`IpoptAlgorithm`]
1009    /// via [`IpoptAlgorithm::with_diagnostics`] so the KKT solver and
1010    /// other dump sites can consult per-iter gating.
1011    diagnostics: Option<Rc<DiagnosticsState>>,
1012    /// Optional interactive debugger hook. When set, it is moved into
1013    /// the main [`IpoptAlgorithm`] for the next `optimize_*` call via
1014    /// [`IpoptAlgorithm::with_debug_hook`], so a REPL or agent can pause
1015    /// at each iteration to inspect / mutate live state. Consumed on use
1016    /// (one solve per installed hook).
1017    debug_hook: Option<std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>>,
1018    /// Provider for the BNW outer loop (pounce#10 Phase 3). When set,
1019    /// `optimize_constrained` consults the provider before each inner
1020    /// solve, replacing `restoration_factory` with a fresh one so
1021    /// multi-pass drivers can run the inner IPM repeatedly without
1022    /// tripping the default factory's one-shot guard.
1023    restoration_factory_provider: Option<RestorationFactoryProvider>,
1024    /// Optional hook fired once per `optimize_*` call on convergence,
1025    /// before the user TNLP's `finalize_solution`. See
1026    /// [`ConvergedCallback`].
1027    on_converged: Option<ConvergedCallback>,
1028    /// Re-evaluate `W` at the converged point before `on_converged` fires.
1029    /// See [`Self::set_on_converged_refreshes_hessian`].
1030    on_converged_refreshes_hessian: bool,
1031    /// Ids handed out so far to `on_converged` firings; the next firing gets
1032    /// one more. Never reset, so an id is unique over the application's life.
1033    /// See [`IpoptData::on_converged_id`](crate::ipopt_data::IpoptData).
1034    on_converged_fired: std::cell::Cell<u64>,
1035    /// When `true`, the per-iteration `IterRecord` trajectory is
1036    /// captured into [`SolveStatistics::iterations`] for downstream
1037    /// consumers (the JSON solve report in pounce-cli, pounce#8). Off
1038    /// by default so library callers that never read the iterations
1039    /// vector don't pay the per-iter alloc.
1040    record_iter_history: bool,
1041    /// Whether [`Self::initialize_with_option_file`] ran — i.e. whether
1042    /// anything on this application actually consulted
1043    /// `option_file_name` and resolved it to a file. Only the `pounce`
1044    /// CLI does; a library caller sets its options directly. The guard
1045    /// in [`Self::unhonored_option_file_name`] reads this so that
1046    /// setting the option on a surface that cannot honor it is refused
1047    /// rather than dropped (gh#518).
1048    option_file_resolved: bool,
1049    /// Whether this caller can route a model to the convex LP/QP/SOCP
1050    /// engines — i.e. whether the `qp_*` knobs those engines read
1051    /// configure anything here. Only the `pounce` CLI can (it owns the
1052    /// `.nl` structure extraction that classifies a model), and it says
1053    /// so via [`Self::set_convex_routing_available`]. The guard in
1054    /// [`Self::unhonored_convex_option`] reads this, on the same
1055    /// contract as `option_file_resolved` above (gh#604).
1056    convex_routing_available: bool,
1057    /// Whether the backend-knob warnings (gh#551) have already been
1058    /// printed for this application. The CLI emits them before routing —
1059    /// a convex model never reaches `optimize_tnlp` — and `optimize_tnlp`
1060    /// emits them for every other frontend; without this flag a CLI run
1061    /// would print each line twice, which is how a warning teaches its
1062    /// reader to skip it.
1063    backend_warnings_emitted: bool,
1064    /// Shared sink that the linear-solver backend writes a rolling
1065    /// [`LinearSolverSummary`] into after every factor. Reset at the
1066    /// top of every solve (so back-to-back `optimize_tnlp` calls don't
1067    /// bleed stats across invocations) and read out via
1068    /// [`Self::linear_solver_summary`] once the solve returns. Only
1069    /// the workspace-default FERAL backend (via
1070    /// [`default_backend_factory_with_sink`]) wires the sink today;
1071    /// custom factories plugged through [`Self::set_linear_backend_factory`]
1072    /// and the HSL MA57 backend leave the sink empty.
1073    linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1074    /// Companion to [`Self::linsol_summary_sink`] for the restoration
1075    /// phase's sub-solves. The frontends that wire a restoration factory
1076    /// install it via [`Self::restoration_summary_sink`]; it is reset with
1077    /// the main sink and surfaces as [`LinearSolverSummary::restoration`].
1078    resto_linsol_summary_sink: Arc<Mutex<LinearSolverSummary>>,
1079    /// The block-parallel KKT partition this solve resolved, published for
1080    /// the restoration sub-IPM (structured-KKT Phase 5b). Restoration's inner
1081    /// builder is minted by the frontend *before* the solve — before the KKT
1082    /// layout, and so the mapping onto it, exists — so the labels cannot be
1083    /// installed on it directly. They are written here as the outer algorithm
1084    /// is built and read when restoration runs. `AugRestoSystemSolver` reduces
1085    /// the restoration KKT onto the original 4-block system before delegating,
1086    /// so the matrix the inner solver factors is the one these labels
1087    /// describe. Reset with the sinks at the top of every solve.
1088    kkt_blocks_published: crate::alg_builder::KktBlocksCell,
1089    /// Shared tally of successful linear-solver quality escalations for
1090    /// the current solve (gh#857). Handed to every `AlgorithmBuilder`
1091    /// this application mints — [`Self::algorithm_builder_from_options`]
1092    /// and [`Self::algorithm_builder_snapshot`] — which is how the
1093    /// restoration sub-solve counts into the same total: each frontend
1094    /// builds the restoration provider's inner builder from
1095    /// `algorithm_builder_from_options`, so it receives this same `Rc`
1096    /// without any frontend having to know the counter exists.
1097    ///
1098    /// Reset at the top of every solve, beside the linear-solver summary
1099    /// sink and for the same reason: a second-opinion retry, or two
1100    /// back-to-back `optimize_tnlp` calls, must not inherit the previous
1101    /// solve's count. Read out into
1102    /// [`SolveStatistics::quality_escalations`] once the solve returns.
1103    quality_escalations: Rc<std::cell::Cell<u64>>,
1104    /// gh#990: the `mu_strategy` value in the option table was written by a
1105    /// POUNCE frontend (the Python no-`hessian` path pins `monotone`), not by
1106    /// the caller. See [`Self::mark_mu_strategy_pounce_chosen`].
1107    mu_strategy_pounce_chosen: bool,
1108    /// gh#884. Set when the running [`IpoptAlgorithm`] observed the
1109    /// biactive dual-divergence signature — a converged primal, a step
1110    /// that has gone to zero on a scale-relative measure, and an
1111    /// *unscaled* dual infeasibility still far above `dual_inf_tol`, all
1112    /// at the same iterate.
1113    ///
1114    /// Read out of the algorithm once `optimize_constrained` returns, so
1115    /// [`Self::run_with_dual_divergence_retry`] — which sits above that
1116    /// call — can see it. Reset at the top of every solve for the same
1117    /// reason as `quality_escalations`: a retry must not inherit the
1118    /// previous attempt's verdict. Also copied into
1119    /// [`SolveStatistics::dual_divergence_signature`].
1120    dual_divergence_signature: std::cell::Cell<bool>,
1121    /// The returned run's algorithm released the tiny-step stop through the
1122    /// `tiny_step_dual_stall_iters` rule. Read by the mu-strategy fallback,
1123    /// which retries a `Search_Direction_Becomes_Too_Small` reached this way
1124    /// as it does an iteration limit. Reset at the top of every solve.
1125    tiny_step_dual_stall: std::cell::Cell<bool>,
1126    /// gh#990 item 3: the derivative checker's structured result for the
1127    /// current solve; copied onto the statistics when the solve finishes.
1128    derivative_check: RefCell<Option<pounce_nlp::derivative_test::DerivativeCheckSummary>>,
1129    /// gh#990 item 13: some attempt of this run refused a termination
1130    /// certificate the objective scaling had masked (strict, acceptable).
1131    /// Sticky across the attempts a retry driver spends, like
1132    /// `dual_divergence_signature`: the returned run is often a re-solve, and
1133    /// the decision that led to it belongs on the record.
1134    obj_scale_refused: std::cell::Cell<(bool, bool)>,
1135    /// gh#884. Set when a dual-divergence retry actually replaced the base
1136    /// attempt's answer. Copied into
1137    /// [`SolveStatistics::dual_divergence_retry_promoted`].
1138    dual_divergence_retry_promoted: std::cell::Cell<bool>,
1139    /// gh#1042 C1. What the `mu_strategy_fallback` retry did in this solve,
1140    /// if it ran. Copied into [`SolveStatistics::mu_strategy_fallback`] by
1141    /// every attempt that follows it, and written into the statistics
1142    /// directly once the retry has decided — so a promoted re-solve no
1143    /// longer hides the first attempt's verdict and cost.
1144    mu_strategy_fallback_record: RefCell<Option<pounce_nlp::MuStrategyFallbackRecord>>,
1145    /// Set when a losing retry's answer was thrown away and an earlier
1146    /// attempt's replayed through `FinalizeSnapshot::replay` — by the μ
1147    /// fallback (pounce#870) or the gh#884 dual-divergence retry.
1148    ///
1149    /// It exists because [`Self::set_on_converged`] fires **per attempt**
1150    /// and the floor does not reach it. A losing retry that reached
1151    /// `Solve_Succeeded` has already run the callback, so a consumer
1152    /// capturing the converged iterate there — the CLI's `nominal_capture`,
1153    /// which is where `.sol` `x`, the JSON's `solution.x` and the dual
1154    /// block all come from — holds the *discarded* attempt's point while
1155    /// the status, objective and every statistic beside it have been
1156    /// floored back to the attempt that won. Measured before this flag
1157    /// existed: on a declined retry the `.sol` carried `f = -6.3274` while
1158    /// the JSON report next to it said `-6.1768`, and `pounce verify` on
1159    /// the `.sol` confirmed the file held the losing point.
1160    ///
1161    /// The `finalize_solution` payload does not have this problem — the
1162    /// replay *is* a `finalize_solution` call, so the last one always
1163    /// carries the answer being reported — which is why the fix is to tell
1164    /// the caller "prefer that payload", not to re-run the callback (the
1165    /// converged KKT state the callback borrows belongs to the retry by
1166    /// then, and cannot be rewound). Consumers of that state select the
1167    /// reported attempt's firing through [`Self::reported_on_converged_id`].
1168    answer_restored_from_floor: std::cell::Cell<bool>,
1169    /// Set only for the duration of the gh#983 scale audit's re-solve: the
1170    /// interior-point arm then widens the inequality rows by
1171    /// `bound_relax_factor` as usual but leaves the **variable box as the
1172    /// caller declared it** (`OrigIpoptNlp::relax_bounds_keeping_box`). See
1173    /// `run_scale_retry` for why.
1174    retry_keeps_declared_box: std::cell::Cell<bool>,
1175    /// The payload of the most recent `finalize_solution` POUNCE sent to the
1176    /// user's TNLP, so a second-opinion retry that loses can put the winning
1177    /// attempt's answer back (pounce#870).
1178    ///
1179    /// Written by [`finalize_via_orig_nlp`] and [`finalize_via_sqp`], which are
1180    /// free functions and so take this as a sink rather than reaching for
1181    /// `self`, and by [`Self::restore_floor`] when a floor is replayed, so it
1182    /// always holds the answer currently delivered. Cleared at the start of
1183    /// each solve. Read by the retry wrappers (each floors to it) and by
1184    /// [`Self::reported_on_converged_id`].
1185    last_finalize: RefCell<Option<FinalizeSnapshot>>,
1186    /// The last `IterStats` sent to the user's `intermediate_callback`
1187    /// (pounce#870), shared with the running `IpoptAlgorithm`.
1188    last_iter_stats: Rc<RefCell<Option<pounce_nlp::tnlp::IterStats>>>,
1189    /// Phase 5c (§6) SQP warm-start input. When `Some`, the next
1190    /// `optimize_tnlp` call on the SQP path consumes the iterate
1191    /// instead of cold-starting; consumed once per solve, then
1192    /// auto-cleared. The IPM path ignores this field. Wire-set
1193    /// via [`Self::set_sqp_warm_start`].
1194    sqp_warm_start: Option<crate::sqp::SqpIterates>,
1195    /// Phase 5c (§6) SQP warm-start output. Populated by every
1196    /// `optimize_sqp_tnlp` call with the final QP working set.
1197    /// Stays valid until the next solve (which overwrites it).
1198    /// Accessed via [`Self::last_sqp_working_set`].
1199    sqp_last_working_set: Option<pounce_qp::WorkingSet>,
1200    /// gh#986 review item 10: the fixed-variable elimination of the solve in
1201    /// progress, `(x_not_fixed_map, n_full_x)`. Working sets are published in
1202    /// the caller's full space (fixed variables marked `Fixed`) and warm
1203    /// starts are mapped through it, so a working set recorded on one node
1204    /// lands on the right columns of a node that fixes different variables.
1205    x_elimination: Option<(Vec<Index>, usize)>,
1206    /// What the post-convergence crossover phase did on the most recent
1207    /// IPM solve (gh#612). `None` when `crossover=no` (the default) or
1208    /// when the solve did not converge — crossover only runs on a
1209    /// converged interior iterate. Read via [`Self::crossover_report`].
1210    ///
1211    /// Kept separate from `sqp_last_working_set`, which crossover *also*
1212    /// populates on success: that field answers "what can the next solve
1213    /// warm-start from", this one answers "was the active set I am about
1214    /// to trust actually identified, or merely inferred".
1215    crossover_report: Option<crate::crossover::CrossoverReport>,
1216    /// What the interior-point → active-set handover did on the most recent
1217    /// IPM solve (gh#1054). `None` when `ipm_sqp_handover=no` (the default).
1218    /// Read via [`Self::handover_report`].
1219    handover_report: Option<crate::handover::HandoverReport>,
1220    /// Whether the current solve is an `algorithm=active-set-sqp` request
1221    /// run as interior point plus handover; see [`Self::sqp_auto_handover`].
1222    auto_handover: std::cell::Cell<bool>,
1223    /// Full primal-dual warm-start iterate for the IPM path, captured by
1224    /// the interactive debugger's `resolve` command. When `Some`, the
1225    /// next `optimize_tnlp` installs this 8-vector (algorithm space)
1226    /// directly onto `data.curr` before the iterate initializer runs, so
1227    /// a warm `resolve` continues from the paused interior point rather
1228    /// than cold-restarting the duals. Consumed once per solve, then
1229    /// auto-cleared. Requires `warm_start_init_point=yes` so the
1230    /// re-optimize branch of `WarmStartIterateInitializer` keeps the
1231    /// installed iterate. Wire-set via [`Self::set_warm_start_iterate`].
1232    warm_start_iterate: Option<crate::debug::IterateSnapshot>,
1233    /// The warm-start initializer's verdict on the most recent solve's
1234    /// supplied iterate (gh#606). Lifted off the solve-local
1235    /// `IpoptData` so a caller can read it after `optimize_tnlp`
1236    /// returns; `None` when the last solve was a cold start.
1237    warm_start_diag: RefCell<Option<crate::init::warm_start::WarmStartDiagnostics>>,
1238    /// Caller-supplied fill-reducing permutation for the KKT linear
1239    /// solver (pounce#180 item 1 / FERAL#107). When `Some`, it overrides
1240    /// whatever `feral_ordering` / `POUNCE_FERAL_ORDERING` resolves to,
1241    /// installing [`pounce_feral::OrderingMethod::External`] on the FERAL
1242    /// backend for the next solve. The vector is a **0-based, new-to-old
1243    /// permutation** whose length must equal the augmented KKT system
1244    /// dimension; FERAL validates it as a bijection and returns
1245    /// `InvalidInput` (never panics) on a wrong length / index. Unlike the
1246    /// warm-start hooks this is treated as persistent config — it is *not*
1247    /// auto-cleared after a solve, so a caller sets it once for a run.
1248    /// Wire-set via [`Self::set_external_ordering`]. Ignored by non-FERAL
1249    /// backends and by any custom factory plugged via
1250    /// [`Self::set_linear_backend_factory`].
1251    external_ordering: Option<Vec<usize>>,
1252    /// Caller-supplied block-triangular / Schur KKT partition (pounce#180
1253    /// item 2). When `Some`, the next IPM solve on the feral + exact-Hessian
1254    /// path routes the KKT linear solve through a
1255    /// [`crate::kkt::SchurAugSystemSolver`] over these **KKT-space indices**
1256    /// (`0..dim` in the `x, s, c, d` block order the aug-system solver
1257    /// assembles): the `S` block is Schur-complemented out and only the two
1258    /// diagonal blocks are factorized, with inertia recovered via Sylvester's
1259    /// law. Beneficial only when `|S| ≪` the eliminated block; the Schur solver
1260    /// falls back to the standard full-space solver transparently when the
1261    /// partition is unsuitable (too large, malformed, or the backend errors),
1262    /// so a stray hook never breaks a solve. Persistent config (not
1263    /// auto-cleared). Wire-set via [`Self::set_kkt_schur_block`].
1264    kkt_schur_block: Option<Vec<usize>>,
1265    /// Block-parallel KKT partition (structured-KKT Phase 5b): KKT-space block
1266    /// labels, `< 0` for the shared border, **empty** meaning "detect".
1267    /// Wire-set via [`Self::set_kkt_block_structure`].
1268    kkt_blocks: Option<Vec<i32>>,
1269    /// The same partition declared in the *model's* own terms — one block per
1270    /// variable and per constraint — which [`map_block_structure_to_kkt`]
1271    /// turns into `kkt_blocks` once the NLP layout is known. Wire-set via
1272    /// [`Self::set_block_structure`].
1273    model_blocks: Option<(Vec<i32>, Vec<i32>)>,
1274    /// The problem-statistics block most recently printed during the current
1275    /// run, so a retry attempt does not reprint an identical one.
1276    ///
1277    /// Every retry driver — the ℓ₁ fallback, the μ-strategy fallback, the
1278    /// second-opinion ladder, the dual-divergence retry — re-enters the solve
1279    /// routine that emits this block, so a run that retried once printed the
1280    /// whole Ipopt-style header twice with nothing between the copies saying a
1281    /// second attempt had started. Read as "the solver printed everything
1282    /// twice", which is what it looked like.
1283    ///
1284    /// Scoped to one run: reset at the top of
1285    /// [`Self::optimize_tnlp_with_derivative_test_tnlp`], which every entry
1286    /// point funnels through. Without that reset a library caller's second
1287    /// deliberate `optimize_tnlp` on the same application would lose its
1288    /// header, which is a different thing entirely from a retry inside one
1289    /// call.
1290    ///
1291    /// Compared rather than counted because the block can legitimately differ
1292    /// between attempts: the ℓ₁ wrapper adds slack variables, so its retry
1293    /// solves a genuinely larger problem and reprinting is informative.
1294    last_printed_problem_stats: RefCell<Option<pounce_solve_report::console::ProblemStats>>,
1295    /// Set while an *outside* retry driver is re-entering `optimize_tnlp` for
1296    /// another attempt on the same problem — today only
1297    /// `pounce_restoration::second_opinion_driver::run_second_opinion_ladder`.
1298    ///
1299    /// The retries that nest INSIDE one `optimize_tnlp` call (the ℓ₁ fallback,
1300    /// the μ-strategy fallback) are covered by `last_printed_problem_stats`
1301    /// alone, because the funnel that resets it runs once for all of them. The
1302    /// ladder's rungs are `optimize_tnlp` calls in their own right, so without
1303    /// this flag each one resets the memo and reprints the header — which is
1304    /// how a four-rung ladder printed five identical copies of it.
1305    ///
1306    /// It also decides who explains the retry. The ladder narrates every rung
1307    /// on stderr, naming the knob it varies and whether the rung recovered, so
1308    /// `emit_problem_stats` stays quiet and lets that narration stand. The
1309    /// in-call fallbacks say nothing at all, so there the suppressed header is
1310    /// replaced by a line announcing the attempt.
1311    in_retry_sequence: std::cell::Cell<bool>,
1312    /// Nesting depth of retry drivers that have taken ownership of the
1313    /// run-ending `EXIT:` / `POUNCE <version>:` verdict.
1314    ///
1315    /// `emit_end_summary` prints the per-attempt statistics block whatever
1316    /// this reads, and prints the verdict only at zero. A driver raises it
1317    /// before its first attempt and lowers it after its last, then prints the
1318    /// verdict once with the status it is actually returning.
1319    ///
1320    /// A counter rather than a flag because the drivers nest: the ℓ₁ fallback
1321    /// can wrap the μ-strategy fallback, which the dual-divergence retry can
1322    /// wrap in turn, and the CLI brackets the whole lot again around the
1323    /// second-opinion ladder. Only the outermost knows the run is over, and
1324    /// "outermost" is exactly "the one that brings this back to zero".
1325    end_verdict_deferrals: std::cell::Cell<u32>,
1326}
1327
1328impl fmt::Debug for IpoptApplication {
1329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330        f.debug_struct("IpoptApplication")
1331            .field("options", &self.options)
1332            .field("statistics", &self.statistics)
1333            .finish_non_exhaustive()
1334    }
1335}
1336
1337impl Default for IpoptApplication {
1338    fn default() -> Self {
1339        Self::new()
1340    }
1341}
1342
1343impl IpoptApplication {
1344    /// New application with empty options and a default journalist.
1345    /// Equivalent to `IpoptApplication::IpoptApplication(true,true)`.
1346    pub fn new() -> Self {
1347        let reg = RegisteredOptions::default();
1348        // Registration of a fresh registry can only fail on a duplicate
1349        // name, which would be a programming error in `reg_op`.
1350        register_all_upstream_options(&reg)
1351            .unwrap_or_else(|e| panic!("Upstream options registration failed: {e}"));
1352        pounce_presolve::register_options(&reg)
1353            .unwrap_or_else(|e| panic!("Presolve options registration failed: {e}"));
1354        let reg = Rc::new(reg);
1355        Self {
1356            options: OptionsList::with_registered(Rc::clone(&reg)),
1357            least_square_init_report: None,
1358            variable_scaling: RefCell::new(None),
1359            row_scaling_active: std::cell::Cell::new(None),
1360            presolve_already_applied: false,
1361            reg_options: reg,
1362            journalist: Rc::new(Journalist::new()),
1363            statistics: RefCell::new(SolveStatistics::new()),
1364            timing: RefCell::new(Rc::new(TimingStatistics::new())),
1365            linear_backend_factory: None,
1366            restoration_factory: None,
1367            diagnostics: None,
1368            debug_hook: None,
1369            restoration_factory_provider: None,
1370            on_converged: None,
1371            on_converged_refreshes_hessian: true,
1372            on_converged_fired: std::cell::Cell::new(0),
1373            record_iter_history: false,
1374            option_file_resolved: false,
1375            convex_routing_available: false,
1376            backend_warnings_emitted: false,
1377            linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1378            resto_linsol_summary_sink: Arc::new(Mutex::new(LinearSolverSummary::default())),
1379            kkt_blocks_published: Arc::new(Mutex::new(None)),
1380            quality_escalations: Rc::new(std::cell::Cell::new(0)),
1381            mu_strategy_pounce_chosen: false,
1382            dual_divergence_signature: std::cell::Cell::new(false),
1383            tiny_step_dual_stall: std::cell::Cell::new(false),
1384            derivative_check: RefCell::new(None),
1385            obj_scale_refused: std::cell::Cell::new((false, false)),
1386            dual_divergence_retry_promoted: std::cell::Cell::new(false),
1387            mu_strategy_fallback_record: RefCell::new(None),
1388            answer_restored_from_floor: std::cell::Cell::new(false),
1389            retry_keeps_declared_box: std::cell::Cell::new(false),
1390            last_finalize: RefCell::new(None),
1391            last_iter_stats: Rc::new(RefCell::new(None)),
1392            sqp_warm_start: None,
1393            sqp_last_working_set: None,
1394            x_elimination: None,
1395            crossover_report: None,
1396            handover_report: None,
1397            auto_handover: std::cell::Cell::new(false),
1398            warm_start_iterate: None,
1399            warm_start_diag: RefCell::new(None),
1400            external_ordering: None,
1401            kkt_schur_block: None,
1402            kkt_blocks: None,
1403            model_blocks: None,
1404            last_printed_problem_stats: RefCell::new(None),
1405            in_retry_sequence: std::cell::Cell::new(false),
1406            end_verdict_deferrals: std::cell::Cell::new(0),
1407        }
1408    }
1409
1410    pub fn options(&self) -> &OptionsList {
1411        &self.options
1412    }
1413
1414    pub fn options_mut(&mut self) -> &mut OptionsList {
1415        &mut self.options
1416    }
1417
1418    /// Declare whether callers have already applied an explicit presolve
1419    /// wrapper to the TNLPs submitted to [`Self::optimize_tnlp`].
1420    ///
1421    /// When set, `optimize_tnlp` leaves its input TNLP unchanged even if the
1422    /// `presolve` option is enabled. This preserves the option table for
1423    /// reporting and debugger use while allowing specialized frontends to
1424    /// supply a wrapper with capabilities unavailable to generic callback
1425    /// TNLPs, such as an expression provider for FBBT.
1426    pub fn set_presolve_already_applied(&mut self, applied: bool) {
1427        self.presolve_already_applied = applied;
1428    }
1429
1430    /// Solve without materializing the generic presolve wrapper.
1431    ///
1432    /// This is for consumers that require the original TNLP coordinate system
1433    /// for the solve's KKT matrix, such as sensitivity and reduced-Hessian
1434    /// drivers. It is scoped to this invocation and does not change the
1435    /// application's `presolve` option or persistent explicit-wrapper setting.
1436    pub fn optimize_tnlp_without_presolve(
1437        &mut self,
1438        tnlp: Rc<RefCell<dyn TNLP>>,
1439    ) -> ApplicationReturnStatus {
1440        let explicit_wrapper = self.presolve_already_applied;
1441        self.presolve_already_applied = true;
1442        let status = self.optimize_tnlp(tnlp);
1443        self.presolve_already_applied = explicit_wrapper;
1444        status
1445    }
1446
1447    pub fn registered_options(&self) -> &Rc<RegisteredOptions> {
1448        &self.reg_options
1449    }
1450
1451    pub fn journalist(&self) -> &Rc<Journalist> {
1452        &self.journalist
1453    }
1454
1455    /// Plug a custom symmetric-linear-solver factory. Useful for tests
1456    /// that want to swap MA57 for a stub. Production callers should
1457    /// leave this unset — the default ([`default_backend_factory`])
1458    /// returns the workspace's MA57 binding.
1459    pub fn set_linear_backend_factory(&mut self, factory: LinearBackendFactory) {
1460        self.linear_backend_factory = Some(factory);
1461    }
1462
1463    /// Plug a restoration-phase factory. Called once per
1464    /// `optimize_tnlp` invocation to mint a fresh
1465    /// `Box<dyn RestorationPhase>` that the outer algorithm uses as
1466    /// its line-search restoration fallback. Lives behind a setter
1467    /// (rather than at construction) because the concrete restoration
1468    /// strategies live in `pounce-restoration`, which depends on this
1469    /// crate; consumers in `pounce-cli` / integration tests wire the
1470    /// factory at the application boundary.
1471    pub fn set_restoration_factory(&mut self, factory: RestorationFactory) {
1472        self.restoration_factory = Some(factory);
1473    }
1474
1475    /// Install the shared diagnostics state. Once set, every
1476    /// subsequent `optimize_tnlp` call forwards the state into the
1477    /// algorithm via [`IpoptAlgorithm::with_diagnostics`] so the KKT
1478    /// solver can emit `--dump kkt:...` artifacts.
1479    pub fn set_diagnostics(&mut self, diag: Rc<DiagnosticsState>) {
1480        self.diagnostics = Some(diag);
1481    }
1482
1483    /// Install an interactive debugger hook for the next `optimize_*`
1484    /// call. The hook is moved into the main [`IpoptAlgorithm`] and
1485    /// consumed by that solve; reinstall it to debug a subsequent solve.
1486    pub fn set_debug_hook(
1487        &mut self,
1488        hook: std::rc::Rc<std::cell::RefCell<dyn crate::debug::DebugHook>>,
1489    ) {
1490        self.debug_hook = Some(hook);
1491    }
1492
1493    /// Read-side accessor for the installed diagnostics state, if any.
1494    /// Lets the CLI write the top-level manifest/timing files after
1495    /// the solve completes.
1496    pub fn diagnostics(&self) -> Option<Rc<DiagnosticsState>> {
1497        self.diagnostics.as_ref().map(Rc::clone)
1498    }
1499
1500    /// The three options that decide how the TNLP is *classified* before any
1501    /// algorithm sees it: the two infinity thresholds and the fixed-variable
1502    /// treatment.
1503    ///
1504    /// One reader, because there were three copies and they drifted. The
1505    /// active-set SQP path built its adapter with `TNLPAdapter::new`, which
1506    /// hard-codes the same three defaults — so the options were accepted and
1507    /// discarded on that arm, and a model with `fixed_variable_treatment=
1508    /// relax_bounds` or a non-default `nlp_upper_bound_inf` was classified one
1509    /// way for the interior-point arm and another for this one. Silently: the
1510    /// defaults coincide, so it only diverges for a caller who sets them, and
1511    /// nothing reported the difference.
1512    ///
1513    /// `make_constraint` / `make_parameter_nodual` are not implemented and
1514    /// fall back to `make_parameter`; the adapter auto-retries to
1515    /// `relax_bounds` when `make_parameter` would leave `n_x_var < n_c`
1516    /// (upstream `IpTNLPAdapter.cpp:623-633`).
1517    fn adapter_options(&self) -> (Number, Number, FixedVarTreatment) {
1518        let lo_inf = self
1519            .options
1520            .get_numeric_value("nlp_lower_bound_inf", "")
1521            .ok()
1522            .and_then(|(v, f)| f.then_some(v))
1523            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF);
1524        let up_inf = self
1525            .options
1526            .get_numeric_value("nlp_upper_bound_inf", "")
1527            .ok()
1528            .and_then(|(v, f)| f.then_some(v))
1529            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF);
1530        let fixed_treatment = match self
1531            .options
1532            .get_string_value("fixed_variable_treatment", "")
1533            .ok()
1534            .and_then(|(v, f)| f.then_some(v))
1535            .as_deref()
1536        {
1537            Some("relax_bounds") => FixedVarTreatment::RelaxBounds,
1538            _ => FixedVarTreatment::MakeParameter,
1539        };
1540        (lo_inf, up_inf, fixed_treatment)
1541    }
1542
1543    /// Whether the final solution reports bound multipliers for variables
1544    /// `make_parameter` removed (see
1545    /// `OrigIpoptNlp::complete_fixed_var_bound_multipliers`).
1546    /// Ipopt 3.14 does, for every treatment except `make_parameter_nodual`,
1547    /// which exists to ask it not to.
1548    pub fn reports_fixed_var_duals(&self) -> bool {
1549        !matches!(
1550            self.options
1551                .get_string_value("fixed_variable_treatment", "")
1552                .ok()
1553                .map(|(v, _)| v)
1554                .as_deref(),
1555            Some("make_parameter_nodual")
1556        )
1557    }
1558
1559    /// Mark that the next `optimize_*` calls are further **attempts at the
1560    /// same problem**, driven from outside, rather than new solves.
1561    ///
1562    /// Retry drivers that re-enter `optimize_tnlp` per attempt — the
1563    /// second-opinion ladder is the only one today — bracket their attempts
1564    /// with `true` … `false`. The effect is confined to console presentation:
1565    /// the Ipopt-style problem-statistics header is printed once for the run
1566    /// instead of once per attempt. Nothing about the solve changes.
1567    ///
1568    /// Callers must clear it on every exit path, including the early returns a
1569    /// ladder takes when a rung promotes; a stuck `true` costs a later solve
1570    /// its header and nothing worse.
1571    pub fn set_in_retry_sequence(&self, active: bool) {
1572        self.in_retry_sequence.set(active);
1573    }
1574
1575    /// Take ownership of the run-ending `EXIT:` / `POUNCE <version>:` verdict
1576    /// for the attempts that follow.
1577    ///
1578    /// Between this and [`Self::release_end_verdict`] the per-attempt end
1579    /// summary prints its statistics block but not the verdict, so a retried
1580    /// run no longer reports a mid-run verdict that reads as the final answer.
1581    /// The releaser prints it once, with the status it is returning.
1582    ///
1583    /// Callers must pair the two on every exit path. An unmatched acquire
1584    /// costs the run its verdict line; the counter saturates rather than
1585    /// wrapping, so an unmatched release cannot make a nested driver print
1586    /// one early.
1587    pub fn defer_end_verdict(&self) {
1588        self.end_verdict_deferrals
1589            .set(self.end_verdict_deferrals.get().saturating_add(1));
1590    }
1591
1592    /// Release one [`Self::defer_end_verdict`]. Returns `true` when this was
1593    /// the outermost one — i.e. when the caller now owns printing the verdict.
1594    #[must_use]
1595    pub fn release_end_verdict(&self) -> bool {
1596        let next = self.end_verdict_deferrals.get().saturating_sub(1);
1597        self.end_verdict_deferrals.set(next);
1598        next == 0
1599    }
1600
1601    /// Print the run-ending verdict, honouring `print_level`.
1602    ///
1603    /// The gate matches `emit_end_summary`'s, which is the block this follows:
1604    /// at `print_level 0` there is no summary for it to end.
1605    pub fn print_end_verdict(&self, status: ApplicationReturnStatus) {
1606        let console_output = match self.options.get_integer_value("print_level", "") {
1607            Ok((v, true)) => v >= 1,
1608            _ => true,
1609        };
1610        if console_output {
1611            pounce_solve_report::console::print_exit_verdict(status);
1612        }
1613    }
1614
1615    /// Plug a restoration-phase **factory provider** for drivers that
1616    /// need to run the inner IPM more than once per `optimize_tnlp`
1617    /// call (notably the Phase-3 ℓ₁-exact penalty-barrier outer loop,
1618    /// pounce#10). On each inner solve, the application consults the
1619    /// provider to mint a fresh [`RestorationFactory`], replacing any
1620    /// stale one, so the default one-shot restoration factory does
1621    /// not panic on its second invocation. If both `set_restoration_factory`
1622    /// and this are configured, the provider wins.
1623    pub fn set_restoration_factory_provider(&mut self, provider: RestorationFactoryProvider) {
1624        self.restoration_factory_provider = Some(provider);
1625    }
1626
1627    /// Register a callback to run once the IPM has converged (status
1628    /// [`ApplicationReturnStatus::SolveSucceeded`] or
1629    /// [`ApplicationReturnStatus::SolvedToAcceptableLevel`]) but before
1630    /// `finalize_solution` flows back to the TNLP. See
1631    /// [`ConvergedCallback`] for the use case (post-optimal sensitivity).
1632    pub fn set_on_converged(&mut self, cb: ConvergedCallback) {
1633        self.on_converged = Some(cb);
1634    }
1635
1636    /// Remove and return the registered on-converged callback, if any, so a
1637    /// caller that installs its own for a while can put the previous one
1638    /// back (`pounce_minima::IpoptLocalSolve` does, gh#966).
1639    pub fn take_on_converged(&mut self) -> Option<ConvergedCallback> {
1640        self.on_converged.take()
1641    }
1642
1643    /// Whether `data.w` is re-evaluated at the converged point `w*` before
1644    /// the [`Self::set_on_converged`] hook fires. On by default.
1645    ///
1646    /// The main loop checks convergence before it updates the Hessian, so at
1647    /// that moment `data.w` is still `W(w_k)` from the final Newton step,
1648    /// while the Jacobians, slacks, multipliers and `Σ` are read at `w*`. A
1649    /// hook that factors the KKT matrix (post-optimal sensitivity) needs the
1650    /// Hessian at `w*` too, or it factors a hybrid of two iterates.
1651    ///
1652    /// The refresh costs one Hessian evaluation, counted in the solve's
1653    /// statistics like any other. A hook that only reads the iterate and
1654    /// never factors (the CLI collecting duals for a `.sol` file) can turn it
1655    /// off so a plain solve reports the same evaluation counts with or
1656    /// without the hook installed.
1657    pub fn set_on_converged_refreshes_hessian(&mut self, refresh: bool) {
1658        self.on_converged_refreshes_hessian = refresh;
1659    }
1660
1661    /// Was the reported answer replayed from an earlier attempt's floor,
1662    /// after a later attempt lost?
1663    ///
1664    /// **A caller that captures the solution in [`Self::set_on_converged`]
1665    /// must consult this.** That callback fires once per *attempt*, and a
1666    /// losing retry that converged has already run it, so the capture
1667    /// belongs to the discarded point while everything else — status,
1668    /// objective, statistics — has been floored back. When this is `true`,
1669    /// take `x` and the multipliers from the last `finalize_solution`
1670    /// payload instead; that one is always the answer being reported,
1671    /// because the floor restores it *by* calling `finalize_solution`.
1672    ///
1673    /// The payload is in the **model's own units** and in the **reduced**
1674    /// presolve space: `CountingTnlp`-style consumers sit inside the gh#486
1675    /// scaling wrapper (so `x /= d`, `z *= d` have already been applied) and
1676    /// outside the presolve one (so the row/column lift has not). A caller
1677    /// swapping it in must therefore skip its own scaling correction and keep
1678    /// its own lift; getting that backwards squares the factor, which is a
1679    /// silent wrong answer of exactly the shape this flag exists to remove.
1680    ///
1681    /// A [`Self::set_on_converged`] consumer that needs more than the point --
1682    /// the converged KKT state and its factorization, which the payload does
1683    /// not carry and which cannot be rewound -- uses
1684    /// [`Self::reported_on_converged_id`] instead: it keeps each firing under
1685    /// its id and holds the one the solve reported, whose handles keep that
1686    /// attempt's state alive. `pounce-sensitivity`'s `Solver` and `SensSolve`
1687    /// and the CLI's hook do.
1688    ///
1689    /// `false` on every solve that never spent a second attempt, which is
1690    /// almost all of them, so the ordinary path is unaffected.
1691    pub fn answer_restored_from_floor(&self) -> bool {
1692        self.answer_restored_from_floor.get()
1693    }
1694
1695    /// The [`Self::set_on_converged`] firing whose attempt produced the
1696    /// answer the last solve reported, or `None` if that attempt did not fire
1697    /// the hook (it did not converge, or it was not the interior-point arm).
1698    ///
1699    /// The hook fires once per converged attempt, and when a later attempt
1700    /// loses the answer is replayed from an earlier one, so the most recent
1701    /// firing is not necessarily the reported one. A hook that keeps state
1702    /// files it under [`IpoptData::on_converged_id`](crate::ipopt_data::IpoptData)
1703    /// and keeps the firing this names; everything else it captured describes
1704    /// an attempt the solver discarded.
1705    pub fn reported_on_converged_id(&self) -> Option<u64> {
1706        self.last_finalize
1707            .borrow()
1708            .as_ref()
1709            .and_then(|s| s.on_converged_id)
1710    }
1711
1712    /// When the last solve ended in local infeasibility, probe the point it
1713    /// reported for a nearby point with less constraint violation
1714    /// ([`crate::infeasibility_saddle`]). `None` when the last solve reported
1715    /// anything else, or when the probe finds no such point.
1716    ///
1717    /// The point probed is the payload the user's TNLP was handed, so it is
1718    /// the reported point after any retry's floor; it is cleared at the start
1719    /// of every solve, so a stale point cannot be probed. `tnlp` must be the
1720    /// TNLP that solve ran on. Read by the second-opinion ladder.
1721    pub fn local_infeasibility_saddle_escape(
1722        &self,
1723        tnlp: &Rc<RefCell<dyn TNLP>>,
1724    ) -> Option<crate::infeasibility_saddle::SaddleEscape> {
1725        let x = self
1726            .last_finalize
1727            .borrow()
1728            .as_ref()
1729            .filter(|s| s.status == SolverReturn::LocalInfeasibility)
1730            .map(|s| s.x.clone())?;
1731        crate::infeasibility_saddle::infeasibility_saddle_escape(
1732            tnlp,
1733            &x,
1734            self.nlp_lower_bound_inf(),
1735            self.nlp_upper_bound_inf(),
1736        )
1737    }
1738
1739    /// Put a losing retry's floor back: re-deliver the winning attempt's
1740    /// payload to the user's TNLP and make it the recorded answer again.
1741    ///
1742    /// Recording it matters beyond this call. The retries nest -- the gh#884
1743    /// retry wraps the μ fallback and the scale audit -- and each takes its
1744    /// floor from `last_finalize`, so a replay that only re-delivered the
1745    /// payload left the *losing* inner retry's payload there for the outer
1746    /// wrapper to floor to, and to deliver as the answer: measured on
1747    /// `mpcc_scholtes4_biactive` with `mu_strategy_fallback=yes`, a declined
1748    /// μ retry and then a declined gh#884 retry
1749    /// (`pounce-sensitivity/tests/floored_solve_retry_wrappers.rs`).
1750    /// `reported_on_converged_id` reads it too, so without the record even a
1751    /// single declined retry would name its own firing.
1752    fn restore_floor(&self, floor: &FinalizeSnapshot, tnlp: &Rc<RefCell<dyn TNLP>>) {
1753        floor.replay(tnlp);
1754        *self.last_finalize.borrow_mut() = Some(floor.clone());
1755        self.answer_restored_from_floor.set(true);
1756    }
1757
1758    /// Enable per-iteration trajectory capture. After the solve
1759    /// returns, [`Self::statistics()`] exposes
1760    /// [`pounce_nlp::solve_statistics::SolveStatistics::iterations`]
1761    /// populated with one [`pounce_nlp::solve_statistics::IterRecord`]
1762    /// per accepted iterate. Off by default — the `pounce_sens` and
1763    /// `pounce` binaries opt in when `--json-output` is passed.
1764    pub fn enable_iter_history(&mut self) {
1765        self.record_iter_history = true;
1766    }
1767
1768    /// Whether [`Self::enable_iter_history`] is in force — read by a stage
1769    /// that produces a verdict outside `optimize_tnlp` (the second-opinion
1770    /// ladder's square-system stage) so its statistics keep the same
1771    /// `iterations` / `iteration_count` pairing.
1772    pub fn iter_history_enabled(&self) -> bool {
1773        self.record_iter_history
1774    }
1775
1776    /// Read the run's options file, resolving *which* file the way
1777    /// upstream's `IpoptApplication::Initialize` does — with one
1778    /// deliberate difference, below.
1779    ///
1780    /// `explicit` is the file the caller named (upstream: the
1781    /// `option_file_name` option, read out of the option store before
1782    /// this point). With `None`, the working directory is probed for
1783    /// [`DEFAULT_OPTION_FILE_NAMES`] and the first hit is read; an
1784    /// absent default file is not an error, it just means "no file".
1785    ///
1786    /// The difference: upstream opens a named file with a bare
1787    /// `std::ifstream` and reads nothing if the open fails, so a typo'd
1788    /// `option_file_name` runs at stock defaults without a word. That
1789    /// silence is what gh#518 was reported for — a benchmark that
1790    /// measured defaults while claiming to measure a configuration — so
1791    /// a named file that cannot be read is an error here.
1792    pub fn initialize_with_option_file(
1793        &mut self,
1794        explicit: Option<&Path>,
1795    ) -> Result<OptionFileLoad, SolverException> {
1796        let mut load = OptionFileLoad::default();
1797        // Set before the early returns below: what this flag records is
1798        // that `option_file_name` was *consulted*, not that a file turned
1799        // up. A caller on this path who names nothing and has no
1800        // `pounce.opt` to find still gets the option honored — there was
1801        // simply nothing to read.
1802        self.option_file_resolved = true;
1803        let path = match explicit {
1804            Some(p) => {
1805                if !p.is_file() {
1806                    return Err(SolverException::new(
1807                        ExceptionKind::IPOPT_APPLICATION_ERROR,
1808                        format!(
1809                            "options file \"{}\" does not exist. It was named by \
1810                             --options-file / option_file_name, so the run would \
1811                             otherwise proceed at stock defaults with none of its \
1812                             settings applied.",
1813                            p.display()
1814                        ),
1815                        file!(),
1816                        line!() as Index,
1817                    ));
1818                }
1819                load.explicit = true;
1820                p.to_path_buf()
1821            }
1822            None => {
1823                let present: Vec<&&str> = DEFAULT_OPTION_FILE_NAMES
1824                    .iter()
1825                    .filter(|n| Path::new(n).is_file())
1826                    .collect();
1827                let Some(first) = present.first() else {
1828                    return Ok(load);
1829                };
1830                // Both default names in one directory: say which one lost,
1831                // rather than let the unread one look applied.
1832                for other in &present[1..] {
1833                    load.warnings.push(format!(
1834                        "`{first}` and `{other}` are both present; reading `{first}` \
1835                         only (pounce's own name wins). Pass \
1836                         `option_file_name={other}` to read that one instead."
1837                    ));
1838                }
1839                PathBuf::from(**first)
1840            }
1841        };
1842        self.initialize_with_options_file(&path)?;
1843        // `option_file_name` set *inside* an options file chains nowhere —
1844        // by the time it is read, the file naming it has already been
1845        // chosen. Upstream documents that ("it does not make any sense to
1846        // specify this option within the options file") and then ignores
1847        // it; name it instead, since an ignored setting that looks live is
1848        // the whole complaint behind gh#518.
1849        if let Ok((named, true)) = self.options.get_string_value("option_file_name", "")
1850            && !named.is_empty()
1851            && Path::new(&named) != path
1852        {
1853            load.warnings.push(format!(
1854                "`{}` sets option_file_name to `{named}`, which has no effect: \
1855                 the options file is chosen before it is read. Pass \
1856                 `option_file_name={named}` on the command line to read that file.",
1857                path.display()
1858            ));
1859        }
1860        load.path = Some(path);
1861        Ok(load)
1862    }
1863
1864    /// Read an `ipopt.opt`-format options file. Equivalent to
1865    /// `IpoptApplication::Initialize(const std::string& options_file)`.
1866    pub fn initialize_with_options_file(&mut self, path: &Path) -> Result<(), SolverException> {
1867        let txt = std::fs::read_to_string(path).map_err(|e| {
1868            SolverException::new(
1869                ExceptionKind::IPOPT_APPLICATION_ERROR,
1870                format!("could not read options file {}: {}", path.display(), e),
1871                file!(),
1872                line!() as Index,
1873            )
1874        })?;
1875        self.options.read_from_str(&txt, true)?;
1876        self.open_output_file_journal();
1877        Ok(())
1878    }
1879
1880    /// Read options from a string in `ipopt.opt` format. Useful for
1881    /// tests and embedded callers.
1882    pub fn initialize_with_options_str(&mut self, s: &str) -> Result<(), SolverException> {
1883        self.options.read_from_str(s, true)?;
1884        self.open_output_file_journal();
1885        Ok(())
1886    }
1887
1888    /// Honor `output_file` / `file_print_level` / `file_append`: when
1889    /// `output_file` is non-empty, attach a `FileJournal` named
1890    /// `"OutputFile:<fname>"` at the requested level. Mirrors
1891    /// `IpoptApplication::OpenOutputFile` (called from `Initialize`).
1892    /// No-op if `output_file` is unset, empty, or could not be opened.
1893    ///
1894    /// NOTE: pounce's iteration output currently bypasses the
1895    /// journalist and writes directly to stdout. The file journal is
1896    /// attached and the timing report (gated by `print_timing_statistics`)
1897    /// is mirrored to it; per-iter rows will start landing in the file
1898    /// once the iter-output path is routed through the journalist.
1899    fn open_output_file_journal(&self) {
1900        let fname = match self.options.get_string_value("output_file", "") {
1901            Ok((v, true)) if !v.is_empty() => v,
1902            _ => return,
1903        };
1904        let level_int = self
1905            .options
1906            .get_integer_value("file_print_level", "")
1907            .ok()
1908            .and_then(|(v, f)| f.then_some(v))
1909            .unwrap_or(5);
1910        let level = journal_level_from_int(level_int);
1911        let append = self
1912            .options
1913            .get_bool_value("file_append", "")
1914            .ok()
1915            .and_then(|(v, f)| f.then_some(v))
1916            .unwrap_or(false);
1917        let jname = format!("OutputFile:{}", fname);
1918        let _ = self
1919            .journalist
1920            .add_file_journal(&jname, &fname, level, append);
1921    }
1922
1923    /// No-op initialize (just succeeds). Mirrors
1924    /// `IpoptApplication::Initialize(bool allow_clobber)` with no
1925    /// options file.
1926    pub fn initialize(&mut self) -> Result<(), SolverException> {
1927        Ok(())
1928    }
1929
1930    /// Mirror `IpoptApplication::OpenOutputFile`. Sets the `output_file`
1931    /// / `file_print_level` options and attaches a matching
1932    /// `FileJournal` named `OutputFile:<fname>` to the journalist.
1933    /// Returns `false` if the file could not be opened or the option
1934    /// store rejected the request (e.g. clamped print level).
1935    pub fn open_output_file(&mut self, fname: &str, print_level: i32) -> bool {
1936        if self
1937            .options
1938            .set_string_value("output_file", fname, true, false)
1939            .is_err()
1940        {
1941            return false;
1942        }
1943        if self
1944            .options
1945            .set_integer_value("file_print_level", print_level as Index, true, false)
1946            .is_err()
1947        {
1948            return false;
1949        }
1950        let level = journal_level_from_int(print_level);
1951        let jname = format!("OutputFile:{}", fname);
1952        // Drop any previous file journal so a second call switches files
1953        // cleanly. `add_file_journal` would otherwise refuse to attach
1954        // a duplicate by name; remove-by-name isn't in the journalist
1955        // API, so we settle for the name-collision case here.
1956        self.journalist
1957            .add_file_journal(&jname, fname, level, false)
1958            .is_some()
1959    }
1960
1961    /// Wrap a TNLP and report problem dimensions. Used in tests until
1962    /// the full IPM path covers every entry shape.
1963    pub fn problem_dimensions(&self, tnlp: &mut dyn TNLP) -> Option<NlpInfo> {
1964        tnlp.get_nlp_info()
1965    }
1966
1967    /// Diagnostics from the safeguarded `least_square_init_primal`
1968    /// initializer step of the last solve (gh#605): the nonlinear
1969    /// violation before and after, the accepted step norm, how many
1970    /// backtracking trials were rejected, and why it stopped. `None`
1971    /// when `least_square_init_primal` was off or the model had no
1972    /// constraints.
1973    pub fn least_square_init_report(&self) -> Option<crate::init::default::LeastSquareInitReport> {
1974        self.least_square_init_report.clone()
1975    }
1976
1977    pub fn statistics(&self) -> SolveStatistics {
1978        self.statistics.borrow().clone()
1979    }
1980
1981    /// What the warm-start initializer made of the iterate the caller
1982    /// supplied to the most recent solve (gh#606): the residuals it
1983    /// measured, whether each multiplier block was accepted,
1984    /// reconstructed or discarded, and the barrier parameter it
1985    /// settled on.
1986    ///
1987    /// `None` when the last solve was a cold start
1988    /// (`warm_start_init_point=no`), or when no solve has run. Reset at
1989    /// the top of every solve, like [`Self::timing_stats`].
1990    pub fn warm_start_diagnostics(&self) -> Option<crate::init::warm_start::WarmStartDiagnostics> {
1991        self.warm_start_diag.borrow().clone()
1992    }
1993
1994    /// Shared timing accumulator from the most recent `optimize_tnlp`
1995    /// call. Each subsystem (algorithm, NLP, KKT solver) bumped its own
1996    /// fields during the solve; consumers read totals out of the
1997    /// returned `Rc`. The instance is replaced at the top of every
1998    /// subsequent solve, so cloning the `Rc` and holding it past a
1999    /// re-solve will give you the previous solve's timings — by design.
2000    pub fn timing_stats(&self) -> Rc<TimingStatistics> {
2001        Rc::clone(&self.timing.borrow())
2002    }
2003
2004    /// Aggregate linear-solver post-mortem from the most recent
2005    /// `optimize_tnlp` call. `Some` when the workspace-default FERAL
2006    /// backend ran at least one factor; `None` when no factors were
2007    /// recorded (custom factory plugged via
2008    /// [`Self::set_linear_backend_factory`], or solve aborted before
2009    /// the first KKT factor). Reset at the top of every solve.
2010    ///
2011    /// Restoration-phase factorizations are attached as
2012    /// [`LinearSolverSummary::restoration`] when the frontend wired
2013    /// [`Self::restoration_summary_sink`] into its restoration factory.
2014    pub fn linear_solver_summary(&self) -> Option<LinearSolverSummary> {
2015        let mut main = self.linsol_summary_sink.lock().ok()?.clone();
2016        let resto = self
2017            .resto_linsol_summary_sink
2018            .lock()
2019            .ok()
2020            .map(|g| g.clone())
2021            .filter(|r| !r.is_empty());
2022        if main.is_empty() && resto.is_none() {
2023            return None;
2024        }
2025        main.restoration = resto.map(Box::new);
2026        // gh#990 item 7: name what was asked for beside what ran.
2027        main.requested = self
2028            .options
2029            .get_string_value("linear_solver", "")
2030            .ok()
2031            .map(|(v, _)| v);
2032        Some(main)
2033    }
2034
2035    /// Snapshot of both linear-solver summary sinks (main and
2036    /// restoration), for a driver that re-solves and must report the
2037    /// summary of the solve whose verdict it keeps. The second-opinion
2038    /// ladder takes one before its rungs and restores it when no rung is
2039    /// promoted, exactly as it does for the statistics.
2040    pub fn linear_solver_summary_state(&self) -> LinearSolverSummaryState {
2041        let read =
2042            |s: &Arc<Mutex<LinearSolverSummary>>| s.lock().map(|g| g.clone()).unwrap_or_default();
2043        LinearSolverSummaryState {
2044            main: read(&self.linsol_summary_sink),
2045            restoration: read(&self.resto_linsol_summary_sink),
2046        }
2047    }
2048
2049    /// Put back a [`Self::linear_solver_summary_state`] snapshot.
2050    pub fn restore_linear_solver_summary_state(&self, state: LinearSolverSummaryState) {
2051        if let Ok(mut g) = self.linsol_summary_sink.lock() {
2052            *g = state.main;
2053        }
2054        if let Ok(mut g) = self.resto_linsol_summary_sink.lock() {
2055            *g = state.restoration;
2056        }
2057    }
2058
2059    /// The sink a restoration backend factory should record into, e.g.
2060    /// through [`default_backend_factory_with_sink`]. Kept separate from
2061    /// the main solve's sink so the main-solve totals stay about the main
2062    /// solve.
2063    pub fn restoration_summary_sink(&self) -> Arc<Mutex<LinearSolverSummary>> {
2064        Arc::clone(&self.resto_linsol_summary_sink)
2065    }
2066
2067    /// Drive a solve.
2068    ///
2069    /// * Constrained problems (`m > 0`) take the primal-dual IPM path:
2070    ///   build a `TNLPAdapter` → `OrigIpoptNlp`, run the
2071    ///   [`AlgorithmBuilder`] with the workspace MA57 backend, and
2072    ///   call [`IpoptAlgorithm::optimize`]. The `SolverReturn` →
2073    ///   `ApplicationReturnStatus` mapping mirrors the table in
2074    ///   `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception →
2075    ///   SolverReturn map").
2076    /// * Unconstrained problems (`m == 0`) keep going through the
2077    ///   in-`pounce-nlp` Newton driver so the trivial path is
2078    ///   independent of the linear-solver backend.
2079    /// Wrap `tnlp` so per-variable scaling factors are applied as a
2080    /// change of variables, when `nlp_scaling_method=user-scaling` is
2081    /// in effect and the problem supplies non-unit factors (gh#486).
2082    ///
2083    /// Returns the TNLP unchanged under any other scaling method, or
2084    /// when the problem asks for no variable scaling, so an unscaled
2085    /// solve pays nothing. The `Err` carries a message ready to print.
2086    fn install_variable_scaling(
2087        &self,
2088        tnlp: Rc<RefCell<dyn TNLP>>,
2089    ) -> Result<Rc<RefCell<dyn TNLP>>, String> {
2090        // Cleared first so the accessor describes *this* solve. An
2091        // application is reusable across solves (`pounce-cinterface`
2092        // holds one across `IpoptSolve` calls), and a stale vector
2093        // would have a later unscaled solve reporting the previous
2094        // solve's factors.
2095        *self.variable_scaling.borrow_mut() = None;
2096        let method = self
2097            .options
2098            .get_string_value("nlp_scaling_method", "")
2099            .ok()
2100            .and_then(|(v, f)| f.then_some(v))
2101            .unwrap_or_else(|| "gradient-based".to_string());
2102        // `curvature-based` (gh #703) delivers its factors through the
2103        // same `get_scaling_parameters` callback, so the per-variable half
2104        // needs the same substitution wrapper user factors get.
2105        if method != "user-scaling" && method != "curvature-based" {
2106            return Ok(tnlp);
2107        }
2108        match pounce_nlp::scaling_tnlp::wrap_with_scaling(
2109            Rc::clone(&tnlp),
2110            self.nlp_lower_bound_inf(),
2111            self.nlp_upper_bound_inf(),
2112        ) {
2113            Ok(Some(wrapped)) => {
2114                *self.variable_scaling.borrow_mut() =
2115                    pounce_nlp::scaling_tnlp::factors_of(&wrapped);
2116                Ok(wrapped)
2117            }
2118            Ok(None) => Ok(tnlp),
2119            Err(why) => Err(format!(
2120                // The trailing newline belongs to the message: the
2121                // caller emits it with `eprint!` and hands the same
2122                // string to the journalist, as the refusals below do.
2123                "pounce: nlp_scaling_method={method} supplied per-variable \
2124                 scaling factors that cannot be applied. {why}. Correct the \
2125                 factors, or drop nlp_scaling_method={method}.\n"
2126            )),
2127        }
2128    }
2129
2130    /// The per-variable scaling factors applied to the last solve, if
2131    /// any (gh#486). A consumer reading the algorithm's iterate rather
2132    /// than the `finalize_solution` payload sees scaled coordinates and
2133    /// must divide `x` by these, and multiply bound multipliers.
2134    pub fn variable_scaling(&self) -> Option<Vec<Number>> {
2135        self.variable_scaling.borrow().clone()
2136    }
2137
2138    /// Install a starting-point conditioner, if one is asked for.
2139    ///
2140    /// Returns the TNLP unchanged when neither `start_point_perturbation` nor
2141    /// `start_point_conditioner` is set, which is the default — so an ordinary
2142    /// solve pays nothing and its trajectory is untouched.
2143    ///
2144    /// Sits *above* the presolve wrapper and *below* the variable-scaling one,
2145    /// so the point it conditions is the point the algorithm will actually
2146    /// start from, in the coordinates the algorithm will see. Both
2147    /// conditioners override only `get_starting_point`; every other callback
2148    /// forwards, so the solve that follows is the solve pounce would have run
2149    /// had the conditioned point been submitted directly.
2150    ///
2151    /// The two are mutually exclusive by construction rather than by refusal:
2152    /// the displacement is the failure-recovery rung and the Adam warm-up is a
2153    /// user opt-in, and stacking them would put random noise on top of a point
2154    /// the warm-up just spent 200 evaluations choosing. The displacement wins
2155    /// when both are set, because the only thing that sets it is a solve that
2156    /// has already failed.
2157    fn install_start_conditioner(&self, tnlp: Rc<RefCell<dyn TNLP>>) -> Rc<RefCell<dyn TNLP>> {
2158        use pounce_nlp::start_conditioner::{AdamConfig, ConditionedStartTnlp, StartConditioner};
2159        // Each option is read with its literal tag rather than through a
2160        // `|name, fallback|` helper. A helper reads better and costs the
2161        // wiring guard in `tests/init_options_wiring.rs` its evidence: that
2162        // test scans the source for `get_*_value("<tag>"` to prove every
2163        // registered Initialization option is actually consumed, and a tag
2164        // passed as a variable is invisible to it. A registered knob nothing
2165        // reads validates, accepts a value, and lies.
2166        let perturbation = self
2167            .options
2168            .get_numeric_value("start_point_perturbation", "")
2169            .map(|(v, _found)| v)
2170            .unwrap_or(0.0);
2171        let conditioner = if perturbation > 0.0 {
2172            let seed = self
2173                .options
2174                .get_integer_value("start_point_perturbation_seed", "")
2175                .map(|(v, _found)| v)
2176                .unwrap_or(0);
2177            StartConditioner::Jitter {
2178                // `Index` is signed and the option is lower-bounded at 0, so
2179                // this cast cannot lose a set bit for any accepted value.
2180                seed: seed.max(0) as u64,
2181                scale: perturbation,
2182            }
2183        } else {
2184            let which = self
2185                .options
2186                .get_string_value("start_point_conditioner", "")
2187                .map(|(v, _found)| v)
2188                .unwrap_or_else(|_| "none".to_string());
2189            if which != "adam" {
2190                return tnlp;
2191            }
2192            let d = AdamConfig::default();
2193            StartConditioner::Adam(AdamConfig {
2194                iters: self
2195                    .options
2196                    .get_integer_value("adam_warmup_iters", "")
2197                    .map(|(v, _found)| v.max(0) as usize)
2198                    .unwrap_or(d.iters),
2199                lr: self
2200                    .options
2201                    .get_numeric_value("adam_warmup_learning_rate", "")
2202                    .map(|(v, _found)| v)
2203                    .unwrap_or(d.lr),
2204                rho: self
2205                    .options
2206                    .get_numeric_value("adam_warmup_penalty", "")
2207                    .map(|(v, _found)| v)
2208                    .unwrap_or(d.rho),
2209                ..d
2210            })
2211        };
2212        // The sentinels have to come from the options, not from the
2213        // conditioner's own default: a caller who moved `nlp_lower_bound_inf`
2214        // would otherwise have a bound the algorithm treats as absent clipped
2215        // against as if it were real.
2216        //
2217        // Passed through unclamped. These were once `lower.min(-DEFAULT)` /
2218        // `upper.max(DEFAULT)`, which honours only a *loosened* sentinel and
2219        // leaves the failure above intact for a tightened one: at
2220        // `nlp_lower_bound_inf=-1e10` the conditioner still used `-1e19`, so a
2221        // `-1e15` bound was absent to the algorithm and present to the
2222        // clipper — the exact case the comment exists to rule out. The
2223        // sentinel means "absent"; there is only one right answer for what it
2224        // is, and it is the caller's.
2225        let lower = self.nlp_lower_bound_inf();
2226        let upper = self.nlp_upper_bound_inf();
2227        let wrapped = ConditionedStartTnlp::new(tnlp, conditioner).with_bound_inf(lower, upper);
2228        Rc::new(RefCell::new(wrapped))
2229    }
2230
2231    pub fn optimize_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2232        self.optimize_tnlp_with_derivative_test_tnlp(tnlp, None)
2233    }
2234
2235    /// Solve through `tnlp`, optionally overriding the derivative-test target.
2236    /// `None` tests the scaled and conditioned TNLP.
2237    pub fn optimize_tnlp_with_derivative_test_tnlp(
2238        &mut self,
2239        tnlp: Rc<RefCell<dyn TNLP>>,
2240        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2241    ) -> ApplicationReturnStatus {
2242        // The statistics belong to this solve, all of them. A solve that
2243        // returns before any attempt runs (the degrees-of-freedom refusal, an
2244        // option refusal, a presolve proof) used to leave the previous solve's
2245        // record standing, so `statistics()` on an application reused for a
2246        // second solve reported the first one's iterations for a solve that
2247        // never iterated. The complementarity driver is the case that showed
2248        // it: each `G·H = 0` finish refused for too few degrees of freedom
2249        // was recorded with the iteration count of the solve before it, and
2250        // `total_iterations` counted it again. This replaces the field-by-field
2251        // clears (gh#983 review item 1: `warnings`; `sqp_warm_working_set_applied`)
2252        // that patched the same leak one field at a time.
2253        *self.statistics.borrow_mut() = SolveStatistics::new();
2254        // Belongs to the scale audit's re-solve alone, which runs below this
2255        // entry point (`optimize_constrained`, never `optimize_tnlp`), so no
2256        // solve that starts here may inherit it. `RetryOptionScope` clears it
2257        // on every exit already; this is the belt to that, for a solve on an
2258        // application a caught panic left behind.
2259        self.retry_keeps_declared_box.set(false);
2260        let status = self.optimize_tnlp_dispatch(tnlp, derivative_test_tnlp);
2261        // Printed once, for the run whose point is returned. They used to be
2262        // printed by every audited attempt, so a promoted retry's console
2263        // carried the discarded base attempt's `WARNING:` lines too.
2264        let console_output = match self.options.get_integer_value("print_level", "") {
2265            Ok((v, true)) => v >= 1,
2266            _ => true,
2267        };
2268        if console_output {
2269            for w in &self.statistics.borrow().warnings {
2270                println!("WARNING: {w}");
2271            }
2272        }
2273        status
2274    }
2275
2276    /// The body of [`Self::optimize_tnlp_with_derivative_test_tnlp`].
2277    fn optimize_tnlp_dispatch(
2278        &mut self,
2279        tnlp: Rc<RefCell<dyn TNLP>>,
2280        derivative_test_tnlp: Option<Rc<RefCell<dyn TNLP>>>,
2281    ) -> ApplicationReturnStatus {
2282        // gh#884. Both belong to this solve, not to whatever ran before
2283        // it. Reset *here* rather than in `optimize_constrained`, which
2284        // runs once per attempt: the signature accumulates across the
2285        // attempts a lower wrapper may spend, so
2286        // `run_with_dual_divergence_retry` reads "some attempt of the base
2287        // solve saw it" rather than "the last one did".
2288        self.dual_divergence_signature.set(false);
2289        self.tiny_step_dual_stall.set(false);
2290        self.obj_scale_refused.set((false, false));
2291        self.dual_divergence_retry_promoted.set(false);
2292        *self.mu_strategy_fallback_record.borrow_mut() = None;
2293        self.answer_restored_from_floor.set(false);
2294        // The answer this solve reports is whatever it finalizes; a payload
2295        // left from an earlier solve must not stand in for one this solve
2296        // never wrote, since `reported_on_converged_id` reads it.
2297        *self.last_finalize.borrow_mut() = None;
2298        // Same scoping argument as the three above, for the same reason: the
2299        // memo suppresses a REPEATED header within one run, so it must not
2300        // carry across runs. A library caller solving twice on one
2301        // application gets its header both times — which is exactly what the
2302        // guard protects: an outside retry driver re-entering here for another
2303        // attempt is not such a caller, and says so by setting the flag.
2304        if !self.in_retry_sequence.get() {
2305            *self.last_printed_problem_stats.borrow_mut() = None;
2306        }
2307        // gh#486 stage 2: per-variable `scaling_factor` is applied by
2308        // substituting variables one level below the algorithm, since
2309        // the core's scaling models the objective and the constraint
2310        // rows only. The wrapper consumes the variable factors and
2311        // forwards the rest, so `OrigIpoptNlp` sees exactly what it
2312        // has always handled. Installed here because every entry point
2313        // funnels through this method, and only under `user-scaling`,
2314        // the one method that consults the TNLP for factors at all.
2315        let tnlp = match self.install_variable_scaling(tnlp) {
2316            Ok(t) => t,
2317            Err(msg) => {
2318                use pounce_common::journalist::JournalCategory;
2319                eprint!("{msg}");
2320                self.journalist
2321                    .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2322                return ApplicationReturnStatus::InvalidOption;
2323            }
2324        };
2325
2326        // Starting-point conditioning (`start_point_perturbation`,
2327        // `start_point_conditioner`). A no-op unless one is set, and set by
2328        // nothing automatic except the local-infeasibility ladder's third
2329        // rung, which only runs after a solve has already failed.
2330        let tnlp = self.install_start_conditioner(tnlp);
2331        let derivative_test_tnlp = derivative_test_tnlp.as_ref().unwrap_or(&tnlp);
2332
2333        if let Some(value) = self.unsupported_library_solver_selection() {
2334            use pounce_common::journalist::JournalCategory;
2335            self.journalist.print(
2336                JournalLevel::J_ERROR,
2337                JournalCategory::J_MAIN,
2338                &format!(
2339                    "pounce: solver_selection={value} routing is only available \
2340                     through the pounce CLI (.nl input); library consumers can use \
2341                     qp-active-set, nlp, or auto.\n"
2342                ),
2343            );
2344            return ApplicationReturnStatus::InvalidOption;
2345        }
2346
2347        // A `linear_solver` pounce does not implement is refused rather
2348        // than quietly served by FERAL (gh#483 follow-up). Checked here,
2349        // before any work, so a library consumer gets the same verdict the
2350        // CLI gives before its banner.
2351        if let Some(value) = self.unimplemented_linear_solver() {
2352            use pounce_common::journalist::JournalCategory;
2353            let msg = format!("{}\n", Self::unimplemented_linear_solver_message(&value));
2354            eprint!("{msg}");
2355            self.journalist
2356                .print(JournalLevel::J_ERROR, JournalCategory::J_MAIN, &msg);
2357            return ApplicationReturnStatus::InvalidOption;
2358        }
2359
2360        // gh#483 follow-up: an option naming a feature pounce does not
2361        // implement is refused, not shrugged off. See
2362        // `unimplemented_options` for how membership was established and
2363        // why an explicitly-set *default* is deliberately still allowed.
2364        // gh#518: same treatment for `option_file_name` on an entry point
2365        // that cannot resolve it. Separate from the table above because
2366        // the *feature* now exists — just not here.
2367        // gh#604: same treatment one level down, for a registered *value*
2368        // of an option pounce otherwise reads (`bound_mult_init_method=
2369        // mu-based`).
2370        // gh#604: and for a convex-engine knob on an entry point that
2371        // cannot route to that engine — `option_file_name`'s case, one
2372        // feature over.
2373        if let Some(msg) = self
2374            .unimplemented_option_refusal()
2375            .or_else(|| self.unimplemented_option_value_refusal())
2376            .or_else(|| self.unhonored_option_file_name())
2377            .or_else(|| self.unhonored_convex_option())
2378        {
2379            use pounce_common::journalist::JournalCategory;
2380            eprintln!("{msg}");
2381            self.journalist.print(
2382                JournalLevel::J_ERROR,
2383                JournalCategory::J_MAIN,
2384                &format!("{msg}\n"),
2385            );
2386            return ApplicationReturnStatus::InvalidOption;
2387        }
2388        // A `ma57_pivtolmax` the user set *below* `ma57_pivtol` is a
2389        // contradiction — the escalation ceiling under its floor — and
2390        // upstream refuses it outright
2391        // (`IpMa57TSolverInterface.cpp:313`, `OPTION_INVALID`). pounce
2392        // used to silently rewrite it to `ma57_pivtol`. That was
2393        // unreachable while gh#825 was live, since no `ma57_*` value
2394        // reached the backend at all, and became reachable the moment
2395        // that was fixed — so it is refused here rather than shipped as
2396        // a new way to be quietly ignored.
2397        if let Some(msg) = self.ma57_pivtol_bracket_refusal() {
2398            use pounce_common::journalist::JournalCategory;
2399            eprintln!("{msg}");
2400            self.journalist.print(
2401                JournalLevel::J_ERROR,
2402                JournalCategory::J_MAIN,
2403                &format!("{msg}\n"),
2404            );
2405            return ApplicationReturnStatus::InvalidOption;
2406        }
2407
2408        let backend_warnings = self.take_unimplemented_backend_warnings();
2409        for warning in self
2410            .unexploited_hint_warnings()
2411            .into_iter()
2412            .chain(backend_warnings)
2413        {
2414            eprintln!("{warning}");
2415        }
2416
2417        // Test before presolve, using the requested coordinate space.
2418        self.run_derivative_test(derivative_test_tnlp);
2419
2420        // Top-level algorithm dispatch (Phase 5b §7.1). When the
2421        // `algorithm` option resolves to "active-set-sqp", route
2422        // to the Phase 5b SQP path; otherwise fall through to the
2423        // existing IPM flow unchanged.
2424        // Materialize generic TNLP presolve once at the public entry point.
2425        // The wrapper owns the submitted callback TNLP, so every algorithm
2426        // path below (including retry paths) continues to postsolve into
2427        // the original user-facing space. With `presolve=no`, this returns
2428        // the exact same Rc unchanged.
2429        let tnlp = if self.presolve_already_applied {
2430            tnlp
2431        } else {
2432            match pounce_presolve::wrap_from_options(tnlp, &self.options) {
2433                Ok(tnlp) => tnlp,
2434                Err(err) => {
2435                    use pounce_common::journalist::JournalCategory;
2436                    self.journalist.print(
2437                        JournalLevel::J_ERROR,
2438                        JournalCategory::J_MAIN,
2439                        &format!("pounce: could not materialize presolve options: {err}\n"),
2440                    );
2441                    return ApplicationReturnStatus::InvalidOption;
2442                }
2443            }
2444        };
2445
2446        if self.is_sqp_algorithm_selected() {
2447            let dims = tnlp
2448                .borrow_mut()
2449                .get_nlp_info()
2450                .map(|i| (i.n.max(0) as usize, i.m.max(0) as usize));
2451            let auto = dims.is_some_and(|(n, m)| self.sqp_auto_handover(n, m));
2452            self.auto_handover.set(auto);
2453            if !auto {
2454                return self.optimize_sqp_tnlp(tnlp);
2455            }
2456            use pounce_common::journalist::JournalCategory;
2457            self.journalist.print(
2458                JournalLevel::J_SUMMARY,
2459                JournalCategory::J_MAIN,
2460                &format!(
2461                    "pounce: active-set SQP on a model this size (n + m ≥ {AUTO_HANDOVER_MIN_DIM}) \
2462                     starts from the interior point and hands over \
2463                     (ipm_sqp_handover=no for a cold active-set SQP).\n"
2464                ),
2465            );
2466        } else {
2467            self.auto_handover.set(false);
2468        }
2469        let info = match tnlp.borrow_mut().get_nlp_info() {
2470            Some(info) => info,
2471            None => return ApplicationReturnStatus::InvalidProblemDefinition,
2472        };
2473
2474        // Presolve-certified infeasibility. `get_nlp_info` above is what forces
2475        // the (lazy) presolve init, so this is the first point at which the
2476        // proof exists. If bound propagation or FBBT established that the
2477        // feasible region is empty, there is nothing left to compute: return
2478        // the verdict directly.
2479        //
2480        // Short-circuiting *here*, before dispatch, is deliberate. Running the
2481        // solve anyway would only re-derive a strictly weaker result — a
2482        // stationary point of the constraint violation, which for a nonconvex
2483        // problem proves nothing globally — and would also hand an
2484        // `InfeasibleProblemDetected` to the ℓ₁ auto-fallback below
2485        // (`is_l1_fallback_trigger`), which would then burn a whole second
2486        // solve retrying a problem already proved to have no solution.
2487        //
2488        // Soundness rests on `presolve_infeasibility_proof` returning `Some`
2489        // only for a contradiction derived on an *un-clamped* box — a
2490        // detection made while a Phase-0 auxiliary elimination is in force can
2491        // be an artifact of that elimination and is re-checked after rollback
2492        // before it is certified. See `PresolveState::certified_infeasible`.
2493        if let Some(proof) = tnlp.borrow().presolve_infeasibility_proof() {
2494            use pounce_common::journalist::JournalCategory;
2495            let detail = match proof {
2496                pounce_nlp::tnlp::InfeasibilityProof::BoundPropagation => {
2497                    "bound propagation crossed a variable's bounds".to_string()
2498                }
2499                pounce_nlp::tnlp::InfeasibilityProof::IntervalArithmetic { witness } => {
2500                    format!("interval arithmetic emptied constraint {witness}'s range")
2501                }
2502            };
2503            self.journalist.print(
2504                JournalLevel::J_SUMMARY,
2505                JournalCategory::J_MAIN,
2506                &format!(
2507                    "\nEXIT: Presolve detected the feasible region is empty ({detail}).\n\
2508                     No feasible point exists; the solve was not run.\n"
2509                ),
2510            );
2511            return ApplicationReturnStatus::InfeasibleProblemDetected;
2512        }
2513        // ℓ₁-exact penalty-barrier opt-in (pounce#10).
2514        // Phase 3 wraps the user TNLP and runs an outer Byrd-Nocedal-
2515        // Waltz ρ-escalation loop around the constrained IPM, with a
2516        // honest-infeasibility status upgrade when the slacks fail to
2517        // collapse at saturated ρ. Phase-1/2 one-shot use is preserved
2518        // when `l1_penalty_max_outer_iter == 1`. The wrapper is a
2519        // no-op for problems with no equality rows, so the
2520        // unconstrained dispatch below is unaffected when there is
2521        // nothing to wrap.
2522        if info.m > 0 && self.is_l1_penalty_enabled() {
2523            if let Some(status) = self.run_l1_penalty_outer_loop(Rc::clone(&tnlp)) {
2524                return status;
2525            }
2526            // Falls through: wrapper construction failed (inner refused
2527            // get_nlp_info / get_bounds_info) or no equality rows to
2528            // slack. Standard dispatch runs unmodified.
2529        }
2530        // Phase 3.5 auto-fallback (pounce#10): if the standard solve
2531        // ends in a trigger-class status, retry transparently with
2532        // the wrapper. Promote the retry's status only if it returns
2533        // SolveSucceeded — otherwise return the original. Skipped if
2534        // the user already opted into the wrapper above (this avoids
2535        // a double pass and keeps semantics predictable).
2536        if info.m > 0 && self.is_l1_fallback_enabled() && !self.is_l1_penalty_enabled() {
2537            return self.run_with_l1_fallback(tnlp);
2538        }
2539        // Biactive dual-divergence retry (gh#884): if the solve settles
2540        // its primal while its multipliers run away, throw the iterate
2541        // away and solve again from scratch with the constraint-Jacobian
2542        // perturbation on. Outermost of the two retry wrappers, so its
2543        // "base solve" is the whole standard dispatch below including the
2544        // μ flip — the signature is about a *solve*, and spending the μ
2545        // flip first is strictly cheaper than spending this one first.
2546        let status = if self.is_dual_divergence_retry_enabled() {
2547            self.run_with_dual_divergence_retry(tnlp)
2548        } else {
2549            self.dispatch_standard_solve(tnlp)
2550        };
2551        // gh#983 review item 3: the verdict-level audit runs once, on the
2552        // final verdict, after every retry and fallback has decided.
2553        self.finalize_quality_verdict(status)
2554    }
2555
2556    /// The standard solve dispatch: the μ-strategy fallback if it is
2557    /// enabled, otherwise one `optimize_constrained` call.
2558    ///
2559    /// Factored out of `optimize_tnlp_with_derivative_test_tnlp` so
2560    /// [`Self::run_with_dual_divergence_retry`] can wrap the whole of it
2561    /// rather than only the bare IPM call (gh#884).
2562    fn dispatch_standard_solve(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
2563        let status = self.dispatch_standard_solve_inner(Rc::clone(&tnlp));
2564        self.audit_solve_quality(tnlp, status)
2565    }
2566
2567    /// [`Self::dispatch_standard_solve`] without the gh#983 quality audit.
2568    fn dispatch_standard_solve_inner(
2569        &mut self,
2570        tnlp: Rc<RefCell<dyn TNLP>>,
2571    ) -> ApplicationReturnStatus {
2572        // μ-strategy auto-fallback (pounce#138): if the standard solve
2573        // stalls, retry once with the opposite mu_strategy and promote
2574        // only on Solve_Succeeded. Which stalls qualify depends on
2575        // whether the caller asked for the retry — see
2576        // `run_with_mu_strategy_fallback` (pounce#748).
2577        // Applies to constrained and unconstrained alike (both run the
2578        // same IPM). Independent of, and lower priority than, the ℓ₁
2579        // fallback above.
2580        if self.is_mu_strategy_fallback_enabled() {
2581            return self.run_with_mu_strategy_fallback(tnlp);
2582        }
2583        // Every problem — constrained or not — goes through the same
2584        // primal-dual IPM, exactly as upstream Ipopt does. There is no
2585        // separate "unconstrained Newton" path: the linear-solver
2586        // backend (FERAL/MA57) handles the augmented system, so the
2587        // sparse IPM covers `m == 0` at any `n` without a dense-Hessian
2588        // blowup.
2589        self.optimize_constrained(tnlp)
2590    }
2591
2592    /// Read the ℓ₁ wrapper master switch from the OptionsList.
2593    /// Default `false` when the option is not set.
2594    fn is_l1_penalty_enabled(&self) -> bool {
2595        self.options
2596            .get_bool_value("l1_exact_penalty_barrier", "")
2597            .ok()
2598            .and_then(|(v, found)| found.then_some(v))
2599            .unwrap_or(false)
2600    }
2601
2602    fn l1_penalty_init(&self) -> Number {
2603        self.options
2604            .get_numeric_value("l1_penalty_init", "")
2605            .ok()
2606            .and_then(|(v, found)| found.then_some(v))
2607            .unwrap_or(1.0)
2608    }
2609    fn l1_penalty_max(&self) -> Number {
2610        self.options
2611            .get_numeric_value("l1_penalty_max", "")
2612            .ok()
2613            .and_then(|(v, found)| found.then_some(v))
2614            .unwrap_or(1.0e6)
2615    }
2616    fn l1_penalty_increase_factor(&self) -> Number {
2617        self.options
2618            .get_numeric_value("l1_penalty_increase_factor", "")
2619            .ok()
2620            .and_then(|(v, found)| found.then_some(v))
2621            .unwrap_or(8.0)
2622    }
2623    fn l1_penalty_max_outer_iter(&self) -> usize {
2624        self.options
2625            .get_integer_value("l1_penalty_max_outer_iter", "")
2626            .ok()
2627            .and_then(|(v, found)| found.then_some(v))
2628            .unwrap_or(8) as usize
2629    }
2630    fn l1_slack_tol(&self) -> Number {
2631        self.options
2632            .get_numeric_value("l1_slack_tol", "")
2633            .ok()
2634            .and_then(|(v, found)| found.then_some(v))
2635            .unwrap_or(1.0e-6)
2636    }
2637    fn l1_steering_factor(&self) -> Number {
2638        self.options
2639            .get_numeric_value("l1_steering_factor", "")
2640            .ok()
2641            .and_then(|(v, found)| found.then_some(v))
2642            .unwrap_or(10.0)
2643    }
2644    fn is_l1_fallback_enabled(&self) -> bool {
2645        self.options
2646            .get_bool_value("l1_fallback_on_restoration_failure", "")
2647            .ok()
2648            .and_then(|(v, found)| found.then_some(v))
2649            .unwrap_or(false)
2650    }
2651
2652    /// Did the caller set `mu_strategy` explicitly?
2653    ///
2654    /// The answer decides whether the limited-memory default applies
2655    /// (see `algorithm_builder_from_options`): upstream only substitutes
2656    /// `adaptive` for the registered `monotone` when the option is
2657    /// absent from the list.
2658    fn mu_strategy_was_set(&self) -> bool {
2659        matches!(
2660            self.options.get_string_value("mu_strategy", ""),
2661            Ok((_, true))
2662        )
2663    }
2664
2665    /// Did the caller set `mu_strategy_fallback` themselves? Separates
2666    /// the opted-in retry from the default-on one, which triggers on a
2667    /// narrower set of statuses (pounce#748).
2668    ///
2669    /// True for an explicit `no` as well as an explicit `yes`, which is
2670    /// harmless: this is only ever read downstream of
2671    /// [`Self::is_mu_strategy_fallback_enabled`], and an explicit `no`
2672    /// stops there.
2673    fn mu_strategy_fallback_was_set(&self) -> bool {
2674        matches!(
2675            self.options.get_bool_value("mu_strategy_fallback", ""),
2676            Ok((_, true))
2677        )
2678    }
2679
2680    /// Options whose presence means a `Solved_To_Acceptable_Level`
2681    /// exit may be something the *caller* asked for rather than a stall
2682    /// POUNCE fell into (gh #757).
2683    ///
2684    /// Every one of them either moves the bar a certificate has to clear
2685    /// (`tol` and the component tolerances, the `acceptable_*` family),
2686    /// arms a guard that refuses a certificate the iterate would
2687    /// otherwise have earned (`kkt_fidelity_tol`, the certificate-mask
2688    /// and noise-floor kappas, the divergence / infeasibility streaks,
2689    /// the restoration-decline pair).
2690    ///
2691    /// Options that only move the *starting point* are deliberately not
2692    /// here. `least_square_init_primal` was tried and removed: a caller
2693    /// who picks an initialization heuristic has said nothing about what
2694    /// convergence means, and listing it made an explicit `=no` behave
2695    /// differently from omitting the option, which is a distinction the
2696    /// rest of the solver does not draw.
2697    const TERMINATION_POLICY_OPTIONS: &'static [&'static str] = &[
2698        "tol",
2699        "dual_inf_tol",
2700        "constr_viol_tol",
2701        "compl_inf_tol",
2702        "acceptable_tol",
2703        "acceptable_iter",
2704        "acceptable_dual_inf_tol",
2705        "acceptable_constr_viol_tol",
2706        "acceptable_compl_inf_tol",
2707        "acceptable_obj_change_tol",
2708        "kkt_fidelity_tol",
2709        "obj_scale_certificate_threshold",
2710        "dual_inf_scale_kappa",
2711        "primal_noise_floor_kappa",
2712        "dual_diverging_streak",
2713        "infeas_max_streak",
2714        "resto_decline_deferrals",
2715        "resto_decline_progress_ratio",
2716        "neg_curv_escapes",
2717        "limited_memory_ls_failure_restarts",
2718    ];
2719
2720    /// Did the caller set any option from
2721    /// [`Self::TERMINATION_POLICY_OPTIONS`]?
2722    ///
2723    /// This is what separates the two readings of a
2724    /// `Solved_To_Acceptable_Level` exit. Under stock convergence
2725    /// settings it means POUNCE's own schedule parked the dual term
2726    /// above `tol` and a flipped schedule is worth one try. Under a
2727    /// caller-modified one it may be the signal the caller armed the
2728    /// option to receive, and erasing it with a retry is exactly the
2729    /// laundering pounce#748 refused to do by default.
2730    fn caller_set_termination_policy(&self) -> bool {
2731        Self::TERMINATION_POLICY_OPTIONS.iter().any(|name| {
2732            matches!(self.options.get_numeric_value(name, ""), Ok((_, true)))
2733                || matches!(self.options.get_integer_value(name, ""), Ok((_, true)))
2734                || matches!(self.options.get_bool_value(name, ""), Ok((_, true)))
2735                || matches!(self.options.get_string_value(name, ""), Ok((_, true)))
2736        })
2737    }
2738
2739    /// The μ strategy this option table actually resolves to, as
2740    /// `algorithm_builder_from_options` will build it: the explicit
2741    /// value when there is one, otherwise `adaptive` for a
2742    /// limited-memory Hessian and `monotone` for anything else.
2743    ///
2744    /// The fallback below flips *this*, not the registered default —
2745    /// flipping the registered default under limited-memory would
2746    /// "retry" with the strategy that just failed.
2747    fn effective_mu_strategy_is_adaptive(&self) -> bool {
2748        mu_strategy_resolves_to_adaptive(&self.options)
2749    }
2750
2751    /// Read the μ-strategy auto-fallback switch (pounce#138).
2752    ///
2753    /// An explicit setting always wins. Absent one the default is **on**
2754    /// (pounce#748) — but only while the user has not chosen a
2755    /// `mu_strategy` themselves. Retrying under the other schedule is a
2756    /// recovery for a solve that stalled on a strategy POUNCE picked; it
2757    /// is not licence to override a strategy the caller named. Without
2758    /// that condition, flipping the default would silently contaminate
2759    /// every controlled comparison that pins `mu_strategy` on purpose,
2760    /// this repository's own benchmark arms included. The motivating
2761    /// case is unaffected: `dirichlet120` stalls under the
2762    /// limited-memory substitution (pounce#746), which by definition
2763    /// only happens when `mu_strategy` is unset.
2764    fn is_mu_strategy_fallback_enabled(&self) -> bool {
2765        match self.options.get_bool_value("mu_strategy_fallback", "") {
2766            Ok((v, true)) => v,
2767            _ => !self.mu_strategy_was_set() || self.mu_strategy_pounce_chosen,
2768        }
2769    }
2770
2771    /// Record that the `mu_strategy` now in the option table was chosen by a
2772    /// POUNCE frontend, not by the caller (gh#990).
2773    ///
2774    /// The Python path for a problem without `hessian` writes
2775    /// `mu_strategy=monotone` so that gh#746's limited-memory -> adaptive
2776    /// substitution does not read a barrier preference out of a Hessian
2777    /// choice POUNCE made itself. Written as an ordinary option, that pin
2778    /// also read as "the caller named a strategy" to
2779    /// [`Self::is_mu_strategy_fallback_enabled`], which switched off the
2780    /// default-on stall retry (gh#748) on exactly that path — the same
2781    /// set-ness defect the second-opinion ladder's write-backs once had.
2782    /// With this mark the pin still decides the schedule, and the fallback
2783    /// stays on. A frontend calls it only when the caller's own options carry
2784    /// no `mu_strategy`.
2785    pub fn mark_mu_strategy_pounce_chosen(&mut self) {
2786        self.mu_strategy_pounce_chosen = true;
2787    }
2788
2789    /// Has the user set `algorithm = active-set-sqp`? Reads the
2790    /// string option and matches case-insensitively against the
2791    /// design-note §7.1 spelling. Any value other than
2792    /// "active-set-sqp" (including absence) routes to the
2793    /// default IPM path.
2794    /// Stash a warm-start iterate for the SQP path. Consumed by
2795    /// the next `optimize_tnlp` call when the `algorithm` option
2796    /// resolves to `active-set-sqp`; the IPM path ignores it.
2797    /// Phase 5c (§6) — the parametric / MPC warm-start hand-off.
2798    ///
2799    /// The iterate is auto-cleared after use, so a follow-up
2800    /// solve without an intervening `set_sqp_warm_start` call
2801    /// cold-starts.
2802    ///
2803    /// `x`, `lambda_g` and `lambda_x` are in the **caller's** space — what
2804    /// `finalize_solution` reports: full-`n` `x` in model units, `lambda_g`
2805    /// in `g` order on the unscaled Lagrangian `f + λᵀg`, and
2806    /// `lambda_x = z_L − z_U`. The solve maps them into the algorithm's
2807    /// space (fixed variables dropped, `[y_c; y_d]` row order, objective,
2808    /// constraint and per-variable scaling) itself, so a converged solve's
2809    /// reported multipliers can be fed back unchanged. The working set is in
2810    /// the same space: bound statuses full-`n` in variable order (fixed
2811    /// variables' entries are ignored), constraint statuses one per `g` row
2812    /// in the user's row order — exactly what [`Self::last_sqp_working_set`]
2813    /// publishes, so a published set can be fed back as-is.
2814    pub fn set_sqp_warm_start(&mut self, warm: crate::sqp::SqpIterates) {
2815        self.sqp_warm_start = Some(warm);
2816    }
2817
2818    /// Drop any pending warm-start iterate without solving.
2819    pub fn clear_sqp_warm_start(&mut self) {
2820        self.sqp_warm_start = None;
2821    }
2822
2823    /// What the crossover phase did on the most recent solve (gh#612).
2824    ///
2825    /// `None` means crossover never ran — either `crossover=no` (the
2826    /// default) or the solve did not converge. A `Some` whose
2827    /// [`CrossoverReport::accepted`] is false means it ran and *declined*;
2828    /// the two are different facts about a solve and consumers that reason
2829    /// about active-set certainty (sensitivity's AMBIGUOUS class, a
2830    /// downstream `var_status`) need to tell them apart.
2831    ///
2832    /// [`CrossoverReport::accepted`]: crate::crossover::CrossoverReport::accepted
2833    pub fn crossover_report(&self) -> Option<&crate::crossover::CrossoverReport> {
2834        self.crossover_report.as_ref()
2835    }
2836
2837    /// What the interior-point → active-set handover did on the most recent
2838    /// solve (gh#1054); `None` unless `ipm_sqp_handover=yes`.
2839    pub fn handover_report(&self) -> Option<&crate::handover::HandoverReport> {
2840        self.handover_report.as_ref()
2841    }
2842
2843    /// Install a full primal-dual warm-start iterate for the next IPM
2844    /// `optimize_tnlp`. Captured by the debugger's `resolve` so the
2845    /// re-solve continues from the paused interior point. The caller is
2846    /// responsible for also enabling `warm_start_init_point=yes` (and
2847    /// usually `warm_start_target_mu=<μ>`) so the re-optimize branch of
2848    /// `WarmStartIterateInitializer` preserves the installed iterate.
2849    /// Consumed once per solve, then auto-cleared.
2850    pub fn set_warm_start_iterate(&mut self, snap: crate::debug::IterateSnapshot) {
2851        self.warm_start_iterate = Some(snap);
2852    }
2853
2854    /// Install a caller-supplied fill-reducing permutation for the KKT
2855    /// linear solver (pounce#180 item 1). The next `optimize_*` builds
2856    /// the FERAL backend with [`pounce_feral::OrderingMethod::External`],
2857    /// overriding the `feral_ordering` string option / env var. Use this
2858    /// to inject a block-triangular / Schur ordering a generic algorithm
2859    /// cannot see (Parker, Garcia & Bent, arXiv:2602.17968) or a tearing
2860    /// ordering from equation-oriented decomposition.
2861    ///
2862    /// `perm` is a **0-based, new-to-old permutation** (`perm[k]` is the
2863    /// original index that becomes index `k`), and its length must equal
2864    /// the augmented KKT system dimension (variables + slacks +
2865    /// constraint duals), *not* the problem's `n`. A wrong length or a
2866    /// non-bijection is rejected by FERAL at the first factorization with
2867    /// an `InvalidInput` error (never a panic), surfacing as a solver
2868    /// failure rather than a silently-wrong solve — the ordering only
2869    /// affects fill/time, never the computed solution.
2870    ///
2871    /// Persistent config: unlike the warm-start hooks it is *not*
2872    /// auto-cleared after a solve. Call [`Self::clear_external_ordering`]
2873    /// to drop it. Ignored by non-FERAL backends and by any custom
2874    /// factory plugged via [`Self::set_linear_backend_factory`].
2875    pub fn set_external_ordering(&mut self, perm: Vec<usize>) {
2876        self.external_ordering = Some(perm);
2877    }
2878
2879    /// Drop any installed external KKT ordering, restoring the
2880    /// `feral_ordering`-driven default for subsequent solves.
2881    pub fn clear_external_ordering(&mut self) {
2882        self.external_ordering = None;
2883    }
2884
2885    /// The currently-installed external KKT ordering, if any.
2886    pub fn external_ordering(&self) -> Option<&[usize]> {
2887        self.external_ordering.as_deref()
2888    }
2889
2890    /// Install a block-triangular / Schur KKT partition (pounce#180 item 2).
2891    /// `indices` are KKT-space indices (`0..dim` in the `x, s, c, d` block
2892    /// order the aug-system solver assembles) naming the Schur block `S`; that
2893    /// block is Schur-complemented out and only the two diagonal blocks are
2894    /// factorized (inertia via Sylvester's law). Honored on the IPM + feral +
2895    /// exact-Hessian path; the Schur solver falls back to the standard
2896    /// full-space solver transparently when the partition is unsuitable (too
2897    /// large a fraction of the system, malformed, or a backend error), so a
2898    /// stray hook never breaks a solve. Persistent config (not auto-cleared);
2899    /// drop it via [`Self::clear_kkt_schur_block`].
2900    /// Declare the block structure in the **model's own terms**: one block id
2901    /// per variable and per constraint, negative for the shared ones
2902    /// (structured-KKT Phase 5b). Blocks must couple only through the shared
2903    /// entries; the solver checks that against the assembled KKT and falls
2904    /// back when it does not hold.
2905    ///
2906    /// This is the form a model can produce — "`pg[g]` is shared, everything
2907    /// in contingency `k` is block `k`" — and pounce maps it to KKT indices
2908    /// itself, accounting for fixed variables and the equality / inequality
2909    /// split. Lengths are the problem's own `n` and `m`; a mismatch is
2910    /// reported and the solve proceeds monolithically.
2911    ///
2912    /// Persistent config; drop it with [`Self::clear_block_structure`].
2913    pub fn set_block_structure(&mut self, var_blocks: Vec<i32>, con_blocks: Vec<i32>) {
2914        self.model_blocks = Some((var_blocks, con_blocks));
2915    }
2916
2917    /// Drop any declared model-space block structure.
2918    pub fn clear_block_structure(&mut self) {
2919        self.model_blocks = None;
2920    }
2921
2922    /// The declared model-space block structure, if any.
2923    pub fn block_structure(&self) -> Option<(&[i32], &[i32])> {
2924        self.model_blocks
2925            .as_ref()
2926            .map(|(v, c)| (v.as_slice(), c.as_slice()))
2927    }
2928
2929    /// Install a block-parallel KKT partition (structured-KKT Phase 5b).
2930    /// `labels` are KKT-space block ids in the solver's internal
2931    /// `x, slack, eq-dual, ineq-dual` order, `< 0` for the shared border; an
2932    /// **empty** vector asks the solver to detect the structure from the
2933    /// assembled KKT. Honored on the IPM + feral + exact-Hessian path, with a
2934    /// transparent fallback to the standard solver when the partition does not
2935    /// match the matrix. Persistent config; drop it with
2936    /// [`Self::clear_kkt_block_structure`].
2937    pub fn set_kkt_block_structure(&mut self, labels: Vec<i32>) {
2938        self.kkt_blocks = Some(labels);
2939    }
2940
2941    /// Drop any installed block partition.
2942    pub fn clear_kkt_block_structure(&mut self) {
2943        self.kkt_blocks = None;
2944    }
2945
2946    /// The currently-installed block partition, if any.
2947    pub fn kkt_block_structure(&self) -> Option<&[i32]> {
2948        self.kkt_blocks.as_deref()
2949    }
2950
2951    pub fn set_kkt_schur_block(&mut self, indices: Vec<usize>) {
2952        self.kkt_schur_block = Some(indices);
2953    }
2954
2955    /// Drop any installed Schur KKT partition, restoring the standard
2956    /// full-space solver for subsequent solves.
2957    pub fn clear_kkt_schur_block(&mut self) {
2958        self.kkt_schur_block = None;
2959    }
2960
2961    /// The currently-installed Schur KKT partition, if any.
2962    pub fn kkt_schur_block(&self) -> Option<&[usize]> {
2963        self.kkt_schur_block.as_deref()
2964    }
2965
2966    /// Return the final QP working set from the most recent SQP
2967    /// solve, or `None` if the last solve wasn't SQP, didn't
2968    /// produce a working set (cold-start declared the iterate
2969    /// optimal before solving any QP), or no SQP solve has run.
2970    ///
2971    /// The set is in the **caller's** index spaces, the ones
2972    /// `finalize_solution` uses: `bounds[j]` is variable `j` of the full
2973    /// `n` (a variable `fixed_variable_treatment = make_parameter` removed
2974    /// reads `Fixed`), and `constraints[i]` is `g` row `i` in the model's
2975    /// own row order — not the SQP's internal equalities-first order. It is
2976    /// the form [`Self::set_sqp_warm_start`] takes back.
2977    pub fn last_sqp_working_set(&self) -> Option<&pounce_qp::WorkingSet> {
2978        self.sqp_last_working_set.as_ref()
2979    }
2980
2981    /// A working set computed in the solve's algorithm space, mapped to the
2982    /// caller's: bound statuses lifted to the full variable vector (gh#986
2983    /// review item 10 — fixed variables are `Fixed`), constraint statuses
2984    /// moved from the algorithm's `[c; d]` row order (equalities first) to
2985    /// the user's `g` row order through the NLP's `c_map` / `d_map`. A
2986    /// bound vector that is not reduced-sized is left as it is.
2987    fn working_set_to_user(
2988        &self,
2989        nlp: &dyn IpoptNlp,
2990        ws: pounce_qp::WorkingSet,
2991    ) -> pounce_qp::WorkingSet {
2992        let bounds = match &self.x_elimination {
2993            Some((map, n_full)) if ws.bounds.len() == map.len() && map.len() != *n_full => {
2994                let mut bounds = vec![pounce_qp::BoundStatus::Fixed; *n_full];
2995                for (k, &j) in map.iter().enumerate() {
2996                    bounds[j as usize] = ws.bounds[k];
2997                }
2998                bounds
2999            }
3000            _ => ws.bounds,
3001        };
3002        pounce_qp::WorkingSet {
3003            bounds,
3004            constraints: working_set_rows_to_user(nlp, ws.constraints),
3005        }
3006    }
3007
3008    /// If `solver_selection` is explicitly set to a value whose routing lives
3009    /// only in the CLI's `.nl` dispatch, return  it; otherwise `None`.
3010    /// `optimize_tnlp` uses this to reject a forced convex selection a library
3011    /// consumer cannot honor.
3012    fn unsupported_library_solver_selection(&self) -> Option<&'static str> {
3013        let (v, found) = self.options.get_string_value("solver_selection", "").ok()?;
3014        if !found {
3015            return None;
3016        }
3017        ["lp-ipm", "qp-ipm", "socp"]
3018            .into_iter()
3019            .find(|c| v.eq_ignore_ascii_case(c))
3020    }
3021
3022    /// The `linear_solver` value when the caller explicitly asked for a
3023    /// backend pounce does not implement; `None` when the request can be
3024    /// served (or was never made).
3025    ///
3026    /// pounce ships two: **FERAL** (pure Rust, the effective default) and
3027    /// **MA57** (HSL, behind the `ma57` feature). The option's valid-value
3028    /// list is a faithful port of upstream Ipopt's — `ma27`, `ma77`,
3029    /// `ma86`, `ma97`, `mumps`, `pardiso`, `pardisomkl`, `spral`, `wsmp`,
3030    /// `custom` — so an `ipopt.opt` written for Ipopt parses here, and
3031    /// every one of those names used to fall through a `_ =>` arm to
3032    /// FERAL. A run "using MUMPS" was a FERAL run; a benchmark comparing
3033    /// backends compared FERAL with itself (gh#483 follow-up).
3034    ///
3035    /// The registered default is `feral`, which pounce implements, so no
3036    /// explicit-vs-default distinction is needed: whatever the option
3037    /// resolves to must be a backend that exists. (It is checked
3038    /// unconditionally on purpose — a future default naming something
3039    /// unimplemented should trip this, not slip past it.)
3040    ///
3041    /// Explicit `ma57` on a build that lacks the feature is *not* refused;
3042    /// that fallback is reported in the banner ("ma57 requested but not
3043    /// compiled"), so it is visible rather than silent, and failing a
3044    /// portable `ipopt.opt` over a build flag would cost more than it buys.
3045    pub fn unimplemented_linear_solver(&self) -> Option<String> {
3046        let (v, _) = self.options.get_string_value("linear_solver", "").ok()?;
3047        ["feral", "ma57"]
3048            .iter()
3049            .all(|ok| !v.eq_ignore_ascii_case(ok))
3050            .then_some(v)
3051    }
3052
3053    /// The message for the first option the caller set that names a
3054    /// feature pounce does not implement, or `None`. Public so the CLI
3055    /// can refuse before routing — the convex dispatch never reaches
3056    /// `optimize_tnlp`. See [`crate::unimplemented_options`].
3057    ///
3058    /// A run configuring nothing but backends pounce does not ship is
3059    /// refused here too, after the per-option table has had its say —
3060    /// see [`crate::unimplemented_options::backend_only_refusal`]. It
3061    /// is folded in rather than given its own accessor so that every
3062    /// surface already refusing on this method refuses on it as well;
3063    /// the CLI is not the only frontend, and a condition worth failing
3064    /// on is not worth failing on only from the CLI.
3065    pub fn unimplemented_option_refusal(&self) -> Option<String> {
3066        crate::unimplemented_options::refusal(&self.options, &self.reg_options).or_else(|| {
3067            crate::unimplemented_options::backend_only_refusal(&self.options, &self.reg_options)
3068        })
3069    }
3070
3071    /// The message for the first string option the caller set to a
3072    /// registered *value* pounce does not implement, or `None`.
3073    ///
3074    /// Separate from [`Self::unimplemented_option_refusal`] because the
3075    /// option itself is read and its other values work — it is one mode
3076    /// that is missing, not the feature. See
3077    /// [`crate::unimplemented_options::UNIMPLEMENTED_VALUES`].
3078    pub fn unimplemented_option_value_refusal(&self) -> Option<String> {
3079        crate::unimplemented_options::value_refusal(&self.options)
3080    }
3081
3082    /// `option_file_name` set on a surface that never resolves it.
3083    ///
3084    /// The option reaches a file through exactly one path —
3085    /// [`Self::initialize_with_option_file`], which the `pounce` CLI
3086    /// drives. A library caller (Python, the C interface, WASM) sets its
3087    /// options directly and calls no such thing, so on those surfaces the
3088    /// option names a whole configuration and applies none of it: gh#518's
3089    /// failure mode, one surface over. It used to be caught by the blanket
3090    /// [`crate::unimplemented_options`] refusal, which no longer covers it
3091    /// now that the feature exists; this keeps the guard exactly where the
3092    /// feature still doesn't.
3093    ///
3094    /// Deliberately *not* fixed by having the library read an options file
3095    /// too: an implicit `./ipopt.opt` lookup under Python or the GAMS C
3096    /// link would be a surprising action at a distance, and `pounce.opt`
3097    /// already means something else to GAMS.
3098    pub fn unhonored_option_file_name(&self) -> Option<String> {
3099        if self.option_file_resolved {
3100            return None;
3101        }
3102        // Same default gate as the table: an explicitly-set *default*
3103        // asks for nothing, so it must not fail. `option_file_name`
3104        // defaults to `ipopt.opt`, and a caller round-tripping a full
3105        // option dump — or a generated config that spells out every
3106        // registered name — hits that value without asking for anything.
3107        if !crate::unimplemented_options::set_to_a_non_default(
3108            &self.options,
3109            &self.reg_options,
3110            "option_file_name",
3111        ) {
3112            return None;
3113        }
3114        match self.options.get_string_value("option_file_name", "") {
3115            Ok((name, true)) if !name.is_empty() => Some(format!(
3116                "pounce: `option_file_name` was set to `{name}`, but this entry \
3117                 point does not read options files — it would configure nothing. \
3118                 The `pounce` CLI honors it (and `./pounce.opt` / `./ipopt.opt`); \
3119                 from a library, read the file yourself and pass its contents to \
3120                 `initialize_with_options_str`, or set the options directly. \
3121                 Tracking issue: https://github.com/jkitchin/pounce/issues/518"
3122            )),
3123            _ => None,
3124        }
3125    }
3126
3127    /// Declare that this caller can route a model to the convex LP/QP /
3128    /// SOCP engines, so the `qp_*` knobs they read configure something.
3129    ///
3130    /// The `pounce` CLI calls this: it owns the `.nl` structure
3131    /// extraction that classifies a model, which is the whole of what
3132    /// `solver_selection`'s convex values need. No library frontend can
3133    /// (see [`Self::unsupported_library_solver_selection`]), so the
3134    /// default is `false` and [`Self::unhonored_convex_option`] refuses
3135    /// the knobs there.
3136    ///
3137    /// Declaring it also covers the CLI's *fallback*: a convex attempt
3138    /// that returns no verified point hands the model to
3139    /// [`Self::optimize_tnlp`], and the `qp_*` values it was given
3140    /// configured that attempt for real. Refusing them at the handoff
3141    /// would fail a run that used them.
3142    pub fn set_convex_routing_available(&mut self, available: bool) {
3143        self.convex_routing_available = available;
3144    }
3145
3146    /// The convex LP/QP knobs are registered core-side so every frontend
3147    /// parses them — but only the CLI can reach the engines that read
3148    /// them. On any other entry point the option names a whole
3149    /// configuration and applies none of it; this is the message that
3150    /// says so, in place of the silence.
3151    ///
3152    /// gh#604. Same shape and same default gate as
3153    /// [`Self::unhonored_option_file_name`]: an explicitly-set *default*
3154    /// asks for nothing and must keep working, so only a value that
3155    /// differs is refused.
3156    pub fn unhonored_convex_option(&self) -> Option<String> {
3157        if self.convex_routing_available {
3158            return None;
3159        }
3160        const CONVEX_ONLY: &[&str] = &[
3161            "qp_presolve",
3162            "qp_tau",
3163            "qp_tau_max",
3164            "qp_reg",
3165            "qp_gondzio_corr",
3166            "qp_infeas_tol",
3167            "qp_hsde",
3168            "qp_equilibrate",
3169            "qp_crossover",
3170        ];
3171        let name = CONVEX_ONLY.iter().find(|name| {
3172            crate::unimplemented_options::set_to_a_non_default(
3173                &self.options,
3174                &self.reg_options,
3175                name,
3176            )
3177        })?;
3178        Some(format!(
3179            "pounce: `{name}` tunes the convex LP/QP interior-point engine, but \
3180             this entry point cannot route a model to it — the option would \
3181             configure nothing. The `pounce` CLI reaches that engine on `.nl` \
3182             input (`solver_selection=lp-ipm` / `qp-ipm` / `socp`, or `auto` on \
3183             a model that classifies as one); the `qp_*` options themselves are \
3184             read only there and by `pounce.solve_qp`. From Python, \
3185             `pounce.solve_qp` drives the engine directly and takes `qp_presolve`, \
3186             `qp_reg`, `qp_hsde`, `qp_equilibrate` and `qp_crossover` as keyword \
3187             arguments (presolve is off there unless asked for). \
3188             On this path, `solver_selection=qp-active-set` \
3189             (or `algorithm=active-set-sqp`) is the nearest thing, tuned by the \
3190             `sqp_qp_*` options. Tracking issue: \
3191             https://github.com/jkitchin/pounce/issues/604"
3192        ))
3193    }
3194
3195    /// Warnings for caching hints pounce does not exploit. These never
3196    /// block a solve: the answer is identical either way, so refusing
3197    /// would cost the caller more than the silence did.
3198    pub fn unexploited_hint_warnings(&self) -> Vec<String> {
3199        crate::unimplemented_options::hint_warnings(&self.options, &self.reg_options)
3200    }
3201
3202    /// Warnings for the constant-derivative hints when the solve routes to
3203    /// `pounce-convex` instead of here. Call site is the convex dispatch
3204    /// in the CLI, next to the other guards that live there for the same
3205    /// reason: that dispatch never reaches [`Self::optimize_tnlp`], so
3206    /// `install_constant_derivative_hints` never runs and the hints are
3207    /// unread. On the NLP route they are honoured, so this must not be
3208    /// called there.
3209    pub fn convex_unexploited_hint_warnings(&self) -> Vec<String> {
3210        crate::unimplemented_options::convex_hint_warnings(&self.options, &self.reg_options)
3211    }
3212
3213    /// Which of the four constant-derivative hints the caller actually
3214    /// asserted, in [`pounce_nlp::constant_derivatives::HINT_OPTIONS`]
3215    /// order — the order [`reconcile`] pairs against the model's own
3216    /// proofs.
3217    ///
3218    /// Each name is read as a literal rather than through the loop
3219    /// variable the caller used to use. The registered-but-unread scan
3220    /// (`tests/no_silent_options.rs`) keys on the option name as it
3221    /// appears at the accessor, so `get_bool_value(name, "")` over an
3222    /// array read as "no key here" and left all four sitting in the
3223    /// silent list while they were fully wired and consumed (#551 /
3224    /// #677).
3225    ///
3226    /// Matching over `HINT_OPTIONS` rather than writing a bare array
3227    /// keeps the slots right by construction, and a fifth hint added to
3228    /// `HINT_OPTIONS` trips the fallback arm instead of silently reading
3229    /// as "not asserted" — which is the failure mode this whole line of
3230    /// work exists to kill.
3231    fn asserted_constant_derivative_hints(&self) -> [bool; 4] {
3232        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
3233        let read_yes = |key: &str| matches!(self.options.get_bool_value(key, ""), Ok((true, true)));
3234        HINT_OPTIONS.map(|name| match name {
3235            "grad_f_constant" => read_yes("grad_f_constant"),
3236            "hessian_constant" => read_yes("hessian_constant"),
3237            "jac_c_constant" => read_yes("jac_c_constant"),
3238            "jac_d_constant" => read_yes("jac_d_constant"),
3239            other => unreachable!("`{other}` is in HINT_OPTIONS with no read site"),
3240        })
3241    }
3242
3243    /// Resolve the four constant-derivative hints for this solve and
3244    /// install the result on the NLP (gh #588, phase Q6).
3245    ///
3246    /// `grad_f_constant` / `hessian_constant` / `jac_c_constant` /
3247    /// `jac_d_constant` are, upstream, unchecked user assertions: Ipopt
3248    /// reuses the derivative and returns a wrong answer if the assertion
3249    /// was false. pounce asks the model first. Where the model *proves*
3250    /// the derivative constant, the reuse happens whether or not the
3251    /// option was set — the hint is redundant. Where the model proves it
3252    /// **varies** and the option was set anyway, the option is refused
3253    /// with a warning, which is the deliberate divergence. Where the
3254    /// model can prove nothing — every callback front end, both GAMS
3255    /// links — the user's assertion is honoured on trust, exactly as
3256    /// upstream, because "unproved" is not "disproved" and silently
3257    /// overriding the caller there would be its own wrong answer.
3258    fn install_constant_derivative_hints(&self, orig_nlp: &mut OrigIpoptNlp) {
3259        use pounce_common::journalist::JournalCategory;
3260        use pounce_nlp::constant_derivatives::reconcile;
3261
3262        // Each name is read as a literal rather than through the loop
3263        // variable: the registered-but-unread scan
3264        // (`tests/no_silent_options.rs`) keys on the option name as it
3265        // appears at the accessor, so `get_bool_value(name, "")` read as
3266        // "no key here" and left all four of these sitting in the silent
3267        // list while they were fully wired and consumed (#551 / #677).
3268        //
3269        // Matching over `HINT_OPTIONS` rather than writing a bare array
3270        // keeps the order right by construction — `reconcile` pairs
3271        // `asserted[k]` with `proofs[k]` — and a fifth hint added to
3272        // `HINT_OPTIONS` trips the fallback arm instead of silently
3273        // reading as "not asserted", which is the failure mode this
3274        // whole line of work exists to kill.
3275        let asserted = self.asserted_constant_derivative_hints();
3276        let proofs = orig_nlp.derivative_proofs();
3277        let (outcomes, enabled) = reconcile(proofs, asserted);
3278
3279        for outcome in &outcomes {
3280            if let Some(warning) = outcome.warning() {
3281                eprintln!("{warning}");
3282                self.journalist.print(
3283                    JournalLevel::J_STRONGWARNING,
3284                    JournalCategory::J_MAIN,
3285                    &format!("{warning}\n"),
3286                );
3287            }
3288        }
3289        if std::env::var("POUNCE_DBG_CONSTDERIV").is_ok() {
3290            for outcome in &outcomes {
3291                eprintln!(
3292                    "[const deriv] {:<15} proof={:?} asserted={} reused={}",
3293                    outcome.name, outcome.proof, outcome.asserted, outcome.honoured,
3294                );
3295            }
3296        }
3297        orig_nlp.set_constant_derivatives(enabled);
3298    }
3299
3300    /// Warnings for knobs of a linear-solver backend pounce does not
3301    /// ship (`ma97_*`, `pardiso_*`, …), one line per backend family.
3302    ///
3303    /// Warnings and not refusals: an `ipopt.opt` carrying settings for
3304    /// several backends so that one file runs everywhere is exactly what
3305    /// the registry exists to accept, and refusing it would fail a run
3306    /// over knobs it never touches. See the "Backend knobs warn, they do
3307    /// not refuse" section of [`crate::unimplemented_options`]. gh#551.
3308    pub fn unimplemented_backend_warnings(&self) -> Vec<String> {
3309        crate::unimplemented_options::backend_warnings(&self.options, &self.reg_options)
3310    }
3311
3312    /// The same warnings, but at most once per application: the second
3313    /// caller gets nothing.
3314    ///
3315    /// Two sites emit them — the CLI, before routing, because a convex
3316    /// model never reaches [`Self::optimize_tnlp`], and `optimize_tnlp`
3317    /// itself, for every frontend that is not the CLI. A CLI run passes
3318    /// through both, and printing the identical paragraph twice is how a
3319    /// warning teaches its reader to skip warnings.
3320    pub fn take_unimplemented_backend_warnings(&mut self) -> Vec<String> {
3321        if self.backend_warnings_emitted {
3322            return Vec::new();
3323        }
3324        self.backend_warnings_emitted = true;
3325        self.unimplemented_backend_warnings()
3326    }
3327
3328    /// Resolve the five registered `derivative_test*` knobs. Every one
3329    /// of them was registered and never read, so `derivative_test=
3330    /// first-order` ran no test and printed nothing — a checker that
3331    /// silently checks nothing reports success by omission (gh#483
3332    /// follow-up).
3333    ///
3334    /// The numeric helper is named `read_num` to match the accessor
3335    /// idiom the rest of this file uses: the registered-but-unread scan
3336    /// (`tests/no_silent_options.rs`) discovers `read_*` helpers and the
3337    /// literal key passed to them, so a differently-named local closure
3338    /// made `derivative_test_perturbation` and `derivative_test_tol`
3339    /// read as silent when they are wired and consumed (#677, #551).
3340    fn derivative_test_options(&self) -> DerivativeTestOptions {
3341        let read_num = |key: &str, default: Number| -> Number {
3342            self.options
3343                .get_numeric_value(key, "")
3344                .ok()
3345                .and_then(|(v, f)| f.then_some(v))
3346                .unwrap_or(default)
3347        };
3348        DerivativeTestOptions {
3349            mode: self
3350                .options
3351                .get_string_value("derivative_test", "")
3352                .ok()
3353                .and_then(|(v, f)| f.then_some(v))
3354                .map(|v| DerivativeTest::from_option(&v))
3355                .unwrap_or_default(),
3356            perturbation: read_num("derivative_test_perturbation", 1e-8),
3357            tol: read_num("derivative_test_tol", 1e-4),
3358            first_index: self
3359                .options
3360                .get_integer_value("derivative_test_first_index", "")
3361                .ok()
3362                .and_then(|(v, f)| f.then_some(v))
3363                .unwrap_or(-2),
3364            print_all: self
3365                .options
3366                .get_bool_value("derivative_test_print_all", "")
3367                .ok()
3368                .and_then(|(v, f)| f.then_some(v))
3369                .unwrap_or(false),
3370        }
3371    }
3372
3373    /// The derivative checker's structured verdict from the most recent
3374    /// [`Self::run_derivative_test`], or `None` when no test ran (gh#990).
3375    /// The IPM and SQP drains copy it into `SolveStatistics`; a caller that
3376    /// builds its own report (the CLI's convex route) reads it here.
3377    pub fn derivative_check(&self) -> Option<pounce_nlp::derivative_test::DerivativeCheckSummary> {
3378        self.derivative_check.borrow().clone()
3379    }
3380
3381    /// Run the derivative checker, if requested, against `tnlp`.
3382    ///
3383    /// Advisory, like upstream: a suspicious entry is reported and the
3384    /// solve continues. The report goes to stderr so it survives
3385    /// `print_level=0` and leaves `--json-output`'s stdout clean.
3386    pub fn run_derivative_test(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
3387        // gh#990 item 3: the structured result belongs to this solve; a solve
3388        // that asks for no test must not inherit the previous one's.
3389        *self.derivative_check.borrow_mut() = None;
3390        let opts = self.derivative_test_options();
3391        if matches!(opts.mode, DerivativeTest::None) {
3392            return;
3393        }
3394        let report = {
3395            let mut borrowed = tnlp.borrow_mut();
3396            pounce_nlp::derivative_test::run(&mut *borrowed, &opts)
3397        };
3398        let Some(report) = report else {
3399            eprintln!(
3400                "pounce: derivative_test was requested but the TNLP declined to \
3401                 supply the information the check needs (dimensions, bounds, or \
3402                 a starting point); no test was run."
3403            );
3404            return;
3405        };
3406        *self.derivative_check.borrow_mut() = Some(report.summary.clone());
3407        use pounce_common::journalist::JournalCategory;
3408        for line in &report.lines {
3409            eprintln!("{line}");
3410            self.journalist.print(
3411                JournalLevel::J_SUMMARY,
3412                JournalCategory::J_MAIN,
3413                &format!("{line}\n"),
3414            );
3415        }
3416    }
3417
3418    /// The message [`Self::unimplemented_linear_solver`] earns, shared by
3419    /// every frontend so they cannot drift apart.
3420    pub fn unimplemented_linear_solver_message(value: &str) -> String {
3421        format!(
3422            "pounce: linear_solver={value} is not implemented. pounce provides \
3423             `feral` (pure-Rust sparse symmetric, the default) and `ma57` (HSL, \
3424             in a `--features ma57` build); the other names in the option's \
3425             list come from the upstream Ipopt registry so an ipopt.opt written \
3426             for Ipopt still parses. Selecting one used to run FERAL silently, \
3427             which makes a backend comparison measure nothing — so it is \
3428             refused instead. Use linear_solver=feral or linear_solver=ma57."
3429        )
3430    }
3431
3432    /// Will the next `optimize_tnlp` run the active-set SQP driver rather
3433    /// than the interior-point one?
3434    ///
3435    /// Public because the dispatch decision has to be *reportable*, not just
3436    /// taken: before this was reachable, the CLI's `Selected solver:` line
3437    /// and the JSON report's `solution.engine` both named the filter-IPM on
3438    /// every `algorithm=active-set-sqp` run, because the only thing either
3439    /// consulted was `solver_selection` — which is `auto` on a general NLP
3440    /// however the `algorithm` option is set. Reading the same predicate
3441    /// `optimize_tnlp` dispatches on is what keeps the report and the run
3442    /// from disagreeing; deriving it a second time in the CLI is how they
3443    /// drifted in the first place.
3444    pub fn is_sqp_algorithm_selected(&self) -> bool {
3445        // `algorithm` is the primary selector.
3446        // `solver_selection = qp-active-set` selects the
3447        // same active-set SQP engine.
3448        let algo_sqp = matches!(
3449            self.options.get_string_value("algorithm", ""),
3450            Ok((v, true)) if v.eq_ignore_ascii_case("active-set-sqp")
3451        );
3452        let selection_sqp = matches!(
3453            self.options.get_string_value("solver_selection", ""),
3454            Ok((v, true)) if v.eq_ignore_ascii_case("qp-active-set")
3455        );
3456        algo_sqp || selection_sqp
3457    }
3458
3459    /// Whether an active-set SQP request on a model with `n` variables and
3460    /// `m` constraints runs as the interior point with the IPM→SQP handover
3461    /// and post-convergence crossover, instead of a cold active-set SQP
3462    /// (gh#1061).
3463    ///
3464    /// A primal active-set QP started cold changes its working set one row or
3465    /// bound per iteration, so the SQP's first step QP needs on the order of
3466    /// one iteration per active constraint, each a KKT update the size of the
3467    /// model. Measured on four 9–20 k-variable equality-heavy NLPs
3468    /// (`brainpc2`, `robot_1600`, `WM_CFy`, `ubh5`): not one first QP finished
3469    /// in 300 s. Started from the interior point instead, `ubh5` solves in
3470    /// 0.5 s and `robot_1600` in 6 s. The active-set SQP produces the answer
3471    /// when a handover attempt is accepted; when every attempt declines, the
3472    /// converged interior point is the answer, exactly as under
3473    /// `ipm_sqp_handover=yes`. Post-convergence `crossover` is not turned on
3474    /// as well: measured, it bought `robot_1600` its active-set answer for
3475    /// 6 s → 41 s, and on `brainpc2` declined after a 194 s step-3 QP, past
3476    /// the wall-time limit.
3477    ///
3478    /// Only above [`AUTO_HANDOVER_MIN_DIM`], where a cold SQP is the problem,
3479    /// and only when `ipm_sqp_handover` was not set: `ipm_sqp_handover=no`
3480    /// asks for the cold active-set SQP and gets it.
3481    pub fn sqp_auto_handover(&self, n: usize, m: usize) -> bool {
3482        self.is_sqp_algorithm_selected()
3483            && n + m >= AUTO_HANDOVER_MIN_DIM
3484            && !matches!(
3485                self.options.get_bool_value("ipm_sqp_handover", ""),
3486                Ok((_, true))
3487            )
3488    }
3489
3490    /// Whether the most recent solve was run as interior point plus handover
3491    /// under [`Self::sqp_auto_handover`].
3492    pub fn auto_handover_ran(&self) -> bool {
3493        self.auto_handover.get()
3494    }
3495
3496    /// Whether the active-set SQP produced the most recent solve's point:
3497    /// always on the cold SQP route, and on the auto-handover route when a
3498    /// handover attempt (or a crossover the user asked for) was accepted.
3499    pub fn answer_from_active_set_sqp(&self) -> bool {
3500        if !self.auto_handover.get() {
3501            return self.is_sqp_algorithm_selected();
3502        }
3503        self.handover_report
3504            .as_ref()
3505            .is_some_and(|r| r.accepted_at_iter.is_some())
3506            || self.crossover_report.as_ref().is_some_and(|r| r.accepted())
3507    }
3508
3509    /// Phase 5b SQP entry point. Builds the same NLP chain
3510    /// (`TNLPAdapter` → `OrigIpoptNlp` → `IpoptNlpAdapter`) the
3511    /// IPM uses, then runs `SqpAlgorithm::optimize`. Maps the
3512    /// `SqpResult.status` back to `ApplicationReturnStatus` and
3513    /// hands the final iterate to the user TNLP's
3514    /// `finalize_solution` callback via `finalize_via_sqp`.
3515    fn optimize_sqp_tnlp(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
3516        use pounce_nlp::ConstObjScaling;
3517        use pounce_nlp::orig_ipopt_nlp::OrigIpoptNlp;
3518        use pounce_nlp::tnlp_adapter::TNLPAdapter;
3519
3520        // Wall-clock for the whole SQP solve, mirroring the IPM path's
3521        // `t_start` (see the `total_wallclock_time_secs` assignment in
3522        // `optimize_tnlp`). Without this the field stayed at its struct
3523        // default of 0.0 on every active-set solve, so `--json-output`
3524        // reported an instantaneous solve regardless of actual runtime and
3525        // the engine could not be speed-compared against qp-ipm at all
3526        // (benchmarks/scripts/compare_qp_four_way.py had to skip the column).
3527        let t_start = std::time::Instant::now();
3528
3529        // `new_with_options`, not `new`: the latter hard-codes the same three
3530        // defaults, so `fixed_variable_treatment`, `nlp_lower_bound_inf` and
3531        // `nlp_upper_bound_inf` were accepted and discarded on this arm. The
3532        // defaults coincide, which is why it went unnoticed — it diverges only
3533        // for a caller who sets one, and then the two arms CLASSIFY THE MODEL
3534        // DIFFERENTLY: a bound at the caller's own infinity threshold is a
3535        // bound here and no bound there, and a fixed variable is eliminated on
3536        // one arm and relaxed on the other. That is a different problem, not a
3537        // different trajectory on one.
3538        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
3539        let adapter = match TNLPAdapter::new_with_options(
3540            Rc::clone(&tnlp),
3541            lo_inf,
3542            up_inf,
3543            fixed_treatment,
3544        ) {
3545            Ok(a) => Rc::new(RefCell::new(a)),
3546            Err(_) => return ApplicationReturnStatus::InvalidProblemDefinition,
3547        };
3548        // The SQP path never runs gradient-based scaling, but the
3549        // constant `obj_scaling_factor` (negative ⇒ maximize) still
3550        // applies via the OrigIpoptNlp constructor.
3551        let obj_scaling_factor = self
3552            .options
3553            .get_numeric_value("obj_scaling_factor", "")
3554            .ok()
3555            .and_then(|(v, f)| f.then_some(v))
3556            .unwrap_or(1.0);
3557        let mut orig_nlp = match OrigIpoptNlp::new(
3558            Rc::clone(&adapter),
3559            Rc::new(ConstObjScaling(obj_scaling_factor)),
3560        ) {
3561            Ok(n) => n,
3562            Err(_) => return ApplicationReturnStatus::InternalError,
3563        };
3564        // Same Q6 reconciliation as the IPM route: the SQP driver
3565        // evaluates the same derivatives through the same NLP object.
3566        self.install_constant_derivative_hints(&mut orig_nlp);
3567        // `bound_relax_factor`, on the convex arm's rule (gh#745's
3568        // `convex_bound_relax`), because this arm's position is the convex
3569        // arm's and not the interior-point arm's.
3570        //
3571        // The widening is a change to the MODEL, and its error is one-signed:
3572        // enlarging the feasible set can only flatter the objective, by `δ`
3573        // times the bound's multiplier, with nothing bounding that product and
3574        // no amount of tightening `tol` closing it. On `LISWET1` it buys `9.0`
3575        // of objective (`27.1221` against the true `36.1224`); over the
3576        // 91-instance netlib LP corpus, dropping it took the median objective
3577        // error from `1.2e-08` to `3.8e-11`.
3578        //
3579        // The interior-point arm keeps it and must: it is a feasible-iterate
3580        // log-barrier that needs `x` strictly inside its bounds, and matching
3581        // Ipopt is that arm's contract — the fixture sweep at
3582        // `bound_relax_factor=0` turns `square_flowsheet_resto` into
3583        // `InfeasibleProblemDetected`. An active-set QP needs none of it: its
3584        // iterates are feasible for the box by construction, which is why this
3585        // arm has always run un-widened without incident.
3586        //
3587        // So: unset means solve the model as declared, which is what this arm
3588        // already did. What it did NOT do is honour an explicit request — the
3589        // option was accepted and discarded, the gh#677 shape, and a caller
3590        // comparing arms under a named `bound_relax_factor` was comparing two
3591        // different models without being told. Set means the caller asked by
3592        // name and gets exactly the interior-point arm's model.
3593        //
3594        // Either branch snapshots the declared bounds first (`relax_bounds`
3595        // does it before widening), which `declared_box_violation` needs: its
3596        // absence is what printed `Variable bound violation: nan` here.
3597        let requested_relax = self
3598            .options
3599            .get_numeric_value("bound_relax_factor", "")
3600            .ok()
3601            .and_then(|(v, set)| set.then_some(v));
3602        match requested_relax {
3603            Some(factor) => {
3604                let cap = self
3605                    .options
3606                    .get_numeric_value("constr_viol_tol", "")
3607                    .ok()
3608                    .and_then(|(v, set)| set.then_some(v))
3609                    .unwrap_or(1e-4);
3610                orig_nlp.relax_bounds(factor, cap);
3611            }
3612            None => orig_nlp.snapshot_declared_bounds(),
3613        }
3614        let nlp_rc: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
3615
3616        let mut sqp_adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(&nlp_rc));
3617
3618        let mut builder = self.algorithm_builder_snapshot();
3619        builder.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
3620        // `max_wall_time` / `max_cpu_time` on this arm (gh#1054). They were
3621        // registered, documented as solve-wide, and read only by the
3622        // interior-point convergence check, so an active-set solve stuck in
3623        // its first QP ran until something outside POUNCE killed it.
3624        builder.sqp.deadline = Some(self.solve_deadline());
3625        // Prefer a caller-installed factory, exactly as `optimize_constrained`
3626        // does, so an embedder that plugs its own backend gets it on both
3627        // arms. `take()` matches the IPM's one-shot semantics rather than
3628        // introducing a second, different lifetime for the same hook.
3629        //
3630        // `maybe_crossover` deliberately does NOT do this: it runs after the
3631        // IPM solve has already taken the factory, so there is never one left
3632        // to find, and its two closures cannot both hold `&mut self` anyway.
3633        let factory = self
3634            .linear_backend_factory
3635            .take()
3636            .unwrap_or_else(|| self.make_backend_factory());
3637        let mut alg = match builder.build_sqp_with_backend(factory) {
3638            Some(a) => a,
3639            None => return ApplicationReturnStatus::InternalError,
3640        };
3641
3642        // Problem statistics + end-of-run summary are emitted by the engine
3643        // itself here (#206), gated on the main `print_level`, so the SQP
3644        // route matches the IPM route across every frontend (CLI, Python, C).
3645        // The SQP's own per-iteration rows stay gated on the separate
3646        // `sqp_print_level`.
3647        let console_output = match self.options.get_integer_value("print_level", "") {
3648            Ok((v, true)) => v >= 1,
3649            _ => true,
3650        };
3651        self.emit_problem_stats(&tnlp, console_output);
3652
3653        // Phase 5c (§6): consume any stashed warm-start iterate.
3654        // `optimize_with_warm_start(warm=None)` is equivalent to
3655        // `optimize`, so cold callers see no change.
3656        let mut warm = self.sqp_warm_start.take();
3657        // gh#986 review item 10: map a warm start given in the caller's full
3658        // variable space through this problem's fixed-variable elimination.
3659        // The working set this application publishes is in that space
3660        // (`working_set_to_user`), and so is what Python's
3661        // `solve(..., working_set=...)` decodes, so a child that fixes `x1`
3662        // gets the parent's statuses for exactly the columns it still has.
3663        // The first pass compared lengths only: a fixed variable made the
3664        // full-space hint "the wrong size" and it was dropped (a cold solve
3665        // and `info["working_set"] = None`), while a reduced-space hint from a
3666        // sibling that fixed a *different* variable had the right size and was
3667        // applied to the wrong columns.
3668        let (x_map, n_full) = {
3669            let a = adapter.borrow();
3670            let cls = a.classification();
3671            (cls.x_not_fixed_map.clone(), cls.n_full_x as usize)
3672        };
3673        let reduced = x_map.len() != n_full;
3674        let prev_elimination = self.x_elimination.replace((x_map.clone(), n_full));
3675        if let Some(w) = warm.as_mut() {
3676            // The staged iterate is in the caller's (user) space; the
3677            // algorithm's is not. Converted here, once, for every frontend.
3678            sqp_warm_start_to_algorithm(&*nlp_rc.borrow(), w);
3679            if reduced {
3680                let mut drop_reason: Option<String> = None;
3681                if let Some(ws) = w.working.as_mut() {
3682                    if ws.bounds.len() == n_full {
3683                        ws.bounds = x_map.iter().map(|&j| ws.bounds[j as usize]).collect();
3684                    } else if ws.bounds.len() == x_map.len()
3685                        && prev_elimination.as_ref() != Some(&(x_map.clone(), n_full))
3686                    {
3687                        // A reduced-space working set from a solve that
3688                        // eliminated *different* variables: its columns do
3689                        // not line up with this problem's, however equal the
3690                        // count.
3691                        drop_reason = Some(
3692                            "its bound statuses are in the reduced space of a solve that \
3693                             fixed different variables"
3694                                .into(),
3695                        );
3696                    }
3697                }
3698                if let Some(why) = drop_reason {
3699                    tracing::warn!(
3700                        target: "pounce::sqp",
3701                        "SQP warm-start working set dropped: {why}; pass the full-space \
3702                         working set (last_sqp_working_set / info[\"working_set\"]) instead"
3703                    );
3704                    w.working = None;
3705                }
3706            }
3707        }
3708        // `warm_start_init_point=yes` with nothing staged: take the TNLP's
3709        // own starting multipliers, as the interior-point arm does. They
3710        // arrive through the same `IpoptNlp` projections the IPM's warm
3711        // initializer uses, so they are already in algorithm space (scaled,
3712        // compressed, `[y_c; y_d]`). Without this the SQP arm read only the
3713        // primal: a `.nl` `d` segment or `ipopt_z*_in` suffix, or a Python
3714        // `lagrange=` start, began from zero multipliers on this arm alone.
3715        if warm.is_none()
3716            && matches!(
3717                self.options.get_bool_value("warm_start_init_point", ""),
3718                Ok((true, _))
3719            )
3720        {
3721            warm = sqp_tnlp_warm_start(&nlp_rc);
3722        }
3723        // gh#986: a warm start recorded on one problem is dimensioned for
3724        // that problem. A child that fixes a variable (branching) reaches
3725        // here with a smaller reduced `n` (and possibly `m`), where the
3726        // algorithm's contract is to refuse a mismatched iterate outright —
3727        // which surfaced as `Internal_Error` on a perfectly legal solve.
3728        // A warm start is only a hint, so drop it with a warning and solve
3729        // cold instead.
3730        if let Some(w) = warm.as_ref() {
3731            use crate::sqp::SqpProblemSpec;
3732            let (n, m) = (sqp_adapter.n(), sqp_adapter.m());
3733            let fits = w.x.len() == n
3734                && w.lambda_x.len() == n
3735                && w.lambda_g.len() == m
3736                && w.working
3737                    .as_ref()
3738                    .map(|ws| ws.validate_dims(n, m).is_ok())
3739                    .unwrap_or(true);
3740            if !fits {
3741                tracing::warn!(
3742                    target: "pounce::sqp",
3743                    "SQP warm start dropped: it is sized for a problem with n = {}, m = {} \
3744                     but this one has n = {n}, m = {m} (a fixed variable or removed row \
3745                     changes the reduced dimensions); solving cold",
3746                    w.x.len(),
3747                    w.lambda_g.len(),
3748                );
3749                warm = None;
3750            }
3751        }
3752        let warm_working_set_applied = warm.as_ref().is_some_and(|w| w.working.is_some());
3753        // gh#1015: the user's `intermediate_callback`, once per iteration,
3754        // with `GetIpoptCurrentIterate` answering from the SQP iterate. The
3755        // snapshot is built before the callback runs because the callback
3756        // holds the TNLP; nothing in it may call back into the user's
3757        // `eval_*`.
3758        {
3759            let hook_nlp = Rc::clone(&nlp_rc);
3760            let hook_tnlp = Rc::clone(&tnlp);
3761            let fixed_var_duals = self.reports_fixed_var_duals();
3762            alg.set_iteration_hook(Box::new(move |info| {
3763                // Built only for a TNLP that reads it, as on the
3764                // interior-point arm: the fixed-variable recovery is not
3765                // free, and most callbacks read only the stats.
3766                let _guard = hook_tnlp.borrow().wants_current_iterate().then(|| {
3767                    crate::intermediate::UserIterateGuard::install(sqp_user_iterate(
3768                        &hook_nlp,
3769                        info.x,
3770                        info.lambda_g,
3771                        info.lambda_x,
3772                        info.c_vals,
3773                        info.grad_lag_x,
3774                        fixed_var_duals,
3775                    ))
3776                });
3777                let stats = pounce_nlp::tnlp::IterStats {
3778                    mode: pounce_nlp::return_codes::AlgorithmMode::RegularMode,
3779                    iter: info.iter as Index,
3780                    obj_value: info.obj,
3781                    inf_pr: info.inf_pr,
3782                    inf_du: info.inf_du,
3783                    // No barrier, no regularisation, no dual step length.
3784                    mu: 0.0,
3785                    d_norm: info.p_inf,
3786                    regularization_size: 0.0,
3787                    alpha_du: 0.0,
3788                    alpha_pr: info.alpha,
3789                    ls_trials: 0,
3790                };
3791                hook_tnlp.borrow_mut().intermediate_callback(
3792                    stats,
3793                    &pounce_nlp::tnlp::IpoptData::default(),
3794                    &pounce_nlp::tnlp::IpoptCq::default(),
3795                )
3796            }));
3797        }
3798        let res = match alg.optimize_with_warm_start(&mut sqp_adapter, warm) {
3799            Ok(r) => r,
3800            Err(e) => {
3801                // Always surface this. It used to be gated on the
3802                // undocumented `POUNCE_DBG_SQP`, so the only thing a user saw
3803                // was a bare `Internal_Error` with no indication of what went
3804                // wrong -- the underlying message here was
3805                // `QpFailure(LinearSolverFailure("QP subproblem returned
3806                // status unbounded"))`, which points straight at the cause.
3807                // A solve that is about to fail is exactly when the reason
3808                // should be cheapest to obtain.
3809                tracing::warn!(
3810                    target: "pounce::sqp",
3811                    "SQP solve failed: {e:?}"
3812                );
3813                return ApplicationReturnStatus::InternalError;
3814            }
3815        };
3816        // Stash the result's working set so the next solve in a
3817        // sequence can fetch it via `last_sqp_working_set` -- in the caller's
3818        // full variable space (gh#986 review item 10).
3819        self.sqp_last_working_set = res
3820            .working_set
3821            .clone()
3822            .map(|ws| self.working_set_to_user(&*nlp_rc.borrow(), ws));
3823        // Populate the shared `SolveStatistics` so the Python /
3824        // C-API post-solve accessors (`GetIpoptIterCount`,
3825        // `info["iter_count"]`, etc.) report the SQP outer-iter
3826        // count rather than zero. Constraint-violation /
3827        // dual-infeasibility residuals get the SQP-side values
3828        // too. The IPM path overwrites this dict on its own
3829        // solves, so SQP-vs-IPM mixing across solves stays
3830        // honest.
3831        {
3832            let mut stats = self.statistics.borrow_mut();
3833            stats.iteration_count = res.n_iter as Index;
3834            // Subproblem counters. The outer iteration count alone
3835            // cannot show what a working-set warm start bought — the
3836            // saved work is inside the QPs — so both are reported.
3837            stats.sqp_qp_solves = res.n_qp_solves as Index;
3838            stats.sqp_qp_working_set_changes = res.n_qp_working_set_changes as Index;
3839            stats.sqp_warm_working_set_applied = warm_working_set_applied;
3840            stats.final_objective = res.obj;
3841            // `final_scaled_objective` defaults to NaN; the SQP path does not
3842            // thread nlp_scaling through the objective (same as the residuals
3843            // mirrored below), so the scaled objective equals the unscaled
3844            // one. Without this it stayed NaN and the console printed
3845            // "Objective ...: nan  <unscaled>" on every active-set solve
3846            // (gh #313), even on a clean optimal solve.
3847            stats.final_scaled_objective = res.obj;
3848            stats.final_dual_inf = res.final_stationarity;
3849            stats.final_constr_viol = res.final_constr_viol;
3850            stats.final_compl = 0.0; // SQP has no barrier — no compl term.
3851            // Overall KKT error. This was previously left at the struct
3852            // default, which made every successful SQP solve report an
3853            // overall error of exactly 0.0 — indistinguishable from a
3854            // genuinely perfect solve, and enough on its own to make
3855            // `pounce.minimize`'s acceptable-KKT fallback upgrade any status
3856            // on this path to `success=True`. Same expression as the unscaled
3857            // twin below; the two agree because the SQP path does not thread
3858            // nlp_scaling through its residuals.
3859            stats.final_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3860            // Unscaled residuals (pounce#173). The SQP path does not thread
3861            // the nlp_scaling factors through to its residuals yet, so these
3862            // mirror the SQP-side values: correct when no scaling is active
3863            // (the common case) and a conservative proxy otherwise. Populated
3864            // here so the info dict's `final_unscaled_*` keys are honest
3865            // rather than left at the 0.0 default.
3866            stats.final_unscaled_dual_inf = res.final_stationarity;
3867            stats.final_unscaled_constr_viol = res.final_constr_viol;
3868            stats.final_unscaled_compl = 0.0;
3869            stats.final_unscaled_kkt_error = res.final_stationarity.max(res.final_constr_viol);
3870            // Ipopt's `Variable bound violation` — how far the returned point
3871            // sits outside the box the caller wrote. Left at its `NaN` default
3872            // until now, which printed `nan` on this arm's every summary.
3873            //
3874            // Measured through the same `declared_box_violation` accessor the
3875            // interior-point arm reads (`curr_declared_box_violation_max`), so
3876            // the two arms cannot drift into reporting different quantities
3877            // under one heading. gh#900 is the precedent and the warning: it
3878            // fixed this row on the NLP and convex arms and noted the two were
3879            // "independent code paths, so a test that exercised one would say
3880            // nothing about the other" — this is the third, and it was missed.
3881            //
3882            // `res.x` is algorithm-space, which is what the accessor expects
3883            // (it lifts to full-x itself); `finalize_via_sqp` wraps it exactly
3884            // this way for the same reason.
3885            stats.final_declared_box_viol = {
3886                use pounce_linalg::dense_vector::DenseVectorSpace;
3887                let nlp_borrow = nlp_rc.borrow();
3888                let x_space = DenseVectorSpace::new(nlp_borrow.n());
3889                let mut x_dv = x_space.make_new_dense();
3890                x_dv.set_values(&res.x);
3891                // `NaN`, not `0.0`, on the abstention — deliberately unlike
3892                // the IPM path's `unwrap_or(0.0)`.
3893                //
3894                // `None` from this accessor means one thing only: the declared
3895                // bounds were never snapshotted. It is NOT "the model has no
3896                // finite bounds" — an unbounded model still snapshots, the
3897                // loops find nothing, and the answer is a measured `Some(0.0)`.
3898                // So on this arm `None` can only mean the
3899                // `snapshot_declared_bounds` call above was lost, and mapping
3900                // that to zero would replace a visible "no answer" with an
3901                // invisible false claim that the point is inside its box.
3902                // gh#900's subject is exactly that: a zero that must not be
3903                // fabricated. Checked by mutation — delete the snapshot call
3904                // and this row goes back to `nan` rather than quietly reading
3905                // `0.00e+00`.
3906                nlp_borrow
3907                    .declared_box_violation(&x_dv)
3908                    .unwrap_or(Number::NAN)
3909            };
3910            // gh#990: the derivative checker's verdict reaches `info` and the
3911            // report on this arm too; it was copied on the IPM drain only.
3912            stats.derivative_check = self.derivative_check.borrow().clone();
3913            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
3914        }
3915        let (app_status, solver_status) = match res.status {
3916            crate::sqp::SqpStatus::Optimal => (
3917                ApplicationReturnStatus::SolveSucceeded,
3918                pounce_nlp::SolverReturn::Success,
3919            ),
3920            crate::sqp::SqpStatus::MaxIter => (
3921                ApplicationReturnStatus::MaximumIterationsExceeded,
3922                pounce_nlp::SolverReturn::MaxiterExceeded,
3923            ),
3924            crate::sqp::SqpStatus::InfeasibleSubproblem => (
3925                ApplicationReturnStatus::InfeasibleProblemDetected,
3926                pounce_nlp::SolverReturn::LocalInfeasibility,
3927            ),
3928            crate::sqp::SqpStatus::LineSearchFailed => (
3929                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3930                pounce_nlp::SolverReturn::ErrorInStepComputation,
3931            ),
3932            // Honest non-committal QP-subproblem failure (#282): the QP
3933            // solver could not compute a step and did NOT certify
3934            // infeasibility. Never report Infeasible_Problem_Detected here
3935            // — a feasible problem has no infeasibility certificate.
3936            crate::sqp::SqpStatus::QpStepFailed => (
3937                ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
3938                pounce_nlp::SolverReturn::ErrorInStepComputation,
3939            ),
3940            // The QP subproblem ran out of its own iteration budget. Same
3941            // #282 guarantee — no infeasibility is asserted — but reported as
3942            // the budget exhaustion it is, so the user sees a limit they can
3943            // raise (`sqp_qp_max_iter`) instead of a step-size stall with no
3944            // remedy. See `SqpStatus::QpIterationLimit` for why these were
3945            // split.
3946            crate::sqp::SqpStatus::QpIterationLimit => (
3947                ApplicationReturnStatus::MaximumIterationsExceeded,
3948                pounce_nlp::SolverReturn::MaxiterExceeded,
3949            ),
3950            // Unbounded below, with a recession ray verified against the
3951            // true NLP (gh #388). `Diverging_Iterates` is POUNCE's (Ipopt's)
3952            // unboundedness verdict and maps to AMPL `solve_result_num=300`
3953            // — the same answer the IPM selectors give on the same model,
3954            // instead of the `Internal_Error` / 500 ("the solver broke")
3955            // this path used to report.
3956            crate::sqp::SqpStatus::Unbounded => (
3957                ApplicationReturnStatus::DivergingIterates,
3958                pounce_nlp::SolverReturn::DivergingIterates,
3959            ),
3960            // A non-finite iterate or constraint value (gh #876). Same
3961            // verdict, from the same condition, as the interior-point arm's
3962            // `if !nlp_err.is_finite()` screen — the two arms must not
3963            // disagree about what a `NaN` iterate means.
3964            crate::sqp::SqpStatus::InvalidNumber => (
3965                ApplicationReturnStatus::InvalidNumberDetected,
3966                pounce_nlp::SolverReturn::InvalidNumberDetected,
3967            ),
3968            crate::sqp::SqpStatus::UserRequestedStop => (
3969                ApplicationReturnStatus::UserRequestedStop,
3970                pounce_nlp::SolverReturn::UserRequestedStop,
3971            ),
3972            // gh#1054: the same verdicts the interior-point arm's
3973            // convergence check gives on the same budgets.
3974            crate::sqp::SqpStatus::WallTimeExceeded => (
3975                ApplicationReturnStatus::MaximumWallTimeExceeded,
3976                pounce_nlp::SolverReturn::WallTimeExceeded,
3977            ),
3978            crate::sqp::SqpStatus::CpuTimeExceeded => (
3979                ApplicationReturnStatus::MaximumCpuTimeExceeded,
3980                pounce_nlp::SolverReturn::CpuTimeExceeded,
3981            ),
3982        };
3983
3984        // Same gate as the IPM path: an infeasible-subproblem exit is a
3985        // numerical inference, and a feasible starting point disproves it
3986        // (gh #379). Only the infeasibility verdict is rewritten — every other
3987        // status passes through untouched, so the pair stays in lockstep.
3988        let refuted = withdraw_infeasibility_if_refuted(
3989            &tnlp,
3990            solver_status,
3991            self.nlp_lower_bound_inf(),
3992            self.nlp_upper_bound_inf(),
3993            self.user_tol(),
3994        );
3995        let (app_status, solver_status) = if refuted == solver_status {
3996            (app_status, solver_status)
3997        } else {
3998            (solver_return_to_app_status(refuted), refuted)
3999        };
4000
4001        // Forward to the user TNLP's finalize_solution. We pass
4002        // the SQP iterate and recovered multipliers via the
4003        // OrigIpoptNlp's lifting hooks. Failure here is silent
4004        // (we still return the algorithm's status) — the user
4005        // sees the right ApplicationReturnStatus regardless.
4006        let _ = finalize_via_sqp(
4007            &nlp_rc,
4008            &res,
4009            solver_status,
4010            &tnlp,
4011            &self.last_finalize,
4012            self.reports_fixed_var_duals(),
4013        );
4014
4015        // Honor the opt-in status-fidelity gate on the SQP path too
4016        // (pounce#173), then emit the end-of-run summary with the final
4017        // (possibly downgraded) status so the console matches the returned
4018        // ApplicationReturnStatus.
4019        let final_status = self.apply_kkt_fidelity_gate(app_status);
4020        self.emit_end_summary(final_status, &nlp_rc, console_output);
4021        final_status
4022    }
4023
4024    /// Opt-in status-fidelity gate (pounce#173), shared by the IPM and
4025    /// SQP solve paths. When the user sets a positive `kkt_fidelity_tol`,
4026    /// a reported `Solve_Succeeded` whose max-norm UNSCALED KKT error
4027    /// (`SolveStatistics::final_unscaled_kkt_error`) exceeds it is
4028    /// downgraded to `Solved_To_Acceptable_Level` — the honest "this is a
4029    /// point, but not converged to the requested fidelity" status. This
4030    /// catches the ill-conditioned / nlp_scaling-deflated case where the
4031    /// scaled convergence test passes but the user-space duals have
4032    /// drifted. It is a pure relabel at termination (no extra iterations);
4033    /// unset or non-positive (the default) is a strict no-op, so every
4034    /// existing caller keeps the Ipopt-faithful status.
4035    fn apply_kkt_fidelity_gate(
4036        &self,
4037        app_status: ApplicationReturnStatus,
4038    ) -> ApplicationReturnStatus {
4039        if !matches!(app_status, ApplicationReturnStatus::SolveSucceeded) {
4040            return app_status;
4041        }
4042        if let Ok((ftol, true)) = self.options.get_numeric_value("kkt_fidelity_tol", "") {
4043            if ftol > 0.0 {
4044                let unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
4045                if unscaled_kkt > ftol {
4046                    tracing::info!(target: "pounce::diagnostics",
4047                        "kkt_fidelity_tol={ftol:.3e}: unscaled KKT error {unscaled_kkt:.3e} \
4048                         exceeds it — downgrading Solve_Succeeded → \
4049                         Solved_To_Acceptable_Level (pounce#173)");
4050                    return ApplicationReturnStatus::SolvedToAcceptableLevel;
4051                }
4052            }
4053        }
4054        app_status
4055    }
4056
4057    /// `nlp_lower_bound_inf` — the magnitude at or below which a bound is
4058    /// treated as absent.
4059    fn nlp_lower_bound_inf(&self) -> Number {
4060        self.options
4061            .get_numeric_value("nlp_lower_bound_inf", "")
4062            .ok()
4063            .and_then(|(v, f)| f.then_some(v))
4064            .unwrap_or(DEFAULT_NLP_LOWER_BOUND_INF)
4065    }
4066
4067    /// `nlp_upper_bound_inf` — the magnitude at or above which a bound is
4068    /// treated as absent.
4069    fn nlp_upper_bound_inf(&self) -> Number {
4070        self.options
4071            .get_numeric_value("nlp_upper_bound_inf", "")
4072            .ok()
4073            .and_then(|(v, f)| f.then_some(v))
4074            .unwrap_or(DEFAULT_NLP_UPPER_BOUND_INF)
4075    }
4076
4077    /// The user's convergence tolerance `tol`.
4078    fn user_tol(&self) -> Number {
4079        self.options
4080            .get_numeric_value("tol", "")
4081            .ok()
4082            .and_then(|(v, f)| f.then_some(v))
4083            .unwrap_or(1e-8)
4084    }
4085
4086    /// The user's `acceptable_tol` — the standard behind
4087    /// `Solved_To_Acceptable_Level`.
4088    fn user_acceptable_tol(&self) -> Number {
4089        self.options
4090            .get_numeric_value("acceptable_tol", "")
4091            .ok()
4092            .and_then(|(v, f)| f.then_some(v))
4093            .unwrap_or(1e-6)
4094    }
4095
4096    /// The user's `constr_viol_tol` — the **absolute** feasibility standard
4097    /// the strict gate's primal component judges by
4098    /// (`OptErrorConvCheck::primal_component_passes`).
4099    fn user_constr_viol_tol(&self) -> Number {
4100        self.options
4101            .get_numeric_value("constr_viol_tol", "")
4102            .ok()
4103            .and_then(|(v, f)| f.then_some(v))
4104            .unwrap_or(1e-4)
4105    }
4106
4107    /// The user's `acceptable_constr_viol_tol` — the same standard at the
4108    /// acceptable tier.
4109    fn user_acceptable_constr_viol_tol(&self) -> Number {
4110        self.options
4111            .get_numeric_value("acceptable_constr_viol_tol", "")
4112            .ok()
4113            .and_then(|(v, f)| f.then_some(v))
4114            .unwrap_or(1e-2)
4115    }
4116
4117    /// `primal_noise_floor_kappa` — the safety factor on the per-row
4118    /// floating-point noise floor (gh#528/gh#590). `0` opts out.
4119    fn user_primal_noise_floor_kappa(&self) -> Number {
4120        self.options
4121            .get_numeric_value("primal_noise_floor_kappa", "")
4122            .ok()
4123            .and_then(|(v, f)| f.then_some(v))
4124            .unwrap_or(64.0)
4125    }
4126
4127    /// Emit the Ipopt-style problem-statistics block (#206) from the
4128    /// engine's own reduced problem, gated on `console_output`
4129    /// (print_level >= 1). Shared by the IPM (`optimize_tnlp`) and SQP
4130    /// (`optimize_sqp_tnlp`) entry points so every algorithm and every
4131    /// frontend (CLI, Python, C) gets the identical block. Built from the
4132    /// same `collect_stats` inputs the CLI used, so the output is
4133    /// byte-identical to the historical CLI block.
4134    fn emit_problem_stats(&self, tnlp: &Rc<RefCell<dyn TNLP>>, console_output: bool) {
4135        if !console_output {
4136            return;
4137        }
4138        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
4139        if let Some(stats) =
4140            pounce_solve_report::console::collect_stats(tnlp, lo_inf, up_inf, fixed_treatment)
4141        {
4142            // A retry re-enters here with the same problem. Reprinting the
4143            // block verbatim is what made a retried run look like it had
4144            // printed its whole report twice for no reason, so say what is
4145            // actually happening instead: a new attempt on an unchanged
4146            // problem. One line, in place of seventeen that carry no
4147            // information the reader does not already have.
4148            //
4149            // The attempt is announced rather than merely suppressed because
4150            // the iteration table below it restarts at iteration 0 either way.
4151            // Silence would leave that table appearing from nowhere — trading
4152            // a confusing duplicate for a confusing gap.
4153            let mut memo = self.last_printed_problem_stats.borrow_mut();
4154            if memo.as_ref() == Some(&stats) {
4155                // Silent under an outside retry driver, which narrates its own
4156                // attempts in more detail than this line could ("pounce:
4157                // second opinion — re-solving with feral_scaling=mc64…").
4158                // Printing both would be two announcements of one event.
4159                if !self.in_retry_sequence.get() {
4160                    println!("Re-solving the same problem (a further attempt follows).");
4161                    println!();
4162                }
4163            } else {
4164                pounce_solve_report::console::print_problem_stats(&stats);
4165                *memo = Some(stats);
4166            }
4167        }
4168    }
4169
4170    /// Drain the NLP's per-eval counters into the shared `SolveStatistics`
4171    /// and emit the Ipopt-style end-of-run summary (#206). Shared by both
4172    /// solve paths. The counts are read from the NLP AFTER the solve (so the
4173    /// final solution evaluation is included, matching the historical count)
4174    /// and written into `SolveStatistics` so the post-solve API accessors
4175    /// (`info["n_obj_evals"]`, …) report them even when the console is
4176    /// silent. c/d (and jac_c/jac_d) are per-subsystem, so the max recovers
4177    /// the eval_g / eval_jac_g call count. The console summary itself is
4178    /// gated on `console_output` (print_level >= 1).
4179    fn emit_end_summary(
4180        &self,
4181        app_status: ApplicationReturnStatus,
4182        nlp: &Rc<RefCell<dyn IpoptNlp>>,
4183        console_output: bool,
4184    ) {
4185        {
4186            let ec = nlp.borrow().eval_counts();
4187            let mut stats = self.statistics.borrow_mut();
4188            stats.num_obj_evals = ec[0];
4189            stats.num_obj_grad_evals = ec[1];
4190            stats.num_constr_evals = ec[2].max(ec[3]);
4191            stats.num_constr_jac_evals = ec[4].max(ec[5]);
4192            stats.num_hess_evals = ec[6];
4193        }
4194        if !console_output {
4195            return;
4196        }
4197        let stats = self.statistics.borrow();
4198        let counts = pounce_solve_report::console::EvalCounts {
4199            n_obj: stats.num_obj_evals as u64,
4200            n_grad_f: stats.num_obj_grad_evals as u64,
4201            n_g: stats.num_constr_evals as u64,
4202            n_jac_g: stats.num_constr_jac_evals as u64,
4203            n_h: stats.num_hess_evals as u64,
4204        };
4205        // gh#987: no widening at `bound_relax_factor = 0`, so the console's
4206        // "before the bound_relax_factor widening" line has nothing to report.
4207        let widening_applied = self
4208            .options
4209            .get_numeric_value("bound_relax_factor", "")
4210            .map(|(v, _)| v > 0.0)
4211            .unwrap_or(true);
4212        pounce_solve_report::console::print_summary_with_widening(
4213            app_status,
4214            &stats,
4215            &counts,
4216            widening_applied,
4217        );
4218        // The verdict belongs to the run, not to the attempt. Held back while
4219        // any retry driver is managing attempts; that driver prints it once,
4220        // with the status it actually returns.
4221        if self.end_verdict_deferrals.get() == 0 {
4222            pounce_solve_report::console::print_exit_verdict(app_status);
4223        }
4224    }
4225
4226    /// Build a *copy* of the algorithm builder configured per the
4227    /// current options. The SQP path uses this so it gets a
4228    /// fresh builder without mutating the application's state.
4229    /// Read the `ipm_sqp_handover*` option family into a
4230    /// [`crate::handover::HandoverOptions`].
4231    fn handover_options(&self) -> crate::handover::HandoverOptions {
4232        let mut o = crate::handover::HandoverOptions::default();
4233        // `sqp_auto_handover` only fires when this option was not set.
4234        o.enabled = self.auto_handover.get();
4235        if let Ok((v, true)) = self.options.get_bool_value("ipm_sqp_handover", "") {
4236            o.enabled = v;
4237        }
4238        if let Ok((v, true)) = self.options.get_numeric_value("ipm_sqp_handover_tol", "") {
4239            o.tol = v;
4240        }
4241        if let Ok((v, true)) = self
4242            .options
4243            .get_integer_value("ipm_sqp_handover_stall_iter", "")
4244        {
4245            o.stall_iter = v.max(0);
4246        }
4247        if let Ok((v, true)) = self
4248            .options
4249            .get_integer_value("ipm_sqp_handover_max_attempts", "")
4250        {
4251            o.max_attempts = v.max(0) as u32;
4252        }
4253        o
4254    }
4255
4256    /// Install the interior-point → active-set handover hook on `alg` when
4257    /// `ipm_sqp_handover=yes` (gh#1054; see [`crate::handover`]). Returns
4258    /// the cells the hook reports into — the report, and the working set of
4259    /// an accepted attempt — for [`Self::finish_handover`] to read after the
4260    /// solve.
4261    #[allow(clippy::type_complexity)]
4262    fn install_handover(
4263        &self,
4264        alg: &mut IpoptAlgorithm,
4265        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4266    ) -> Option<(
4267        Rc<RefCell<crate::handover::HandoverReport>>,
4268        Rc<RefCell<Option<pounce_qp::WorkingSet>>>,
4269    )> {
4270        let hopts = self.handover_options();
4271        if !hopts.enabled {
4272            return None;
4273        }
4274        let mut trigger = crate::handover::HandoverTrigger::new(hopts);
4275        let xopts = crate::crossover::CrossoverOptions {
4276            enabled: true,
4277            ..self.crossover_options()
4278        };
4279        let snapshot = self.algorithm_builder_snapshot();
4280        let qp_opts = snapshot.sqp_qp.clone();
4281        let data = Rc::clone(&alg.data);
4282        let nlp = Rc::clone(nlp_handle);
4283        // One factory serves every backend the attempts build: a factory is
4284        // reusable, but `build_sqp_with_backend` takes one by value, so the
4285        // step-4 SQP gets a forwarding closure onto the shared one.
4286        let backend = Rc::new(RefCell::new(self.make_backend_factory()));
4287        let tols = self.user_tolerances();
4288        let report = Rc::new(RefCell::new(crate::handover::HandoverReport::default()));
4289        let working = Rc::new(RefCell::new(None));
4290        let (report_out, working_out) = (Rc::clone(&report), Rc::clone(&working));
4291        let (wall0, cpu0) = (
4292            pounce_common::utils::wallclock_time(),
4293            pounce_common::utils::cpu_time(),
4294        );
4295        alg.handover = Some(Box::new(move |curr, iter, err, mu| {
4296            if !trigger.should_try(iter, err) {
4297                return None;
4298            }
4299            let seed = crossover_seed(&nlp, curr);
4300            let x = crate::crossover::CrossoverOptions {
4301                primal_tol: crate::handover::identification_primal_tol(xopts.primal_tol, mu),
4302                ..xopts.clone()
4303            };
4304            // An attempt may spend at most what the interior method has
4305            // spent so far (floor 1 s), and never past the solve's own
4306            // budget. Without a cap a declined attempt is unbounded: on
4307            // `deb7` (813 variables) one ran the crossover fallback for
4308            // minutes, against a 114-iteration interior solve. With it, a
4309            // declined attempt costs at most a doubling — the right scale
4310            // for a bet on shortening the tail.
4311            let (wall_left, cpu_left) = data
4312                .borrow()
4313                .deadline
4314                .as_ref()
4315                .map_or((Number::INFINITY, Number::INFINITY), |d| {
4316                    (d.remaining_wall(), d.remaining_cpu())
4317                });
4318            let spent_wall = (pounce_common::utils::wallclock_time() - wall0).max(1.0);
4319            let spent_cpu = (pounce_common::utils::cpu_time() - cpu0).max(1.0);
4320            let sqp_opts = crate::sqp::SqpOptions {
4321                deadline: Some(pounce_common::timing::Deadline::new(
4322                    spent_wall.min(wall_left),
4323                    spent_cpu.min(cpu_left),
4324                )),
4325                ..snapshot.sqp.clone()
4326            };
4327            // Declared bounds, for the reason `maybe_crossover` gives.
4328            let mut adapter =
4329                crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(&nlp));
4330            let (mut rep, mut accepted) = crate::crossover::run(
4331                &mut adapter,
4332                &seed,
4333                &x,
4334                &sqp_opts,
4335                &qp_opts,
4336                || (backend.borrow_mut())(crate::alg_builder::LinearSolverChoice::Feral),
4337                |step4_opts| {
4338                    let mut b = snapshot.clone();
4339                    b.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
4340                    b.sqp = step4_opts;
4341                    let shared = Rc::clone(&backend);
4342                    b.build_sqp_with_backend(Box::new(move |c| (shared.borrow_mut())(c)))
4343                },
4344            );
4345            // The interior-point verdict this replaces is issued in user
4346            // units on the declared model; so is this one.
4347            if let Some(res) = &accepted
4348                && !meets_user_tolerances(&nlp, res, &rep, &tols)
4349            {
4350                rep = rep.decline(crate::crossover::CrossoverDecline::UserTolerances);
4351                accepted = None;
4352            }
4353            tracing::info!(
4354                target: "pounce::handover",
4355                "IPM→SQP handover attempt {} at iteration {iter} (error {err:.2e}, mu {mu:.2e}): {}",
4356                trigger.attempts(),
4357                if rep.accepted() { "accepted" } else { "declined" }
4358            );
4359            tracing::debug!(target: "pounce::handover", "handover: {rep:?}");
4360            let mut r = report.borrow_mut();
4361            r.attempts = trigger.attempts();
4362            r.last = Some(rep);
4363            let res = accepted?;
4364            let next = crossover_iterate(&nlp, curr, &res)?;
4365            r.accepted_at_iter = Some(iter);
4366            *working.borrow_mut() = res.working_set;
4367            Some(next)
4368        }));
4369        Some((report_out, working_out))
4370    }
4371
4372    /// After the solve: publish the handover report, and an accepted
4373    /// attempt's working set as the next SQP solve's warm start (the same
4374    /// hand-off crossover makes).
4375    fn finish_handover(
4376        &mut self,
4377        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4378        cells: Option<(
4379            Rc<RefCell<crate::handover::HandoverReport>>,
4380            Rc<RefCell<Option<pounce_qp::WorkingSet>>>,
4381        )>,
4382    ) {
4383        self.handover_report = None;
4384        let Some((report, working)) = cells else {
4385            return;
4386        };
4387        let report = report.borrow().clone();
4388        if report.accepted_at_iter.is_some()
4389            && let Some(ws) = working.borrow_mut().take()
4390        {
4391            self.sqp_last_working_set = Some(self.working_set_to_user(&*nlp_handle.borrow(), ws));
4392        }
4393        self.handover_report = Some(report);
4394    }
4395
4396    /// The interior-point arm's user-unit tolerances, which a crossed-over
4397    /// point must also meet (see [`meets_user_tolerances`]).
4398    fn user_tolerances(&self) -> UserTolerances {
4399        let read = |name: &str, default: Number| {
4400            self.options
4401                .get_numeric_value(name, "")
4402                .map_or(default, |(v, _)| v)
4403        };
4404        UserTolerances {
4405            constr_viol: read("constr_viol_tol", 1e-4),
4406            dual_inf: read("dual_inf_tol", 1.0),
4407            compl_inf: read("compl_inf_tol", 1e-4),
4408        }
4409    }
4410
4411    /// A [`pounce_common::timing::Deadline`] for `max_wall_time` /
4412    /// `max_cpu_time`, starting now.
4413    fn solve_deadline(&self) -> pounce_common::timing::Deadline {
4414        let read = |name: &str| {
4415            self.options
4416                .get_numeric_value(name, "")
4417                .map_or(1e6, |(v, _)| v)
4418        };
4419        pounce_common::timing::Deadline::new(read("max_wall_time"), read("max_cpu_time"))
4420    }
4421
4422    /// Read the `crossover*` option family into a [`CrossoverOptions`].
4423    fn crossover_options(&self) -> crate::crossover::CrossoverOptions {
4424        let mut o = crate::crossover::CrossoverOptions::default();
4425        if let Ok((v, true)) = self.options.get_bool_value("crossover", "") {
4426            o.enabled = v;
4427        }
4428        if let Ok((v, true)) = self.options.get_integer_value("crossover_max_iter", "") {
4429            o.max_iter = v.max(0) as u32;
4430        }
4431        if let Ok((v, true)) = self.options.get_numeric_value("crossover_mult_tol", "") {
4432            o.mult_tol = v;
4433        }
4434        if let Ok((v, true)) = self.options.get_numeric_value("crossover_primal_tol", "") {
4435            o.primal_tol = v;
4436        }
4437        o
4438    }
4439
4440    /// Post-convergence crossover (gh#612): hand the converged interior
4441    /// iterate to the active-set path so the solve ends on an exact active
4442    /// set. See [`crate::crossover`] for the algorithm.
4443    ///
4444    /// On acceptance this **replaces `data.curr`** rather than reporting
4445    /// alongside it. Everything downstream — the residual drain, the KKT
4446    /// fidelity gate, `on_converged`, `finalize_via_orig_nlp`, the end
4447    /// summary — already reads that one iterate, so replacing it is what
4448    /// makes the crossed-over point the solution instead of an annotation on
4449    /// it, and it does so without a second copy of the unscaling path.
4450    ///
4451    /// A no-op unless `crossover=yes` and the solve converged: an
4452    /// unconverged interior point is not a KKT point, so there is no active
4453    /// set at it worth identifying.
4454    fn maybe_crossover(
4455        &mut self,
4456        alg: &mut IpoptAlgorithm,
4457        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4458        solver_status: SolverReturn,
4459    ) {
4460        self.crossover_report = None;
4461        // Cleared on every entry, alongside the report, so the flag
4462        // describes this solve and not a previous one — the same reason
4463        // `crossover_report` is reset here rather than only written on
4464        // the accept path.
4465        //
4466        // Except when the in-solve handover installed the iterate (gh#1054):
4467        // then the flag was set during *this* solve and is still true of the
4468        // point in `curr` — clearing it here mislabelled the handover's
4469        // declared-frame point as an interior one, and its complementarity
4470        // was reported in the relaxed frame (`0.1` on `jit1`).
4471        let handover_point = self
4472            .handover_report
4473            .as_ref()
4474            .is_some_and(|h| h.accepted_at_iter.is_some());
4475        if !handover_point {
4476            alg.data.borrow_mut().curr_from_crossover = false;
4477        }
4478        let xopts = self.crossover_options();
4479        if !xopts.enabled {
4480            return;
4481        }
4482        if !matches!(
4483            solver_status,
4484            SolverReturn::Success | SolverReturn::StopAtAcceptablePoint
4485        ) {
4486            return;
4487        }
4488        let Some(curr) = alg.data.borrow().curr.clone() else {
4489            return;
4490        };
4491
4492        let seed = crossover_seed(nlp_handle, &curr);
4493
4494        let snapshot = self.algorithm_builder_snapshot();
4495        let mut sqp_opts = snapshot.sqp.clone();
4496        // The interior-point phase's own deadline, not a fresh one:
4497        // crossover is part of the same solve, so it spends what the IPM
4498        // left of `max_wall_time` / `max_cpu_time` (gh#1054). Before this it
4499        // had no budget at all and could outlive the solve's by any amount.
4500        sqp_opts.deadline = alg
4501            .data
4502            .borrow()
4503            .deadline
4504            .clone()
4505            .or_else(|| Some(self.solve_deadline()));
4506        let qp_opts = snapshot.sqp_qp.clone();
4507        // Declared bounds, not the live relaxed ones: crossover's whole claim
4508        // is that the returned point sits *on* the constraints the user
4509        // wrote. Against the `bound_relax_factor`-widened box it would pivot
4510        // to a point `1e-8` shy of every one of them and then correctly
4511        // report an empty active set.
4512        let mut adapter =
4513            crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(nlp_handle));
4514        let (report, accepted) = crate::crossover::run(
4515            &mut adapter,
4516            &seed,
4517            &xopts,
4518            &sqp_opts,
4519            &qp_opts,
4520            || {
4521                let mut f = self.make_backend_factory();
4522                // `make_backend_factory` ships the workspace-default
4523                // backend regardless of the choice passed, exactly as the
4524                // SQP path's `build_sqp_with_backend` call does; naming
4525                // `Feral` here keeps that visible rather than implicit.
4526                f(crate::alg_builder::LinearSolverChoice::Feral)
4527            },
4528            |step4_opts| {
4529                let mut b = self.algorithm_builder_snapshot();
4530                b.algorithm = crate::alg_builder::AlgorithmChoice::ActiveSetSqp;
4531                b.sqp = step4_opts;
4532                b.build_sqp_with_backend(self.make_backend_factory())
4533            },
4534        );
4535
4536        let tols = self.user_tolerances();
4537        let (report, accepted) = match accepted {
4538            Some(res) if !meets_user_tolerances(nlp_handle, &res, &report, &tols) => (
4539                report.decline(crate::crossover::CrossoverDecline::UserTolerances),
4540                None,
4541            ),
4542            other => (report, other),
4543        };
4544        if let Some(res) = accepted {
4545            self.install_crossover_iterate(alg, nlp_handle, &curr, &res);
4546            // Publish the identified set as the SQP warm-start output. This
4547            // is the IPM → SQP handoff the active-set path never had: a
4548            // sequence whose first solve wants the interior method can now
4549            // feed the next `algorithm=active-set-sqp` solve a working set.
4550            self.sqp_last_working_set = res
4551                .working_set
4552                .clone()
4553                .map(|ws| self.working_set_to_user(&*nlp_handle.borrow(), ws));
4554        }
4555        tracing::debug!(target: "pounce::crossover", "crossover: {report:?}");
4556        self.crossover_report = Some(report);
4557    }
4558
4559    /// Write an accepted crossover result back onto the IPM iterate (built by
4560    /// [`crossover_iterate`]).
4561    fn install_crossover_iterate(
4562        &self,
4563        alg: &mut IpoptAlgorithm,
4564        nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
4565        curr: &crate::iterates_vector::IteratesVector,
4566        res: &crate::sqp::SqpResult,
4567    ) {
4568        let Some(out) = crossover_iterate(nlp_handle, curr, res) else {
4569            return;
4570        };
4571        let mut d = alg.data.borrow_mut();
4572        d.set_curr(out);
4573        // Mark which frame the installed iterate belongs to. It sits on the
4574        // *declared* bounds, and every barrier quantity built off `curr` —
4575        // slacks, and through them `Σ = z/s` — is measured against the
4576        // `bound_relax_factor`-widened ones, so a consumer that wants the
4577        // point's own geometry rather than the barrier's has to know this
4578        // happened (gh#654). Set only on the path that actually replaced
4579        // `curr`: a declined or abandoned crossover leaves the interior
4580        // iterate, which is an interior-frame point.
4581        d.curr_from_crossover = true;
4582    }
4583
4584    fn algorithm_builder_snapshot(&self) -> AlgorithmBuilder {
4585        let mut builder = AlgorithmBuilder {
4586            quality_escalation_counter: Some(Rc::clone(&self.quality_escalations)),
4587            ..AlgorithmBuilder::default()
4588        };
4589        apply_sqp_options(&self.options, &mut builder.sqp);
4590        apply_qp_subproblem_options(&self.options, &mut builder.sqp_qp);
4591        builder
4592    }
4593
4594    /// Refuse an explicitly set `ma57_pivtolmax` that sits below
4595    /// `ma57_pivtol`, at either option prefix.
4596    ///
4597    /// Upstream's `Ma57TSolverInterface::InitializeImpl` asserts
4598    /// `pivtolmax >= pivtol` and raises `OPTION_INVALID`, but only when
4599    /// the user set `ma57_pivtolmax` explicitly; left unset, the
4600    /// registered default is lifted to `ma57_pivtol` instead. Both
4601    /// halves are mirrored — the lifting in
4602    /// `pounce_hsl::ma57::Options::from_options_list`, the refusal here.
4603    ///
4604    /// Checked at **both** prefixes because the restoration sub-IPM
4605    /// configures its own MA57 backend from `"resto."`-scoped options
4606    /// (gh#825), so `resto.ma57_pivtolmax` can contradict
4607    /// `resto.ma57_pivtol` without the un-prefixed pair being wrong.
4608    ///
4609    /// Deliberately **not** gated on the `ma57` cargo feature or on
4610    /// `linear_solver` resolving to MA57. It is a consistency check on
4611    /// two numbers the user wrote, needs no HSL to perform, and a
4612    /// verdict that changed with a build flag would be worse than a
4613    /// consistent one — it would also be untestable in CI, which cannot
4614    /// link CoinHSL. Only an *explicitly set* `ma57_pivtolmax` can
4615    /// trigger it, so an options file that never mentions the option is
4616    /// unaffected.
4617    fn ma57_pivtol_bracket_refusal(&self) -> Option<String> {
4618        for prefix in ["", "resto."] {
4619            // `(_, true)` is the explicitly-set arm; an unset option
4620            // reports the registry default with `false` and is the
4621            // branch upstream lifts rather than refuses.
4622            let Ok((pivtolmax, true)) = self.options.get_numeric_value("ma57_pivtolmax", prefix)
4623            else {
4624                continue;
4625            };
4626            let pivtol = self
4627                .options
4628                .get_numeric_value("ma57_pivtol", prefix)
4629                .map(|(v, _)| v)
4630                .unwrap_or(1e-8);
4631            if pivtolmax < pivtol {
4632                return Some(format!(
4633                    "pounce: {prefix}ma57_pivtolmax ({pivtolmax:e}) is below \
4634                     {prefix}ma57_pivtol ({pivtol:e}). ma57_pivtolmax is the ceiling MA57 \
4635                     may raise the pivot tolerance to when it escalates for accuracy, so it \
4636                     cannot sit below the tolerance it starts from. Raise \
4637                     {prefix}ma57_pivtolmax to at least {pivtol:e}, or lower \
4638                     {prefix}ma57_pivtol."
4639                ));
4640            }
4641        }
4642        None
4643    }
4644
4645    /// Build a linear-solver factory from the application's current options,
4646    /// for the paths that do not go through `optimize_constrained`'s own
4647    /// factory plumbing — the active-set SQP driver and the post-convergence
4648    /// crossover.
4649    ///
4650    /// This used to ignore its `choice` argument and return
4651    /// `FeralSolverInterface::new()`: a default-configured FERAL, whatever the
4652    /// caller asked for. Three things were silently dropped on every SQP
4653    /// solve. `linear_solver=ma57` ran FERAL while the banner said
4654    /// `MA57 (HSL)`, so an MA57-vs-FERAL comparison on this path measured
4655    /// nothing — the same defect as gh#825, one path over. Every `feral_*`
4656    /// option (`feral_refine`, `feral_ordering`, `feral_scaling`,
4657    /// `feral_increase_quality`, …) was accepted and discarded. And
4658    /// `set_external_ordering` — whose whole purpose is to inject an ordering
4659    /// a generic algorithm cannot derive — reached the IPM and not this arm.
4660    ///
4661    /// Reads the same two snapshots and calls the same constructor the IPM
4662    /// path does, so there is one answer to "what does `linear_solver` mean"
4663    /// rather than one per algorithm.
4664    fn make_backend_factory(&self) -> LinearBackendFactory {
4665        // `RefineCarveOut::None`: this arm does not refine the unreduced system
4666        // itself, so the backend loop is the only refinement in the stack and
4667        // the interior-point carve-out's premise is false here. See
4668        // `feral_config_from_options_scoped` for the measurement.
4669        let mut feral_cfg = feral_config_from_options_scoped(&self.options, RefineCarveOut::None);
4670        // Same override, and for the same reason, as the IPM path: the
4671        // external permutation carries a vector, which no string option can
4672        // express, so it arrives through the side-channel field instead.
4673        if let Some(perm) = &self.external_ordering {
4674            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
4675        }
4676        let ma57_cfg = ma57_config_from_options(&self.options, "");
4677        default_backend_factory_with_sink(
4678            feral_cfg,
4679            ma57_cfg,
4680            Arc::clone(&self.linsol_summary_sink),
4681        )
4682    }
4683
4684    /// Phase 3.5 auto-fallback driver.
4685    ///
4686    /// Runs the standard solve (no wrapper) first. If it ends in a
4687    /// trigger-class status (`Restoration_Failed`, `Infeasible_Problem_Detected`,
4688    /// `Solved_To_Acceptable_Level`, `Maximum_Iterations_Exceeded`, or
4689    /// `Not_Enough_Degrees_Of_Freedom`), retries transparently with
4690    /// the ℓ₁ wrapper enabled. Promotes the retry's status only if
4691    /// it returns `Solve_Succeeded`; otherwise returns the original
4692    /// status.
4693    ///
4694    /// Caveat: the user TNLP's `finalize_solution` runs once per
4695    /// attempt. When the retry doesn't promote, the user's captured
4696    /// fields hold the retry's iterate (the ℓ₁-best least-infeasible
4697    /// point) even though the returned status is the original's.
4698    /// Documented on the option's help text; tightening this is a
4699    /// Phase-4 follow-up.
4700    fn run_with_l1_fallback(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
4701        // First attempt: the standard IPM solve, no ℓ₁ wrapper. Only
4702        // reached for `m > 0`, so `optimize_constrained` is exact.
4703        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4704        if !is_l1_fallback_trigger(first_status) {
4705            return first_status;
4706        }
4707        // gh#987 item 6: the plain attempt's iterations are part of what this
4708        // call spent, and the retry's `optimize_constrained` resets them.
4709        let first_attempt = self.statistics.borrow().clone();
4710        // Trigger fired. Flip the wrapper option for the retry and
4711        // restore it after — keeps the user's option-table view of the
4712        // session exactly as they left it.
4713        let prev = self
4714            .options
4715            .get_string_value("l1_exact_penalty_barrier", "")
4716            .ok();
4717        let _ = self
4718            .options
4719            .set_string_value("l1_exact_penalty_barrier", "yes", true, false);
4720        let retry_status = self
4721            .run_l1_penalty_outer_loop(Rc::clone(&tnlp))
4722            .unwrap_or(ApplicationReturnStatus::InternalError);
4723        let _ = self.options.set_string_value(
4724            "l1_exact_penalty_barrier",
4725            prev.as_ref().map(|(v, _)| v.as_str()).unwrap_or("no"),
4726            true,
4727            false,
4728        );
4729        // Fold the plain attempt in ahead of the retry's passes. A retry that
4730        // never ran a pass (wrapper construction declined) leaves the plain
4731        // attempt's own statistics standing untouched.
4732        {
4733            let mut st = self.statistics.borrow_mut();
4734            if !st.passes.is_empty() {
4735                let mut head = MultiPassTotals::default();
4736                head.push_pass(&first_attempt, None, first_status);
4737                let shift = head.rows.len();
4738                let mut passes = head.passes;
4739                passes.extend(st.passes.iter().cloned().map(|mut p| {
4740                    p.first_row += shift;
4741                    p
4742                }));
4743                let mut rows = head.rows;
4744                rows.append(&mut st.iterations);
4745                st.iterations = rows;
4746                st.iteration_count += first_attempt.iteration_count;
4747                st.num_obj_evals += first_attempt.num_obj_evals;
4748                st.num_constr_evals += first_attempt.num_constr_evals;
4749                st.num_obj_grad_evals += first_attempt.num_obj_grad_evals;
4750                st.num_constr_jac_evals += first_attempt.num_constr_jac_evals;
4751                st.num_hess_evals += first_attempt.num_hess_evals;
4752                st.restoration_calls += first_attempt.restoration_calls;
4753                st.restoration_inner_iters += first_attempt.restoration_inner_iters;
4754                st.restoration_outer_iters += first_attempt.restoration_outer_iters;
4755                st.passes = passes;
4756            }
4757        }
4758        // A retry the caller's intermediate callback stopped reports the
4759        // stop: returning the first attempt's status would override it.
4760        if matches!(
4761            retry_status,
4762            ApplicationReturnStatus::SolveSucceeded | ApplicationReturnStatus::UserRequestedStop
4763        ) {
4764            retry_status
4765        } else {
4766            first_status
4767        }
4768    }
4769
4770    /// μ-strategy auto-fallback driver (pounce#138).
4771    ///
4772    /// Runs the standard solve first. If it stalls short of optimal in a
4773    /// way a μ-strategy flip can plausibly fix — `Solved_To_Acceptable_Level`
4774    /// or `Maximum_Iterations_Exceeded`, the two signatures seen on the
4775    /// princetonlib instances where the dual infeasibility parks above
4776    /// `tol` while constraint violation and complementarity are already
4777    /// deeply converged — it flips `mu_strategy` (adaptive↔monotone) and
4778    /// solves once more. The retry's status is promoted only if it returns
4779    /// `Solve_Succeeded`; otherwise the original status is returned.
4780    ///
4781    /// (maxcut/price stall at acceptable-level under adaptive; fermat2_vareps
4782    /// stalls at `max_iter` — hence both triggers. flosp2tm is μ-independent
4783    /// and correctly does not promote.)
4784    ///
4785    /// The flip direction is taken from the strategy the option table
4786    /// actually resolves to (`effective_mu_strategy_is_adaptive`):
4787    /// `adaptive` → `monotone`, otherwise → `adaptive`. Absence is not
4788    /// the same as `monotone` — under a limited-memory Hessian an unset
4789    /// `mu_strategy` resolves to `adaptive` (gh#746), and flipping the
4790    /// *registered* default there would re-run the strategy that just
4791    /// stalled. The option table is restored to the resolved view
4792    /// afterward.
4793    ///
4794    /// Caveat (shared with the ℓ₁ fallback): the user TNLP's
4795    /// `finalize_solution` runs once per attempt, so when the retry
4796    /// doesn't promote the captured fields hold the retry's iterate.
4797    fn run_with_mu_strategy_fallback(
4798        &mut self,
4799        tnlp: Rc<RefCell<dyn TNLP>>,
4800    ) -> ApplicationReturnStatus {
4801        let first_status = self.optimize_constrained(Rc::clone(&tnlp));
4802        // Which statuses are worth a second solve depends on who asked
4803        // for the retry (pounce#748).
4804        //
4805        // An explicit `mu_strategy_fallback=yes` keeps the historical
4806        // pair: the caller opted in and can afford the second solve.
4807        //
4808        // The *default*-on retry takes `Maximum_Iterations_Exceeded`
4809        // unconditionally, and `Solved_To_Acceptable_Level` only when
4810        // the caller left the convergence configuration alone
4811        // (gh #757). pounce#748 refused the latter status outright, for
4812        // three reasons; two of them are properties of a *caller-
4813        // modified* configuration, not of the status. It launders
4814        // downgrades the caller induced deliberately -- a tight
4815        // `kkt_fidelity_tol`, a certificate veto, `least_square_init_
4816        // primal` -- so the signal the option exists to produce never
4817        // reaches them. And because the retry returns the other run's
4818        // *point*, not just its status, it can hand back a different
4819        // local solution: on `autocorr_bern55-06` with the
4820        // dual-divergence guard on it swaps -2304.0000278 for
4821        // -2320.0000298 (crates/pounce-cli/tests/
4822        // issue_250_dual_guard_never_worse.rs). Both cases -- and all
4823        // five test targets the wide trigger broke -- arm a
4824        // non-default option from `TERMINATION_POLICY_OPTIONS`, so
4825        // deferring to that set preserves every one of them while
4826        // leaving a stock-options stall retryable. The third reason,
4827        // cost, stands and is the price: one extra solve on a run that
4828        // reached only the acceptable tolerance, paid to try for the
4829        // certificate. `cho_parmest` is the motivating case -- monotone
4830        // parks `inf_du` on a ~1e-6 evaluation-noise floor and misses
4831        // `tol` by 5%, taking six null steps of 1e-12 at `mu_min`,
4832        // while adaptive certifies it in 20 iterations.
4833        //
4834        // `dirichlet120`, the case that motivated turning the retry on,
4835        // stalls at `Maximum_Iterations_Exceeded`, so it is recovered
4836        // either way.
4837        let retry_worthy = match first_status {
4838            ApplicationReturnStatus::MaximumIterationsExceeded => true,
4839            // A tiny-step stop the `tiny_step_dual_stall_iters` rule released
4840            // is an iteration limit reached early: the solve had stopped
4841            // moving with its multipliers running away, and before the rule
4842            // it took the remaining budget to say so and then came here as
4843            // `Maximum_Iterations_Exceeded`. Retrying it keeps that rescue.
4844            // A tiny-step stop upstream's own rule reached (multiplier step
4845            // settled) is not retried, as before.
4846            ApplicationReturnStatus::SearchDirectionBecomesTooSmall => {
4847                self.tiny_step_dual_stall.get()
4848            }
4849            ApplicationReturnStatus::SolvedToAcceptableLevel => {
4850                self.mu_strategy_fallback_was_set() || !self.caller_set_termination_policy()
4851            }
4852            _ => false,
4853        };
4854        if !retry_worthy {
4855            return first_status;
4856        }
4857        // gh#857: decline the flip when the solve that just failed escalated
4858        // the factorization and an escalation-off re-solve is enabled.
4859        //
4860        // The mu flip is a *blind* second opinion: it changes the barrier
4861        // schedule and hopes. A `feral_increase_quality` escalation is a
4862        // *measured* fact about the run that just failed -- FERAL reroutes
4863        // which pivots are taken and never steps back down, so every
4864        // iteration after the first escalation, restoration sub-solves
4865        // included, ran on a trajectory the defaults do not describe. Flipping
4866        // `mu_strategy` while leaving that in place is not a controlled
4867        // experiment: it varies the knob that is not implicated and holds the
4868        // one that is.
4869        //
4870        // It is not free either. On `square_flowsheet_resto`'s lbfgs leg the
4871        // flip escalates 25 times all over again, burns a second full
4872        // 3000-iteration budget, and ends no better than the first -- after
4873        // which rung 4 of the second-opinion ladder converges the model in 178
4874        // with the escalation off. That is 6178 real iterations to reach an
4875        // answer that 3178 reach without the flip, and the flip contributes
4876        // nothing to it. Measured both ways: `mu_strategy=adaptive` alone
4877        // still gives 3000 with 25 escalations, and `feral_increase_quality=no`
4878        // gives 178 under *either* mu strategy.
4879        //
4880        // Why decline rather than fold the escalation off into this retry: the
4881        // backend factory is minted from an options snapshot taken by the
4882        // caller *before* `solve()`, so writing `feral_increase_quality` here
4883        // is too late to reach the retry's linear solver. `mu_strategy` is read
4884        // per-solve from the option table and is not; that asymmetry is why
4885        // this layer can only choose whether to spend the solve, not what to
4886        // spend it on.
4887        //
4888        // Restricted to `Maximum_Iterations_Exceeded`, which is exactly the
4889        // status rung 4 opens on. A `Solved_To_Acceptable_Level` exit opens no
4890        // escalation rung, so declining there would drop a retry with nothing
4891        // in its place. Gated on `feral_increase_quality_retry`, so setting
4892        // that option to `no` restores the historical behaviour on both sides
4893        // at once: no rung 4, and no decline here.
4894        //
4895        // The one place the stand-down is not paired with the rung is the
4896        // multi-start paths (`solve_nlp_batch`, the CLI's `minima` search),
4897        // which deliberately do not drive the ladder -- a failed start there is
4898        // routine and extra solves per start multiply. Those paths lose the
4899        // flip on an escalating budget exit and gain nothing back, which is the
4900        // one behaviour change here that is not a strict improvement. It is the
4901        // same trade they already take on every other rung, and for the same
4902        // reason: an escalating capped start is one of many, and doubling its
4903        // cost to re-run the trajectory the escalation governs is the worse end
4904        // of it.
4905        if matches!(
4906            first_status,
4907            ApplicationReturnStatus::MaximumIterationsExceeded
4908        ) && self.quality_escalations.get() >= 1
4909            && self
4910                .options
4911                .get_bool_value("feral_increase_quality_retry", "")
4912                .map(|(v, _found)| v)
4913                .unwrap_or(true)
4914            && self
4915                .options
4916                .get_bool_value("feral_increase_quality", "")
4917                .map(|(v, _found)| v)
4918                .unwrap_or(true)
4919        {
4920            return first_status;
4921        }
4922        // Flip the strategy for one retry. The parser maps "adaptive" →
4923        // Adaptive and every other value (incl. unset) → Monotone, so the
4924        // opposite of an explicit "adaptive" is "monotone" and the
4925        // opposite of anything else is "adaptive".
4926        let saved_mu_strategy = self.options.snapshot_entry("mu_strategy");
4927        let was_adaptive = self.effective_mu_strategy_is_adaptive();
4928        let flipped = if was_adaptive { "monotone" } else { "adaptive" };
4929        // Unwind cover only; the normal path restores the same snapshot
4930        // below. A panic in the retry used to leave the flipped strategy in
4931        // the option table of an application `ffi_guard` keeps.
4932        let mut scope = RetryOptionScope::enter(self, &["mu_strategy"], true);
4933        let _ = scope
4934            .options
4935            .set_string_value("mu_strategy", flipped, true, false);
4936        // Floor the *answer*, not just the status (pounce#870).
4937        //
4938        // The promote-only-on-`Solve_Succeeded` rule below has always floored
4939        // the status. It did not floor the point, and the point is what the
4940        // caller consumes: `optimize_constrained` calls the user TNLP's
4941        // `finalize_solution` once per attempt, so a retry that fails to
4942        // promote still overwrites the answer with its own iterate, and the
4943        // statistics with its own residuals. The result is a status describing
4944        // one attempt attached to a point from another.
4945        //
4946        // Measured on a random corpus of 1200 nonconvex models, 20 of them
4947        // (1.7%) returned a materially worse point under an unchanged status,
4948        // the worst flipping sign: a `Maximum_Iterations_Exceeded` exit went
4949        // from -2.38e7 to +7.89e7, and a `Solved_To_Acceptable_Level` one from
4950        // -3.83e7 to +3.41e5 while its reported `final_kkt_error` rose to
4951        // 2.85e-4 — 285x the `acceptable_tol` its own status names, so the
4952        // report contradicted itself. The known example on record understated
4953        // it by three orders: `autocorr_bern55-06` swapping -2304.0000278 for
4954        // -2320.0000298 is the same defect at 0.07%.
4955        //
4956        // This is the floor idiom the rest of the codebase already uses for a
4957        // bet it might lose — `honour_neg_curv_floor` (gh#797),
4958        // `honour_decline_floor` (gh#534), `honour_best_acceptable_after_dual_
4959        // guard` — applied to the one bet that was only half-floored.
4960        //
4961        // Not extended to `run_with_l1_fallback`, which carries the same
4962        // caveat in its doc comment but is NOT the same call: its retry
4963        // deliberately reports the l1-best least-infeasible point, which the
4964        // option help calls informative in its own right. Changing that needs
4965        // its own measurement.
4966        let solution_floor = scope.last_finalize.borrow().clone();
4967        let certificate_floor = SolutionCertificate::of(&scope.statistics.borrow());
4968        let trace_floor = *scope.last_iter_stats.borrow();
4969        // gh#1042 C1: the first attempt's verdict and cost, recorded before
4970        // the re-solve overwrites the statistics. A promoted re-solve reports
4971        // its own `iteration_count` and `restoration_calls` only, and without
4972        // this nothing says the first attempt got worse.
4973        let mut record = {
4974            let st = scope.statistics.borrow();
4975            pounce_nlp::MuStrategyFallbackRecord {
4976                base_status: first_status.upstream_name().to_string(),
4977                base_iteration_count: st.iteration_count,
4978                base_restoration_calls: st.restoration_calls,
4979                base_objective: st.final_objective,
4980                retry_mu_strategy: flipped.to_string(),
4981                ..Default::default()
4982            }
4983        };
4984        *scope.mu_strategy_fallback_record.borrow_mut() = Some(record.clone());
4985        let retry_status = scope.optimize_constrained(Rc::clone(&tnlp));
4986        record.retry_status = retry_status.upstream_name().to_string();
4987        record.retry_iteration_count = scope.statistics.borrow().iteration_count;
4988        record.promoted = matches!(retry_status, ApplicationReturnStatus::SolveSucceeded);
4989        *scope.mu_strategy_fallback_record.borrow_mut() = Some(record.clone());
4990        // Put the entry back exactly as it was, absence as absence. Writing
4991        // the resolved strategy back instead marked it caller-set, and a
4992        // caller-set `mu_strategy` switches this fallback off
4993        // (`is_mu_strategy_fallback_enabled`): every later solve on the same
4994        // application lost it, which the declared-complementarity driver --
4995        // one application, every stage -- hit whenever an early stage fell
4996        // back. An unset entry still resolves the same way, so the view the
4997        // write-back was preserving is unchanged.
4998        scope
4999            .options
5000            .restore_entry("mu_strategy", saved_mu_strategy);
5001        drop(scope);
5002        self.statistics.borrow_mut().mu_strategy_fallback = Some(record);
5003        // A retry the caller's intermediate callback stopped reports the
5004        // stop, at the point it stopped: the first attempt's status would
5005        // override the request.
5006        if matches!(
5007            retry_status,
5008            ApplicationReturnStatus::SolveSucceeded | ApplicationReturnStatus::UserRequestedStop
5009        ) {
5010            return retry_status;
5011        }
5012        // The bet lost. Put the first attempt's answer back, so the point and
5013        // the statistics describe the same solve the returned status does.
5014        //
5015        // `finalize_solution` therefore runs once more than the number of
5016        // attempts on this path. That is deliberate, and is the cheaper of the
5017        // two corrections: withholding the retry's `finalize_solution` until it
5018        // is known to promote would deprive a caller that watches the callback
5019        // of the retry's progress, and buys nothing, since the retry's payload
5020        // is discarded either way.
5021        if let Some(floor) = solution_floor {
5022            tracing::debug!(target: "pounce::algorithm",
5023                "[POUNCE] the mu_strategy_fallback retry did not promote \
5024                 ({:?} is not Solve_Succeeded); restoring the first attempt's \
5025                 solution and statistics alongside its status (pounce#870).",
5026                retry_status);
5027            self.restore_floor(&floor, &tnlp);
5028            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5029            // Third sink: the per-iteration trace. Consumers accumulate that
5030            // themselves from `intermediate_callback` — the CasADi plugin
5031            // pushes into its own vectors and clears once per `nlpsol` call —
5032            // so POUNCE cannot rewind it, and both attempts concatenate into
5033            // one trace. Restoring the certificate without touching the trace
5034            // leaves the reported numbers describing attempt 1 while the trace
5035            // ends on the retry, which breaks the invariant
5036            // `casadi/test_parity.py` states outright: "The final numbers and
5037            // the end of the trace are the same quantities, and must not come
5038            // from two different places."
5039            //
5040            // Re-emitting the winning attempt's final row restores it. It is
5041            // the trace analogue of `FinalizeSnapshot::replay` above, and it
5042            // makes the property hold by construction rather than by hoping a
5043            // consumer resets on an attempt boundary — nothing in the callback
5044            // contract marks one, and gh#634 is what happens when a consumer
5045            // has to guess the scope of a trace.
5046            //
5047            // The row is a real iterate that was already sent once, not a
5048            // synthesized one, so a trace still contains only points the solver
5049            // actually visited.
5050            // The replayed row is the reported answer's last iterate, so a
5051            // `false` here is a stop request on it, honored as a solve's
5052            // final-iterate stop is.
5053            if let Some(stats) = trace_floor {
5054                if !tnlp.borrow_mut().intermediate_callback(
5055                    stats,
5056                    &TnlpIpoptData::default(),
5057                    &TnlpIpoptCq::default(),
5058                ) {
5059                    return ApplicationReturnStatus::UserRequestedStop;
5060                }
5061            }
5062        }
5063        first_status
5064    }
5065
5066    /// Is the gh#884 biactive dual-divergence retry enabled? Default
5067    /// `yes`; `dual_divergence_retry=no` is the kill switch, and
5068    /// restores the pre-gh#884 behaviour outright (no detector cost, no
5069    /// second solve, and the base attempt's verdict returned unchanged).
5070    fn is_dual_divergence_retry_enabled(&self) -> bool {
5071        self.options
5072            .get_bool_value("dual_divergence_retry", "")
5073            .map(|(v, _found)| v)
5074            .unwrap_or(true)
5075    }
5076
5077    /// gh#884: throw the iterate away and solve again from scratch with
5078    /// `perturb_always_cd` on, when the base solve settled its primal
5079    /// while its multipliers ran away.
5080    ///
5081    /// # The defect
5082    ///
5083    /// On an MPCC lowered through an exact complementarity product
5084    /// `G·H = 0`, a pair that is **biactive** at the solution — both
5085    /// `G` and `H` zero — leaves that row's gradient
5086    /// `H∇G + G∇H` identically zero. The row is still there, so its
5087    /// multiplier is *arbitrary* rather than nonexistent, and the IPM
5088    /// drives it to infinity while the primal iterate sits on the
5089    /// answer. Because the convergence verdict is reached on an
5090    /// `s_d`-normalised aggregate and `s_d` grows with the mean
5091    /// multiplier magnitude, the aggregate reads clean: MacMPEC's
5092    /// `qpec_small` under `ncp_eq`/`prod_eq` reported
5093    /// `Solved_To_Acceptable_Level` at an *unscaled* dual infeasibility
5094    /// of `7.9e+04`.
5095    ///
5096    /// # Why a retry rather than a gate
5097    ///
5098    /// Four other shapes of fix were measured and rejected — a Hessian
5099    /// sparsity hypothesis, engaging `delta_c` *in flight*, flipping
5100    /// `perturb_always_cd` on globally, and putting a dual ceiling on
5101    /// the acceptable-level gate. `dev-notes/mpcc-biactive-dual-
5102    /// divergence.md` records all four with numbers. The short version:
5103    /// by the time the runaway is visible this iterate is unrecoverable,
5104    /// so the only action left is to *stop using it*; and the remedy
5105    /// that works — `perturb_always_cd=yes` — is measured to return a
5106    /// wrong answer reported as success on `ralph1`
5107    /// (`Solve_Succeeded` at `f = -2.71e-5`, below `f* = 0`), so it
5108    /// cannot be turned on for everyone.
5109    ///
5110    /// **The detector is therefore the entire safety barrier**, and the
5111    /// promotion gate below is the second one. `ralph1` is exactly the
5112    /// model the detector must not fire on, and
5113    /// `IpoptAlgorithm`'s scale-relative step floor is what keeps it
5114    /// from doing so: `qpec_small` settles to `4.3e-8` while `ralph1`
5115    /// bottoms out at `7.2e-3`, five orders apart.
5116    ///
5117    /// # The gate
5118    ///
5119    /// The retry's verdict replaces the base one only when **all** of:
5120    ///
5121    /// 1. the base attempt saw the signature (a converged primal, a step
5122    ///    at zero, and an unscaled `‖∇L‖∞` far above `dual_inf_tol`, all
5123    ///    at one iterate — see `IpoptAlgorithm::dual_divergence_signature`);
5124    /// 2. the base status is `Solved_To_Acceptable_Level` or
5125    ///    `Restoration_Failed` — the two verdicts the vanishing-gradient
5126    ///    row produces directly. Generic exhaustion exits are excluded;
5127    ///    `deb7` under L-BFGS is why, and the reason is in the code
5128    ///    below;
5129    /// 3. the retry returns `Solve_Succeeded`;
5130    /// 4. the retry's claimed success is **real in the model's own
5131    ///    units** — unscaled KKT error at or below `tol`-scale, which is
5132    ///    the property the base attempt failed and the whole point of
5133    ///    the issue;
5134    /// 5. the retry's unscaled KKT error is *strictly better* than the
5135    ///    base attempt's.
5136    ///
5137    /// Otherwise the base attempt's status, point and statistics are all
5138    /// put back, by the same three-sink floor
5139    /// [`Self::run_with_mu_strategy_fallback`] uses and for the same
5140    /// reason (pounce#870): a status describing one attempt attached to
5141    /// a point from another is worse than either.
5142    fn run_with_dual_divergence_retry(
5143        &mut self,
5144        tnlp: Rc<RefCell<dyn TNLP>>,
5145    ) -> ApplicationReturnStatus {
5146        let first_status = self.dispatch_standard_solve(Rc::clone(&tnlp));
5147        if !self.dual_divergence_signature.get() {
5148            return first_status;
5149        }
5150        // Which base verdicts this remedy is *for*.
5151        //
5152        // Two, and the narrowing was bought with a measurement. The
5153        // detector is a statement about the iterate; it is not a
5154        // statement that `perturb_always_cd` will help. `deb7` under
5155        // L-BFGS is the corpus case that separates the two: the
5156        // signature is real there — iteration 346, scale-relative step
5157        // `6.5e-6`, `inf_pr` `3.0e-12`, unscaled `inf_du` `9.2e5`,
5158        // which is an order *above* the gh#884 reproducer's `7.9e4`, so
5159        // no dual floor excludes it, and the step conjunct separates the
5160        // two only by fitting the default onto one fixture and spending
5161        // the margin that holds `ralph1` out — and the retry still does
5162        // not work: 3000 iterations to
5163        // `Maximum_Iterations_Exceeded` at an unscaled KKT error of
5164        // `6.7e1` against the base attempt's `9.9e1`. Pure cost, 4x the
5165        // base trajectory, on a fixture whose verdict does not move.
5166        //
5167        // The exclusion is by *status*, so it is only as complete as the
5168        // status is stable, and on this very fixture it is not. `deb7`
5169        // reaches `Error_In_Step_Computation` at default options and is
5170        // out; under `limited_memory_ls_failure_restarts=1` (gh#818's
5171        // rung, off by default) it reaches `Restoration_Failed` instead
5172        // and is therefore *in*. It used to pay exactly the cost above
5173        // there — 6.1 s to 25.2 s wall clock for the same
5174        // `Restoration_Failed` verdict and a declined retry, which is
5175        // gh#887. That is the price of scoping by status rather than by
5176        // model, and it is why the second gate below scopes by the
5177        // *answer* instead: `deb7` now declines before spending
5178        // anything. The status scope is kept because it is cheap and
5179        // reads on the verdict a caller sees, but it is not what is
5180        // being relied on.
5181        //
5182        // What separates them is the *status*, and it separates them
5183        // for a reason rather than by luck:
5184        //
5185        //  * `Solved_To_Acceptable_Level` is gh#884 verbatim — the
5186        //    runaway laundered itself through `s_d` into a success.
5187        //  * `Restoration_Failed` is the same defect one step earlier:
5188        //    the rows whose gradients vanished drive the solve into
5189        //    restoration, and restoration cannot repair a row that has
5190        //    no gradient. It is where the `qpec_small` TNLP fixture
5191        //    lands (unscaled KKT `3.3e11`).
5192        //  * `Error_In_Step_Computation` and
5193        //    `Maximum_Iterations_Exceeded` are generic exhaustion
5194        //    exits. Every hard model reaches them, for every reason.
5195        //    Retrying *those* is not "repair the runaway", it is "try
5196        //    again harder" — which is what `mu_strategy_fallback` and
5197        //    the second-opinion ladder already are, and `deb7` is what
5198        //    that costs.
5199        //
5200        // `Solve_Succeeded` is excluded because it is already the best
5201        // verdict available and its certificate has already been
5202        // checked in the model's own units; there is nothing to buy.
5203        //
5204        // Worst-case cost is therefore one extra solve under the
5205        // caller's own `max_iter` — the same contract
5206        // `run_with_mu_strategy_fallback` already has.
5207        //
5208        // Deliberately **not** deferred to `TERMINATION_POLICY_OPTIONS`
5209        // the way the μ flip's acceptable-level trigger is (gh#757).
5210        // That deferral exists because the μ flip returns a different
5211        // *local solution*, so laundering a caller's deliberate
5212        // downgrade loses a signal they asked for. This retry cannot:
5213        // conjunct 4 requires the promoted answer to satisfy the KKT
5214        // conditions in the model's own units, which a downgrade the
5215        // caller induced on purpose does not. And the gh#884 reproducer
5216        // sets `tol=1e-8` explicitly, so deferring would decline the
5217        // retry on the one case the issue is about.
5218        let retry_worthy = matches!(
5219            first_status,
5220            ApplicationReturnStatus::SolvedToAcceptableLevel
5221                | ApplicationReturnStatus::RestorationFailed
5222        );
5223        if !retry_worthy {
5224            return first_status;
5225        }
5226        let base_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
5227        // The runaway has to be the *whole* residual of the answer being
5228        // reported.
5229        //
5230        // The detector is a statement about an *iterate*, and the iterate
5231        // it fires on need not be the one the solve ends at. A run can
5232        // pass through a settled point with a diverged multiplier, work
5233        // its way back down, and report something ordinary — and then
5234        // there is nothing left here for `perturb_always_cd` to repair,
5235        // whatever the trajectory did in the middle. This is what makes
5236        // "one extra solve" a cost the caller only pays on a run that
5237        // still *exhibits* the defect (gh#887).
5238        //
5239        // The test is `runaway_is_the_whole_residual`, which reads only
5240        // the reported answer and only as a ratio within it; its doc
5241        // comment carries the rule and the measured populations.
5242        let (base_viol, base_compl) = {
5243            let st = self.statistics.borrow();
5244            (st.final_unscaled_constr_viol, st.final_unscaled_compl)
5245        };
5246        let base_dual_inf = self.statistics.borrow().final_unscaled_dual_inf;
5247        if !runaway_is_the_whole_residual(
5248            base_dual_inf,
5249            base_viol,
5250            base_compl,
5251            self.options
5252                .get_numeric_value("dual_divergence_retry_du_floor", "")
5253                .map(|(v, _)| v)
5254                .unwrap_or(DUAL_DIV_RETRY_DU_FLOOR),
5255        ) {
5256            tracing::debug!(target: "pounce::algorithm",
5257                "[POUNCE] gh#884: the signature fired mid-trajectory, but the \
5258                 answer being reported is not a converged point with a runaway \
5259                 multiplier — unscaled dual {:.3e} against viol {:.3e} and \
5260                 complementarity {:.3e}. Nothing here for perturb_always_cd to \
5261                 repair, so no retry (gh#887).",
5262                base_dual_inf, base_viol, base_compl);
5263            return first_status;
5264        }
5265        // Floor all three sinks — solution payload, certificate, and the
5266        // last trace row — exactly as the μ fallback does (pounce#870).
5267        let solution_floor = self.last_finalize.borrow().clone();
5268        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
5269        let trace_floor = *self.last_iter_stats.borrow();
5270        tracing::debug!(target: "pounce::algorithm",
5271            "[POUNCE] gh#884: the primal settled while the multipliers ran away \
5272             (base {:?}, unscaled KKT {:.3e}); re-solving from scratch with \
5273             perturb_always_cd=yes.",
5274            first_status, base_unscaled_kkt);
5275        let saved_cd = self.options.snapshot_entry("perturb_always_cd");
5276        // Unwind cover only, as for the μ-strategy fallback; the normal path
5277        // restores the same snapshot below.
5278        let mut scope = RetryOptionScope::enter(self, &["perturb_always_cd"], true);
5279        let _ = scope
5280            .options
5281            .set_string_value("perturb_always_cd", "yes", true, false);
5282        let retry_status = scope.dispatch_standard_solve(Rc::clone(&tnlp));
5283        // Exactly as it was, absence as absence, so a later solve on the
5284        // same application does not read a caller-set `no`.
5285        scope.options.restore_entry("perturb_always_cd", saved_cd);
5286        drop(scope);
5287        // A retry the caller's intermediate callback stopped reports the
5288        // stop, at the point it stopped; the comparison below would put the
5289        // first attempt's status back over the request.
5290        if retry_status == ApplicationReturnStatus::UserRequestedStop {
5291            return retry_status;
5292        }
5293        let retry_unscaled_kkt = self.statistics.borrow().final_unscaled_kkt_error;
5294        let retry_viol = self.statistics.borrow().final_unscaled_constr_viol;
5295        // Conjuncts 3, 4 and 5. Conjunct 4 is the one that distinguishes
5296        // this gate from every other promote-on-`Solve_Succeeded` retry
5297        // in this file: the base attempt's defect *was* a status that its
5298        // own unscaled residual contradicts, so promoting on the status
5299        // alone would reproduce the bug one attempt later.
5300        let accept_tol = self.dual_divergence_retry_accept_tol();
5301        let claimed_success_is_real = (retry_unscaled_kkt <= accept_tol
5302            && retry_viol <= accept_tol)
5303            || retry_certificate_dominates(
5304                base_unscaled_kkt,
5305                retry_unscaled_kkt,
5306                retry_viol,
5307                accept_tol,
5308            );
5309        // Conjuncts 6 and 7 — see `retry_answer_is_admissible`. Everything
5310        // above this line ranks the two attempts on their *certificates*;
5311        // this ranks them as *answers*, which is what a caller receives.
5312        // Without it a better multiplier is allowed to buy a worse point:
5313        // measured, `-13.0057 -> -1.2072` on a random QPEC, and
5314        // `+1.82e-09 -> -6.61e-05` on `scholtes4`, whose `f*` is exactly 0.
5315        let retry_obj = self.statistics.borrow().final_objective;
5316        // `obj_scaling_factor < 0` is how a maximization is posed, and
5317        // `final_objective` is the user's signed objective, so the
5318        // comparison direction has to follow it (R2).
5319        let sense = if self
5320            .options
5321            .get_numeric_value("obj_scaling_factor", "")
5322            .map(|(v, _)| v)
5323            .unwrap_or(1.0)
5324            < 0.0
5325        {
5326            -1.0
5327        } else {
5328            1.0
5329        };
5330        let answer_is_admissible = retry_answer_is_admissible(
5331            certificate_floor.objective,
5332            certificate_floor.unscaled_constr_viol,
5333            retry_obj,
5334            retry_viol,
5335            self.dual_divergence_retry_accept_tol(),
5336            sense,
5337        );
5338        let promote = matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
5339            && claimed_success_is_real
5340            && retry_unscaled_kkt < base_unscaled_kkt
5341            && answer_is_admissible;
5342        // Say on the console which of the two answers shipped.
5343        //
5344        // The per-attempt end summary cannot: `emit_end_summary` runs
5345        // inside `optimize_constrained`, once per attempt, and the
5346        // promotion is decided after the last of them. So a summary that
5347        // reported the promotion would report `false` on the very run that
5348        // promotes, contradicting the JSON report written from the same
5349        // statistics. The summary reports the *signature*, which is true
5350        // when it prints; this line reports the *outcome*, printed once,
5351        // where it is known.
5352        //
5353        // Gated on `print_level >= 1`, matching `emit_end_summary` — the
5354        // block this line follows.
5355        let console_output = match self.options.get_integer_value("print_level", "") {
5356            Ok((v, true)) => v >= 1,
5357            _ => true,
5358        };
5359        if console_output {
5360            println!();
5361            if promote {
5362                println!(
5363                    "gh#884 dual-divergence retry: promoted — unscaled KKT error \
5364                     {base_unscaled_kkt:.4e} -> {retry_unscaled_kkt:.4e}."
5365                );
5366            } else if !answer_is_admissible {
5367                // A distinct line, because this decline looks like a
5368                // contradiction otherwise: the retry converged, its
5369                // certificate is clean, and it was still refused. Say
5370                // which of the two rules refused it and on what numbers,
5371                // so the reader is not left comparing KKT errors that
5372                // had nothing to do with it.
5373                println!(
5374                    "gh#884 dual-divergence retry: declined on the ANSWER, not the \
5375                     certificate — the retry converged (unscaled KKT error \
5376                     {retry_unscaled_kkt:.4e} against the base attempt's \
5377                     {base_unscaled_kkt:.4e}) but its objective {retry_obj:.8e} at \
5378                     constraint violation {retry_viol:.4e} is not admissible next to \
5379                     the base attempt's {:.8e} at {:.4e}; the base attempt's answer \
5380                     is the one reported.",
5381                    certificate_floor.objective, certificate_floor.unscaled_constr_viol
5382                );
5383            } else {
5384                println!(
5385                    "gh#884 dual-divergence retry: declined ({retry_status:?}, \
5386                     unscaled KKT error {retry_unscaled_kkt:.4e} against the base \
5387                     attempt's {base_unscaled_kkt:.4e}); the base attempt's answer \
5388                     is the one reported."
5389                );
5390            }
5391        }
5392        if promote {
5393            self.dual_divergence_retry_promoted.set(true);
5394            self.statistics.borrow_mut().dual_divergence_retry_promoted = true;
5395            tracing::debug!(target: "pounce::algorithm",
5396                "[POUNCE] gh#884: the retry promoted — unscaled KKT {:.3e} \
5397                 (base {:.3e}).",
5398                retry_unscaled_kkt, base_unscaled_kkt);
5399            return retry_status;
5400        }
5401        if let Some(floor) = solution_floor {
5402            tracing::debug!(target: "pounce::algorithm",
5403                "[POUNCE] gh#884: the retry did not promote ({:?}, unscaled KKT \
5404                 {:.3e} vs base {:.3e}); restoring the first attempt's solution \
5405                 and statistics alongside its status.",
5406                retry_status, retry_unscaled_kkt, base_unscaled_kkt);
5407            self.restore_floor(&floor, &tnlp);
5408            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5409            // The signature belongs to the attempt whose numbers are now
5410            // reported, and `certificate_floor` does not carry it.
5411            self.statistics.borrow_mut().dual_divergence_signature = true;
5412            // The replayed row is the reported answer's last iterate, so a
5413            // `false` here is a stop request on it, honored as a solve's
5414            // final-iterate stop is.
5415            if let Some(stats) = trace_floor {
5416                if !tnlp.borrow_mut().intermediate_callback(
5417                    stats,
5418                    &TnlpIpoptData::default(),
5419                    &TnlpIpoptCq::default(),
5420                ) {
5421                    return ApplicationReturnStatus::UserRequestedStop;
5422                }
5423            }
5424        }
5425        first_status
5426    }
5427
5428    /// Is the gh#983 solve-quality audit enabled? Default `yes`;
5429    /// `solve_quality_audit=no` restores the pre-gh#983 behaviour (no
5430    /// re-scale retry, no `warnings`).
5431    fn is_solve_quality_audit_enabled(&self) -> bool {
5432        self.options
5433            .get_bool_value("solve_quality_audit", "")
5434            .map(|(v, _found)| v)
5435            .unwrap_or(true)
5436    }
5437
5438    /// gh#983 items 2 and 3: audit a success verdict against the *model's
5439    /// own* scale, re-solve once when the scaling is what is wrong, and say
5440    /// so in `statistics.warnings` when it is not fixed.
5441    ///
5442    /// The strict gate judges a scaled aggregate. Gradient-based scaling
5443    /// measures the objective gradient once, at the starting point, and
5444    /// freezes the factor; it also only ever scales *down*. Two failures
5445    /// follow, one on each side, and neither is visible to a gate that reads
5446    /// the scaled space:
5447    ///
5448    /// * **Frozen at a huge-gradient start** (LJ7 from a start whose gradient
5449    ///   is `3e8`): the factor is `3e-7`, the scaled test passes at a point
5450    ///   whose unscaled stationarity residual is `2.9e-2`, and no amount of
5451    ///   continued iteration under that factor improves it
5452    ///   (`obj_scale_certificate_threshold` already tries, and its budget is
5453    ///   spent). The fix is the one the issue names: re-evaluate the scaling
5454    ///   *at the returned point*, where the gradient is small, and solve
5455    ///   again from there.
5456    /// * **Small user objective** (profit in M$/L, gradient `1e-5`): nothing
5457    ///   scales up, so the absolute complementarity floor `~mu` is a
5458    ///   `2.5e-4` fraction of the objective gradient and the answer sits
5459    ///   `4.7e-4` (relative) off the optimum on an active bound. The retry
5460    ///   multiplies the objective by `1/max|grad f|` and solves again from
5461    ///   the returned point.
5462    ///
5463    /// Both retries are *bets that are tested*, floored exactly like the
5464    /// gh#884 and mu-strategy retries: the retry is promoted only when it
5465    /// returns a clean verdict, its unscaled KKT error is no worse, its
5466    /// complementarity (small-objective case) or unscaled KKT error (frozen
5467    /// case) is strictly better, and its answer is admissible next to the
5468    /// base attempt's. Otherwise the base attempt's status, point and
5469    /// statistics are restored and a structured warning is attached.
5470    fn audit_solve_quality(
5471        &mut self,
5472        tnlp: Rc<RefCell<dyn TNLP>>,
5473        first_status: ApplicationReturnStatus,
5474    ) -> ApplicationReturnStatus {
5475        if !self.is_solve_quality_audit_enabled()
5476            || !matches!(
5477                first_status,
5478                ApplicationReturnStatus::SolveSucceeded
5479                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5480            )
5481        {
5482            return first_status;
5483        }
5484        let num = |name: &str, default: Number| -> Number {
5485            self.options
5486                .get_numeric_value(name, "")
5487                .ok()
5488                .and_then(|(v, f)| f.then_some(v))
5489                .unwrap_or(default)
5490        };
5491        let acceptable_tol = num("acceptable_tol", 1e-6);
5492        let masked_threshold = num("obj_scale_certificate_threshold", 1e-4);
5493        // `equilibration-based` is registered but pounce runs it as
5494        // gradient-based (see `algorithm_builder_from_options`), so it gets the
5495        // gradient-based audit.
5496        let gradient_based = self
5497            .options
5498            .get_string_value("nlp_scaling_method", "")
5499            .ok()
5500            .and_then(|(v, f)| f.then_some(v))
5501            .map(|v| v == "gradient-based" || v == "equilibration-based")
5502            .unwrap_or(true);
5503        let base = self.statistics.borrow().clone();
5504        // gh#983 review item 2: measure the objective gradient at the point
5505        // being returned, so the audit asks what re-evaluating the scaling
5506        // *there* would do instead of keying on the start alone.
5507        let final_grad_max = self
5508            .last_finalize
5509            .borrow()
5510            .as_ref()
5511            .and_then(|f| {
5512                let mut g = vec![0.0; f.x.len()];
5513                tnlp.borrow_mut()
5514                    .eval_grad_f(&f.x, true, &mut g)
5515                    .then(|| g.iter().fold(0.0_f64, |m, v| m.max(v.abs())))
5516            })
5517            .unwrap_or(Number::NAN);
5518        let rescaled_obj_scale = if final_grad_max.is_finite() {
5519            pounce_nlp::orig_ipopt_nlp::gradient_obj_scale(
5520                final_grad_max,
5521                num("nlp_scaling_max_gradient", 100.0),
5522                num("nlp_scaling_min_value", 1e-8),
5523                num("nlp_scaling_obj_target_gradient", 0.0),
5524            )
5525        } else {
5526            Number::NAN
5527        };
5528        let input = ScaleAuditInput {
5529            tol: num("tol", 1e-8),
5530            obj_scale: base.final_obj_scaling_factor,
5531            rescaled_obj_scale,
5532            start_grad_max: base.start_obj_grad_max,
5533            final_grad_max,
5534            unscaled_kkt: base.final_unscaled_kkt_error,
5535            unscaled_compl: base.final_unscaled_compl,
5536            acceptable_tol,
5537            masked_threshold,
5538            warm_start: self
5539                .options
5540                .get_bool_value("warm_start_init_point", "")
5541                .map(|(v, _)| v)
5542                .unwrap_or(false),
5543        };
5544        let grad_scale = input.grad_scale();
5545        let trigger = scale_audit_trigger(input);
5546        let mut status = first_status;
5547        match trigger {
5548            Some(ScaleAudit::SmallObjective) => {
5549                self.statistics
5550                    .borrow_mut()
5551                    .warnings
5552                    .push(scale_audit_warning(
5553                        ScaleAudit::SmallObjective,
5554                        &base,
5555                        grad_scale,
5556                        acceptable_tol,
5557                        "",
5558                    ));
5559            }
5560            Some(kind) if gradient_based => {
5561                status = self.run_scale_retry(tnlp, first_status, kind, grad_scale);
5562            }
5563            Some(kind) => {
5564                // The caller owns the scaling (`none` / `user-scaling`): not ours
5565                // to override, but the verdict still deserves its caveat.
5566                self.statistics
5567                    .borrow_mut()
5568                    .warnings
5569                    .push(scale_audit_warning(
5570                        kind,
5571                        &base,
5572                        grad_scale,
5573                        acceptable_tol,
5574                        "was not attempted: nlp_scaling_method is not gradient-based",
5575                    ));
5576            }
5577            None => {}
5578        }
5579        status
5580    }
5581
5582    /// gh#983 review items 1 and 3: the verdict-level half of the audit, run
5583    /// **once**, on the run whose point is being returned -- after every
5584    /// retry and fallback has decided.
5585    ///
5586    /// * The item-5 downgrade (a strict verdict on a run that saw the gh#884
5587    ///   signature and still carries an unscaled dual infeasibility above
5588    ///   `max(acceptable_tol, 1e-3)`) used to run inside each attempt, so it
5589    ///   could turn a base `Solve_Succeeded` into the acceptable level *before*
5590    ///   the gh#884 retry decided, reopening that retry for a case it was
5591    ///   deliberately not widened to; and it read the cumulative signature, so
5592    ///   a promoted mu-fallback run that never showed it was downgraded for its
5593    ///   discarded sibling. It now reads
5594    ///   `returned_run_dual_divergence_signature`, which the certificate floor
5595    ///   saves and restores with the rest of the run's tally.
5596    /// * The model-scale caveats ([`quality_warnings`]) are attached here, and
5597    ///   deduplicated by code, so a code appears at most once.
5598    fn finalize_quality_verdict(
5599        &mut self,
5600        status: ApplicationReturnStatus,
5601    ) -> ApplicationReturnStatus {
5602        if !self.is_solve_quality_audit_enabled() {
5603            return status;
5604        }
5605        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5606        let mut status = status;
5607        if matches!(status, ApplicationReturnStatus::SolveSucceeded) {
5608            let (sig, du, du_scale) = {
5609                let st = self.statistics.borrow();
5610                (
5611                    st.returned_run_dual_divergence_signature,
5612                    st.final_unscaled_dual_inf,
5613                    st.final_unscaled_dual_scale,
5614                )
5615            };
5616            // gh#983 item 5. `1e-3` is `UNSCALED_DUAL_WARN`; the measured
5617            // population behind it is in that constant's doc. A residual at
5618            // the rounding floor of its own terms is not evidence of a miss
5619            // (gh#1000, II.22): see `UNSCALED_DUAL_ROUNDOFF_ULPS`.
5620            if sig
5621                && du.is_finite()
5622                && du > acceptable_tol.max(UNSCALED_DUAL_WARN)
5623                && !unscaled_dual_inf_is_roundoff(du, du_scale)
5624            {
5625                status = ApplicationReturnStatus::SolvedToAcceptableLevel;
5626                push_warning_once(
5627                    &mut self.statistics.borrow_mut().warnings,
5628                    format!(
5629                        "unscaled_dual_inf_above_acceptable: the run saw a settled primal with a \
5630                         runaway multiplier (gh#884) and the returned point's unscaled dual \
5631                         infeasibility is {du:.2e}, above {:.0e}; the status is downgraded from \
5632                         Solve_Succeeded to Solved_To_Acceptable_Level",
5633                        acceptable_tol.max(UNSCALED_DUAL_WARN)
5634                    ),
5635                );
5636            }
5637        }
5638        let st = self.statistics.borrow().clone();
5639        let extra = quality_warnings(
5640            status,
5641            st.final_unscaled_dual_inf,
5642            st.final_unscaled_dual_scale,
5643            self.options
5644                .get_numeric_value("dual_inf_tol", "")
5645                .map(|(v, _)| v)
5646                .unwrap_or(1.0),
5647            acceptable_tol,
5648            self.options
5649                .get_numeric_value("bound_relax_factor", "")
5650                .is_ok_and(|(v, _)| v == 0.0),
5651        );
5652        let mut sm = self.statistics.borrow_mut();
5653        for w in extra {
5654            push_warning_once(&mut sm.warnings, w);
5655        }
5656        status
5657    }
5658
5659    /// The variable box `tnlp` declares, `(x_L, x_U)` in its own (full-x)
5660    /// space -- the space a `finalize_solution` payload is in. `None` if the
5661    /// TNLP declines to say.
5662    fn declared_x_box(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> Option<(Vec<Number>, Vec<Number>)> {
5663        let mut t = tnlp.borrow_mut();
5664        let info = t.get_nlp_info()?;
5665        let (n, m) = (info.n.max(0) as usize, info.m.max(0) as usize);
5666        let (mut x_l, mut x_u) = (vec![0.0; n], vec![0.0; n]);
5667        let (mut g_l, mut g_u) = (vec![0.0; m], vec![0.0; m]);
5668        t.get_bounds_info(BoundsInfo {
5669            x_l: &mut x_l,
5670            x_u: &mut x_u,
5671            g_l: &mut g_l,
5672            g_u: &mut g_u,
5673        })
5674        .then_some((x_l, x_u))
5675    }
5676
5677    /// The re-solve half of [`Self::audit_solve_quality`].
5678    fn run_scale_retry(
5679        &mut self,
5680        tnlp: Rc<RefCell<dyn TNLP>>,
5681        first_status: ApplicationReturnStatus,
5682        kind: ScaleAudit,
5683        grad_scale: Number,
5684    ) -> ApplicationReturnStatus {
5685        let acceptable_tol = self.dual_divergence_retry_accept_tol();
5686        let solution_floor = self.last_finalize.borrow().clone();
5687        let certificate_floor = SolutionCertificate::of(&self.statistics.borrow());
5688        let trace_floor = *self.last_iter_stats.borrow();
5689        let base = self.statistics.borrow().clone();
5690        let Some(seed) = solution_floor.as_ref().map(|f| f.x.clone()) else {
5691            return first_status;
5692        };
5693        // Budget the re-solve: an iteration cap tied to the base solve
5694        // (`SCALE_AUDIT_RETRY_ITER_FACTOR`), and only the time the caller's
5695        // limits have left. Every solve builds a fresh deadline, so without
5696        // this the re-solve got a second full `max_cpu_time` / `max_wall_time`
5697        // after the run had already succeeded. Restored below, absence as
5698        // absence.
5699        let prev_iter = self.options.get_integer_value("max_iter", "").ok();
5700        let prev_cpu = self.options.get_numeric_value("max_cpu_time", "").ok();
5701        let prev_wall = self.options.get_numeric_value("max_wall_time", "").ok();
5702        let cpu_left = prev_cpu.map(|(v, _)| v - base.total_cpu_time_secs);
5703        let wall_left = prev_wall.map(|(v, _)| v - base.total_wallclock_time_secs);
5704        if cpu_left.is_some_and(|t| t <= 0.0) || wall_left.is_some_and(|t| t <= 0.0) {
5705            return first_status;
5706        }
5707        let retry_iter = (SCALE_AUDIT_RETRY_ITER_FACTOR * base.iteration_count)
5708            .max(SCALE_AUDIT_RETRY_MIN_ITER)
5709            .min(prev_iter.map_or(Index::MAX, |(v, _)| v));
5710        let seeded: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(
5711            pounce_nlp::seeded_tnlp::SeededTnlp::new(Rc::clone(&tnlp), seed),
5712        ));
5713        // gh#983 review item 7: remember whether the caller *named* the
5714        // factor, so the restore puts back absence as absence. Writing the
5715        // default back with `found = true` left `obj_scaling_factor` reading as
5716        // user-set after the audit, which every "did the caller name it" test
5717        // downstream (`TERMINATION_POLICY_OPTIONS`, the gh#884 sense) then
5718        // misread.
5719        let prev_user = self
5720            .options
5721            .get_numeric_value("obj_scaling_factor", "")
5722            .ok()
5723            .and_then(|(v, f)| f.then_some(v));
5724        let prev_user_factor = prev_user.unwrap_or(1.0);
5725        let caller_named_relax = self
5726            .options
5727            .get_numeric_value("bound_relax_factor", "")
5728            .is_ok_and(|(_, found)| found);
5729        // Everything below until the scope drops is this re-solve's own
5730        // configuration; the scope puts every entry back, and clears the box
5731        // flag, however the re-solve exits.
5732        let mut scope = RetryOptionScope::enter(
5733            self,
5734            &[
5735                "obj_scaling_factor",
5736                "max_iter",
5737                "max_cpu_time",
5738                "max_wall_time",
5739            ],
5740            false,
5741        );
5742        if let ScaleAudit::Upscale(k) = kind {
5743            let _ = scope.options.set_numeric_value(
5744                "obj_scaling_factor",
5745                prev_user_factor * k,
5746                true,
5747                false,
5748            );
5749        }
5750        let _ = scope
5751            .options
5752            .set_integer_value("max_iter", retry_iter, true, false);
5753        // Solve the re-solve on the caller's own variable box: the rows are
5754        // widened by `bound_relax_factor` exactly as in the base attempt, the
5755        // box is not -- unless the caller named a widening.
5756        //
5757        // The re-solve exists to drive complementarity down (`Upscale`) or the
5758        // unscaled residual (`Rescale`), and on a bound-active variable that
5759        // is the same motion as driving the point onto its bound: `s · z = mu`
5760        // with `z` multiplied by the objective factor, so the slack to the
5761        // *widened* bound shrinks by that factor and the point lands at
5762        // `x_U + bound_relax_factor · max(1, |x_U|)` -- outside the box the
5763        // caller wrote. The base attempt, less converged, usually sat inside
5764        // it. So every promoted re-solve on a bound-active model shipped a
5765        // point outside its declared bounds: measured with `pounce verify`,
5766        // `ex1_320` `1.0e-8` across thousands of controls, `trainf` `7.0e-8`,
5767        // `reading1` `9.9e-9`, against `0` from the base attempt.
5768        //
5769        // The improvement itself is real, not bought with that slack: solved
5770        // with the declared box the re-solve reaches the same objective
5771        // (`reading1` `-1.604802802e-1` against `-1.604802843e-1` widened, the
5772        // base attempt's `-1.604578481e-1`) with the box held exactly. So the
5773        // box widening is dropped for this one solve rather than the re-solve
5774        // refused: it starts from a point that already satisfies the box, and
5775        // `bound_push` moves the seed off any bound it sits on.
5776        //
5777        // Why the box and not `bound_relax_factor=0`: that also un-widens the
5778        // inequality rows, which makes the re-solve a strictly tighter model
5779        // than the base attempt, and its objective then reads *worse* than
5780        // the base's by the row widening's worth -- measured on
5781        // `masked_certificate_fuzz` case 12, `-3.453863914e7` against
5782        // `-3.453863947e7`, with both points inside their box. The rows are
5783        // what the base attempt's `final_unscaled_constr_viol` and rule 2 of
5784        // `retry_answer_is_admissible` already compare like with like; the box
5785        // is the one thing neither did.
5786        //
5787        // A caller who named the factor defined the model that way and keeps
5788        // it; for that case the declared-box conjunct of the promotion gate
5789        // below is what holds the line.
5790        scope.retry_keeps_declared_box.set(!caller_named_relax);
5791        if let Some(t) = cpu_left {
5792            let _ = scope
5793                .options
5794                .set_numeric_value("max_cpu_time", t, true, false);
5795        }
5796        if let Some(t) = wall_left {
5797            let _ = scope
5798                .options
5799                .set_numeric_value("max_wall_time", t, true, false);
5800        }
5801        tracing::debug!(target: "pounce::algorithm",
5802            "[POUNCE] gh#983: {:?} verdict audited ({:?}); re-solving from the \
5803             returned point (max_iter {retry_iter}).", first_status, kind);
5804        // One IPM solve, without the mu-strategy fallback: the re-solve is
5805        // already a second opinion on a run that succeeded, and when it hit
5806        // its cap the flip spent the same budget again (`meyer3` 768 + 768,
5807        // `brainpc3` 120 + 120, `brainpc9` timing out in the second leg).
5808        // No promoted re-solve in the release sweep needed the flip except
5809        // `robot_b` past the cap, which keeps its `Solve_Succeeded` base.
5810        if match scope.options.get_integer_value("print_level", "") {
5811            Ok((v, true)) => v >= 1,
5812            _ => true,
5813        } {
5814            println!();
5815            println!(
5816                "gh#983 scale audit: re-solving from the returned point ({kind:?}); the \
5817                 summary below is a candidate's, and the line after it says whether it \
5818                 replaced the answer above."
5819            );
5820        }
5821        let retry_status = scope.optimize_constrained(Rc::clone(&seeded));
5822        drop(scope);
5823        // A re-solve the caller's intermediate callback stopped is declined
5824        // like any unclean one -- the audit only runs after a converged base,
5825        // and the stop's mid-run iterate must not replace it -- but the
5826        // status reported is the stop, and nothing calls back after it.
5827        let stopped = retry_status == ApplicationReturnStatus::UserRequestedStop;
5828        let retry = self.statistics.borrow().clone();
5829        let sense = if prev_user_factor < 0.0 { -1.0 } else { 1.0 };
5830        let clean = match first_status {
5831            ApplicationReturnStatus::SolveSucceeded => {
5832                matches!(retry_status, ApplicationReturnStatus::SolveSucceeded)
5833            }
5834            _ => matches!(
5835                retry_status,
5836                ApplicationReturnStatus::SolveSucceeded
5837                    | ApplicationReturnStatus::SolvedToAcceptableLevel
5838            ),
5839        };
5840        let better = match kind {
5841            ScaleAudit::Rescale => retry.final_unscaled_kkt_error < base.final_unscaled_kkt_error,
5842            ScaleAudit::Upscale(_) | ScaleAudit::SmallObjective => {
5843                retry.final_unscaled_compl < 0.1 * base.final_unscaled_compl
5844                    && retry.final_unscaled_kkt_error <= base.final_unscaled_kkt_error
5845            }
5846        };
5847        let admissible = retry_answer_is_admissible(
5848            certificate_floor.objective,
5849            certificate_floor.unscaled_constr_viol,
5850            retry.final_objective,
5851            retry.final_unscaled_constr_viol,
5852            acceptable_tol,
5853            sense,
5854        );
5855        // Measured on the two `finalize_solution` payloads -- the points a
5856        // caller would actually receive -- against the box the user TNLP
5857        // declares.
5858        let (base_box_rel, retry_box_rel) = match self.declared_x_box(&tnlp) {
5859            Some((x_l, x_u)) => {
5860                let (lo, up) = (self.nlp_lower_bound_inf(), self.nlp_upper_bound_inf());
5861                let rel = |x: &[Number]| declared_box_relative_violation(x, &x_l, &x_u, lo, up);
5862                (
5863                    solution_floor.as_ref().map_or(Number::NAN, |f| rel(&f.x)),
5864                    self.last_finalize
5865                        .borrow()
5866                        .as_ref()
5867                        .map_or(Number::NAN, |f| rel(&f.x)),
5868                )
5869            }
5870            None => (Number::NAN, Number::NAN),
5871        };
5872        let keeps_box = retry_keeps_declared_box(base_box_rel, retry_box_rel);
5873        let promote = clean && better && admissible && keeps_box;
5874        let console_output = match self.options.get_integer_value("print_level", "") {
5875            Ok((v, true)) => v >= 1,
5876            _ => true,
5877        };
5878        if console_output {
5879            println!();
5880            if clean && better && admissible && !keeps_box {
5881                println!(
5882                    "gh#983 scale audit: declined (the re-solve's point is {:.4e} outside the \
5883                     declared variable bounds, the base attempt's {:.4e}); the base attempt's \
5884                     answer is the one reported.",
5885                    retry.final_declared_box_viol, certificate_floor.declared_box_viol
5886                );
5887            } else if promote {
5888                println!(
5889                    "gh#983 scale audit: promoted -- unscaled KKT error {:.4e} -> {:.4e}, \
5890                     unscaled complementarity {:.4e} -> {:.4e}.",
5891                    base.final_unscaled_kkt_error,
5892                    retry.final_unscaled_kkt_error,
5893                    base.final_unscaled_compl,
5894                    retry.final_unscaled_compl
5895                );
5896            } else {
5897                println!(
5898                    "gh#983 scale audit: declined ({retry_status:?}, unscaled KKT error \
5899                     {:.4e} against the base attempt's {:.4e}); the base attempt's answer \
5900                     is the one reported.",
5901                    retry.final_unscaled_kkt_error, base.final_unscaled_kkt_error
5902                );
5903            }
5904            if !promote {
5905                // The re-solve's own end summary printed above this line, with
5906                // *its* objective and bound violation, before the verdict was
5907                // known (`emit_end_summary` runs inside each attempt). Say
5908                // which block that was and restate the numbers that ship, so
5909                // the console cannot be read as reporting the discarded point.
5910                println!(
5911                    "gh#983 scale audit: the summary block above is the discarded re-solve's; \
5912                     the reported answer is the base attempt's (objective {:.16e}, variable \
5913                     bound violation {:.16e}).",
5914                    certificate_floor.objective, certificate_floor.declared_box_viol
5915                );
5916            }
5917        }
5918        if promote {
5919            return retry_status;
5920        }
5921        if let Some(floor) = solution_floor {
5922            self.restore_floor(&floor, &tnlp);
5923            certificate_floor.restore_into(&mut self.statistics.borrow_mut());
5924            self.statistics.borrow_mut().dual_divergence_signature |=
5925                retry.dual_divergence_signature;
5926            // The replayed row is the reported answer's last iterate, so a
5927            // `false` here is a stop request on it, honored as a solve's
5928            // final-iterate stop is.
5929            if let Some(stats) = trace_floor.filter(|_| !stopped) {
5930                if !tnlp.borrow_mut().intermediate_callback(
5931                    stats,
5932                    &TnlpIpoptData::default(),
5933                    &TnlpIpoptCq::default(),
5934                ) {
5935                    return ApplicationReturnStatus::UserRequestedStop;
5936                }
5937            }
5938        }
5939        if stopped {
5940            return retry_status;
5941        }
5942        let detail = if keeps_box {
5943            format!(
5944                "was declined: the re-solve returned {retry_status:?} with unscaled KKT error {:.2e}",
5945                retry.final_unscaled_kkt_error
5946            )
5947        } else {
5948            format!(
5949                "was declined: the re-solve returned {retry_status:?} at a point {:.2e} outside \
5950                 the declared variable bounds",
5951                retry.final_declared_box_viol
5952            )
5953        };
5954        self.statistics
5955            .borrow_mut()
5956            .warnings
5957            .push(scale_audit_warning(
5958                kind,
5959                &base,
5960                grad_scale,
5961                acceptable_tol,
5962                &detail,
5963            ));
5964        first_status
5965    }
5966
5967    /// The tolerance conjunct 4 of the dual-divergence promotion gate
5968    /// tests the retry's *unscaled* residuals against.
5969    ///
5970    /// `acceptable_tol`-scale rather than `tol`-scale on purpose: the
5971    /// unscaled residual is the one quantity nothing in the solve is
5972    /// driven against, so holding it to `tol` would decline honest
5973    /// retries on badly scaled models for a reason that has nothing to
5974    /// do with gh#884. `qpec_small`'s honest retry reaches `9.96e-8`,
5975    /// four orders inside it.
5976    fn dual_divergence_retry_accept_tol(&self) -> Number {
5977        self.options
5978            .get_numeric_value("acceptable_tol", "")
5979            .ok()
5980            .and_then(|(v, f)| f.then_some(v))
5981            .unwrap_or(1e-6)
5982    }
5983
5984    /// Phase-3 ℓ₁-exact penalty-barrier outer loop.
5985    ///
5986    /// Builds an [`L1PenaltyBarrierTnlp`] wrapper around the user
5987    /// TNLP, runs the constrained IPM at the current ρ, escalates ρ
5988    /// per Byrd-Nocedal-Waltz steering, and terminates on any of:
5989    ///   - slack sum collapses (`Σ(p+n) ≤ l1_slack_tol`)
5990    ///   - inner solve returns non-Optimal (escalation won't fix
5991    ///     numerical / restoration failure at this ρ)
5992    ///   - ρ already at `l1_penalty_max`
5993    ///   - `l1_penalty_max_outer_iter` reached
5994    ///
5995    /// After the loop, if the inner status is `SolveSucceeded` or
5996    /// `SolvedToAcceptableLevel` but slacks didn't collapse, override
5997    /// to `Infeasible_Problem_Detected` — the returned point is the
5998    /// ℓ₁-best least-infeasible iterate, which is informative even
5999    /// though the original constraints are not satisfied.
6000    ///
6001    /// Returns `Some(status)` if the wrapper ran the solve, `None` if
6002    /// wrapper construction failed (caller should fall through to the
6003    /// standard dispatch path).
6004    fn run_l1_penalty_outer_loop(
6005        &mut self,
6006        tnlp: Rc<RefCell<dyn TNLP>>,
6007    ) -> Option<ApplicationReturnStatus> {
6008        let rho_init = self.l1_penalty_init();
6009        let rho_max = self.l1_penalty_max().max(rho_init);
6010        let factor = self.l1_penalty_increase_factor().max(1.0);
6011        let tau = self.l1_steering_factor();
6012        let slack_tol = self.l1_slack_tol();
6013        let max_outer = self.l1_penalty_max_outer_iter().max(1);
6014
6015        let mut wrapper = pounce_l1penalty::L1PenaltyBarrierTnlp::new(Rc::clone(&tnlp), rho_init)?;
6016        if wrapper.m_eq() == 0 {
6017            // Nothing to slack — let the standard dispatch path handle
6018            // this TNLP unmodified.
6019            return None;
6020        }
6021        wrapper.set_defer_inner_finalize(true);
6022        let wrapper_rc = Rc::new(RefCell::new(wrapper));
6023
6024        let mut rho = rho_init;
6025        let mut last_status = ApplicationReturnStatus::InternalError;
6026        // gh#987 item 6: every pass resets the statistics, so without this the
6027        // report described only the last ρ — `iter_count` 26 for a solve that
6028        // ran 18 + 22 + 22 + 26 iterations. Accumulated here, applied once
6029        // after the loop.
6030        let mut totals = MultiPassTotals::default();
6031        for _outer in 0..max_outer {
6032            wrapper_rc.borrow_mut().set_rho(rho);
6033            let dyn_tnlp: Rc<RefCell<dyn TNLP>> = wrapper_rc.clone();
6034            last_status = self.optimize_constrained(dyn_tnlp);
6035            totals.push_pass(&self.statistics.borrow(), Some(rho), last_status);
6036
6037            let w = wrapper_rc.borrow();
6038            if !w.has_solution() {
6039                // Inner solve aborted before producing an iterate.
6040                drop(w);
6041                break;
6042            }
6043            let slack_sum = w.last_slack_sum();
6044            let y_eq_inf = w.last_y_eq_inf_norm();
6045            let x_here: Vec<Number> = w.last_x_trunc().to_vec();
6046            drop(w);
6047            totals.set_slack_sum(slack_sum);
6048
6049            // Termination decisions.
6050            let inner_ok = matches!(
6051                last_status,
6052                ApplicationReturnStatus::SolveSucceeded
6053                    | ApplicationReturnStatus::SolvedToAcceptableLevel
6054            );
6055            if !inner_ok {
6056                break;
6057            }
6058            // Stop escalating ρ once the **user's** constraints are
6059            // satisfied to the tolerance the caller asked for — not once
6060            // `Σ(p + n)` falls under `l1_slack_tol`, which is a different
6061            // quantity judged by a different number (gh#794 P1). The
6062            // slack sum stays the BNW steering signal below, which is
6063            // the job it is right for. One extra `eval_g` per outer
6064            // iteration buys the difference between stopping at the
6065            // penalty solution and stopping at the model's own.
6066            let feasible_here = {
6067                let m_inner = tnlp
6068                    .borrow_mut()
6069                    .get_nlp_info()
6070                    .map(|i| i.m.max(0) as usize)
6071                    .unwrap_or(0);
6072                let mut g_here = vec![0.0; m_inner];
6073                let evaluated =
6074                    m_inner == 0 || tnlp.borrow_mut().eval_g(&x_here, true, &mut g_here);
6075                evaluated
6076                    .then(|| {
6077                        original_space_feasibility(
6078                            &tnlp,
6079                            &x_here,
6080                            &g_here,
6081                            self.nlp_lower_bound_inf(),
6082                            self.nlp_upper_bound_inf(),
6083                            self.user_tol(),
6084                            self.user_acceptable_tol(),
6085                            self.user_constr_viol_tol(),
6086                            self.user_acceptable_constr_viol_tol(),
6087                            self.user_primal_noise_floor_kappa(),
6088                        )
6089                    })
6090                    .flatten()
6091                    .map(|f| {
6092                        totals.set_violation(f.max_violation);
6093                        f.negligible_at_tol
6094                    })
6095            };
6096            match feasible_here {
6097                Some(true) => break,
6098                Some(false) => {}
6099                // Unmeasurable model: fall back to the historical
6100                // slack-sum test rather than looping to the cap.
6101                None if slack_sum.is_finite() && slack_sum <= slack_tol => break,
6102                None => {}
6103            }
6104            if rho >= rho_max {
6105                break;
6106            }
6107            // BNW steering: ρ_new = max(ρ·factor, τ·‖y_eq‖∞ + ε)
6108            let geom = rho * factor;
6109            let steer = tau * y_eq_inf + 1.0e-12;
6110            rho = geom.max(steer).min(rho_max);
6111        }
6112
6113        // gh#987 item 6: total iterations and the per-pass summary.
6114        totals.apply(&mut self.statistics.borrow_mut());
6115
6116        // Forward to the user's inner.finalize_solution exactly once.
6117        let w = wrapper_rc.borrow();
6118        if w.has_solution() {
6119            let x_trunc: Vec<Number> = w.last_x_trunc().to_vec();
6120            let lambda: Vec<Number> = w.last_lambda().to_vec();
6121            let z_l: Vec<Number> = w.last_z_l_trunc().to_vec();
6122            let z_u: Vec<Number> = w.last_z_u_trunc().to_vec();
6123            let solver_status = w.last_status().unwrap_or(SolverReturn::InternalError);
6124            let slack_sum = w.last_slack_sum();
6125            drop(w);
6126
6127            // Recompute f(x*) and c(x*) on the inner. Both are needed
6128            // before the status is decided, because the status now turns
6129            // on the *original-space* feasibility at this point.
6130            let f_inner = tnlp
6131                .borrow_mut()
6132                .eval_f(&x_trunc, true)
6133                .unwrap_or(Number::NAN);
6134            let m = tnlp
6135                .borrow_mut()
6136                .get_nlp_info()
6137                .map(|i| i.m as usize)
6138                .unwrap_or(0);
6139            // The success flag decides whether `g_inner` is a measurement
6140            // or a zero-filled buffer. Dropping it would let a TNLP whose
6141            // final `eval_g` fails fabricate feasibility: every row would
6142            // read `0`, `original_space_feasibility` would return a
6143            // violation of zero, and that would flow into both the exit
6144            // status and the reported residuals. Gate it exactly as the
6145            // ρ-escalation measurement above does, so an evaluation
6146            // failure produces `None` and follows the documented
6147            // `l1_slack_tol` fallback instead (gh#794 review).
6148            let mut g_inner = vec![0.0; m];
6149            let g_evaluated = m == 0 || tnlp.borrow_mut().eval_g(&x_trunc, false, &mut g_inner);
6150
6151            // gh#794 P1. Everything below used to argue from `Σ(p + n)`,
6152            // the sum of the augmented slacks, judged against
6153            // `l1_slack_tol`. That is not the user's constraint
6154            // violation and it is not judged by the user's tolerance:
6155            //
6156            //   * the violation of equality row `i` is `|p_i − n_i|`,
6157            //     not `p_i + n_i`, and at the barrier's interior both
6158            //     slacks stay positive where their difference is zero,
6159            //     so the sum is an upper bound that is loose in one
6160            //     direction; and
6161            //   * `l1_slack_tol` defaults to `1e-6`, four orders looser
6162            //     than a `tol = 1e-8` solve asked for, so a violation
6163            //     that the solver's own strict gate would refuse on the
6164            //     unwrapped problem read as "the constraints are
6165            //     satisfied".
6166            //
6167            // Measured, not argued: the MPCC benchmark's `ralph1`
6168            // (`benchmarks/mpcc/`) returned `Solve_Succeeded` at a point
6169            // violating its one equality row by `2.5e-07`, with the
6170            // reported `final_constr_viol` — the *augmented* residual —
6171            // at `9.6e-15`, so no field in the result disclosed it. The
6172            // objective came back `5.0e-04` below the true optimum,
6173            // which is reachable only off the feasible set.
6174            //
6175            // So: measure the user's own rows at the returned point, and
6176            // judge them by the tolerances the caller set. The slack sum
6177            // keeps its other job unchanged — it is the BNW steering
6178            // signal for ρ escalation inside the loop above, which is
6179            // what it is the right quantity for.
6180            let feas = g_evaluated
6181                .then(|| {
6182                    original_space_feasibility(
6183                        &tnlp,
6184                        &x_trunc,
6185                        &g_inner,
6186                        self.nlp_lower_bound_inf(),
6187                        self.nlp_upper_bound_inf(),
6188                        self.user_tol(),
6189                        self.user_acceptable_tol(),
6190                        self.user_constr_viol_tol(),
6191                        self.user_acceptable_constr_viol_tol(),
6192                        self.user_primal_noise_floor_kappa(),
6193                    )
6194                })
6195                .flatten();
6196
6197            // The reported constraint violation must be the user's, not
6198            // the augmented problem's. Without this the KKT block of a
6199            // successful ℓ₁ solve describes a problem the caller never
6200            // posed. The aggregate errors take a `max` rather than a
6201            // rewrite: the NLP error's primal term enters undivided, so
6202            // the aggregate is never below the constraint violation, and
6203            // the other two components are unaffected by the wrapper.
6204            //
6205            // `f.max_violation` is measured on the inner TNLP's own rows
6206            // and bounds, so it is in the model's **original units**. That
6207            // decides which field family may carry it. `SolveStatistics`
6208            // documents `final_*` as the max-norms in the internally
6209            // scaled NLP space and `final_unscaled_*` as the same
6210            // residuals with the scaling divided back out — equal only
6211            // when no scaling is active — and `docs/src/python.md` states
6212            // the same contract to Python callers. Writing an
6213            // original-units number into `final_constr_viol` would break
6214            // it on any run with `nlp_scaling_method` engaged (gh#794
6215            // review).
6216            //
6217            // So the unscaled family always takes the measurement, and
6218            // the scaled family mirrors it exactly when per-row scaling
6219            // did not engage — the case in which the contract requires
6220            // the two to agree anyway. Under active row scaling the
6221            // scaled fields keep what the inner solve reported; the
6222            // converted number is not available here, because the
6223            // augmented problem's row-scale factors belong to an NLP that
6224            // `optimize_constrained` has already dropped. The status
6225            // decision below does not read these fields — it reads
6226            // `feas` directly — so an active-scaling run is judged on the
6227            // user's rows either way.
6228            // gh#987 (remaining item b): `final_declared_constr_viol` is the
6229            // violation of the model AS THE USER DECLARED IT. The inner
6230            // solve's value describes the wrapper's augmented rows, where
6231            // the elastic slacks absorb any violation, so it read ~1e-12
6232            // even at an infeasible point. Overwrite it with the measurement
6233            // on the user's own rows and box (original units, the same
6234            // quantity the non-l1 path reports); `NaN` when the model could
6235            // not be evaluated, never the augmented number.
6236            self.statistics.borrow_mut().final_declared_constr_viol =
6237                feas.as_ref().map_or(Number::NAN, |f| f.max_violation);
6238            if let Some(f) = feas.as_ref() {
6239                let scaled_may_mirror = self.row_scaling_active.get() == Some(false);
6240                let mut stats = self.statistics.borrow_mut();
6241                stats.final_unscaled_constr_viol = f.max_violation;
6242                stats.final_unscaled_kkt_error =
6243                    stats.final_unscaled_kkt_error.max(f.max_violation);
6244                if scaled_may_mirror {
6245                    stats.final_constr_viol = f.max_violation;
6246                    stats.final_kkt_error = stats.final_kkt_error.max(f.max_violation);
6247                    stats.final_kkt_error_above_noise =
6248                        stats.final_kkt_error_above_noise.max(f.max_violation);
6249                }
6250            }
6251
6252            let inner_claimed_success = matches!(
6253                last_status,
6254                ApplicationReturnStatus::SolveSucceeded
6255                    | ApplicationReturnStatus::SolvedToAcceptableLevel
6256            );
6257
6258            // Downgrade, not upgrade: a solve that reached the strict
6259            // standard on the user's own rows keeps whatever status the
6260            // inner gave it, and nothing here can turn a failure into a
6261            // success.
6262            let downgrade_to_acceptable = inner_claimed_success
6263                && feas
6264                    .as_ref()
6265                    .is_some_and(|f| !f.negligible_at_tol && f.negligible_at_acceptable);
6266
6267            let infeasible_certificate = inner_claimed_success
6268                && match feas.as_ref() {
6269                    // Measured: the point does not satisfy the user's
6270                    // constraints even to `acceptable_tol`.
6271                    Some(f) => !f.negligible_at_acceptable,
6272                    // Unmeasurable model — fall back to the historical
6273                    // slack-sum argument rather than to silence.
6274                    None => slack_sum.is_finite() && slack_sum > slack_tol,
6275                };
6276
6277            if let Some(f) = feas.as_ref()
6278                && inner_claimed_success
6279                && !f.negligible_at_tol
6280            {
6281                tracing::info!(
6282                    target: "pounce::application",
6283                    "l1 penalty-barrier: the inner solve converged the augmented NLP, \
6284                     but the returned point violates the model's own constraints by \
6285                     {:.3e}, which does not meet tol; reporting {} rather than success \
6286                     (gh#794)",
6287                    f.max_violation,
6288                    if f.negligible_at_acceptable {
6289                        "Solved_To_Acceptable_Level"
6290                    } else {
6291                        "an infeasibility verdict"
6292                    },
6293                );
6294            }
6295            // …unless the model's own starting point satisfies every
6296            // constraint, which disproves the certificate outright (gh #379).
6297            // Same gate as the IPM and SQP paths; see
6298            // `withdraw_infeasibility_if_refuted`.
6299            let refuted = infeasible_certificate
6300                && withdraw_infeasibility_if_refuted(
6301                    &tnlp,
6302                    SolverReturn::LocalInfeasibility,
6303                    self.nlp_lower_bound_inf(),
6304                    self.nlp_upper_bound_inf(),
6305                    self.user_tol(),
6306                ) != SolverReturn::LocalInfeasibility;
6307            let final_solver_status = match (infeasible_certificate, refuted) {
6308                (true, false) => SolverReturn::LocalInfeasibility,
6309                // The point is not feasible, so `Solve_Succeeded` would be
6310                // just as wrong as `Infeasible_Problem_Detected`. Report the
6311                // breakdown.
6312                (true, true) => SolverReturn::ErrorInStepComputation,
6313                (false, _) if downgrade_to_acceptable => SolverReturn::StopAtAcceptablePoint,
6314                (false, _) => solver_status,
6315            };
6316            let final_app_status = match (infeasible_certificate, refuted) {
6317                (true, false) => ApplicationReturnStatus::InfeasibleProblemDetected,
6318                (true, true) => ApplicationReturnStatus::ErrorInStepComputation,
6319                (false, _) if downgrade_to_acceptable => {
6320                    ApplicationReturnStatus::SolvedToAcceptableLevel
6321                }
6322                (false, _) => last_status,
6323            };
6324
6325            tnlp.borrow_mut().finalize_solution(
6326                Solution {
6327                    status: final_solver_status,
6328                    x: &x_trunc,
6329                    z_l: &z_l,
6330                    z_u: &z_u,
6331                    g: &g_inner,
6332                    lambda: &lambda,
6333                    obj_value: f_inner,
6334                },
6335                &TnlpIpoptData::default(),
6336                &TnlpIpoptCq::default(),
6337            );
6338            return Some(final_app_status);
6339        }
6340        // No solution captured at all — pass the inner status through.
6341        Some(last_status)
6342    }
6343
6344    /// Constrained-NLP path: build adapter → OrigIpoptNlp → algorithm
6345    /// bundle, run `optimize`, populate statistics, and call
6346    /// `finalize_solution` on the user's TNLP.
6347    /// Whether an over-determined model (more equality rows than free
6348    /// variables) is *provably* infeasible by linear bound propagation.
6349    ///
6350    /// Consulted only on the `NotEnoughDegreesOfFreedom` failure path, where
6351    /// the solve never runs and therefore can never itself discover the
6352    /// infeasibility (gh#387). Builds a throwaway presolve wrapper with only
6353    /// Phase 1 (bound tightening) enabled and asks it for a certified proof —
6354    /// this inherits the certification safety net wholesale: the crossing must
6355    /// exceed the solver's own acceptance margin at the crossed pair's scale,
6356    /// and a concrete witness point satisfying every constraint withdraws the
6357    /// verdict. A `false` here costs nothing but keeping the DOF error.
6358    ///
6359    /// The witness gate runs under [`pounce_presolve::WitnessRule`]'s
6360    /// `DeclaredRowRelative` form, which is admissible only because the solve
6361    /// cannot run on this path (gh#391) — see the comment on the probe below.
6362    ///
6363    /// Deliberately independent of the `presolve` master switch: this is not a
6364    /// model transformation (the wrapper is dropped without solving through
6365    /// it), it is a last check before reporting a structural error for a
6366    /// problem whose verdict is already decided.
6367    fn overdetermined_model_certified_infeasible(&self, tnlp: &Rc<RefCell<dyn TNLP>>) -> bool {
6368        let mut opts = pounce_presolve::PresolveOptions::from_options_list(&self.options)
6369            .unwrap_or_else(|_| pounce_presolve::PresolveOptions::defaults());
6370        opts.enabled = true;
6371        opts.bound_tightening = true;
6372        // Certification needs Phase 1 only; every transformative or
6373        // diagnostic phase is dead weight on a wrapper that is never
6374        // solved through.
6375        opts.auxiliary = false;
6376        opts.fbbt = false;
6377        opts.redundant_constraint_removal = false;
6378        opts.licq_check = false;
6379        opts.warm_z_bounds = false;
6380        // The one place the witness rule is raised off the solver's own
6381        // acceptance test (gh#391). It is sound *here specifically* because the
6382        // gate has already established the solve cannot run: the alternative to
6383        // the proof is the structural 5xx error, never `Solve_Succeeded`, so
6384        // the #380 "two routes, two answers" contradiction the clamp exists to
6385        // prevent has no second route to contradict. See `WitnessRule` for the
6386        // full argument and the homogeneous-row fallback.
6387        let mut probe =
6388            pounce_presolve::PresolveTnlp::new(Rc::clone(tnlp), opts).probing_without_a_solve();
6389        if probe.get_nlp_info().is_none() {
6390            return false;
6391        }
6392        probe.certified_infeasible().is_some()
6393    }
6394
6395    fn optimize_constrained(&mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> ApplicationReturnStatus {
6396        let t_start = Instant::now();
6397
6398        // Invalidate the row-scaling record before anything can read it.
6399        //
6400        // It is written near the end of this function, from the NLP the
6401        // solve actually built, so a solve that bails before that point
6402        // leaves whatever the *previous* one recorded. The ℓ₁ outer loop
6403        // calls this repeatedly and reads the flag after each call, so a
6404        // stale `Some(false)` would let it mirror an original-units
6405        // violation into the scaled family — the exact contract this flag
6406        // exists to protect (gh#794 review round 2). Clearing it here
6407        // makes the failure mode fail-closed: "not recorded" reads as
6408        // "cannot mirror", never as "scaling was off".
6409        self.row_scaling_active.set(None);
6410        // gh#983 review item 1: the structured warnings describe the run whose
6411        // point is returned, so each attempt starts with none. They used to
6412        // accumulate on the application for its lifetime, and a promoted
6413        // gh#884 retry (`Solve_Succeeded` at `du = 1.6e-7`) carried the
6414        // discarded base attempt's `large_dual_scale ... 1.43e9`. A declined
6415        // retry restores the floored attempt's own list via
6416        // `SolutionCertificate`.
6417        self.statistics.borrow_mut().warnings.clear();
6418        self.statistics
6419            .borrow_mut()
6420            .returned_run_dual_divergence_signature = false;
6421
6422        // `print_user_options yes` — dump the OptionsList before the
6423        // solve. Mirrors `IpoptApplication::call_optimize` (upstream
6424        // calls `Jnlst().Printf(.., "%s", options_->PrintUserOptions())`).
6425        let print_opts = self
6426            .options
6427            .get_bool_value("print_user_options", "")
6428            .ok()
6429            .and_then(|(v, f)| f.then_some(v))
6430            .unwrap_or(false);
6431        if print_opts {
6432            print!(
6433                "\nList of user-set options:\n\n{}",
6434                self.options.print_user_options()
6435            );
6436        }
6437
6438        // `print_options_documentation yes` — dump the full registry
6439        // (every option with type, default, valid range/strings, and
6440        // long description) before the solve. Honors
6441        // `print_options_mode` (`text` / `latex` / `doxygen`; only
6442        // `text` is implemented today, the others fall through with a
6443        // one-line note) and `print_advanced_options`. Mirrors
6444        // upstream `IpoptApplication::call_optimize`'s
6445        // `print_options_documentation` branch and `Common/IpRegOptions.cpp`
6446        // `OutputOptionDocumentation`.
6447        let print_doc = self
6448            .options
6449            .get_bool_value("print_options_documentation", "")
6450            .ok()
6451            .and_then(|(v, f)| f.then_some(v))
6452            .unwrap_or(false);
6453        if print_doc {
6454            let mode = self
6455                .options
6456                .get_string_value("print_options_mode", "")
6457                .ok()
6458                .map(|(v, _)| PrintOptionsMode::from_tag(&v))
6459                .unwrap_or(PrintOptionsMode::Text);
6460            let advanced = self
6461                .options
6462                .get_bool_value("print_advanced_options", "")
6463                .ok()
6464                .map(|(v, _)| v)
6465                .unwrap_or(false);
6466            print!(
6467                "\n# Pounce options registry\n\n{}",
6468                self.reg_options.print_options_documentation(mode, advanced)
6469            );
6470        }
6471
6472        // Mint a fresh `TimingStatistics` for this solve — shared (via
6473        // `Rc`) with the data and the NLP below so every `eval_*` and
6474        // every iterate-phase records into the same accumulator. The
6475        // application keeps its own `Rc` so callers can read totals out
6476        // via [`Self::timing_stats`].
6477        let timing = Rc::new(TimingStatistics::new());
6478        *self.timing.borrow_mut() = Rc::clone(&timing);
6479        // gh#606: same lifetime as the timings — a solve that bails out
6480        // before the initializer runs must not report the previous
6481        // solve's warm-start verdict.
6482        *self.warm_start_diag.borrow_mut() = None;
6483        // Gate the *detailed* per-subsystem timers on `timing_statistics`
6484        // (default "no"), matching upstream Ipopt. Without this, every
6485        // timed `eval_*` / phase section pays two `getrusage` syscalls per
6486        // start/end even when statistics are off — 16-20% of busy CPU on
6487        // fast-objective NLPs (issue #190). `print_timing_statistics=yes`
6488        // implies `timing_statistics=yes` (per its option help), so either
6489        // one enables the detailed timers. `overall_alg` is started
6490        // unconditionally below: it feeds the `max_cpu_time` check and is
6491        // reported regardless of the option.
6492        //
6493        // Each name is read as a literal rather than looped over an
6494        // array: the registered-but-unread scan
6495        // (`tests/no_silent_options.rs`) keys on the option name as it
6496        // appears at the accessor, so a loop variable reads as "no key
6497        // here" and hid `timing_statistics` among the silent options
6498        // when it has been wired since #190 (#677, #551).
6499        let read_yes = |key: &str| -> bool {
6500            self.options
6501                .get_bool_value(key, "")
6502                .ok()
6503                .and_then(|(v, f)| f.then_some(v))
6504                .unwrap_or(false)
6505        };
6506        let timing_enabled = read_yes("timing_statistics") || read_yes("print_timing_statistics");
6507        timing.set_detailed_enabled(timing_enabled);
6508        timing.overall_alg.start();
6509
6510        // Reset the linear-solver summary sink so back-to-back solves
6511        // don't bleed factor counters / extremal pivots into each
6512        // other. Surviving the lock failure with a debug-assert keeps
6513        // a poisoned mutex from sinking a release build that doesn't
6514        // even consume the summary.
6515        for sink in [&self.linsol_summary_sink, &self.resto_linsol_summary_sink] {
6516            match sink.lock() {
6517                Ok(mut guard) => {
6518                    *guard = LinearSolverSummary::default();
6519                }
6520                _ => {
6521                    debug_assert!(false, "linsol summary sink mutex poisoned");
6522                }
6523            }
6524        }
6525        // Same reasoning for the quality-escalation tally (gh#857): the
6526        // number belongs to this solve, not to whatever ran before it.
6527        self.quality_escalations.set(0);
6528        // And for the published partition: back-to-back solves on one
6529        // application can differ in which variables are fixed, so last
6530        // solve's labels must not describe this solve's KKT. Cleared here and
6531        // written again below only if this solve resolves one.
6532        if let Ok(mut g) = self.kkt_blocks_published.lock() {
6533            *g = None;
6534        }
6535
6536        // Build adapter + Nlp. Honor `fixed_variable_treatment` (default
6537        // `make_parameter`; pounce additionally implements `relax_bounds`,
6538        // which the adapter also auto-selects as a fallback when
6539        // `make_parameter` would leave `n_x_var < n_c` — mirrors upstream
6540        // `IpTNLPAdapter.cpp:623-633`).
6541        let (lo_inf, up_inf, fixed_treatment) = self.adapter_options();
6542        let adapter = match TNLPAdapter::new_with_options(
6543            Rc::clone(&tnlp),
6544            lo_inf,
6545            up_inf,
6546            fixed_treatment,
6547        ) {
6548            Ok(a) => Rc::new(RefCell::new(a)),
6549            Err(_) => {
6550                timing.overall_alg.end();
6551                return ApplicationReturnStatus::InvalidProblemDefinition;
6552            }
6553        };
6554        // Carry the user's constant `obj_scaling_factor` (default 1.0;
6555        // negative ⇒ maximize) into the NLP. Until pounce#128's
6556        // follow-up this option was registered but never read, so it
6557        // was silently a no-op — maximization diverged because the
6558        // algorithm minimized the unscaled objective.
6559        let obj_scaling_factor = self
6560            .options
6561            .get_numeric_value("obj_scaling_factor", "")
6562            .ok()
6563            .and_then(|(v, f)| f.then_some(v))
6564            .unwrap_or(1.0);
6565        let mut orig_nlp = match OrigIpoptNlp::new(
6566            Rc::clone(&adapter),
6567            Rc::new(ConstObjScaling(obj_scaling_factor)),
6568        ) {
6569            Ok(n) => n,
6570            Err(_) => {
6571                timing.overall_alg.end();
6572                return ApplicationReturnStatus::InternalError;
6573            }
6574        };
6575        orig_nlp.set_timing_stats(Rc::clone(&timing));
6576        // Q6: decide which derivatives may be reused across iterates,
6577        // before anything is evaluated (gh #588).
6578        self.install_constant_derivative_hints(&mut orig_nlp);
6579
6580        // Mirror upstream `OrigIpoptNLP::InitializeStructures` (IpOrigIpoptNLP.cpp:299):
6581        // bail out with NotEnoughDegreesOfFreedom when there are fewer free
6582        // variables than equality constraints. Without this gate, square /
6583        // over-determined systems push the algorithm into restoration on
6584        // iter 0 and exit Restoration_Failed instead of the cleaner DOF code.
6585        let n_x_var = orig_nlp.x_space().dim();
6586        let n_c = orig_nlp.c_space().dim();
6587        if n_x_var > 0 && n_x_var < n_c {
6588            timing.overall_alg.end();
6589            // An over-determined system can still be *provably* infeasible —
6590            // `x == 0.2` with `x == 0.8` is about as provable as infeasibility
6591            // gets — and for such a model the structural DOF error is the
6592            // strictly weaker answer: it reports "cannot attempt this" for a
6593            // problem whose verdict is already decided (gh#387). The DOF gate
6594            // fires before any iteration runs, so nothing downstream will ever
6595            // get the chance to detect the infeasibility; check for a
6596            // bound-propagation proof here, on the rare failure path only.
6597            // The probe reuses presolve's full certification pipeline
6598            // (crossing margin + witness refutation), so a model the solver
6599            // would accept as feasible at its own tolerance is never upgraded
6600            // to "proved infeasible" — those still report the DOF error.
6601            if self.overdetermined_model_certified_infeasible(&tnlp) {
6602                use pounce_common::journalist::JournalCategory;
6603                self.journalist.print(
6604                    JournalLevel::J_SUMMARY,
6605                    JournalCategory::J_MAIN,
6606                    "\nEXIT: Problem has too few degrees of freedom, and bound \
6607                     propagation proves its constraints inconsistent.\n\
6608                     No feasible point exists; the solve was not run.\n",
6609                );
6610                return ApplicationReturnStatus::InfeasibleProblemDetected;
6611            }
6612            return ApplicationReturnStatus::NotEnoughDegreesOfFreedom;
6613        }
6614
6615        // Relax `x_L / x_U / d_L / d_U` by `bound_relax_factor` (default
6616        // 1e-8), capped by `constr_viol_tol` (default 1e-4). Matches
6617        // `OrigIpoptNLP::InitializeStructures` lines 343-358.
6618        let bound_relax_factor = self
6619            .options
6620            .get_numeric_value("bound_relax_factor", "")
6621            .ok()
6622            .and_then(|(v, f)| f.then_some(v))
6623            .unwrap_or(1e-8);
6624        let constr_viol_tol = self
6625            .options
6626            .get_numeric_value("constr_viol_tol", "")
6627            .ok()
6628            .and_then(|(v, f)| f.then_some(v))
6629            .unwrap_or(1e-4);
6630        if self.retry_keeps_declared_box.get() {
6631            orig_nlp.relax_bounds_keeping_box(bound_relax_factor, constr_viol_tol);
6632        } else {
6633            orig_nlp.relax_bounds(bound_relax_factor, constr_viol_tol);
6634        }
6635
6636        // `honor_original_bounds` (default `no`, matching upstream):
6637        // project the reported point back into the un-relaxed box. Must
6638        // follow `relax_bounds`, which snapshots the bounds to project
6639        // onto. Registered but never read before, so a user asking for
6640        // it still got a bound-pinned solution sitting up to
6641        // `min(bound_relax_factor·max(1,|b|), constr_viol_tol)` outside
6642        // its own bounds (gh#483 follow-up).
6643        let honor_original_bounds = self
6644            .options
6645            .get_bool_value("honor_original_bounds", "")
6646            .ok()
6647            .and_then(|(v, f)| f.then_some(v))
6648            .unwrap_or(false);
6649        orig_nlp.set_honor_original_bounds(honor_original_bounds);
6650
6651        // Apply automatic NLP scaling per `nlp_scaling_method` option
6652        // (port of `OrigIpoptNLP::InitializeStructures` →
6653        // `NLPScalingObject::DetermineScaling`). Default is
6654        // `gradient-based` to match upstream Ipopt 3.14.
6655        let scaling_method = self
6656            .options
6657            .get_string_value("nlp_scaling_method", "")
6658            .ok()
6659            .and_then(|(v, f)| f.then_some(v))
6660            .unwrap_or_else(|| "gradient-based".to_string());
6661        let scaling_method = match scaling_method.as_str() {
6662            "none" => ScalingMethod::None,
6663            "gradient-based" => ScalingMethod::GradientBased,
6664            // `curvature-based` computes the factors from the model's
6665            // quadratic coefficients and hands them back through
6666            // `TNLP::get_scaling_parameters` (gh #703), so from the
6667            // engine's side it *is* user scaling — the only difference is
6668            // who filled the vectors in.
6669            "user-scaling" | "curvature-based" => ScalingMethod::UserScaling,
6670            // `equilibration-based` is registered upstream but not yet
6671            // implemented in pounce; fall back to gradient-based (the
6672            // upstream default) to keep behavior predictable.
6673            _ => ScalingMethod::GradientBased,
6674        };
6675        let max_gradient = self
6676            .options
6677            .get_numeric_value("nlp_scaling_max_gradient", "")
6678            .ok()
6679            .and_then(|(v, f)| f.then_some(v))
6680            .unwrap_or(100.0);
6681        let min_value = self
6682            .options
6683            .get_numeric_value("nlp_scaling_min_value", "")
6684            .ok()
6685            .and_then(|(v, f)| f.then_some(v))
6686            .unwrap_or(1e-8);
6687        let obj_target_gradient = self
6688            .options
6689            .get_numeric_value("nlp_scaling_obj_target_gradient", "")
6690            .ok()
6691            .and_then(|(v, f)| f.then_some(v))
6692            .unwrap_or(0.0);
6693        let constr_target_gradient = self
6694            .options
6695            .get_numeric_value("nlp_scaling_constr_target_gradient", "")
6696            .ok()
6697            .and_then(|(v, f)| f.then_some(v))
6698            .unwrap_or(0.0);
6699        orig_nlp.determine_scaling_from_starting_point(
6700            scaling_method,
6701            max_gradient,
6702            min_value,
6703            obj_target_gradient,
6704            constr_target_gradient,
6705        );
6706
6707        let nlp_handle: Rc<RefCell<dyn IpoptNlp>> = Rc::new(RefCell::new(orig_nlp));
6708
6709        // Build the algorithm strategy bundle. Read coarse knobs from
6710        // the OptionsList where we have them; fall through to defaults
6711        // otherwise. The full upstream parsing surface (mu_strategy,
6712        // hessian_approximation, line_search_method, ...) is wired by
6713        // `AlgBuilder::RegisterOptions` in upstream — that registry
6714        // hookup lands as a follow-up; default builder is correct for
6715        // HS71-class problems.
6716        let mut builder = self.algorithm_builder_from_options();
6717
6718        // The objective element's support for the partitioned Hessian.
6719        // Every constraint element reads its support off a Jacobian row;
6720        // only the objective has none declared, so without this the
6721        // updater falls back to the first `∇f`'s nonzeros — a
6722        // value-derived pattern. See
6723        // `TNLPAdapter::objective_nonlinear_vars`.
6724        if matches!(
6725            builder.hessian_approximation,
6726            HessianApproxChoice::Partitioned | HessianApproxChoice::FiniteDifference
6727        ) {
6728            builder.objective_nonlinear_vars = adapter.borrow().objective_nonlinear_vars();
6729        }
6730        // gh#989 item 5: the declared Lagrangian Hessian structure splits the
6731        // partitioned elements into the independent blocks they really are.
6732        if matches!(
6733            builder.hessian_approximation,
6734            HessianApproxChoice::Partitioned
6735        ) {
6736            let declared = !matches!(
6737                self.options.get_string_value("partitioned_structure", ""),
6738                Ok((ref v, true)) if v == "jacobian"
6739            );
6740            if declared {
6741                builder.hessian_declared_pattern = adapter.borrow().lagrangian_hessian_pattern();
6742            }
6743        }
6744
6745        // Which variables the limited-memory Hessian should span (gh#624).
6746        // Upstream's precedence: a TNLP that implements
6747        // `get_number_of_nonlinear_variables` wins, and
6748        // `num_linear_variables` is only the contiguous-prefix fallback.
6749        // Exact-Hessian solves never consult either.
6750        if matches!(
6751            builder.hessian_approximation,
6752            HessianApproxChoice::LimitedMemory | HessianApproxChoice::FiniteDifference
6753        ) {
6754            let num_linear_variables = self
6755                .options
6756                .get_integer_value("num_linear_variables", "")
6757                .ok()
6758                .and_then(|(v, f)| f.then_some(v))
6759                .unwrap_or(0);
6760            match adapter
6761                .borrow()
6762                .quasi_newton_nonlinear_vars(num_linear_variables)
6763            {
6764                Ok(mask) => builder.limited_memory_nonlinear_vars = mask,
6765                Err(e) => {
6766                    use pounce_common::journalist::JournalCategory;
6767                    self.journalist.print(
6768                        JournalLevel::J_ERROR,
6769                        JournalCategory::J_MAIN,
6770                        &format!("\nEXIT: Invalid nonlinear-variable list: {}\n", e.message),
6771                    );
6772                    timing.overall_alg.end();
6773                    return ApplicationReturnStatus::InvalidProblemDefinition;
6774                }
6775            }
6776        }
6777
6778        // Linear-solver backend. The default factory is option-aware
6779        // — it reads the `feral_*` extension options off the same
6780        // `OptionsList` that drove the IPM-level builder above so
6781        // per-problem `.opt` files can flip backend knobs without
6782        // rebuilding pounce.
6783        let mut feral_cfg = feral_config_from_options(&self.options);
6784        // Block-triangular / Schur KKT partition (pounce#180 item 2). Configure
6785        // the Schur block solvers from the *base* feral cfg: a full-KKT external
6786        // ordering (item 1) is sized for the whole system and cannot apply to
6787        // the A_FF sub-block, so the Schur path keeps the default sub-block
6788        // ordering. `build_with_backend` honors this only on the IPM + feral +
6789        // exact-Hessian path and falls back to the standard solver otherwise.
6790        if let Some(indices) = &self.kkt_schur_block {
6791            builder.set_kkt_schur(indices.clone(), feral_cfg.clone());
6792            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6793        }
6794        // Block-parallel KKT partition (structured-KKT Phase 5b), explicit or
6795        // detected (`kkt_block_detect`).
6796        let detect = matches!(
6797            self.options.get_string_value("kkt_block_detect", ""),
6798            Ok((ref v, true)) if v.eq_ignore_ascii_case("yes")
6799        );
6800        // A model-space declaration (§45) is mapped to KKT indices here, where
6801        // the NLP layout — which variables survived fixing, how constraints
6802        // split into equalities and inequalities — is known.
6803        {
6804            let a = adapter.borrow();
6805            let cls = a.classification();
6806            self.x_elimination = Some((cls.x_not_fixed_map.clone(), cls.n_full_x as usize));
6807        }
6808        let mapped = self.model_blocks.as_ref().and_then(|(v, c)| {
6809            let cls = adapter.borrow().classification().clone();
6810            match map_block_structure_to_kkt(&cls, v, c) {
6811                Ok(l) => Some(l),
6812                Err(e) => {
6813                    tracing::warn!(
6814                        target: "pounce::kkt",
6815                        error = %e,
6816                        "declared block structure does not fit this problem; using the standard solver"
6817                    );
6818                    None
6819                }
6820            }
6821        });
6822        if let Some(labels) = mapped
6823            .or_else(|| self.kkt_blocks.clone())
6824            .or(detect.then(Vec::new))
6825        {
6826            builder.set_kkt_blocks(labels.clone(), feral_cfg.clone());
6827            builder.set_kkt_schur_summary_sink(Arc::clone(&self.linsol_summary_sink));
6828            // And to the restoration sub-IPM, whose builder was minted before
6829            // this mapping existed. Its reduced system is this one, so the
6830            // same labels apply; see `kkt_blocks_published`. Off with
6831            // `kkt_block_restoration no`, which is how restoration's own
6832            // contribution is measured.
6833            let resto_blocks = !matches!(
6834                self.options.get_string_value("kkt_block_restoration", ""),
6835                Ok((ref v, _)) if v.eq_ignore_ascii_case("no")
6836            );
6837            if resto_blocks {
6838                if let Ok(mut g) = self.kkt_blocks_published.lock() {
6839                    *g = Some((labels, feral_cfg.clone()));
6840                }
6841            }
6842        }
6843        // A caller-supplied KKT permutation (pounce#180 item 1) overrides
6844        // the string-option / env ordering: `OrderingMethod::External`
6845        // can't be expressed through the OptionsList (it carries a
6846        // vector), so it is injected here from the side-channel field.
6847        // Only applies to the workspace-default FERAL backend below; a
6848        // custom `linear_backend_factory` owns its own config.
6849        if let Some(perm) = &self.external_ordering {
6850            feral_cfg.ordering = pounce_feral::OrderingMethod::External(perm.clone());
6851        }
6852        // MA57's knobs come off the same `OptionsList`, at the main-IPM
6853        // prefix. The restoration sub-IPM reads them again under
6854        // `"resto."` when its caller mints the inner backend factory —
6855        // see `ma57_config_from_options`.
6856        let ma57_cfg = ma57_config_from_options(&self.options, "");
6857        // gh#987 item 3: publish the unperturbed trials' inertia next to the
6858        // backend's own per-factorization record.
6859        builder.inertia_sink = Some(Arc::clone(&self.linsol_summary_sink));
6860        let factory = self.linear_backend_factory.take().unwrap_or_else(|| {
6861            default_backend_factory_with_sink(
6862                feral_cfg,
6863                ma57_cfg,
6864                Arc::clone(&self.linsol_summary_sink),
6865            )
6866        });
6867        let bundle = builder.build_with_backend(factory);
6868
6869        // Wire the data / cq pair around the NLP. Install the shared
6870        // `TimingStatistics` so the algorithm's iterate phases
6871        // (output, convergence, hessian, μ, search-direction,
6872        // line-search, accept) all record into the same accumulator
6873        // the application exposes via `timing_stats()`.
6874        let data: crate::ipopt_data::IpoptDataHandle = Rc::new(RefCell::new(AlgIpoptData::new()));
6875        data.borrow_mut().timing = Rc::clone(&timing);
6876        // Install a shared wall/CPU-time deadline (pounce#242) so the time
6877        // budget is honored at the granularity of the expensive inner
6878        // steps — the main loop's KKT factorization / line search and the
6879        // restoration inner IPM — instead of only between outer iterations.
6880        // The `Deadline` starts its clock now (right after `overall_alg`),
6881        // and the restoration sub-solve reuses this same instance, so the
6882        // caller's budget bounds the whole solve rather than each nested
6883        // level independently. The convergence check treats it as
6884        // authoritative when present (see `conv_check::opt_error`).
6885        data.borrow_mut().deadline = Some(pounce_common::timing::Deadline::new(
6886            builder.conv_check.max_wall_time,
6887            builder.conv_check.max_cpu_time,
6888        ));
6889        let cq: crate::ipopt_cq::IpoptCqHandle = Rc::new(RefCell::new(
6890            IpoptCalculatedQuantities::new(Rc::clone(&data), Rc::clone(&nlp_handle)),
6891        ));
6892        // Correction size for very small slacks (default mach_eps^{3/4});
6893        // drives the safe-slack bound-adjustment mechanism.
6894        if let Ok((v, true)) = self.options.get_numeric_value("slack_move", "") {
6895            cq.borrow_mut().slack_move = v;
6896        }
6897        // `kappa_d` — weight of the linear damping term added to the
6898        // barrier objective/gradient to handle one-sided bounds
6899        // (`IpIpoptCalculatedQuantities.cpp`). Registered (default 1e-5)
6900        // but previously never read, so a user override was silently
6901        // ignored (#191). Routed through the builder for parity with the
6902        // other numeric knobs; the default matches the registered
6903        // default, so only explicit overrides change behavior.
6904        cq.borrow_mut().kappa_d = builder.kappa_d;
6905        // `s_max` — cap on the average multiplier magnitude in the
6906        // `(s_d, s_c)` scaling of the KKT error test. Same shape as
6907        // `kappa_d`: registered (default 100) and previously never read,
6908        // so an override was silently ignored (#551 / #677).
6909        cq.borrow_mut().s_max = builder.s_max;
6910
6911        // Seed `data.curr` with a zero-valued iterate of the correct
6912        // dimensions. The `IterateInitializer` consumes these as its
6913        // template (it overwrites `x`, `s`, multipliers in place); we
6914        // just need the dim metadata.
6915        {
6916            let nlp_borrow = nlp_handle.borrow();
6917            let n_x = nlp_borrow.n();
6918            let n_s = nlp_borrow.m_ineq();
6919            let n_yc = nlp_borrow.m_eq();
6920            let n_yd = nlp_borrow.m_ineq();
6921            let n_zl = nlp_borrow.x_l().dim();
6922            let n_zu = nlp_borrow.x_u().dim();
6923            let n_vl = nlp_borrow.d_l().dim();
6924            let n_vu = nlp_borrow.d_u().dim();
6925            drop(nlp_borrow);
6926            let iv = IteratesVector::new(
6927                Rc::new(DenseVectorSpace::new(n_x).make_new_dense()),
6928                Rc::new(DenseVectorSpace::new(n_s).make_new_dense()),
6929                Rc::new(DenseVectorSpace::new(n_yc).make_new_dense()),
6930                Rc::new(DenseVectorSpace::new(n_yd).make_new_dense()),
6931                Rc::new(DenseVectorSpace::new(n_zl).make_new_dense()),
6932                Rc::new(DenseVectorSpace::new(n_zu).make_new_dense()),
6933                Rc::new(DenseVectorSpace::new(n_vl).make_new_dense()),
6934                Rc::new(DenseVectorSpace::new(n_vu).make_new_dense()),
6935            );
6936            data.borrow_mut().set_curr(iv);
6937        }
6938
6939        // Full primal-dual warm restart (debugger `resolve`): if a
6940        // captured iterate is queued, install it onto `data.curr` over
6941        // the placeholder so the `WarmStartIterateInitializer`'s
6942        // re-optimize branch (x already initialized) keeps it and only
6943        // clamps multipliers / sets target_mu — no cold re-seed from the
6944        // NLP. Skipped (with a warning) if the dimensions don't line up,
6945        // e.g. an option changed the problem structure between solves.
6946        if let Some(snap) = self.warm_start_iterate.take() {
6947            let dims_match = {
6948                let borrow = data.borrow();
6949                borrow
6950                    .curr
6951                    .as_ref()
6952                    .map(|c| iterates_dims(c) == iterates_dims(snap.iterates()))
6953                    .unwrap_or(false)
6954            };
6955            if dims_match {
6956                data.borrow_mut().set_curr(snap.iterates().clone());
6957                data.borrow_mut().curr_mu = snap.mu();
6958            } else {
6959                tracing::warn!(
6960                    target: "pounce::warm_start",
6961                    "debugger warm-restart iterate dimensions differ from the fresh \
6962                     solve; ignoring the captured iterate and seeding normally"
6963                );
6964            }
6965        }
6966
6967        let max_iter = self
6968            .options
6969            .get_integer_value("max_iter", "")
6970            .ok()
6971            .and_then(|(v, f)| f.then_some(v))
6972            .unwrap_or(3000);
6973        let tol = self
6974            .options
6975            .get_numeric_value("tol", "")
6976            .ok()
6977            .and_then(|(v, f)| f.then_some(v))
6978            .unwrap_or(1e-8);
6979        data.borrow_mut().tol = tol;
6980
6981        let mut alg = IpoptAlgorithm::new(data, cq, bundle)
6982            .with_nlp(Rc::clone(&nlp_handle))
6983            .with_tnlp(Rc::clone(&tnlp));
6984        alg.last_iter_stats_sink = Some(Rc::clone(&self.last_iter_stats));
6985        alg.live_iterate_fixed_var_duals = self.reports_fixed_var_duals();
6986        // Mint a fresh restoration factory per inner solve if a
6987        // provider is configured (pounce#10 Phase 3). Falls back to
6988        // the legacy one-shot `restoration_factory` slot when no
6989        // provider is set, preserving single-shot caller behavior.
6990        if let Some(provider) = self.restoration_factory_provider.as_mut() {
6991            self.restoration_factory = Some(provider());
6992        }
6993        if let Some(factory) = self.restoration_factory.as_mut() {
6994            alg = alg.with_restoration(factory());
6995        }
6996        if let Some(diag) = self.diagnostics.as_ref() {
6997            alg = alg.with_diagnostics(Rc::clone(diag));
6998        }
6999        // Move the interactive debugger hook (if any) into the main
7000        // algorithm. Taken — not cloned — so it drives exactly this
7001        // solve; a subsequent solve must reinstall it.
7002        if let Some(hook) = self.debug_hook.take() {
7003            alg = alg.with_debug_hook(hook);
7004        }
7005        alg.max_iter = max_iter;
7006        // `kappa_sigma` — factor bounding how far the bound multipliers
7007        // may deviate from their primal estimates; the clamp runs after
7008        // every accepted step (`IpIpoptAlg.cpp`, Eqn. (16)). Registered
7009        // (default 1e10) but previously never read, so a user override —
7010        // including the documented `< 1` "disable the correction" — was
7011        // silently ignored (#191). Routed through the builder; the struct
7012        // default matches the registered default, so default runs are
7013        // unchanged.
7014        alg.kappa_sigma = builder.kappa_sigma;
7015        alg.ftb_centrality_floor = builder.ftb_centrality_floor;
7016        // `recalc_y` (#677) — see the read site above for why the
7017        // limited-memory path defaults it on.
7018        // `linear_system_scaling=slack-based` (#677) — the only scaling
7019        // choice whose factors depend on the iterate, so the main loop
7020        // has to refresh them. See `IpoptAlgorithm::push_slack_scaling`.
7021        alg.slack_based_scaling = matches!(
7022            builder.linear_system_scaling,
7023            crate::alg_builder::LinearSystemScalingChoice::SlackBased
7024        );
7025        alg.recalc_y = builder.recalc_y;
7026        alg.recalc_y_feas_tol = builder.recalc_y_feas_tol;
7027        // `start_with_resto` — the outer loop is what acts on it. It was
7028        // previously copied only into the restoration sub-solver's own
7029        // builder, which has no first outer iteration to force, so
7030        // setting the option did nothing at all.
7031        alg.start_with_resto = builder.resto.start_with_resto;
7032        // Tiny-step and divergence guards (#191): registered but
7033        // previously never read. Struct defaults match the registered
7034        // defaults, so default runs are unchanged.
7035        alg.tiny_step_tol = builder.tiny_step_tol;
7036        alg.tiny_step_y_tol = builder.tiny_step_y_tol;
7037        alg.diverging_iterates_tol = builder.diverging_iterates_tol;
7038        alg.dual_diverging_streak = builder.dual_diverging_streak.max(0) as usize;
7039        alg.dual_divergence_retry_step_tol = builder.dual_divergence_retry_step_tol;
7040        alg.dual_divergence_retry_du_floor = builder.dual_divergence_retry_du_floor;
7041        alg.tiny_stall = crate::tiny_step_stall::TinyStepDualStall::new(
7042            builder.tiny_step_dual_stall_iters.max(0) as usize,
7043        );
7044        alg.resto_decline_deferrals = builder.resto_decline_deferrals.max(0) as usize;
7045        alg.resto_decline_progress_ratio = builder.resto_decline_progress_ratio;
7046        alg.neg_curv_escapes = builder.neg_curv_escapes.max(0) as usize;
7047        alg.lbfgs_ls_failure_restarts = builder.limited_memory_ls_failure_restarts.max(0) as usize;
7048        alg.kkt_fidelity_tol = builder.kkt_fidelity_tol;
7049        // Honor `print_level == 0`: silence the algorithm's direct-to-stdout
7050        // output — the per-iteration table and, new in #206, the
7051        // problem-statistics and end-of-run summary blocks the engine now
7052        // emits itself. Default (unset) or any positive level shows them; the
7053        // CLI's JSON mode forces print_level 0, so structured output stays
7054        // clean. (The Phase-7 journalist surface respects print_level already;
7055        // this is the legacy direct-print site that needs the same gate.)
7056        let console_output = match self.options.get_integer_value("print_level", "") {
7057            Ok((v, true)) => v >= 1,
7058            _ => true,
7059        };
7060        if !console_output {
7061            alg.print_iter_output = false;
7062            // The nested restoration IPM is built inside the restoration
7063            // driver, not by `IpoptAlgorithm::new`, so it never sees this
7064            // gate unless we forward it.
7065            if let Some(resto) = alg.restoration.as_mut() {
7066                resto.set_print_iter_output(false);
7067            }
7068        }
7069
7070        // Problem statistics, Ipopt-style, emitted before the iteration table
7071        // from the engine's own reduced problem (#206). Built from the same
7072        // collect_stats inputs the CLI used, so the block is byte-identical;
7073        // emitting it here means every frontend (CLI, Python, C) and every
7074        // algorithm (IPM, SQP) gets it.
7075        self.emit_problem_stats(&tnlp, console_output);
7076
7077        // Per-iteration history (pounce#71): when requested, capture the
7078        // `pounce::iteration` events emitted during the solve into an
7079        // `IterRecord` trajectory via the observability collector layer.
7080        // This replaces the old in-loop `iter_history` accumulation; it
7081        // requires the collector to be installed in the active
7082        // subscriber (the CLI / Python / C frontends install it via
7083        // `pounce_observability::init_subscriber`; tests call
7084        // `init_for_tests`). The collector scopes out restoration
7085        // sub-solve iterations via the `restoration` span, so the
7086        // trajectory matches the previous behavior (outer iters only).
7087        let iter_capture = self
7088            .record_iter_history
7089            .then(pounce_observability::IterCaptureGuard::start);
7090
7091        let handover_cells = self.install_handover(&mut alg, &nlp_handle);
7092        let solver_status = alg.optimize();
7093        self.finish_handover(&nlp_handle, handover_cells);
7094        // Keep the initializer's feasibility diagnostics reachable
7095        // after the algorithm goes out of scope (gh#605).
7096        self.least_square_init_report = alg.least_square_init_report();
7097
7098        let captured_iters = iter_capture.map(|g| g.finish()).unwrap_or_default();
7099        // Propagate to any enclosing capture (e.g. `with_iter_capture`
7100        // wrapped around a solve with iteration history enabled), whose
7101        // buffer this inner guard would otherwise leave empty.
7102        pounce_observability::extend_active_capture(&captured_iters);
7103        // Close the overall-algorithm timer on the success path. The
7104        // early-return arms above end it themselves before bailing out;
7105        // this one matches upstream `IpoptApplication::call_optimize`
7106        // (which calls `EndCpuTime()` on overall_alg right after
7107        // `Optimize` returns, regardless of solver_status).
7108        timing.overall_alg.end();
7109
7110        // gh#612: opt-in crossover. Runs here — after the algorithm is done
7111        // but BEFORE the statistics drain, the status gates, the
7112        // `on_converged` hook and `finalize_via_orig_nlp` — so that when it
7113        // accepts, every one of those describes the point actually returned.
7114        // Placing it later would mean reporting residuals for an iterate the
7115        // user is not given, and would hide the exact active set from the
7116        // post-optimal sensitivity hook, which is the first of the three
7117        // consumers this exists for.
7118        self.maybe_crossover(&mut alg, &nlp_handle, solver_status);
7119
7120        // Drain counters / iter count off the algorithm.
7121        {
7122            let mut stats = self.statistics.borrow_mut();
7123            {
7124                let d = alg.data.borrow();
7125                stats.iteration_count = d.iter_count;
7126                // Converged barrier parameter μ — threaded forward into a
7127                // warm-started corrector's `mu_init` / `warm_start_target_mu`
7128                // for predictor–corrector path following (pounce#86).
7129                stats.final_mu = d.curr_mu;
7130            }
7131            // gh#606: the warm-start initializer's verdict on what the
7132            // caller supplied. Lifted off the (solve-local) data handle
7133            // so it outlives the solve; `None` on a cold start.
7134            *self.warm_start_diag.borrow_mut() = alg.data.borrow().warm_start_diagnostics.clone();
7135            stats.total_wallclock_time_secs = t_start.elapsed().as_secs_f64();
7136            // Restoration-phase audit counters (pounce#12). Zero on
7137            // problems where restoration never fires; populated by
7138            // `IpoptAlgorithm::invoke_restoration`.
7139            // Finite-difference Hessian census (gh#823 review). `None` on
7140            // every other updater, which leaves the `-1` sentinel in
7141            // place and says "this mode did not run" rather than "it ran
7142            // and found nothing".
7143            if let Some(fd) = alg.bundle.hess.fd_hessian_stats() {
7144                use crate::hess::fd_hessian::FdPatternSource;
7145                stats.fd_hessian_pattern_used = match fd.pattern_used {
7146                    Some(FdPatternSource::Declared) => 0,
7147                    Some(FdPatternSource::Jacobian) => 1,
7148                    None => -1,
7149                };
7150                stats.fd_hessian_nnz = fd.nnz as Index;
7151                stats.fd_hessian_n = fd.n as Index;
7152                stats.fd_hessian_groups = fd.groups as Index;
7153                stats.fd_hessian_rho_max = fd.rho_max as Index;
7154                stats.fd_hessian_coloring_fell_back = fd.coloring_fell_back;
7155                stats.fd_hessian_objective_clique_widened = fd.objective_clique_widened;
7156            }
7157            stats.restoration_calls = alg.resto_calls;
7158            stats.restoration_inner_iters = alg.resto_inner_iters;
7159            stats.restoration_outer_iters = alg.resto_outer_iters;
7160            stats.restoration_wall_secs = alg.resto_wall_secs;
7161            // gh#857. Read off the shared cell rather than the algorithm's
7162            // own `PdFullSpaceSolver`, so restoration sub-solves — which
7163            // run their own solver instance — are included.
7164            stats.quality_escalations = self.quality_escalations.get() as Index;
7165            // gh#1042: which `Restoration_Failed` this is, for the ladder.
7166            stats.unreleased_handback_exit = alg.unreleased_handback_exit();
7167            // gh#884. Read off the algorithm that just ran, so
7168            // `run_with_dual_divergence_retry` — which sits above this
7169            // call — can see what it observed.
7170            self.dual_divergence_signature
7171                .set(self.dual_divergence_signature.get() || alg.dual_divergence_signature());
7172            stats.dual_divergence_signature = self.dual_divergence_signature.get();
7173            stats.returned_run_dual_divergence_signature = alg.dual_divergence_signature();
7174            self.tiny_step_dual_stall.set(alg.tiny_step_dual_stall());
7175            stats.dual_divergence_retry_promoted = self.dual_divergence_retry_promoted.get();
7176            stats.mu_strategy_fallback = self.mu_strategy_fallback_record.borrow().clone();
7177            stats.derivative_check = self.derivative_check.borrow().clone();
7178            let (rs, ra) = self.obj_scale_refused.get();
7179            self.obj_scale_refused.set((
7180                rs || alg.obj_scale_certificate_refused(),
7181                ra || alg.obj_scale_acceptable_refused(),
7182            ));
7183            stats.obj_scale_certificate_refused = self.obj_scale_refused.get().0;
7184            stats.obj_scale_acceptable_refused = self.obj_scale_refused.get().1;
7185            stats.iterations = captured_iters;
7186            // A refused starting point does not produce a valid iterate.
7187            // Leave final objective/residual fields at their NaN defaults.
7188            // Capture the final *scaled* objective at the algorithm's
7189            // (compressed `x_var`-space) iterate via the NLP: the
7190            // algorithm-side `eval_f` returns `f * obj_scale_factor`.
7191            // `final_objective` is seeded with it only as a best-effort
7192            // fallback; the success path below overwrites it with the
7193            // true unscaled objective from `finalize_via_orig_nlp`
7194            // (which evaluates the user TNLP directly).
7195            if solver_status != SolverReturn::InvalidProblemDefinition {
7196                let curr_x = alg.data.borrow().curr.as_ref().map(|c| c.x.clone());
7197                if let Some(x) = curr_x {
7198                    if let Ok(f) = try_eval_curr_f(&nlp_handle, &x) {
7199                        stats.final_objective = f;
7200                        stats.final_scaled_objective = f;
7201                    }
7202                }
7203                // Final residuals straight off the cq cache. These mirror
7204                // the values upstream prints in its end-of-run summary
7205                // ("Dual infeasibility / Constraint violation /
7206                // Complementarity / Overall NLP error").
7207                let cq = alg.cq.borrow();
7208                stats.final_dual_inf = cq.curr_dual_infeasibility_max();
7209                // Stays on the *internal* measure deliberately: the summary's
7210                // "Overall NLP error" is `curr_nlp_error`, and it is built from
7211                // this same `max(||c||, ||d - s||)`. Switching the violation line
7212                // alone to the original-NLP measure
7213                // (`curr_unscaled_nlp_constraint_violation_max`, now used by the
7214                // `inf_pr` column) would leave the block self-inconsistent —
7215                // an error larger than the max of its own components. Making
7216                // them agree means deciding whether *convergence* should be
7217                // judged on the original NLP, which is a behaviour change for
7218                // every model, not a reporting fix. See pounce#476.
7219                //
7220                // NOTE (gh #528): "Overall NLP error" is no longer the number
7221                // the strict gate tests. That gate judges
7222                // `curr_nlp_error_above_primal_noise` — the same aggregate with
7223                // each row's residual counted only above what it can represent
7224                // in floating point — so on a model whose constraint values run
7225                // to `~1e8` the summary can report an error above `tol` beside
7226                // `EXIT: Optimal Solution Found`. The gap is exactly the part
7227                // of the residual that is quantisation noise, and it is bounded
7228                // by `constr_viol_tol`, which is still tested here on the full
7229                // unfloored residual. Reporting is deliberately left on the raw
7230                // value: it is the honest measurement, and at these magnitudes
7231                // the default `bound_relax_factor = 1e-8` has already moved
7232                // every bound by orders of magnitude more than the floor
7233                // forgives, so the raw number was never an exact statement
7234                // about the original NLP either.
7235                stats.final_constr_viol = cq.curr_primal_infeasibility_max();
7236                // How far outside the model AS DECLARED the returned point
7237                // sits. The line above is the internal slack measure the
7238                // convergence test reads, on the `bound_relax_factor`-widened
7239                // model this arm genuinely solves; the widening stays here
7240                // because a feasible-iterate log-barrier needs `x` strictly
7241                // inside its bounds (the convex arm's does not -- see
7242                // `qp_extract::BoundRelax`). The two can differ by orders and
7243                // nothing used to say so: on netlib `wood1p` this reports
7244                // `1.71e-14` at a point `7.96e-09` outside the declared rows
7245                // and `9.84e-09` outside the declared box. Reported on
7246                // every solve (see gh#987 below).
7247                //
7248                // gh#987: computed on every solve, not only a widened one.
7249                // `final_constr_viol` is documented as the internal scaled
7250                // residual, so under row scaling with `bound_relax_factor=0`
7251                // the user-unit violation was reported nowhere (the field read
7252                // NaN). Without a widening the declared and live models
7253                // coincide, but the *units* do not, and this is the one field
7254                // that is always in the caller's.
7255                stats.final_declared_constr_viol = cq.curr_declared_primal_violation_max();
7256                // The box half of the same measurement, unconditionally: this
7257                // one is a *summary line* (Ipopt's `Variable bound
7258                // violation`), not an extra warning, so it has to carry a real
7259                // number on every solve rather than only on a widened one. At
7260                // `bound_relax_factor = 0` the honest number is `0` and the
7261                // accessor returns it by measurement, not by assumption.
7262                stats.final_declared_box_viol = cq.curr_declared_box_violation_max();
7263                // Infinity-norm complementarity, max over all four bound
7264                // blocks (s_xl·z_l, s_xu·z_u, s_sl·v_l, s_su·v_u). The
7265                // empty-bound blocks return `0` from amax(), so the max is
7266                // safe even when only one side has bounds.
7267                let compl = cq
7268                    .curr_compl_x_l()
7269                    .amax()
7270                    .max(cq.curr_compl_x_u().amax())
7271                    .max(cq.curr_compl_s_l().amax())
7272                    .max(cq.curr_compl_s_u().amax());
7273                stats.final_compl = compl;
7274                stats.final_kkt_error = cq.curr_nlp_error();
7275                // The aggregate the strict gate tested (gh #528). Reported
7276                // alongside the raw one so a summary can account for the gap
7277                // between them; equal to it on every `O(1)` model, and on any
7278                // run with `primal_noise_floor_kappa = 0`.
7279                stats.final_kkt_error_above_noise = cq
7280                    .curr_nlp_error_above_primal_noise(builder.conv_check.primal_noise_floor_kappa);
7281                // Unscaled (user-space) counterparts — divide the nlp_scaling
7282                // back out so a consumer can verify the certificate in its own
7283                // units (pounce#173). Identical to the scaled fields when no
7284                // scaling is active.
7285                stats.final_unscaled_dual_inf = cq.curr_unscaled_dual_infeasibility_max();
7286                stats.final_unscaled_dual_scale = cq.curr_unscaled_dual_infeasibility_scale_max();
7287                stats.final_obj_scaling_factor = cq.computed_obj_scaling_factor();
7288                stats.final_total_obj_scaling_factor = cq.obj_scaling_factor().abs();
7289                stats.start_obj_grad_max = cq.start_obj_gradient_max();
7290                stats.final_unscaled_constr_viol = cq.curr_unscaled_primal_infeasibility_max();
7291                // Record whether per-row scaling actually engaged, so a
7292                // wrapper that measures the user's rows in the model's own
7293                // units knows which field family may carry that number.
7294                // `curr_unscaled_primal_infeasibility_max` treats both
7295                // vectors absent as "scaled == unscaled"; the ℓ₁ outer loop
7296                // relies on the same equivalence (gh#794 review).
7297                {
7298                    let nlp_ref = nlp_handle.borrow();
7299                    self.row_scaling_active.set(Some(
7300                        nlp_ref.c_scale_vec().is_some() || nlp_ref.d_scale_vec().is_some(),
7301                    ));
7302                }
7303                stats.final_unscaled_compl = cq.curr_unscaled_complementarity_max();
7304                stats.final_unscaled_kkt_error = cq.curr_unscaled_nlp_error();
7305
7306                // Report an accepted crossover in the frame it solved in
7307                // (#646). Everything above measures against the bounds the
7308                // interior iteration ran against, which `bound_relax_factor`
7309                // widened by `δ` before the solve. That is the right frame
7310                // for an interior iterate — it never touches a bound — but a
7311                // crossed-over point sits *exactly* on the constraints of the
7312                // problem as declared, i.e. `δ` inside the relaxed ones, so
7313                // the four `s·z` blocks above read `|multiplier| · δ`. For a
7314                // unit multiplier and the default `δ = 1e-8` that is `1e-8`,
7315                // which is `tol`: a strictly better point printed an `Overall
7316                // NLP error` above tolerance, and the opt-in
7317                // `kkt_fidelity_tol` gate below downgraded it.
7318                //
7319                // Only complementarity moves. Stationarity involves no
7320                // bounds, and the crossed-over point is *interior* to the
7321                // relaxed box, so its violation is zero under either reading.
7322                //
7323                // The substitution is confined to reporting. Crossover runs
7324                // after the status is decided, and it only ever installs a
7325                // point the never-regress gate accepted on the declared-bound
7326                // residuals, so this cannot dress up a worse iterate — the
7327                // measurement it replaces is the artifact.
7328                // The same holds for a point the in-solve handover installed
7329                // (gh#1054) while it is still the iterate being reported —
7330                // `curr_from_crossover` is cleared if the interior method
7331                // moved on from it.
7332                let declared_compl = self
7333                    .crossover_report
7334                    .as_ref()
7335                    .filter(|r| r.accepted())
7336                    .or_else(|| {
7337                        self.handover_report
7338                            .as_ref()
7339                            .filter(|_| alg.data.borrow().curr_from_crossover)
7340                            .and_then(|h| h.last.as_ref())
7341                            .filter(|r| r.accepted())
7342                    })
7343                    .map(|r| r.compl_after)
7344                    .filter(|c| c.is_finite());
7345                if let Some(compl_declared) = declared_compl {
7346                    stats.final_compl = compl_declared;
7347                    stats.final_kkt_error =
7348                        cq.curr_nlp_error_with_complementarity(compl_declared, 0.0);
7349                    stats.final_kkt_error_above_noise = cq.curr_nlp_error_with_complementarity(
7350                        compl_declared,
7351                        builder.conv_check.primal_noise_floor_kappa,
7352                    );
7353                    // Same unscaling as `curr_unscaled_complementarity_max`:
7354                    // the slack's row factor and the multiplier's cancel in
7355                    // the product, leaving the objective factor. Magnitude —
7356                    // `obj_scaling_factor` is signed, `-1` being the
7357                    // documented way to pose a maximization.
7358                    let df = cq.obj_scaling_factor().abs();
7359                    stats.final_unscaled_compl = if df == 0.0 || df == 1.0 {
7360                        compl_declared
7361                    } else {
7362                        compl_declared / df
7363                    };
7364                    stats.final_unscaled_kkt_error = stats
7365                        .final_unscaled_dual_inf
7366                        .max(stats.final_unscaled_constr_viol)
7367                        .max(stats.final_unscaled_compl);
7368                }
7369            }
7370        }
7371
7372        // Never report `Infeasible_Problem_Detected` while holding a point that
7373        // satisfies every constraint. The gates that produce this verdict argue
7374        // from a stalled feasibility sub-problem, and gh #379 is what that looks
7375        // like when the argument is wrong — a model whose own starting point is
7376        // exactly feasible, reported infeasible. See
7377        // `withdraw_infeasibility_if_refuted`.
7378        let solver_status =
7379            withdraw_infeasibility_if_refuted(&tnlp, solver_status, lo_inf, up_inf, tol);
7380
7381        // Map SolverReturn → ApplicationReturnStatus per
7382        // MAIN_LOOP.md's exception table, then apply the opt-in
7383        // status-fidelity gate (pounce#173).
7384        let app_status = self.apply_kkt_fidelity_gate(solver_return_to_app_status(solver_status));
7385        // gh#986 item 5: `mehrotra_algorithm=yes` runs with no line search
7386        // (every trial step is accepted), which is sound on LP / convex QP and
7387        // not on a general NLP — there an unglobalized step can walk the
7388        // iterate into an infeasible region that restoration then cannot
7389        // leave. (A *feasible* iterate is no longer sent to restoration by the
7390        // probing guard: it is recentred, gh#986 item 5, so this no longer
7391        // fires on the guard's own account.) Say so when it happens.
7392        if app_status == ApplicationReturnStatus::RestorationFailed
7393            && matches!(
7394                self.options.get_string_value("mehrotra_algorithm", ""),
7395                Ok((ref v, true)) if v == "yes"
7396            )
7397        {
7398            tracing::warn!(
7399                target: "pounce::algorithm",
7400                "pounce: restoration failed under mehrotra_algorithm=yes. That option \
7401                 disables the line search and is intended for LPs and convex QPs; on a \
7402                 general NLP every trial step is accepted, so the iterate can leave the \
7403                 region restoration can repair, and a successful run may stop at a \
7404                 different local solution than the default algorithm finds. Retry with \
7405                 the default (mehrotra_algorithm=no)."
7406            );
7407        }
7408
7409        // On convergence, fire the user-supplied callback (post-optimal
7410        // sensitivity hook, pounce#16) before flowing back through
7411        // `finalize_via_orig_nlp`. Borrowed handles into the converged
7412        // KKT state stay alive for the duration of the closure.
7413        if matches!(
7414            app_status,
7415            ApplicationReturnStatus::SolveSucceeded
7416                | ApplicationReturnStatus::SolvedToAcceptableLevel
7417        ) {
7418            if let Some(cb) = self.on_converged.as_mut() {
7419                // `data.w` is one iterate behind here: the main loop checks
7420                // convergence before it updates the Hessian, so it still holds
7421                // `W(w_k)` from the final Newton step while every other block
7422                // the hook factors (Jacobians, slacks, multipliers, `Σ`) is
7423                // read at the converged point `w*`. Re-evaluate it so the
7424                // sensitivity matrix is the KKT Jacobian at `w*` rather than a
7425                // hybrid of two iterates. Updaters with no `W` to re-evaluate
7426                // (the quasi-Newton ones) answer `None` and keep theirs.
7427                // See `set_on_converged_refreshes_hessian`.
7428                if self.on_converged_refreshes_hessian
7429                    && let Some(w) = alg.bundle.hess.hessian_at_current(&alg.data, &alg.cq)
7430                {
7431                    alg.data.borrow_mut().w = Some(w);
7432                }
7433                if let Some(sd) = alg.search_dir.as_mut() {
7434                    let pd = sd.pd_solver_rc();
7435                    // Tag the firing before it runs, so the hook can file what
7436                    // it keeps under the id `finalize_via_orig_nlp` then
7437                    // stamps on this attempt's payload.
7438                    let id = self.on_converged_fired.get() + 1;
7439                    self.on_converged_fired.set(id);
7440                    alg.data.borrow_mut().on_converged_id = Some(id);
7441                    cb(&alg.data, &alg.cq, &nlp_handle, pd);
7442                }
7443            }
7444        }
7445
7446        // Finalize: forward the final iterate to the user's TNLP. The
7447        // returned objective is evaluated on the *user* TNLP at the
7448        // unscaled iterate, so it overrides the scaled best-effort
7449        // value stashed in `final_objective` above (the algorithm-side
7450        // `eval_f` returns `f * obj_scale_factor`).
7451        if solver_status != SolverReturn::InvalidProblemDefinition {
7452            match finalize_via_orig_nlp(
7453                &nlp_handle,
7454                &alg,
7455                solver_status,
7456                app_status,
7457                &tnlp,
7458                &self.last_finalize,
7459                self.reports_fixed_var_duals(),
7460            ) {
7461                Ok(f_unscaled) => {
7462                    self.statistics.borrow_mut().final_objective = f_unscaled;
7463                }
7464                Err(()) => {}
7465            }
7466        }
7467
7468        // End-of-solve timing report. Gated on `print_timing_statistics`
7469        // (default "no"); mirrors upstream's
7470        // `IpoptApplication::call_optimize` →
7471        // `IpTimingStatistics::PrintAllValues` call site. The report
7472        // goes to stdout (for parity with the banner / iter-row output
7473        // path) and is also fanned out to the journalist so an
7474        // `output_file` attached via `Initialize` picks it up.
7475        let print_timing = self
7476            .options
7477            .get_bool_value("print_timing_statistics", "")
7478            .ok()
7479            .and_then(|(v, f)| f.then_some(v))
7480            .unwrap_or(false);
7481        if print_timing {
7482            let report = timing.report();
7483            print!("{}", report);
7484            use pounce_common::journalist::{JournalCategory, JournalLevel};
7485            self.journalist.print(
7486                JournalLevel::J_SUMMARY,
7487                JournalCategory::J_TIMING_STATISTICS,
7488                &report,
7489            );
7490        }
7491
7492        // End-of-run summary, Ipopt-style, emitted last (after any timing
7493        // report) from the engine's own statistics (#206). Drains the eval
7494        // tallies into SolveStatistics (read AFTER finalize so the final
7495        // solution evaluation is included) and prints the summary, gated on
7496        // the same print_level as the rest of the console.
7497        self.emit_end_summary(app_status, &nlp_handle, console_output);
7498
7499        app_status
7500    }
7501
7502    /// Build an [`AlgorithmBuilder`] populated from the app's
7503    /// [`OptionsList`]. Public so callers wiring the restoration
7504    /// factory can hand the *inner* IPM a builder that mirrors the
7505    /// outer's `mu_strategy`/`mu_oracle`/line-search choices —
7506    /// matching upstream `IpAlgBuilder::BuildRestoIpoptAlgorithm`,
7507    /// which reads the same `mu_strategy` option with prefix `"resto."
7508    /// + prefix` and falls back to the outer setting.
7509    pub fn algorithm_builder_from_options(&self) -> AlgorithmBuilder {
7510        let mut builder = AlgorithmBuilder::new();
7511        // gh#857: share this application's escalation tally. Every
7512        // frontend builds the restoration provider's inner builder from
7513        // this method, so restoration escalations aggregate here too.
7514        builder.quality_escalation_counter = Some(Rc::clone(&self.quality_escalations));
7515        // Structured-KKT Phase 5b: the same reasoning, one solve later. The
7516        // partition this solve resolves is not known yet — it is derived from
7517        // a KKT layout that does not exist until `optimize` builds it — so the
7518        // builder takes the cell rather than the labels, and reads it when
7519        // restoration actually runs. Block-path factorizations record into the
7520        // restoration sink, so `linear_solver.restoration` reports them where
7521        // the rest of restoration's linear algebra is reported.
7522        if let Ok((v, _)) = self.options.get_integer_value("kkt_block_min_size", "") {
7523            builder.kkt_block_min_size = v.max(0) as usize;
7524        }
7525        builder.set_kkt_blocks_cell(Arc::clone(&self.kkt_blocks_published));
7526        builder.set_kkt_schur_summary_sink(Arc::clone(&self.resto_linsol_summary_sink));
7527
7528        // `mehrotra_algorithm` is parsed first so its cascading
7529        // defaults (mu_strategy=adaptive, mu_oracle=probing) can be
7530        // overridden by an explicit user setting of those keys
7531        // below. Mirrors `IpAlgBuilder.cpp:Mehrotra`.
7532        // `fast_step_computation` — skip the search-direction residual
7533        // check and allow an inexact linear solve. `PdSearchDirCalc` has
7534        // consumed this flag since it landed, hard-coded to `false`; the
7535        // option's read site was simply missing, so setting it did
7536        // nothing at all (gh#483 follow-up, #191 round 2).
7537        if let Ok((v, true)) = self.options.get_string_value("fast_step_computation", "") {
7538            builder.fast_step_computation = v.eq_ignore_ascii_case("yes");
7539        }
7540
7541        let mut mehrotra_on = false;
7542        if let Ok((v, found)) = self.options.get_string_value("mehrotra_algorithm", "") {
7543            if found && v == "yes" {
7544                mehrotra_on = true;
7545                builder.mehrotra_algorithm = true;
7546                builder.mu_strategy = MuStrategyChoice::Adaptive;
7547                builder.mu_oracle = crate::mu::adaptive::MuOracleKind::Probing;
7548                // `accept_every_trial_step` short-circuits the alpha
7549                // loop / filter — Mehrotra steps would otherwise be
7550                // rejected by the filter on LP-shaped problems because
7551                // the barrier objective is non-monotone along the
7552                // corrector. Mirrors upstream `IpAlgBuilder.cpp:Mehrotra`.
7553                builder.line_search.accept_every_trial_step = true;
7554                // Aggressive iterate-push defaults (`SetNumericValueIfUnset`
7555                // in upstream). The explicit user parses below will
7556                // overwrite these if the user set them explicitly.
7557                builder.init.bound_push = 10.0;
7558                builder.init.bound_frac = 0.2;
7559                builder.init.slack_bound_push = 10.0;
7560                builder.init.slack_bound_frac = 0.2;
7561                builder.init.bound_mult_init_val = 10.0;
7562                builder.init.constr_mult_init_max = 0.0;
7563                // `alpha_for_y=bound-mult` — Mehrotra wants the
7564                // equality multipliers to advance with the dual
7565                // alpha so they stay in step with z/v. Mirrors
7566                // upstream `IpIpoptAlg.cpp:InitializeImpl`.
7567                builder.line_search.alpha_for_y =
7568                    crate::line_search::backtracking::AlphaForY::BoundMult;
7569                // `adaptive_mu_globalization=never-monotone-mode` —
7570                // upstream `IpIpoptAlg.cpp:148-154` enforces this:
7571                // Mehrotra disables the globalization switch entirely
7572                // (no fallback to monotone mode when convergence
7573                // stalls). Required for the unsafeguarded Mehrotra
7574                // path to function.
7575                builder.mu.adaptive_mu_globalization =
7576                    crate::mu::adaptive::AdaptiveMuGlobalization::NeverMonotoneMode;
7577                // `least_square_init_primal=yes` — upstream
7578                // `IpIpoptAlg.cpp:182` enables this for the Mehrotra
7579                // cascade. Replaces the user's starting `x` with the
7580                // min-norm primal that satisfies the linearized
7581                // equality+inequality constraints. Critical on
7582                // LP-shaped problems where the user's starting point
7583                // can be wildly infeasible (e.g. nuffield2_trap).
7584                builder.init.least_square_init_primal = true;
7585            }
7586        }
7587
7588        if let Ok((v, found)) = self.options.get_string_value("mu_strategy", "") {
7589            if found {
7590                let parsed = match v.as_str() {
7591                    "adaptive" => MuStrategyChoice::Adaptive,
7592                    _ => MuStrategyChoice::Monotone,
7593                };
7594                if mehrotra_on && matches!(parsed, MuStrategyChoice::Monotone) {
7595                    // Upstream Ipopt refuses this combination: Mehrotra
7596                    // needs an affine step every iter, which only the
7597                    // adaptive path computes. Keep adaptive and warn.
7598                    tracing::warn!(target: "pounce::algorithm",
7599                        "pounce: mehrotra_algorithm=yes requires \
7600                         mu_strategy=adaptive; ignoring \
7601                         mu_strategy=monotone."
7602                    );
7603                } else {
7604                    builder.mu_strategy = parsed;
7605                }
7606            }
7607        }
7608        if let Ok((v, found)) = self.options.get_string_value("mu_oracle", "") {
7609            if found {
7610                builder.mu_oracle = match v.as_str() {
7611                    "loqo" => crate::mu::adaptive::MuOracleKind::Loqo,
7612                    "probing" => crate::mu::adaptive::MuOracleKind::Probing,
7613                    _ => crate::mu::adaptive::MuOracleKind::QualityFunction,
7614                };
7615            }
7616        }
7617        if let Ok((v, found)) = self
7618            .options
7619            .get_string_value("adaptive_mu_globalization", "")
7620        {
7621            if found {
7622                use crate::mu::adaptive::AdaptiveMuGlobalization;
7623                builder.mu.adaptive_mu_globalization = match v.as_str() {
7624                    "kkt-error" => AdaptiveMuGlobalization::KktError,
7625                    "never-monotone-mode" => AdaptiveMuGlobalization::NeverMonotoneMode,
7626                    _ => AdaptiveMuGlobalization::ObjConstrFilter,
7627                };
7628            }
7629        }
7630        if let Ok((v, found)) = self.options.get_string_value("hessian_approximation", "") {
7631            if found {
7632                builder.hessian_approximation = match v.as_str() {
7633                    "limited-memory" => HessianApproxChoice::LimitedMemory,
7634                    "partitioned" => HessianApproxChoice::Partitioned,
7635                    "finite-difference" => HessianApproxChoice::FiniteDifference,
7636                    _ => HessianApproxChoice::Exact,
7637                };
7638            }
7639        }
7640        // **Upstream changes the `mu_strategy` default for a
7641        // limited-memory Hessian.** `IpAlgBuilder.cpp:1059`:
7642        //
7643        //     if( !options.GetStringValue("mu_strategy", smuupdate, prefix) )
7644        //     {
7645        //        // Change default for quasi-Newton option (then we use adaptive)
7646        //        ... if( hessian_approximation == LIMITED_MEMORY )
7647        //               smuupdate = "adaptive";
7648        //     }
7649        //
7650        // and again at `:920` for the restoration-phase algorithm.
7651        // Registered default is `monotone`; the quasi-Newton path takes
7652        // `adaptive` unless the caller says otherwise. pounce read the
7653        // registered default unconditionally, so every L-BFGS solve ran
7654        // a barrier schedule Ipopt does not use on that path — a
7655        // trajectory divergence on the arm the Python frontend and the
7656        // CasADi plugin select automatically (gh#746).
7657        //
7658        // The restoration sub-IPM inherits this: `run_inner_resto`
7659        // clones the configured `inner_alg_builder`, so the flag set
7660        // here is what the resto algorithm gets, matching `:920`.
7661        //
7662        // Only when unset — an explicit `mu_strategy` still wins, and
7663        // `mehrotra_algorithm` (parsed above) has already forced
7664        // adaptive on its own terms.
7665        if builder.hessian_approximation == HessianApproxChoice::LimitedMemory
7666            && !self.mu_strategy_was_set()
7667        {
7668            builder.mu_strategy = MuStrategyChoice::Adaptive;
7669        }
7670        // Limited-memory quasi-Newton update formula. Registered upstream
7671        // (`limited_memory_update_type`, IpLimMemQuasiNewtonUpdater.cpp) but
7672        // until now read nowhere on the IPM path — the updater was hard-wired
7673        // to Powell-damped BFGS. SR1 is honored too (the updater and the
7674        // low-rank/inertia path already handle its indefinite models).
7675        // Partitioned quasi-Newton knobs. `partitioned_update_type`
7676        // defaults to SR1 rather than BFGS — see
7677        // `crates::hess::partitioned_quasi_newton` for why damping is
7678        // the wrong choice on a per-constraint element.
7679        if let Ok((v, found)) = self.options.get_string_value("partitioned_update_type", "") {
7680            if found {
7681                builder.partitioned_update_type = match v.as_str() {
7682                    "bfgs" => UpdateType::Bfgs,
7683                    _ => UpdateType::Sr1,
7684                };
7685                builder.partitioned_update_type_was_set = true;
7686            }
7687        }
7688        if let Ok((v, found)) = self
7689            .options
7690            .get_integer_value("partitioned_max_element", "")
7691        {
7692            if found && v > 0 {
7693                builder.partitioned_max_element = v as usize;
7694            }
7695        }
7696        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_pattern", "") {
7697            if found {
7698                builder.fd_hessian_pattern = match v.as_str() {
7699                    "jacobian" => crate::hess::fd_hessian::FdPatternSource::Jacobian,
7700                    _ => crate::hess::fd_hessian::FdPatternSource::Declared,
7701                };
7702            }
7703        }
7704        if let Ok((v, found)) = self.options.get_string_value("fd_hessian_coloring", "") {
7705            if found {
7706                builder.fd_hessian_coloring = match v.as_str() {
7707                    "cpr" => crate::hess::fd_hessian::FdColoring::Cpr,
7708                    _ => crate::hess::fd_hessian::FdColoring::Star,
7709                };
7710            }
7711        }
7712        if let Ok((v, found)) = self.options.get_numeric_value("fd_hessian_reuse_tol", "") {
7713            if found && v >= 0.0 {
7714                builder.fd_hessian_reuse_tol = v;
7715            }
7716        }
7717        if let Ok((v, found)) = self.options.get_string_value("partitioned_elements", "") {
7718            if found {
7719                builder.partitioned_elements = match v.as_str() {
7720                    "blocks" => crate::hess::partitioned_quasi_newton::ElementMode::PrimalBlock,
7721                    _ => crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
7722                };
7723            }
7724        }
7725        if let Ok((v, found)) = self.options.get_integer_value("partitioned_block_size", "") {
7726            if found && v > 0 {
7727                builder.partitioned_block_size = v as usize;
7728            }
7729        }
7730        if let Ok((v, found)) = self
7731            .options
7732            .get_numeric_value("partitioned_curvature_cap", "")
7733        {
7734            if found && v > 0.0 {
7735                builder.partitioned_curvature_cap = v;
7736            }
7737        }
7738        if let Ok((v, found)) = self
7739            .options
7740            .get_string_value("limited_memory_update_type", "")
7741        {
7742            if found {
7743                builder.limited_memory_update_type = match v.as_str() {
7744                    "sr1" => UpdateType::Sr1,
7745                    _ => UpdateType::Bfgs,
7746                };
7747            }
7748        }
7749        // Limited-memory history length (`limited_memory_max_history`).
7750        if let Ok((v, found)) = self
7751            .options
7752            .get_integer_value("limited_memory_max_history", "")
7753        {
7754            if found && v >= 0 {
7755                builder.limited_memory_max_history = v as Index;
7756            }
7757        }
7758        // `limited_memory_initialization` — which formula picks the
7759        // initial Hessian scalar σ. Registered since the option port with
7760        // upstream's `scalar1` default and read nowhere until #677, so
7761        // the updater's own `Scalar2` default was the only value any
7762        // solve ever used: setting the option did nothing, and it warned
7763        // nothing. Same miss as gh#483 / #191 round 2 (which wired
7764        // `limited_memory_init_val_max`/`_min`) — this is the third
7765        // argument to that same `initial_hessian_scalar` call.
7766        //
7767        // The effective default now follows the registry (`scalar1`),
7768        // matching Ipopt. σ_scalar2/σ_scalar1 = (yᵀy·sᵀs)/(sᵀy)² ≥ 1 and
7769        // is unbounded as the curvature pair degrades, so on an
7770        // ill-conditioned problem `scalar2` inflates `B0 = σI` until it
7771        // swamps the rank-2 corrections and the step collapses.
7772        if let Ok((v, found)) = self
7773            .options
7774            .get_string_value("limited_memory_initialization", "")
7775        {
7776            if found {
7777                use crate::hess::lim_mem_quasi_newton::InitialApprox;
7778                // Every registered value is named explicitly. #551 §3
7779                // held this option back precisely because wiring only
7780                // the values that mapped would leave the rest falling
7781                // back silently — a new no-op created by the fix — so a
7782                // catch-all standing in for a real value is the one
7783                // shape to avoid here. `OptionsList` rejects any
7784                // unregistered value before this runs (`options_list.rs`
7785                // `OPTION_INVALID`), so the final arm is unreachable
7786                // rather than a fallback.
7787                builder.limited_memory_initialization = match v.as_str() {
7788                    "scalar1" => InitialApprox::Scalar1,
7789                    "scalar2" => InitialApprox::Scalar2,
7790                    "scalar3" => InitialApprox::Scalar3,
7791                    "scalar4" => InitialApprox::Scalar4,
7792                    "constant" => InitialApprox::Constant,
7793                    "history-max" => InitialApprox::HistoryMax,
7794                    _ => InitialApprox::Scalar2,
7795                };
7796            }
7797        }
7798        // `recalc_y` / `recalc_y_feas_tol` — least-square re-estimation
7799        // of the equality multipliers once feasible (#677).
7800        //
7801        // Upstream registers `recalc_y` as `no`, but its own option text
7802        // ends "If a limited memory quasi-Newton option is chosen, this
7803        // is used by default", so upstream's effective default is
7804        // conditional on the Hessian approximation.
7805        //
7806        // **pounce does not follow that, and the discrepancy is
7807        // deliberate.** Auto-enabling it for the limited-memory path was
7808        // implemented and measured against the fixture corpus first: it
7809        // moved 16 of 57 fixtures on the L-BFGS leg and took **7 from
7810        // solved to not solved, with nothing moving the other way** —
7811        // `airport` 56 it → `SearchDirectionBecomesTooSmall` at 541,
7812        // `pooling_rt2stp` 413 it → the same at 1775, all three `jit1`
7813        // variants, `linear_eq_collapsed_box`, and `hs13_bigstart` to
7814        // the iteration cap. The signature is consistent: re-estimating
7815        // `y` on every feasible iteration overwrites Newton multipliers
7816        // that were converging, the dual never settles, and the step
7817        // vanishes short of the certificate.
7818        //
7819        // So the feature is available and off by default. That still
7820        // closes the gap that mattered — until #677 the option was
7821        // refused outright as unimplemented, so an L-BFGS user could not
7822        // reach Ipopt's behaviour at all. They can now, by asking.
7823        //
7824        // Why it is worth having: a quasi-Newton model's dual step is
7825        // computed from an approximate `W`, so L-BFGS can settle a
7826        // feasible primal and still not drive `inf_du` to tolerance —
7827        // the failure a 59,939-variable CasADi model hit, oscillating
7828        // `inf_du` between 3.6e-3 and 1.8e+01 for 300 iterations with
7829        // the objective already settled. On that shape it is the fix;
7830        // on a corpus of small well-conditioned models it is a
7831        // pessimisation. Matching upstream's conditional default needs
7832        // to explain the 7 regressions first.
7833        if let Ok((v, true)) = self.options.get_string_value("recalc_y", "") {
7834            builder.recalc_y = v == "yes";
7835        }
7836        if let Ok((v, true)) = self.options.get_numeric_value("recalc_y_feas_tol", "") {
7837            builder.recalc_y_feas_tol = v;
7838        }
7839        // `limited_memory_init_val` — σ before any curvature pair exists,
7840        // and every iteration under `constant`. Also unread until #677;
7841        // the empty-history branch hard-coded the same `1.0`.
7842        if let Ok((v, true)) = self
7843            .options
7844            .get_numeric_value("limited_memory_init_val", "")
7845        {
7846            builder.limited_memory_init_val = v;
7847        }
7848        // `limited_memory_max_skipping` (#686) — registered and unread,
7849        // and the feature behind it did not exist either: the updater
7850        // counted nothing and never discarded its history.
7851        if let Ok((v, true)) = self
7852            .options
7853            .get_integer_value("limited_memory_max_skipping", "")
7854        {
7855            if v >= 0 {
7856                builder.limited_memory_max_skipping = v as Index;
7857            }
7858        }
7859        if let Ok((v, found)) = self.options.get_string_value("line_search_method", "") {
7860            if found {
7861                builder.line_search_method = match v.as_str() {
7862                    // Unreachable from a real solve since gh#981:
7863                    // `cg-penalty` is refused by
7864                    // `unimplemented_options::UNIMPLEMENTED_VALUES`
7865                    // before the builder is configured, because the
7866                    // variant assembles the plain penalty acceptor.
7867                    "cg-penalty" => LineSearchChoice::CgPenalty,
7868                    "penalty" => LineSearchChoice::Penalty,
7869                    _ => LineSearchChoice::Filter,
7870                };
7871            }
7872        }
7873        // `accept_every_trial_step` — direct user override. Parsed
7874        // after the Mehrotra cascade so an explicit `no` still wins.
7875        if let Ok((v, found)) = self.options.get_string_value("accept_every_trial_step", "") {
7876            if found {
7877                builder.line_search.accept_every_trial_step = v == "yes";
7878            }
7879        }
7880        // `alpha_for_y` — direct user override. Parsed after the
7881        // Mehrotra cascade so an explicit value still wins.
7882        if let Ok((v, found)) = self.options.get_string_value("alpha_for_y", "") {
7883            if found {
7884                use crate::line_search::backtracking::AlphaForY;
7885                builder.line_search.alpha_for_y = match v.as_str() {
7886                    "primal" => AlphaForY::Primal,
7887                    "bound-mult" | "bound_mult" => AlphaForY::BoundMult,
7888                    "full" => AlphaForY::Full,
7889                    "min" => AlphaForY::Min,
7890                    "max" => AlphaForY::Max,
7891                    "primal-and-full" | "dual-and-full" => AlphaForY::Primal,
7892                    _ => AlphaForY::Primal,
7893                };
7894            }
7895        }
7896        // `nlp_scaling_method` is consumed NLP-side in
7897        // `OrigIpoptNlp::determine_scaling_from_starting_point` (see the
7898        // `determine_scaling_from_starting_point` call earlier in this
7899        // method); there is no algorithm-side scaling strategy to wire.
7900        // `limited_memory_init_val_max` / `_min` — the clamp on the
7901        // initial Hessian scalar. `LimMemQuasiNewtonUpdater` consumes
7902        // both in `initial_hessian_scalar`; only the read sites were
7903        // missing, so setting either did nothing (gh#483, #191 round 2).
7904        if let Ok((v, true)) = self
7905            .options
7906            .get_numeric_value("limited_memory_init_val_max", "")
7907        {
7908            builder.limited_memory_init_val_max = v;
7909        }
7910        if let Ok((v, true)) = self
7911            .options
7912            .get_numeric_value("limited_memory_init_val_min", "")
7913        {
7914            builder.limited_memory_init_val_min = v;
7915        }
7916
7917        // Unlike the other options here, we always honor the registry
7918        // value (not just when the user set it explicitly): the option
7919        // registry default is "ma57" but `AlgorithmBuilder::default`
7920        // has `linear_solver: Feral`, so gating on `found` would
7921        // silently route default runs through Feral while the banner
7922        // (and ipopt-compatible behavior) advertises MA57.
7923        //
7924        // Record the **effective** backend, not the requested one. MA57 lives
7925        // behind the optional `ma57` cargo feature (HSL is licensed and needs a
7926        // Fortran toolchain); without it `default_backend_factory` silently
7927        // substitutes FERAL. Storing `Ma57` here therefore made
7928        // `builder.linear_solver` disagree with the backend actually built, and
7929        // consumers acted on the lie: the Schur KKT gate in
7930        // `alg_builder::build_with_backend` tests `== Feral`, so on the
7931        // pure-Rust default build — where the registry default (then upstream's
7932        // "ma57") resolved to FERAL anyway — `set_kkt_schur_block()` silently
7933        // never engaged for ANY user. Resolving here keeps the field truthful
7934        // for every consumer.
7935        //
7936        // The `_ =>` arm is now only reachable for `feral`: every other name
7937        // is refused up front by `unimplemented_linear_solver`. It used to
7938        // swallow `mumps`, `pardiso`, `ma97`, … and run FERAL instead.
7939        if let Ok((v, _found)) = self.options.get_string_value("linear_solver", "") {
7940            let requested = if v.eq_ignore_ascii_case("ma57") {
7941                LinearSolverChoice::Ma57
7942            } else {
7943                LinearSolverChoice::Feral
7944            };
7945            builder.linear_solver =
7946                if matches!(requested, LinearSolverChoice::Ma57) && !cfg!(feature = "ma57") {
7947                    LinearSolverChoice::Feral
7948                } else {
7949                    requested
7950                };
7951        }
7952
7953        // `linear_system_scaling` — symmetric scaling of the augmented
7954        // KKT matrix before factorization. Port of
7955        // `IpTSymLinearSolver.cpp:RegisterOptions` plumbing. Default
7956        // "none"; "ruiz" invokes the Ruiz-2001 symmetric ∞-norm
7957        // equilibration in `RuizTSymScalingMethod`. "mc19" and
7958        // "slack-based" are accepted by the registry but not yet
7959        // implemented at this layer; they fall back to no scaling
7960        // with a one-line notice.
7961        //
7962        // `slack-based` is implemented as of #677. It used to reach the
7963        // no-scaling fallback through the catch-all arm, which meant it
7964        // fell back **silently** — the comment above promised a notice
7965        // that only `mc19` actually emitted. It is not a hypothetical
7966        // value: it is what Ipopt's own recommended configuration for
7967        // large collocation NLPs uses, so the users most likely to set
7968        // it were the least likely to be told it did nothing. The
7969        // catch-all is left for genuinely unreachable input —
7970        // `OptionsList` rejects anything the registry does not list.
7971        if let Ok((v, found)) = self.options.get_string_value("linear_system_scaling", "") {
7972            if found {
7973                builder.linear_system_scaling = match v.as_str() {
7974                    "ruiz" => crate::alg_builder::LinearSystemScalingChoice::Ruiz,
7975                    "mc19" => crate::alg_builder::LinearSystemScalingChoice::Mc19,
7976                    "slack-based" => crate::alg_builder::LinearSystemScalingChoice::SlackBased,
7977                    _ => crate::alg_builder::LinearSystemScalingChoice::None,
7978                };
7979            }
7980        }
7981        if let Ok((v, found)) = self.options.get_bool_value("linear_scaling_on_demand", "") {
7982            if found {
7983                builder.linear_scaling_on_demand = v;
7984            }
7985        }
7986
7987        // Convergence tolerances (port of `IpOptErrorConvCheck.cpp`'s
7988        // `RegisterOptions` consumers). Defaults already match upstream
7989        // — only override when the user set the key explicitly.
7990        let read_num = |key: &str| -> Option<f64> {
7991            self.options
7992                .get_numeric_value(key, "")
7993                .ok()
7994                .and_then(|(v, f)| f.then_some(v))
7995        };
7996        let read_int = |key: &str| -> Option<i32> {
7997            self.options
7998                .get_integer_value(key, "")
7999                .ok()
8000                .and_then(|(v, f)| f.then_some(v))
8001        };
8002        if let Some(v) = read_num("tol") {
8003            builder.conv_check.tol = v;
8004        }
8005        if let Some(v) = read_num("obj_scale_certificate_threshold") {
8006            builder.conv_check.obj_scale_certificate_threshold = v;
8007        }
8008        if let Some(v) = read_num("primal_noise_floor_kappa") {
8009            builder.conv_check.primal_noise_floor_kappa = v;
8010        }
8011        if let Some(v) = read_num("acceptable_progress_kappa") {
8012            builder.conv_check.acceptable_progress_kappa = v;
8013        }
8014        if let Some(v) = read_num("dual_inf_scale_kappa") {
8015            builder.conv_check.dual_inf_scale_kappa = v;
8016        }
8017        if let Some(v) = read_num("kkt_fidelity_tol") {
8018            builder.kkt_fidelity_tol = v;
8019        }
8020        if let Some(v) = read_num("dual_inf_tol") {
8021            builder.conv_check.dual_inf_tol = v;
8022            // gh#983 item 1: a caller who names `dual_inf_tol` has asked for
8023            // that absolute standard. The scale-relative floor (gh#532) is a
8024            // default for a caller who has not, and it let `1e-6` certify a
8025            // point with `‖∇L‖∞ = 0.144` because the multipliers were 3.5e9
8026            // (a failed constraint qualification, which is not a reason to
8027            // loosen the test). Naming `dual_inf_scale_kappa` as well opts the
8028            // floor back in.
8029            //
8030            // gh#983 review: a value equal to the registered default is read
8031            // as "not named". Front ends that echo every default (option
8032            // files copied from Ipopt's documentation, wrappers that pass the
8033            // full table) would otherwise lose the gh#532 floor without asking
8034            // for anything. That is safe because the floor with the default
8035            // tolerance IS the default behaviour; a caller who wants the
8036            // absolute standard at `1` names `dual_inf_scale_kappa 0`, which
8037            // the option help documents.
8038            let default_tol = crate::alg_builder::ConvCheckOptions::default().dual_inf_tol;
8039            if read_num("dual_inf_scale_kappa").is_none() && v != default_tol {
8040                builder.conv_check.dual_inf_scale_kappa = 0.0;
8041            }
8042        }
8043        if let Some(v) = read_num("constr_viol_tol") {
8044            builder.conv_check.constr_viol_tol = v;
8045        }
8046        if let Some(v) = read_num("compl_inf_tol") {
8047            builder.conv_check.compl_inf_tol = v;
8048        }
8049        if let Some(v) = read_int("max_iter") {
8050            builder.conv_check.max_iter = v;
8051        }
8052        if let Some(v) = read_num("max_cpu_time") {
8053            builder.conv_check.max_cpu_time = v;
8054        }
8055        if let Some(v) = read_num("max_wall_time") {
8056            builder.conv_check.max_wall_time = v;
8057        }
8058        if let Some(v) = read_num("acceptable_tol") {
8059            builder.conv_check.acceptable_tol = v;
8060        }
8061        if let Some(v) = read_num("acceptable_dual_inf_tol") {
8062            builder.conv_check.acceptable_dual_inf_tol = v;
8063        }
8064        if let Some(v) = read_num("acceptable_constr_viol_tol") {
8065            builder.conv_check.acceptable_constr_viol_tol = v;
8066        }
8067        if let Some(v) = read_num("acceptable_compl_inf_tol") {
8068            builder.conv_check.acceptable_compl_inf_tol = v;
8069        }
8070        if let Some(v) = read_num("acceptable_obj_change_tol") {
8071            builder.conv_check.acceptable_obj_change_tol = v;
8072        }
8073        if let Some(v) = read_int("acceptable_iter") {
8074            builder.conv_check.acceptable_iter = v;
8075        }
8076        if let Some(v) = read_num("infeas_stationarity_tol") {
8077            builder.conv_check.infeas_stationarity_tol = v;
8078        }
8079        if let Some(v) = read_num("infeas_viol_kappa") {
8080            builder.conv_check.infeas_viol_kappa = v;
8081        }
8082        if let Some(v) = read_int("infeas_max_streak") {
8083            builder.conv_check.infeas_max_streak = v;
8084        }
8085
8086        // Bound-multiplier / barrier damping constants (#191). Both were
8087        // registered but never read, so user overrides were silently
8088        // dropped; the algorithm ran with the hard-coded struct defaults.
8089        // Defaults equal the registered defaults, so this changes nothing
8090        // for a run that doesn't set them.
8091        if let Some(v) = read_num("kappa_sigma") {
8092            builder.kappa_sigma = v;
8093        }
8094        if let Some(v) = read_num("ftb_centrality_floor") {
8095            builder.ftb_centrality_floor = v;
8096        }
8097        if let Some(v) = read_num("kappa_d") {
8098            builder.kappa_d = v;
8099        }
8100        // `s_max` — the cap in the `(s_d, s_c)` scaling of the KKT error
8101        // test (#551 / #677). `IpoptCalculatedQuantities` carried it as a
8102        // hard-coded 100 (the registered default) and nothing read the
8103        // option; a run that does not set it is unaffected.
8104        if let Some(v) = read_num("s_max") {
8105            builder.s_max = v;
8106        }
8107        if let Some(v) = read_num("tiny_step_tol") {
8108            builder.tiny_step_tol = v;
8109        }
8110        if let Some(v) = read_num("tiny_step_y_tol") {
8111            builder.tiny_step_y_tol = v;
8112        }
8113        if let Some(v) = read_num("diverging_iterates_tol") {
8114            builder.diverging_iterates_tol = v;
8115        }
8116        if let Some(v) = read_int("dual_diverging_streak") {
8117            builder.dual_diverging_streak = v;
8118        }
8119        if let Some(v) = read_num("dual_divergence_retry_step_tol") {
8120            builder.dual_divergence_retry_step_tol = v;
8121        }
8122        if let Some(v) = read_num("dual_divergence_retry_du_floor") {
8123            builder.dual_divergence_retry_du_floor = v;
8124        }
8125        if let Some(v) = read_int("tiny_step_dual_stall_iters") {
8126            builder.tiny_step_dual_stall_iters = v;
8127        }
8128        if let Some(v) = read_int("resto_decline_deferrals") {
8129            builder.resto_decline_deferrals = v;
8130        }
8131        if let Some(v) = read_num("resto_decline_progress_ratio") {
8132            builder.resto_decline_progress_ratio = v;
8133        }
8134        if let Some(v) = read_int("neg_curv_escapes") {
8135            builder.neg_curv_escapes = v;
8136        }
8137        if let Some(v) = read_int("limited_memory_ls_failure_restarts") {
8138            builder.limited_memory_ls_failure_restarts = v;
8139        }
8140
8141        // Barrier-parameter (μ) options — consumers in
8142        // `IpMonotoneMuUpdate.cpp` / `IpAdaptiveMuUpdate.cpp`. Both
8143        // updaters share the same option names; the builder forwards
8144        // each into whichever strategy is assembled.
8145        if let Some(v) = read_num("mu_init") {
8146            builder.mu.mu_init = v;
8147        }
8148        if let Some(v) = read_num("mu_max") {
8149            builder.mu.mu_max = v;
8150        }
8151        if let Some(v) = read_num("mu_max_fact") {
8152            builder.mu.mu_max_fact = v;
8153        }
8154        if let Some(v) = read_num("mu_min") {
8155            builder.mu.mu_min = v;
8156        }
8157        if let Some(v) = read_num("mu_target") {
8158            builder.mu.mu_target = v;
8159        }
8160        if let Some(v) = read_num("mu_linear_decrease_factor") {
8161            builder.mu.mu_linear_decrease_factor = v;
8162        }
8163        if let Some(v) = read_num("mu_superlinear_decrease_power") {
8164            builder.mu.mu_superlinear_decrease_power = v;
8165        }
8166        if let Ok((v, found)) = self
8167            .options
8168            .get_string_value("mu_allow_fast_monotone_decrease", "")
8169        {
8170            if found {
8171                builder.mu.mu_allow_fast_monotone_decrease = v == "yes";
8172            }
8173        }
8174        if let Some(v) = read_num("barrier_tol_factor") {
8175            builder.mu.barrier_tol_factor = v;
8176        }
8177        // `tau_min` — floor on the fraction-to-the-boundary parameter
8178        // (#551 / #677). Both `MonotoneMuUpdate` and `AdaptiveMuUpdate`
8179        // carried the field with upstream's 0.99 default and nothing
8180        // read the option, so an override was silently dropped. The
8181        // default equals the registered default, so this changes
8182        // nothing for a run that does not set it.
8183        if let Some(v) = read_num("tau_min") {
8184            builder.mu.tau_min = v;
8185        }
8186        if let Some(v) = read_num("sigma_max") {
8187            builder.mu.sigma_max = v;
8188        }
8189        if let Some(v) = read_num("sigma_min") {
8190            builder.mu.sigma_min = v;
8191        }
8192
8193        // Quality-function oracle knobs — consumers in
8194        // `IpQualityFunctionMuOracle.cpp:RegisterOptions`. Forwarded
8195        // to the oracle on every free-mode call.
8196        if let Ok((v, found)) = self
8197            .options
8198            .get_string_value("quality_function_norm_type", "")
8199        {
8200            if found {
8201                use crate::mu::oracle::quality_function::NormType;
8202                builder.mu.quality_function_norm_type = match v.as_str() {
8203                    "1-norm" => NormType::OneNorm,
8204                    "2-norm" => NormType::TwoNorm,
8205                    "max-norm" => NormType::MaxNorm,
8206                    _ => NormType::TwoNormSquared,
8207                };
8208            }
8209        }
8210        if let Ok((v, found)) = self
8211            .options
8212            .get_string_value("quality_function_centrality", "")
8213        {
8214            if found {
8215                use crate::mu::oracle::quality_function::CentralityType;
8216                builder.mu.quality_function_centrality = match v.as_str() {
8217                    "log" => CentralityType::LogCenter,
8218                    "reciprocal" => CentralityType::ReciprocalCenter,
8219                    "cubed-reciprocal" => CentralityType::CubedReciprocalCenter,
8220                    _ => CentralityType::None,
8221                };
8222            }
8223        }
8224        if let Ok((v, found)) = self
8225            .options
8226            .get_string_value("quality_function_balancing_term", "")
8227        {
8228            if found {
8229                use crate::mu::oracle::quality_function::BalancingTermType;
8230                builder.mu.quality_function_balancing_term = match v.as_str() {
8231                    "cubic" => BalancingTermType::CubicTerm,
8232                    _ => BalancingTermType::None,
8233                };
8234            }
8235        }
8236        if let Some(v) = read_int("quality_function_max_section_steps") {
8237            builder.mu.quality_function_max_section_steps = v;
8238        }
8239        if let Some(v) = read_num("quality_function_section_sigma_tol") {
8240            builder.mu.quality_function_section_sigma_tol = v;
8241        }
8242        if let Some(v) = read_num("quality_function_section_qf_tol") {
8243            builder.mu.quality_function_section_qf_tol = v;
8244        }
8245
8246        // `probing_iterate_quality_factor` — pounce-specific guard
8247        // (pounce#58) on the probing μ-oracle's input iterate. When
8248        // `curr_avrg_compl / curr_mu` exceeds this factor, the
8249        // μ-update layer signals restoration via
8250        // `IpoptData::request_resto` instead of letting probing
8251        // return `σ · mu_curr` ≫ previous μ. Default 1e4; set to ≤ 0
8252        // to disable. No upstream Ipopt counterpart.
8253        if let Some(v) = read_num("probing_iterate_quality_factor") {
8254            builder.mu.probing_iterate_quality_factor = v;
8255        }
8256
8257        // Adaptive-μ extras — consumers in
8258        // `IpAdaptiveMuUpdate.cpp:RegisterOptions`. Only active when
8259        // `mu_strategy=adaptive`.
8260        if let Some(v) = read_num("adaptive_mu_safeguard_factor") {
8261            builder.mu.adaptive_mu_safeguard_factor = v;
8262        }
8263        if let Some(v) = read_num("adaptive_mu_monotone_init_factor") {
8264            builder.mu.adaptive_mu_monotone_init_factor = v;
8265        }
8266        if let Ok((v, found)) = self
8267            .options
8268            .get_bool_value("adaptive_mu_restore_previous_iterate", "")
8269        {
8270            if found {
8271                builder.mu.adaptive_mu_restore_previous_iterate = v;
8272            }
8273        }
8274        if let Some(v) = read_int("adaptive_mu_max_free_returns") {
8275            builder.mu.adaptive_mu_max_free_returns = v;
8276        }
8277        if let Some(v) = read_num("adaptive_mu_budget_pin_fraction") {
8278            builder.mu.adaptive_mu_budget_pin_fraction = v;
8279        }
8280        if let Some(v) = read_int("adaptive_mu_kkterror_red_iters") {
8281            if v >= 0 {
8282                builder.mu.adaptive_mu_kkterror_red_iters = v as usize;
8283            }
8284        }
8285        if let Some(v) = read_num("adaptive_mu_kkterror_red_fact") {
8286            builder.mu.adaptive_mu_kkterror_red_fact = v;
8287        }
8288        // `filter_margin_fact` / `filter_max_margin` (#551) — the margin
8289        // an entry must clear in the `obj-constr-filter` globalization
8290        // test. `AdaptiveMuUpdate` computes
8291        // `filter_margin_fact * min(filter_max_margin, err)` and has
8292        // always done so; only these two read sites were missing, so
8293        // setting either did nothing. Defaults equal the registered
8294        // defaults (1e-5 / 1.0), so an unset run is unchanged.
8295        if let Some(v) = read_num("filter_margin_fact") {
8296            builder.mu.filter_margin_fact = v;
8297        }
8298        if let Some(v) = read_num("filter_max_margin") {
8299            builder.mu.filter_max_margin = v;
8300        }
8301        if let Ok((v, found)) = self
8302            .options
8303            .get_string_value("adaptive_mu_kkt_norm_type", "")
8304        {
8305            if found {
8306                use crate::mu::adaptive::AdaptiveMuKktNorm;
8307                builder.mu.adaptive_mu_kkt_norm_type = match v.as_str() {
8308                    "1-norm" => AdaptiveMuKktNorm::OneNorm,
8309                    "2-norm" => AdaptiveMuKktNorm::TwoNorm,
8310                    "max-norm" => AdaptiveMuKktNorm::MaxNorm,
8311                    _ => AdaptiveMuKktNorm::TwoNormSquared,
8312                };
8313            }
8314        }
8315
8316        // Watchdog options — consumers in
8317        // `IpBacktrackingLineSearch.cpp:RegisterOptions`. Baked into
8318        // the `BacktrackingLineSearch` at build time.
8319        if let Some(v) = read_int("watchdog_shortened_iter_trigger") {
8320            builder.line_search.watchdog_shortened_iter_trigger = v;
8321        }
8322        if let Some(v) = read_int("watchdog_trial_iter_max") {
8323            builder.line_search.watchdog_trial_iter_max = v;
8324        }
8325        if let Some(v) = read_num("soft_resto_pderror_reduction_factor") {
8326            builder.line_search.soft_resto_pderror_reduction_factor = v;
8327        }
8328        if let Some(v) = read_int("max_soft_resto_iters") {
8329            builder.line_search.max_soft_resto_iters = v;
8330        }
8331        // `alpha_red_factor` (#678) and `accept_after_max_steps` (#551)
8332        // — both consumed by the α-loop in `BacktrackingLineSearch`,
8333        // both registered without a read site until those issues.
8334        // `alpha_red_factor`'s default (0.5) equals the registered one,
8335        // and `accept_after_max_steps` defaults to `-1`, which disables
8336        // the escape hatch, so neither moves a solve that leaves them
8337        // alone.
8338        if let Some(v) = read_num("alpha_red_factor") {
8339            builder.line_search.alpha_red_factor = v;
8340        }
8341        if let Some(v) = read_num("alpha_red_factor_min") {
8342            builder.line_search.alpha_red_factor_min = Some(v);
8343        }
8344        if let Some(v) = read_int("accept_after_max_steps") {
8345            builder.line_search.accept_after_max_steps = v;
8346        }
8347
8348        // Filter switching / Armijo / margin constants (#191). Consumed
8349        // by `FilterLsAcceptor` (only on the `Filter` line-search path);
8350        // registered but never read, so overrides were silently dropped.
8351        // Defaults equal the registered defaults.
8352        if let Some(v) = read_num("eta_phi") {
8353            builder.line_search.eta_phi = v;
8354        }
8355        // `delta` (#551) — the switching rule's multiplier on the
8356        // constraint violation (Eqn. (19)); `FilterLsAcceptor` has
8357        // always used it as `delta_armijo`, only the read site was
8358        // missing. Default 1.0 equals the registered default.
8359        if let Some(v) = read_num("delta") {
8360            builder.line_search.delta = v;
8361        }
8362        if let Some(v) = read_num("theta_min_fact") {
8363            builder.line_search.theta_min_fact = v;
8364        }
8365        if let Some(v) = read_num("theta_max_row_scale_kappa") {
8366            builder.line_search.theta_max_row_scale_kappa = v;
8367        }
8368        if let Some(v) = read_int("theta_max_adaptive_trigger") {
8369            builder.line_search.theta_max_adaptive_trigger = v.max(0) as u32;
8370        }
8371        if let Some(v) = read_num("theta_max_adaptive_factor") {
8372            builder.line_search.theta_max_adaptive_factor = v;
8373        }
8374        if let Some(v) = read_int("theta_max_adaptive_max_raises") {
8375            builder.line_search.theta_max_adaptive_max_raises = v.max(0) as u32;
8376        }
8377        if let Some(v) = read_num("theta_max_fact") {
8378            builder.line_search.theta_max_fact = v;
8379        }
8380        if let Some(v) = read_num("gamma_phi") {
8381            builder.line_search.gamma_phi = v;
8382        }
8383        if let Some(v) = read_num("gamma_theta") {
8384            builder.line_search.gamma_theta = v;
8385        }
8386        if let Some(v) = read_num("s_phi") {
8387            builder.line_search.s_phi = v;
8388        }
8389        if let Some(v) = read_num("s_theta") {
8390            builder.line_search.s_theta = v;
8391        }
8392        if let Some(v) = read_num("alpha_min_frac") {
8393            builder.line_search.alpha_min_frac = v;
8394        }
8395        if let Some(v) = read_num("obj_max_inc") {
8396            builder.line_search.obj_max_inc = v;
8397        }
8398        if let Some(v) = read_int("max_filter_resets") {
8399            builder.line_search.max_filter_resets = v;
8400        }
8401        if let Some(v) = read_int("filter_reset_trigger") {
8402            builder.line_search.filter_reset_trigger = v;
8403        }
8404        // `filter_theta_roundoff_retry` (gh#945).
8405        if let Ok((v, true)) = self
8406            .options
8407            .get_bool_value("filter_theta_roundoff_retry", "")
8408        {
8409            builder.line_search.filter_theta_roundoff_retry = v;
8410        }
8411        // `objective_noise_wolfe` (gh#1016).
8412        if let Ok((v, true)) = self.options.get_bool_value("objective_noise_wolfe", "") {
8413            builder.line_search.objective_noise_wolfe = v;
8414        }
8415        // Penalty line-search constants (#551), consumed by
8416        // `PenaltyLsAcceptor` (only on the `line_search_method=penalty`
8417        // / `cg-penalty` paths). The acceptor implements ν and the
8418        // Armijo test on the penalty merit function already; these four
8419        // were registered with no read site, so tuning the penalty
8420        // update did nothing. Defaults equal the registered defaults.
8421        if let Some(v) = read_num("nu_init") {
8422            builder.line_search.nu_init = v;
8423        }
8424        if let Some(v) = read_num("nu_inc") {
8425            builder.line_search.nu_inc = v;
8426        }
8427        if let Some(v) = read_num("rho") {
8428            builder.line_search.rho = v;
8429        }
8430        if let Some(v) = read_num("eta_penalty") {
8431            builder.line_search.eta_penalty = v;
8432        }
8433
8434        // Second-order-correction constants (#191), consumed by
8435        // `BacktrackingLineSearch`. `max_soc = 0` disables SOC.
8436        if let Some(v) = read_int("max_soc") {
8437            builder.line_search.max_soc = v;
8438        }
8439        if let Some(v) = read_num("kappa_soc") {
8440            builder.line_search.kappa_soc = v;
8441        }
8442        if let Some(v) = read_int("soc_method") {
8443            builder.line_search.soc_method = v;
8444        }
8445
8446        // Inertia-correction / Jacobian-regularization constants (#191),
8447        // consumed by `PdPerturbationHandler`. Registered but never read.
8448        if let Some(v) = read_num("max_hessian_perturbation") {
8449            builder.perturbation.max_hessian_perturbation = v;
8450        }
8451        if let Some(v) = read_num("min_hessian_perturbation") {
8452            builder.perturbation.min_hessian_perturbation = v;
8453        }
8454        if let Some(v) = read_num("perturb_inc_fact_first") {
8455            builder.perturbation.perturb_inc_fact_first = v;
8456        }
8457        if let Some(v) = read_num("perturb_inc_fact") {
8458            builder.perturbation.perturb_inc_fact = v;
8459        }
8460        if let Some(v) = read_num("perturb_dec_fact") {
8461            builder.perturbation.perturb_dec_fact = v;
8462        }
8463        if let Some(v) = read_num("first_hessian_perturbation") {
8464            builder.perturbation.first_hessian_perturbation = v;
8465        }
8466        if let Some(v) = read_num("jacobian_regularization_value") {
8467            builder.perturbation.jacobian_regularization_value = v;
8468        }
8469        if let Some(v) = read_num("jacobian_regularization_exponent") {
8470            builder.perturbation.jacobian_regularization_exponent = v;
8471        }
8472        if let Ok((v, true)) = self.options.get_bool_value("perturb_always_cd", "") {
8473            builder.perturbation.perturb_always_cd = v;
8474        }
8475        if let Some(v) = read_int("perturb_delta_c_max_rungs") {
8476            builder.perturbation.perturb_delta_c_max_rungs = v;
8477        }
8478        if let Some(v) = read_num("perturb_slack_fact") {
8479            builder.perturbation.perturb_slack_fact = v;
8480        }
8481        if let Some(v) = read_int("perturb_slack_max_rows") {
8482            builder.perturbation.perturb_slack_max_rows = v;
8483        }
8484
8485        // Iterative-refinement constants (#191), consumed by
8486        // `PdFullSpaceSolver`. Registered but never read.
8487        if let Some(v) = read_int("min_refinement_steps") {
8488            builder.refinement.min_refinement_steps = v;
8489        }
8490        if let Some(v) = read_int("max_refinement_steps") {
8491            builder.refinement.max_refinement_steps = v;
8492        }
8493        if let Some(v) = read_num("residual_ratio_max") {
8494            builder.refinement.residual_ratio_max = v;
8495        }
8496        if let Some(v) = read_num("residual_ratio_singular") {
8497            builder.refinement.residual_ratio_singular = v;
8498        }
8499        if let Some(v) = read_num("residual_improvement_factor") {
8500            builder.refinement.residual_improvement_factor = v;
8501        }
8502
8503        // Inertia-free curvature test (#551 / #677), also consumed by
8504        // `PdFullSpaceSolver`. `neg_curv_test_tol` had a field that only
8505        // ever held its 0.0 default, and `neg_curv_test_reg` had none at
8506        // all; both are now read, and the curvature test they configure
8507        // is implemented in `PdFullSpaceSolver::solve_once`. At the
8508        // registered default (`0.0`) the heuristic is off and the
8509        // inertia check runs as before.
8510        if let Some(v) = read_num("neg_curv_test_tol") {
8511            builder.refinement.neg_curv_test_tol = v;
8512        }
8513        if let Ok((v, true)) = self.options.get_bool_value("neg_curv_test_reg", "") {
8514            builder.refinement.neg_curv_test_reg = v;
8515        }
8516
8517        // Restoration-phase constants (#191). Carried on the outer builder
8518        // and copied into the `RestoAlgorithmBuilder` when the restoration
8519        // factory is minted (the frontends pass this builder in). The
8520        // restoration builder was never options-configured, so these were
8521        // registered but never read. Defaults equal the registered
8522        // defaults.
8523        if let Some(v) = read_num("bound_mult_reset_threshold") {
8524            builder.resto.bound_mult_reset_threshold = v;
8525        }
8526        if let Some(v) = read_num("constr_mult_reset_threshold") {
8527            builder.resto.constr_mult_reset_threshold = v;
8528        }
8529        if let Some(v) = read_num("resto_penalty_parameter") {
8530            builder.resto.resto_penalty_parameter = v;
8531        }
8532        if let Some(v) = read_num("resto_proximity_weight") {
8533            builder.resto.resto_proximity_weight = v;
8534        }
8535        // `required_infeasibility_reduction` (#439) — the κ_resto guard the
8536        // restoration sub-solve exits on. Registered since #191 but the
8537        // value was hardcoded at the callsite, so setting it was a silent
8538        // no-op.
8539        if let Some(v) = read_num("required_infeasibility_reduction") {
8540            builder.resto.required_infeasibility_reduction = v;
8541        }
8542        // gh#483 / #191 round 2: three restoration switches whose fields
8543        // `RestoAlgorithmBuilder` has consumed all along — the read site
8544        // was the only missing piece, so setting them did nothing.
8545        let read_yes = |key: &str| -> Option<bool> {
8546            match self.options.get_string_value(key, "") {
8547                Ok((v, true)) => Some(v.eq_ignore_ascii_case("yes")),
8548                _ => None,
8549            }
8550        };
8551        if let Some(v) = read_yes("evaluate_orig_obj_at_resto_trial") {
8552            builder.resto.evaluate_orig_obj_at_resto_trial = v;
8553        }
8554        if let Some(v) = read_yes("expect_infeasible_problem") {
8555            builder.resto.expect_infeasible_problem = v;
8556        }
8557        if let Some(v) = read_yes("start_with_resto") {
8558            builder.resto.start_with_resto = v;
8559        }
8560        // `max_resto_iter` (#551 / #677) — the cap on *successive*
8561        // restoration iterations. `RestoConvCheckAdapter` has enforced a cap
8562        // all along (returning `MaxIterExceeded` at the limit); the number
8563        // it enforced was a hard-coded constant in `resto_inner_solver.rs`,
8564        // so setting the option did nothing. The consumer's field is
8565        // `maximum_resto_iters`, not the option name — grepping for
8566        // `max_resto_iter` found only the registry (#551 caution 2).
8567        //
8568        // DEFAULT MISMATCH, LEFT AS IT IS ON PURPOSE: the registry declares
8569        // upstream's 3000000, pounce's effective cap is 3000
8570        // (`RestoOptions::default`). `read_int` fires only when the user set
8571        // the key, so an unset `max_resto_iter` still means 3000 and this
8572        // wiring is trajectory-neutral. Adopting upstream's number would let
8573        // restorations pounce currently truncates run on, which is a
8574        // trajectory change and needs its own measurement.
8575        if let Some(v) = read_int("max_resto_iter") {
8576            builder.resto.max_resto_iter = v;
8577        }
8578
8579        // Iteration-output options — consumed by `OrigIterationOutput`.
8580        if let Some(v) = read_int("print_frequency_iter") {
8581            builder.output.print_frequency_iter = v;
8582        }
8583        if let Some(v) = read_num("print_frequency_time") {
8584            builder.output.print_frequency_time = v;
8585        }
8586        if let Ok((v, found)) = self.options.get_bool_value("print_info_string", "") {
8587            if found {
8588                builder.output.print_info_string = v;
8589            }
8590        }
8591        if let Ok((v, found)) = self.options.get_string_value("inf_pr_output", "") {
8592            if found {
8593                builder.output.inf_pr_output_internal = v == "internal";
8594            }
8595        }
8596
8597        // Warm-start options — consumed by `WarmStartIterateInitializer`
8598        // (port of `IpWarmStartIterateInitializer.cpp:RegisterOptions`).
8599        // `warm_start_init_point` is the toggle that picks between the
8600        // default (cold) and warm-start initializers; the remaining
8601        // knobs are baked onto the chosen initializer at build time.
8602        if let Ok((v, found)) = self.options.get_bool_value("warm_start_init_point", "") {
8603            if found {
8604                builder.warm_start_init_point = v;
8605            }
8606        }
8607        if let Some(v) = read_num("warm_start_bound_push") {
8608            builder.warm.bound_push = v;
8609        }
8610        if let Some(v) = read_num("warm_start_bound_frac") {
8611            builder.warm.bound_frac = v;
8612        }
8613        if let Some(v) = read_num("warm_start_slack_bound_push") {
8614            builder.warm.slack_bound_push = v;
8615        }
8616        if let Some(v) = read_num("warm_start_slack_bound_frac") {
8617            builder.warm.slack_bound_frac = v;
8618        }
8619        if let Some(v) = read_num("warm_start_mult_bound_push") {
8620            builder.warm.mult_bound_push = v;
8621        }
8622        if let Some(v) = read_num("warm_start_mult_init_max") {
8623            builder.warm.mult_init_max = v;
8624        }
8625        if let Some(v) = read_num("warm_start_target_mu") {
8626            builder.warm.target_mu = v;
8627        }
8628        // gh#606: residual-adaptive recentering. `warm_start_entire_iterate`
8629        // and `warm_start_same_structure` used to be parsed here into
8630        // fields nothing read; they are refused by
8631        // `unimplemented_options` instead (they name the
8632        // `GetWarmStartIterate` TNLP surface pounce does not expose).
8633        if let Ok((v, found)) = self.options.get_string_value("warm_start_recentering", "") {
8634            if found {
8635                builder.warm.recentering = if v.eq_ignore_ascii_case("none") {
8636                    crate::alg_builder::WarmStartRecentering::None
8637                } else {
8638                    crate::alg_builder::WarmStartRecentering::Residual
8639                };
8640            }
8641        }
8642
8643        // `DefaultIterateInitializer` knobs — parsed after the Mehrotra
8644        // cascade so explicit user values win
8645        // (mirrors upstream's `SetNumericValueIfUnset` semantics).
8646        if let Some(v) = read_num("bound_push") {
8647            builder.init.bound_push = v;
8648        }
8649        if let Some(v) = read_num("bound_frac") {
8650            builder.init.bound_frac = v;
8651        }
8652        if let Some(v) = read_num("slack_bound_push") {
8653            builder.init.slack_bound_push = v;
8654        }
8655        if let Some(v) = read_num("slack_bound_frac") {
8656            builder.init.slack_bound_frac = v;
8657        }
8658        if let Some(v) = read_num("constr_mult_init_max") {
8659            builder.init.constr_mult_init_max = v;
8660        }
8661        if let Some(v) = read_num("bound_mult_init_val") {
8662            builder.init.bound_mult_init_val = v;
8663        }
8664        if let Ok((v, found)) = self.options.get_string_value("bound_mult_init_method", "") {
8665            if found {
8666                builder.init.bound_mult_init_method = v;
8667            }
8668        }
8669        if let Ok((v, found)) = self
8670            .options
8671            .get_string_value("least_square_init_primal", "")
8672        {
8673            if found {
8674                builder.init.least_square_init_primal = v == "yes";
8675            }
8676        }
8677        builder
8678    }
8679}
8680
8681/// Map the integer `print_level` / `file_print_level` option to the
8682/// matching [`JournalLevel`] variant. Mirrors upstream's
8683/// `static_cast<EJournalLevel>(int_value)` with clamping.
8684/// The eight block dimensions of an iterate, in canonical order
8685/// (x, s, y_c, y_d, z_l, z_u, v_l, v_u). Used to guard the debugger's
8686/// warm-restart install against a structural mismatch between solves.
8687fn iterates_dims(c: &IteratesVector) -> [i32; 8] {
8688    [
8689        c.x.dim(),
8690        c.s.dim(),
8691        c.y_c.dim(),
8692        c.y_d.dim(),
8693        c.z_l.dim(),
8694        c.z_u.dim(),
8695        c.v_l.dim(),
8696        c.v_u.dim(),
8697    ]
8698}
8699
8700fn journal_level_from_int(v: i32) -> JournalLevel {
8701    match v.clamp(0, 12) {
8702        0 => JournalLevel::J_NONE,
8703        1 => JournalLevel::J_ERROR,
8704        2 => JournalLevel::J_STRONGWARNING,
8705        3 => JournalLevel::J_SUMMARY,
8706        4 => JournalLevel::J_WARNING,
8707        5 => JournalLevel::J_ITERSUMMARY,
8708        6 => JournalLevel::J_DETAILED,
8709        7 => JournalLevel::J_MOREDETAILED,
8710        8 => JournalLevel::J_VECTOR,
8711        9 => JournalLevel::J_MOREVECTOR,
8712        10 => JournalLevel::J_MATRIX,
8713        11 => JournalLevel::J_MOREMATRIX,
8714        _ => JournalLevel::J_ALL,
8715    }
8716}
8717
8718/// MA57 backend knobs snapshotted off an `OptionsList`, ready to be
8719/// handed to a backend factory.
8720///
8721/// The type exists — rather than passing `pounce_hsl::Ma57Options`
8722/// directly — so that the factory signature is the same shape whether or
8723/// not the `ma57` cargo feature is on. `pounce-py`, `pounce-cinterface`
8724/// and `pounce-restoration` all call [`default_backend_factory`] and none
8725/// of them can name a `pounce-hsl` type; without the feature this struct
8726/// carries nothing and costs nothing.
8727///
8728/// Build it with [`ma57_config_from_options`]. It is the MA57 half of
8729/// what [`feral_config_from_options`] does for FERAL, and the asymmetry
8730/// between the two was the root cause of gh#825: FERAL's knobs were
8731/// threaded into the factory and MA57's were not, so the factory had
8732/// nothing to give MA57 and called `Ma57SolverInterface::new()` — which
8733/// hard-codes the defaults. Every `ma57_*` option was registered,
8734/// documented, accepted, and then silently discarded.
8735#[derive(Debug, Clone, Default)]
8736pub struct Ma57Config {
8737    #[cfg(feature = "ma57")]
8738    opts: pounce_hsl::Ma57Options,
8739}
8740
8741impl Ma57Config {
8742    /// The wrapped MA57 settings.
8743    #[cfg(feature = "ma57")]
8744    pub fn options(&self) -> &pounce_hsl::Ma57Options {
8745        &self.opts
8746    }
8747}
8748
8749/// Read the `ma57_*` options off `options` under `prefix`, for handing
8750/// to [`default_backend_factory`] / [`default_backend_factory_with_sink`].
8751///
8752/// `prefix` is `""` for the main IPM and `"resto."` for the restoration
8753/// sub-IPM, mirroring upstream's
8754/// `Ma57TSolverInterface::InitializeImpl(options, prefix)`. The
8755/// restoration sub-IPM builds its own backend through its own
8756/// `InnerBackendFactoryFactory` (see
8757/// `pounce_restoration::resto_inner_solver`), so the two really are
8758/// separately configurable — before gh#825 neither was.
8759///
8760/// Without the `ma57` cargo feature this returns an empty config and
8761/// does not touch `options`; nothing downstream can consume MA57
8762/// settings in that build.
8763pub fn ma57_config_from_options(
8764    options: &pounce_common::options_list::OptionsList,
8765    prefix: &str,
8766) -> Ma57Config {
8767    #[cfg(feature = "ma57")]
8768    {
8769        Ma57Config {
8770            opts: pounce_hsl::Ma57Options::from_options_list(options, prefix),
8771        }
8772    }
8773    #[cfg(not(feature = "ma57"))]
8774    {
8775        let _ = (options, prefix);
8776        Ma57Config::default()
8777    }
8778}
8779
8780/// Construct the MA57 backend for a factory, or fall back to FERAL when
8781/// the `ma57` cargo feature is off.
8782///
8783/// Factored out of the two factories below so there is exactly one place
8784/// that decides how an MA57 backend is built from a [`Ma57Config`]. Both
8785/// factories used to inline `Ma57SolverInterface::new()`, and the
8786/// duplication is half of why gh#825 was easy to miss.
8787fn make_ma57_backend(
8788    ma57_cfg: &Ma57Config,
8789    feral_fallback: impl FnOnce() -> Box<dyn SparseSymLinearSolverInterface>,
8790) -> Box<dyn SparseSymLinearSolverInterface> {
8791    #[cfg(feature = "ma57")]
8792    {
8793        let _ = feral_fallback;
8794        Box::new(pounce_hsl::Ma57SolverInterface::with_options(
8795            *ma57_cfg.options(),
8796        ))
8797    }
8798    #[cfg(not(feature = "ma57"))]
8799    {
8800        // ma57 feature not compiled in — fall back to FERAL.
8801        let _ = ma57_cfg;
8802        feral_fallback()
8803    }
8804}
8805
8806/// Default symmetric linear-solver factory, parameterized by the
8807/// pounce-extension FERAL knobs and the `ma57_*` knobs read off the
8808/// application's `OptionsList`.
8809///
8810/// FERAL (pure-Rust) is the shipping default. The HSL MA57 backend is
8811/// available when the `ma57` cargo feature is enabled; without it,
8812/// requesting `linear_solver = ma57` falls back to FERAL with a
8813/// warning printed by the journalist (see [`AlgorithmBuilder`]).
8814///
8815/// Both configs are snapshots, not live views: take them with
8816/// [`feral_config_from_options`] and [`ma57_config_from_options`] at the
8817/// point the application's options are fully populated. The factory is
8818/// called more than once per solve (the main KKT solver and, under
8819/// limited memory, the Hessian-free bypass solver), so each call gets a
8820/// fresh backend built from the same snapshot.
8821pub fn default_backend_factory(
8822    feral_cfg: pounce_feral::FeralConfig,
8823    ma57_cfg: Ma57Config,
8824) -> LinearBackendFactory {
8825    Box::new(
8826        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8827            match choice {
8828                LinearSolverChoice::Feral => Box::new(
8829                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone()),
8830                ),
8831                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8832                    Box::new(pounce_feral::FeralSolverInterface::with_config(
8833                        feral_cfg.clone(),
8834                    ))
8835                }),
8836            }
8837        },
8838    )
8839}
8840
8841/// Turn a model-space block declaration into the KKT-space labels the block
8842/// solver takes (structured-KKT Phase 5b's mapper, plan §63.6).
8843///
8844/// The KKT is laid out `[x | slacks | equality duals | inequality duals]`, so
8845/// each part inherits a label from what it belongs to:
8846///
8847/// * an `x` column takes its variable's label — skipping variables fixed out
8848///   by `fixed_variable_treatment`, which are not in the KKT at all;
8849/// * a slack and its inequality dual take their constraint's label;
8850/// * an equality dual takes its constraint's label.
8851///
8852/// `var_blocks` / `con_blocks` are in the model's own indexing (`n_full_x`,
8853/// `n_full_g`); negative means shared. Returns the label per KKT index, or an
8854/// error naming the mismatch — the caller then falls back rather than
8855/// mislabel, because a label that is off by one row silently declares a
8856/// structure the matrix does not have.
8857pub fn map_block_structure_to_kkt(
8858    cls: &pounce_nlp::tnlp_adapter::BoundClassification,
8859    var_blocks: &[i32],
8860    con_blocks: &[i32],
8861) -> Result<Vec<i32>, String> {
8862    if var_blocks.len() != cls.n_full_x as usize {
8863        return Err(format!(
8864            "block structure has {} variable labels, the problem has {} variables",
8865            var_blocks.len(),
8866            cls.n_full_x
8867        ));
8868    }
8869    if con_blocks.len() != cls.n_full_g as usize {
8870        return Err(format!(
8871            "block structure has {} constraint labels, the problem has {} constraints",
8872            con_blocks.len(),
8873            cls.n_full_g
8874        ));
8875    }
8876    let n_x = cls.x_not_fixed_map.len();
8877    let n_c = cls.c_map.len();
8878    let n_d = cls.d_map.len();
8879    let mut labels = Vec::with_capacity(n_x + 2 * n_d + n_c);
8880    for &full in &cls.x_not_fixed_map {
8881        labels.push(var_blocks[full as usize]);
8882    }
8883    for &full in &cls.d_map {
8884        labels.push(con_blocks[full as usize]); // slack
8885    }
8886    for &full in &cls.c_map {
8887        labels.push(con_blocks[full as usize]); // equality dual
8888    }
8889    for &full in &cls.d_map {
8890        labels.push(con_blocks[full as usize]); // inequality dual
8891    }
8892    Ok(labels)
8893}
8894
8895/// Sink-aware variant of [`default_backend_factory`]. Identical
8896/// dispatch, but the FERAL backend is constructed with a
8897/// `LinearSolverSummary` sink so [`IpoptApplication`] can read out
8898/// aggregate post-mortem stats (factor counts, fill ratio, extremal
8899/// pivots, final inertia) after the solve returns. MA57 ignores the
8900/// sink — the HSL backend doesn't carry the same instrumentation yet.
8901pub fn default_backend_factory_with_sink(
8902    feral_cfg: pounce_feral::FeralConfig,
8903    ma57_cfg: Ma57Config,
8904    sink: Arc<Mutex<LinearSolverSummary>>,
8905) -> LinearBackendFactory {
8906    Box::new(
8907        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
8908            match choice {
8909                LinearSolverChoice::Feral => Box::new(
8910                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8911                        .with_summary_sink(Arc::clone(&sink)),
8912                ),
8913                LinearSolverChoice::Ma57 => make_ma57_backend(&ma57_cfg, || {
8914                    Box::new(
8915                        pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone())
8916                            .with_summary_sink(Arc::clone(&sink)),
8917                    )
8918                }),
8919            }
8920        },
8921    )
8922}
8923
8924/// Read the `feral_*` extension options off `options`, falling
8925/// back to the env-var defaults baked into [`pounce_feral::FeralConfig::from_env`]
8926/// for any knob the caller did not set explicitly. The returned
8927/// config is what every default-factory invocation (main IPM and
8928/// restoration sub-IPM) consumes.
8929pub fn feral_config_from_options(
8930    options: &pounce_common::options_list::OptionsList,
8931) -> pounce_feral::FeralConfig {
8932    feral_config_from_options_scoped(options, RefineCarveOut::InteriorPoint)
8933}
8934
8935/// Whether [`feral_config_from_options_scoped`] applies the interior-point
8936/// arm's limited-memory `feral_refine` carve-out.
8937#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8938pub enum RefineCarveOut {
8939    /// Apply it: under `hessian_approximation=limited-memory`, force
8940    /// `refine = false` unless the user said otherwise. This is the shipped
8941    /// interior-point behaviour and what [`feral_config_from_options`] does.
8942    InteriorPoint,
8943    /// Skip it. For arms that do not refine the unreduced system themselves,
8944    /// where the backend loop is the only refinement in the stack.
8945    None,
8946}
8947
8948/// [`feral_config_from_options`] with the limited-memory `refine` carve-out
8949/// made explicit.
8950///
8951/// The carve-out is interior-point-specific in both of its premises, and
8952/// neither holds on the active-set SQP arm. It is justified by
8953/// `PdFullSpaceSolver::compute_residuals` already refining the *unreduced*
8954/// Newton system — the SQP arm has no such host loop, so
8955/// `pounce_qp::factor::LinearSolver` relies on the backend's own refinement
8956/// ("refinement is *implicit* in this layer", that module's docs) and turning
8957/// it off removes refinement from the stack entirely. And it keys off
8958/// `hessian_approximation`, which is not that arm's Hessian selector at all:
8959/// `sqp_hessian` is.
8960///
8961/// Measured, and this is why the parameter exists rather than the SQP path
8962/// just calling the plain function: inheriting the carve-out moved 10 of 97
8963/// fixtures on the sweep's L-BFGS leg under `algorithm=active-set-sqp`, while
8964/// the exact leg did not move at all. Some of that movement looked like a win
8965/// (`mu_fallback_point_floor` MaximumIterationsExceeded/200 ->
8966/// SolveSucceeded/8), but it was a win bought by disabling refinement for a
8967/// reason that does not apply here, and it came with `hs13_bigstart` landing
8968/// on a different point (objective 1 -> 1.0018) and `eigena2` and
8969/// `mpcc_scholtes4_biactive` likewise. Turning refinement off on this arm may
8970/// well be worth measuring on its own merits; it should not arrive as a side
8971/// effect of honouring `linear_solver`.
8972pub fn feral_config_from_options_scoped(
8973    options: &pounce_common::options_list::OptionsList,
8974    carve_out: RefineCarveOut,
8975) -> pounce_feral::FeralConfig {
8976    let mut cfg = pounce_feral::FeralConfig::from_env();
8977    // Tri-state: the `(_, true)` arm only fires when the user set the
8978    // option explicitly. Leaving it unset keeps `cfg.cascade_break` at
8979    // `None`, which inherits FERAL's `NumericParams::default()` (CB on
8980    // as of FERAL Phase B / pounce#55). `Some(false)` explicitly
8981    // disarms (reproduces pre-Phase-B behaviour, surfaces FERAL's
8982    // `DelayBudgetExceeded` on non-root cascade victims).
8983    if let Ok((v, true)) = options.get_bool_value("feral_cascade_break", "") {
8984        cfg.cascade_break = Some(v);
8985    }
8986    if let Ok((v, true)) = options.get_bool_value("feral_fma", "") {
8987        cfg.fma = v;
8988    }
8989    // Not tri-state, and deliberately not: on the limited-memory path
8990    // the IPM's default is the opposite of the library's (gh#710,
8991    // gh#698 obs 5). `FeralConfig` ships `refine = true` because a
8992    // caller that only refines its own system needs the backend loop.
8993    //
8994    // Scoped to limited-memory, because that is where the win was
8995    // measured and where it comes from. Under L-BFGS the Hessian-free
8996    // bypass batches the low-rank SMW correction into one multi-RHS
8997    // back-solve, and the backend loop refines per right-hand side, so
8998    // its cost scales with the memory depth — while what it polishes is
8999    // the *condensed* system, which is not where Waechter-Biegler 3.10
9000    // puts refinement. Turning it off takes `laptime` under
9001    // limited-memory from 1397 s to 394 s.
9002    //
9003    // The same switch is a net loss on the exact path, so it is not
9004    // applied there. It costs `NARX_CFy` 230 iterations (400 -> 630,
9005    // 173 s -> 250 s) to buy back 34 on `laptime` (380 -> 346). And the
9006    // exact path has no rung left to stand in for it: the
9007    // `increase_quality` escalation that once argued for dropping the
9008    // backend loop here proved inert and was itself removed, so with
9009    // `refine` off the host loop in `PdFullSpaceSolver` is the only
9010    // refinement in the stack — and it stops the moment it crosses
9011    // `residual_ratio_max` (1e-10), three orders looser than the ~1e-16
9012    // the backend-refined solves reach.
9013    //
9014    // Tightening that threshold instead is not the fix, and was measured
9015    // rather than assumed: it is chaotic on this corpus, flipping `deb7`
9016    // to `Error_In_Step_Computation` at 1e-12 and swinging
9017    // `pooling_rt2stp` between 107 and 199 iterations across 1e-11 to
9018    // 1e-13. Forcing extra passes via `min_refinement_steps` behaves the
9019    // same way (both fixtures break at 2). Restoring the backend loop is
9020    // trajectory-neutral next to either (`deb7` 146 -> 147,
9021    // `pooling_rt2stp` 107 -> 109).
9022    //
9023    // Ordered env-then-registry-then-option so `POUNCE_FERAL_REFINE`
9024    // still reaches this path and an explicit `feral_refine` still beats
9025    // both.
9026    //
9027    // gh#909: the registry read below takes the value and IGNORES the
9028    // found flag, which is the whole point. Reading it as `Ok((v, true))`
9029    // — the tri-state shape every other option in this function uses —
9030    // consults the user's setting and never the *registered default*, so
9031    // an unset option left `cfg.refine` at `FeralConfig::default()`'s
9032    // `true` while `pounce --print-options` reported the registry's.
9033    // Registered `no`, ran `yes`: the gh#677 shape, one option family
9034    // over. It is fixed by making the registry authoritative here rather
9035    // than by changing what runs — see below for why — so the registered
9036    // default moved to `yes` in the same commit and this read is what
9037    // keeps the two from drifting apart again.
9038    //
9039    // The scoping stays. There is no single default that is right on both
9040    // paths, and this is a two-sided trade of the same shape as
9041    // `feral_increase_quality` above: the option is the lever, and the
9042    // default is a choice rather than a fact. Measured on `e5f5830b`,
9043    // one binary, `feral_refine=no` against the default:
9044    //
9045    //   fixture corpus, exact leg: 10 legs move, NO status flips, and
9046    //     the net is favourable -- `issue_508_infeasible_gap_1em4`
9047    //     441 -> 245, `square_flowsheet_resto` 54 -> 47 (tot 185 -> 176),
9048    //     `issue_508_infeasible_gap_1em2` 114 -> 112, `deb7` 147 -> 146,
9049    //     `pooling_rt2stp` 109 -> 107, against one loss
9050    //     (`mu_fallback_point_floor` 31 -> 32).
9051    //   fixture corpus, lbfgs leg: identical, refine is already off there.
9052    //   `NARX_CFy` (Mittelmann): 400 -> 630 iterations, 208.7 s -> 254.2 s.
9053    //   `eigena2` final dual infeasibility: 3.43e-10 -> 5.20e-09, both
9054    //     inside `tol`, and see `issue_540_eigena2_superlinear_tail.rs`.
9055    //   AC-OPF (PGLib), gh#909: 10-18% faster, iteration counts
9056    //     unchanged, solution identical to ~13 significant figures.
9057    //
9058    // So the corpus and the AC-OPF benchmarks both prefer `no` and
9059    // `NARX_CFy` pays 57% more iterations for it. Nothing here separates
9060    // those, which is why the default is scoped rather than flipped.
9061    let limited_memory = carve_out == RefineCarveOut::InteriorPoint
9062        && matches!(
9063            options.get_string_value("hessian_approximation", ""),
9064            Ok((ref s, true)) if s == "limited-memory"
9065        );
9066    if std::env::var_os("POUNCE_FERAL_REFINE").is_none() {
9067        // Deliberately `_`, not `true`: see above.
9068        if let Ok((v, _)) = options.get_bool_value("feral_refine", "") {
9069            cfg.refine = v;
9070        }
9071        if limited_memory {
9072            cfg.refine = false;
9073        }
9074    }
9075    // An explicit setting beats both the carve-out and the environment.
9076    if let Ok((v, true)) = options.get_bool_value("feral_refine", "") {
9077        cfg.refine = v;
9078    }
9079    // gh #850: `feral_increase_quality` exists because this rung is a genuine
9080    // two-sided trade, and the option is the lever — the default is left ON,
9081    // which is the 0.11 behaviour.
9082    //
9083    // Ipopt's `IncreaseQuality` contract assumes a *monotone* escalation: MA57
9084    // raises `pivtol` toward `pivtolmax`, strictly more conservative each time,
9085    // so keeping it raised for the rest of the solve can only make the
9086    // factorization safer. FERAL's ladder changes which pivots are taken, which
9087    // is lateral in trajectory terms, and it persists the same way. So it
9088    // reroutes solves, and the reroute goes both ways:
9089    //
9090    //   it COSTS two whole solves, both `square_flowsheet_resto`:
9091    //     exact  Optimal/99  -> RestorationFailed/131 (a second-opinion rung
9092    //                          rescues it, at 185 iterations total)
9093    //     lbfgs  Optimal/178 -> 3000 iterations at the cap, rescued by nothing
9094    //   it BUYS accuracy where nothing else does:
9095    //     `watchdog_trial_is_not_a_divergence_verdict`'s 12-variable model ends
9096    //     `SolvedToAcceptableLevel` at obj 3.7e-6 with the rung and at obj 3.42
9097    //     against `f* = 0` without it — a wrong-ish answer under a
9098    //     success-shaped status, which is worse than an honest failure.
9099    //   and it buys iterations on five more fixture-legs (15-25%).
9100    //
9101    // There is no scoping that separates those. Measured with a process-global
9102    // firing cap on `square_flowsheet_resto`: the rung fires twice, once in the
9103    // main solve at iteration 25 and once inside restoration at `76r`, and
9104    // allowing only the first still loses the leg — so declining it just for
9105    // the restoration sub-solve would not help. Nor does a count separate them:
9106    // `deb7` and `square_flowsheet_resto` each fire it exactly twice on their
9107    // exact legs, one gaining 16% of its iterations and the other losing its
9108    // verdict.
9109    //
9110    // So the default stands, and the losing direction now recovers itself:
9111    // `feral_increase_quality_retry` (gh#857) re-solves once with this off when
9112    // a solve that actually escalated ends `Restoration_Failed` or
9113    // `Maximum_Iterations_Exceeded`.
9114    //
9115    // It is a re-solve rather than a *revertible* escalation because the
9116    // revertible one was tried. jkitchin/feral#192 landed as `reset_quality`,
9117    // was plumbed here and instrumented (376 escalations, 376 matching resets
9118    // on one solve), and recovers neither leg at either re-baselining boundary
9119    // -- the harm is the destination, not the duration. See
9120    // `dev-notes/second-opinion-promotions-in-the-sweep.md`.
9121    if let Ok((v, true)) = options.get_bool_value("feral_increase_quality", "") {
9122        cfg.increase_quality = v;
9123    }
9124    // Only consulted when `refine` is on; see `FeralConfig::refine_max_steps`
9125    // (gh#710). Registered as an integer option with lower bound 0, so the
9126    // cast cannot go negative.
9127    if let Ok((v, true)) = options.get_integer_value("feral_refine_steps", "") {
9128        cfg.refine_max_steps = v.max(0) as usize;
9129    }
9130    // Also only consulted when `refine` is on. Registered with lower bound
9131    // 0, and 0 disables the pre-check; see `FeralConfig::refine_target`.
9132    if let Ok((v, true)) = options.get_numeric_value("feral_refine_target", "") {
9133        cfg.refine_target = v.max(0.0);
9134    }
9135    // Explicit static-pivoting opt-in (feral#8 cascade breaker, pounce#254).
9136    // Same tri-state discipline: unset leaves `cfg.static_pivoting` at
9137    // whatever `from_env` resolved (`None` → inherit feral's delayed-pivot
9138    // default), so the default numeric path is unchanged.
9139    if let Ok((v, true)) = options.get_bool_value("feral_static_pivoting", "") {
9140        cfg.static_pivoting = Some(v);
9141    }
9142    if let Ok((v, true)) = options.get_numeric_value("feral_singular_pivot_floor", "") {
9143        cfg.singular_pivot_floor = v;
9144    }
9145    // Explicitly set pins an absolute floor for every dimension (`0`
9146    // disables the trigger); left unset, `None` keeps the dimension-aware
9147    // `n * eps` default (pounce gh#592).
9148    if let Ok((v, true)) = options.get_numeric_value("feral_inertia_pivot_floor", "") {
9149        cfg.inertia_pivot_floor = Some(v);
9150    }
9151    // Number option (not integer): the gate is a u64 and Index is i32, too
9152    // narrow for large flop counts or the u64::MAX reject-all sentinel. The
9153    // lower bound (0.0) rules out negatives; `as u64` then saturates a very
9154    // large finite value to u64::MAX (reject all tree-level parallelism).
9155    if let Ok((v, true)) = options.get_numeric_value("feral_min_par_flops", "") {
9156        cfg.min_par_flops = Some(v as u64);
9157    }
9158    if let Ok((v, true)) = options.get_numeric_value("feral_pivtol", "") {
9159        cfg.pivtol = v;
9160    }
9161    // Only override on explicit set so `from_env` (which itself
9162    // defaults to OrderingMethod::Auto) keeps governing unset cases.
9163    // Unrecognized tags are silently ignored — the registered enum
9164    // restricts inputs at the OptionsList layer.
9165    if let Ok((v, true)) = options.get_string_value("feral_ordering", "") {
9166        if let Some(m) = pounce_feral::parse_ordering_method(&v) {
9167            cfg.ordering = m;
9168        }
9169    }
9170    if let Ok((v, true)) = options.get_string_value("feral_ordering_preprocess", "") {
9171        if let Some(p) = pounce_feral::parse_ordering_preprocess(&v) {
9172            cfg.ordering_preprocess = p;
9173        }
9174    }
9175    // Same explicit-set discipline as `feral_ordering`: `from_env`
9176    // defaults to ScalingStrategy::Auto (FERAL's current default), so
9177    // leaving the option unset preserves existing behaviour exactly.
9178    if let Ok((v, true)) = options.get_string_value("feral_scaling", "") {
9179        if let Some(s) = pounce_feral::parse_scaling_strategy(&v) {
9180            cfg.scaling = s;
9181        }
9182    }
9183    cfg
9184}
9185
9186/// Withdraw a numerical infeasibility verdict the model's own starting point
9187/// disproves.
9188///
9189/// Applied at every site in this file that can return
9190/// `Infeasible_Problem_Detected` from a *numerical* argument — the IPM path's
9191/// restoration / cycle gates, the SQP path's infeasible-subproblem exit, and the
9192/// ℓ₁ wrapper's uncollapsed-slack certificate. Deliberately one gate rather than
9193/// three: the two preceding safeguards in this area (gh #376, gh #380) were each
9194/// added to one path and not its twin, and a hole survived both times.
9195///
9196/// Not applied to a presolve *certificate*
9197/// (`TNLP::presolve_infeasibility_proof`), which carries its own, tighter
9198/// refutation
9199/// (`pounce_presolve::witness_refutes_infeasibility`) and is a proof rather than
9200/// a numerical inference.
9201///
9202/// The replacement is `Error_In_Step_Computation`, the status this codebase
9203/// already uses for "the solve broke down and we are **not** claiming
9204/// infeasibility" — see the `cycle_exit` fallback in
9205/// [`crate::ipopt_alg::IpoptAlgorithm::invoke_restoration`], which picks between
9206/// exactly these two on exactly this question. It maps to AMPL 500, an honest
9207/// failure the caller can see, instead of AMPL 200, a wrong answer they cannot.
9208///
9209/// gh #379.
9210fn withdraw_infeasibility_if_refuted(
9211    tnlp: &Rc<RefCell<dyn TNLP>>,
9212    solver_status: SolverReturn,
9213    lo_inf: Number,
9214    up_inf: Number,
9215    tol: Number,
9216) -> SolverReturn {
9217    if solver_status != SolverReturn::LocalInfeasibility {
9218        return solver_status;
9219    }
9220    // A presolve proof is not a numerical inference; it does its own refutation.
9221    if tnlp.borrow().presolve_infeasibility_proof().is_some() {
9222        return solver_status;
9223    }
9224    match crate::infeasibility_refutation::starting_point_refutes_infeasibility(
9225        tnlp, lo_inf, up_inf, tol,
9226    ) {
9227        Some(w) => {
9228            tracing::debug!(
9229                target: "pounce::application",
9230                "[PN_INFEAS_REFUTED] the model's starting point satisfies every constraint \
9231                 (max violation {:.3e}) — withdrawing Infeasible_Problem_Detected",
9232                w.max_violation
9233            );
9234            SolverReturn::ErrorInStepComputation
9235        }
9236        None => solver_status,
9237    }
9238}
9239
9240/// How well a point satisfies the **user's own** rows and bounds.
9241///
9242/// Computed from `g = c(x)` and the inner TNLP's declared bounds, in the
9243/// user's units, with no reference to whatever problem the algorithm
9244/// actually iterated on. That distinction is the whole reason this
9245/// exists: on the ℓ₁ path the IPM converges the *augmented* NLP
9246/// `c(x) − p + n = target`, whose equality rows the slacks satisfy to
9247/// machine precision by construction, and reporting that residual as
9248/// the solve's constraint violation says nothing about `c(x) − target`
9249/// (gh#794 finding P1).
9250struct OriginalSpaceFeasibility {
9251    /// Largest absolute violation of any row or bound, in the user's units.
9252    max_violation: Number,
9253    /// Every row and bound negligible at `tol`, judged scale-relative.
9254    negligible_at_tol: bool,
9255    /// The same at `acceptable_tol`.
9256    negligible_at_acceptable: bool,
9257}
9258
9259/// Measure [`OriginalSpaceFeasibility`] at `x`, given `g = c(x)`.
9260///
9261/// `is_negligible` rather than `!is_significant`, deliberately, and for
9262/// the reason that function's own documentation gives: the question here
9263/// is "did the solve converge well enough to call this point feasible",
9264/// which must never demand more precision than the solver promised, so
9265/// the threshold is clamped at `tol` from below (`tol · max(|scale|, 1)`).
9266/// The refutation path next door asks the opposite question — "is this
9267/// residual real at this row's scale" — and correctly uses the pure
9268/// relative form.
9269///
9270/// Returns `None` when the model cannot be measured (bounds unreadable, a
9271/// non-finite value). `None` means "not measured", never "feasible": the
9272/// caller keeps whatever verdict it already had.
9273fn original_space_feasibility(
9274    tnlp: &Rc<RefCell<dyn TNLP>>,
9275    x: &[Number],
9276    g: &[Number],
9277    lower_bound_inf: Number,
9278    upper_bound_inf: Number,
9279    tol: Number,
9280    acceptable_tol: Number,
9281    constr_viol_tol: Number,
9282    acceptable_constr_viol_tol: Number,
9283    noise_floor_kappa: Number,
9284) -> Option<OriginalSpaceFeasibility> {
9285    use pounce_common::tolerance::is_negligible;
9286
9287    let info = tnlp.borrow_mut().get_nlp_info()?;
9288    let n = info.n.max(0) as usize;
9289    let m = info.m.max(0) as usize;
9290    if x.len() < n || g.len() < m {
9291        return None;
9292    }
9293
9294    let mut x_l = vec![0.0; n];
9295    let mut x_u = vec![0.0; n];
9296    let mut g_l = vec![0.0; m];
9297    let mut g_u = vec![0.0; m];
9298    if !tnlp.borrow_mut().get_bounds_info(BoundsInfo {
9299        x_l: &mut x_l,
9300        x_u: &mut x_u,
9301        g_l: &mut g_l,
9302        g_u: &mut g_u,
9303    }) {
9304        return None;
9305    }
9306
9307    let mut max_violation: Number = 0.0;
9308    let mut ok_tol = true;
9309    let mut ok_acceptable = true;
9310
9311    // Only *finite, present* bounds inform a row's magnitude: letting the
9312    // `±1e19` sentinel set the scale would make every row look satisfied,
9313    // the same trap `infeasibility_refutation` documents.
9314    let present = |b: Number, is_lower: bool| -> Option<Number> {
9315        let absent = if is_lower {
9316            b <= lower_bound_inf
9317        } else {
9318            b >= upper_bound_inf
9319        };
9320        (b.is_finite() && !absent).then_some(b)
9321    };
9322
9323    // Accumulates into `max_violation` / `ok_tol` / `ok_acceptable`; a
9324    // non-positive `viol` means the side is satisfied and contributes
9325    // nothing. Returns nothing — every caller is a statement.
9326    let mut judge = |viol: Number, scale: Number| {
9327        if viol <= 0.0 {
9328            return;
9329        }
9330        max_violation = max_violation.max(viol);
9331        // The scale-relative test alone is not a feasibility standard, and
9332        // on a large-magnitude row it is not even close to one: it accepts
9333        // anything up to `tol · |row|`, which on a row near `1e10` is `1e2`
9334        // at the default `tol`. An adversary probe on this branch built a
9335        // model infeasible by exactly `50` with its row at `1e10` and got
9336        // `Solve_Succeeded` — a *worse* verdict than this branch's own
9337        // parent, which refused the same point (the old `Σ(p+n)` argument
9338        // was crude but absolute). So the wrapper has to judge feasibility
9339        // the way the rest of the solver does.
9340        //
9341        // `OptErrorConvCheck::primal_component_passes` is that standard:
9342        // an absolute `constr_viol <= constr_viol_tol`, with scale-awareness
9343        // supplied by an abstention when every row sits at its own
9344        // floating-point noise floor (gh#528/gh#590) rather than by
9345        // multiplying the tolerance by the row's magnitude. That
9346        // abstention "cannot fabricate a success on a genuinely infeasible
9347        // model: such a model's violation is pinned at its infeasibility
9348        // gap, orders above `eps ·` the row's own magnitude" — which is
9349        // exactly the property `is_negligible` lacks and the probe
9350        // exploited (`50` is `~2e7 ×` this row's floor).
9351        //
9352        // The strict gate's `primal_resolvable` cannot be reused verbatim:
9353        // it is computed by the CQ on the *augmented* NLP, whose rows the
9354        // slacks satisfy to machine precision, so it would abstain always
9355        // and accept everything. The floor is therefore recomputed here on
9356        // the user's own row, from the same `kappa · eps · magnitude` the
9357        // option documents. `primal_noise_floor_kappa = 0` opts out, as it
9358        // does for the strict gate.
9359        //
9360        // Both arms are conjoined rather than substituted: the relative
9361        // test still catches a violation that is small in absolute terms
9362        // but large for its row, which is the gh#794 P1 case itself
9363        // (`ralph1` at `2.5e-7` under a `2.5e-11` tol).
9364        let noise = noise_floor_kappa * Number::EPSILON * scale.abs();
9365        let absolute_ok = |bound: Number| viol <= bound || viol <= noise;
9366        ok_tol &= is_negligible(viol, scale, tol) && absolute_ok(constr_viol_tol);
9367        ok_acceptable &=
9368            is_negligible(viol, scale, acceptable_tol) && absolute_ok(acceptable_constr_viol_tol);
9369    };
9370
9371    for i in 0..m {
9372        let v = g[i];
9373        if !v.is_finite() {
9374            return None;
9375        }
9376        let lo = present(g_l[i], true);
9377        let hi = present(g_u[i], false);
9378        let scale = v
9379            .abs()
9380            .max(lo.map_or(0.0, Number::abs))
9381            .max(hi.map_or(0.0, Number::abs));
9382        judge(lo.map_or(0.0, |b| b - v), scale);
9383        judge(hi.map_or(0.0, |b| v - b), scale);
9384    }
9385    for j in 0..n {
9386        let v = x[j];
9387        if !v.is_finite() {
9388            return None;
9389        }
9390        let lo = present(x_l[j], true);
9391        let hi = present(x_u[j], false);
9392        let scale = v
9393            .abs()
9394            .max(lo.map_or(0.0, Number::abs))
9395            .max(hi.map_or(0.0, Number::abs));
9396        judge(lo.map_or(0.0, |b| b - v), scale);
9397        judge(hi.map_or(0.0, |b| v - b), scale);
9398    }
9399
9400    Some(OriginalSpaceFeasibility {
9401        max_violation,
9402        negligible_at_tol: ok_tol,
9403        negligible_at_acceptable: ok_acceptable,
9404    })
9405}
9406
9407/// Map upstream `SolverReturn` codes to `ApplicationReturnStatus`.
9408/// Mirrors the table in
9409/// `ref/Ipopt/AGENT_REFERENCE/MAIN_LOOP.md` ("exception → SolverReturn
9410/// map") and the corresponding switch in
9411/// `IpIpoptApplication.cpp:call_optimize`.
9412fn solver_return_to_app_status(s: SolverReturn) -> ApplicationReturnStatus {
9413    match s {
9414        SolverReturn::Success => ApplicationReturnStatus::SolveSucceeded,
9415        SolverReturn::StopAtAcceptablePoint => ApplicationReturnStatus::SolvedToAcceptableLevel,
9416        SolverReturn::FeasiblePointFound => ApplicationReturnStatus::FeasiblePointFound,
9417        SolverReturn::MaxiterExceeded => ApplicationReturnStatus::MaximumIterationsExceeded,
9418        SolverReturn::CpuTimeExceeded => ApplicationReturnStatus::MaximumCpuTimeExceeded,
9419        SolverReturn::WallTimeExceeded => ApplicationReturnStatus::MaximumWallTimeExceeded,
9420        SolverReturn::StopAtTinyStep => ApplicationReturnStatus::SearchDirectionBecomesTooSmall,
9421        SolverReturn::LocalInfeasibility => ApplicationReturnStatus::InfeasibleProblemDetected,
9422        SolverReturn::UserRequestedStop => ApplicationReturnStatus::UserRequestedStop,
9423        SolverReturn::DivergingIterates => ApplicationReturnStatus::DivergingIterates,
9424        SolverReturn::RestorationFailure => ApplicationReturnStatus::RestorationFailed,
9425        SolverReturn::ErrorInStepComputation => ApplicationReturnStatus::ErrorInStepComputation,
9426        SolverReturn::InvalidNumberDetected => ApplicationReturnStatus::InvalidNumberDetected,
9427        SolverReturn::TooFewDegreesOfFreedom => ApplicationReturnStatus::NotEnoughDegreesOfFreedom,
9428        SolverReturn::InvalidProblemDefinition => ApplicationReturnStatus::InvalidProblemDefinition,
9429        SolverReturn::InvalidOption => ApplicationReturnStatus::InvalidOption,
9430        SolverReturn::OutOfMemory => ApplicationReturnStatus::InsufficientMemory,
9431        SolverReturn::InternalError | SolverReturn::Unassigned => {
9432            ApplicationReturnStatus::InternalError
9433        }
9434    }
9435}
9436
9437/// Best-effort evaluation of the objective at the algorithm's final
9438/// `x`. Returns the *scaled* objective (`f * obj_scale_factor`); used
9439/// to populate `SolveStatistics::final_scaled_objective`.
9440fn try_eval_curr_f(
9441    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9442    x: &Rc<dyn pounce_linalg::Vector>,
9443) -> Result<Number, ()> {
9444    let mut nlp_mut = nlp.borrow_mut();
9445    Ok(nlp_mut.eval_f(&**x))
9446}
9447
9448/// Trigger predicate for the Phase-3.5 ℓ₁ auto-fallback path. Returns
9449/// `true` when a status warrants a retry through the wrapper. Mirrors
9450/// ripopt#23's trigger set, extended per the audit's Refinement B
9451/// (pounce-side `Not_Enough_Degrees_Of_Freedom` is added because
9452/// pounce's DOF early-exit blocks NE-suffix problems that ripopt's
9453/// equivalent would let pass to the wrapper).
9454fn is_l1_fallback_trigger(status: ApplicationReturnStatus) -> bool {
9455    matches!(
9456        status,
9457        ApplicationReturnStatus::RestorationFailed
9458            | ApplicationReturnStatus::InfeasibleProblemDetected
9459            | ApplicationReturnStatus::SolvedToAcceptableLevel
9460            | ApplicationReturnStatus::MaximumIterationsExceeded
9461            | ApplicationReturnStatus::NotEnoughDegreesOfFreedom
9462    )
9463}
9464
9465/// Forward the final iterate back to the user's `TNLP::finalize_solution`.
9466/// We pull `x` (compressed in `x_var`-space) off the algorithm's
9467/// `data.curr`, lift it back to full TNLP indexing, and pass empty
9468/// multipliers for now (the algorithm's `y_c`, `y_d`, `z_l`, `z_u` are
9469/// in compressed split form — re-assembling them into the user's
9470/// `lambda` / `z_l` / `z_u` is mechanical but lives behind a
9471/// `OrigIpoptNlp::finalize_solution_*` accessor that's still being
9472/// fleshed out). On success returns the unscaled objective evaluated
9473/// on the user TNLP at the final iterate; returns `Err` if the final
9474/// iterate is missing.
9475/// Read a `dyn Vector`'s entries. Empty for a non-dense backing; POUNCE is
9476/// dense-only, so that is defensive rather than a supported case.
9477/// `constr_viol_tol`, `dual_inf_tol` and `compl_inf_tol`, as the user set
9478/// them (unscaled).
9479struct UserTolerances {
9480    constr_viol: Number,
9481    dual_inf: Number,
9482    compl_inf: Number,
9483}
9484
9485/// Whether a crossed-over point meets the user's tolerances in user units on
9486/// the model as declared (gh#1054).
9487///
9488/// Crossover's own acceptance reads the SQP's residuals, which live in the
9489/// scaled space. That is the right space for the never-regress comparison
9490/// against the interior iterate, and the wrong one for "is this a solution of
9491/// the user's problem": gradient-based scaling sized a row at a start point
9492/// with `x₀ = 1e4`, and at `x = (2, 0)` a violation of `1` read `3.3e-7` —
9493/// under every scaled tolerance, so `hs13_bigstart` came back
9494/// `Solve_Succeeded` at an infeasible point with every printed residual `0`.
9495/// The interior-point verdict is gated in user units (pounce#173); a point
9496/// that replaces it is held to the same gate. Stationarity and
9497/// complementarity unscale by `|df|`, as the calculated quantities do.
9498fn meets_user_tolerances(
9499    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9500    res: &crate::sqp::SqpResult,
9501    report: &crate::crossover::CrossoverReport,
9502    tols: &UserTolerances,
9503) -> bool {
9504    let adapter = crate::sqp::IpoptNlpAdapter::new_with_declared_bounds(Rc::clone(nlp_handle));
9505    let (rows, bx) = adapter.declared_violation(&res.x);
9506    let df = adapter.obj_scale();
9507    let dual = res.final_stationarity / df;
9508    let compl = report.compl_after / df;
9509    let ok = rows <= tols.constr_viol
9510        && bx.unwrap_or(0.0) <= tols.constr_viol
9511        && dual <= tols.dual_inf
9512        && (compl.is_nan() || compl <= tols.compl_inf);
9513    if !ok {
9514        tracing::debug!(
9515            target: "pounce::crossover",
9516            "crossed-over point fails the user tolerances: rows {rows:.2e}, box {bx:?}, \
9517             dual {dual:.2e}, compl {compl:.2e}"
9518        );
9519    }
9520    ok
9521}
9522
9523/// The converged-or-not interior iterate `curr` as a crossover seed, in the
9524/// algorithm's compressed / scaled space. The SQP adapter presents that same
9525/// space, so nothing is translated beyond repacking the bound duals:
9526/// `λ_x = z_l − z_u`.
9527fn crossover_seed(
9528    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9529    curr: &crate::iterates_vector::IteratesVector,
9530) -> crate::crossover::CrossoverSeed {
9531    crate::crossover::CrossoverSeed {
9532        x: dense_values(&*curr.x),
9533        lambda_g: {
9534            let mut v = dense_values(&*curr.y_c);
9535            v.extend(dense_values(&*curr.y_d));
9536            v
9537        },
9538        lambda_x: crate::sqp::ipopt_adapter::pack_bound_multipliers(
9539            nlp_handle,
9540            &dense_values(&*curr.z_l),
9541            &dense_values(&*curr.z_u),
9542        ),
9543    }
9544}
9545
9546/// An accepted crossover result as an interior-point iterate.
9547///
9548/// All eight components have to move together: leaving `s`, `v_l` or `v_u`
9549/// describing the interior point while `x` and the duals describe the
9550/// crossed-over one would make the calculated quantities read off an iterate
9551/// that never existed, and the residuals reported to the user would be
9552/// neither point's. The slack relations are the barrier problem's own —
9553/// `s = d(x)` and `v_l − v_u = −y_d`. `None` (with a warning) when the result
9554/// does not fit the iterate's vectors.
9555fn crossover_iterate(
9556    nlp_handle: &Rc<RefCell<dyn IpoptNlp>>,
9557    curr: &crate::iterates_vector::IteratesVector,
9558    res: &crate::sqp::SqpResult,
9559) -> Option<crate::iterates_vector::IteratesVector> {
9560    let (m_c, m_d) = {
9561        let b = nlp_handle.borrow();
9562        (b.m_eq() as usize, b.m_ineq() as usize)
9563    };
9564    let y_c = &res.lambda_g[..m_c];
9565    let y_d = &res.lambda_g[m_c..];
9566    // `s = d(x)`: the adapter's combined constraint vector is `[c ; d]`,
9567    // so the inequality block is its tail.
9568    let mut adapter = crate::sqp::IpoptNlpAdapter::new(Rc::clone(nlp_handle));
9569    let c_all = crate::sqp::SqpProblemSpec::eval_c(&mut adapter, &res.x);
9570    let s_new = &c_all[m_c..];
9571    debug_assert_eq!(s_new.len(), m_d);
9572    let (z_l, z_u) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp_handle, &res.lambda_x);
9573    let (v_l, v_u) = crate::sqp::ipopt_adapter::split_slack_multipliers(nlp_handle, y_d);
9574
9575    let mut out = curr.deep_copy();
9576    let ok = set_dense(&mut *out.x, &res.x)
9577        && set_dense(&mut *out.s, s_new)
9578        && set_dense(&mut *out.y_c, y_c)
9579        && set_dense(&mut *out.y_d, y_d)
9580        && set_dense(&mut *out.z_l, &z_l)
9581        && set_dense(&mut *out.z_u, &z_u)
9582        && set_dense(&mut *out.v_l, &v_l)
9583        && set_dense(&mut *out.v_u, &v_u);
9584    if !ok {
9585        // A non-dense backing or a length mismatch. POUNCE is dense-only,
9586        // so this is defensive — but a partially-written iterate is worse
9587        // than no crossover at all, so bail without touching `curr`.
9588        tracing::warn!(
9589            target: "pounce::crossover",
9590            "crossover result did not fit the iterate; keeping the interior point"
9591        );
9592        return None;
9593    }
9594    Some(out.freeze())
9595}
9596
9597fn dense_values(v: &dyn pounce_linalg::Vector) -> Vec<Number> {
9598    v.as_any()
9599        .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
9600        .map(|d| d.expanded_values())
9601        .unwrap_or_default()
9602}
9603
9604/// Overwrite a `dyn Vector`'s entries. Returns false — writing nothing —
9605/// when the backing is not dense or the lengths disagree, so a caller
9606/// updating several components together can abandon the whole update rather
9607/// than leave a half-written iterate.
9608fn set_dense(v: &mut dyn pounce_linalg::Vector, vals: &[Number]) -> bool {
9609    match v
9610        .as_any_mut()
9611        .downcast_mut::<pounce_linalg::dense_vector::DenseVector>()
9612    {
9613        Some(d) if pounce_linalg::Vector::dim(d) as usize == vals.len() => {
9614            d.set_values(vals);
9615            true
9616        }
9617        _ => false,
9618    }
9619}
9620
9621/// An owned copy of a [`Solution`] payload already delivered to the user's
9622/// TNLP, enough to deliver it again.
9623///
9624/// Exists because a losing second-opinion retry has to be undoable. The status
9625/// a retry earns is already floored — `run_with_mu_strategy_fallback` returns
9626/// `first_status` unless the retry promotes — but the *point* was not, and the
9627/// user consumes the point. See that function for what went wrong without this.
9628#[derive(Debug, Clone)]
9629struct FinalizeSnapshot {
9630    status: SolverReturn,
9631    x: Vec<Number>,
9632    z_l: Vec<Number>,
9633    z_u: Vec<Number>,
9634    g: Vec<Number>,
9635    lambda: Vec<Number>,
9636    obj_value: Number,
9637    /// The `on_converged` firing of the attempt that produced this payload,
9638    /// `None` if the hook did not fire for it. Travels with the payload, so a
9639    /// floor replay brings the matching firing back with the answer.
9640    on_converged_id: Option<u64>,
9641}
9642
9643/// The option-table overrides (and the box flag) one retry applies for its
9644/// own solve, put back when the scope ends -- on **every** exit, unwinding
9645/// included.
9646///
9647/// The retries used to restore by hand after `optimize_constrained`
9648/// returned, so a panic inside it left the overrides in place. That is not
9649/// hypothetical for an embedder: `pounce-cinterface`'s `ffi_guard` catches the
9650/// panic and keeps the `IpoptApplication`, so the next `IpoptSolve` on that
9651/// handle ran with the scale audit's `max_iter` (`3x` the base solve's),
9652/// `obj_scaling_factor` multiplied by `k`, a CPU / wall budget shrunk to what
9653/// the audited run had left -- and, since gh#983's declared-box fix, the
9654/// variable box un-widened.
9655///
9656/// Derefs to the application, so the retry runs *through* the scope:
9657/// `scope.optimize_constrained(..)`. Each entry is restored with
9658/// [`OptionsList::restore_entry`], i.e. exactly as it stood, absence as
9659/// absence.
9660///
9661/// `on_unwind_only` is for the two retries (μ-strategy fallback, gh#884)
9662/// whose normal-path restore is deliberately *not* "as it stood" -- both
9663/// write the resolved value back with `found = true` -- and whose behaviour
9664/// on that path this guard must not change: there it only covers the unwind.
9665struct RetryOptionScope<'a> {
9666    app: &'a mut IpoptApplication,
9667    saved: Vec<(
9668        &'static str,
9669        pounce_common::options_list::OptionEntrySnapshot,
9670    )>,
9671    on_unwind_only: bool,
9672}
9673
9674impl<'a> RetryOptionScope<'a> {
9675    fn enter(app: &'a mut IpoptApplication, tags: &[&'static str], on_unwind_only: bool) -> Self {
9676        let saved = tags
9677            .iter()
9678            .map(|&t| (t, app.options.snapshot_entry(t)))
9679            .collect();
9680        Self {
9681            app,
9682            saved,
9683            on_unwind_only,
9684        }
9685    }
9686}
9687
9688impl std::ops::Deref for RetryOptionScope<'_> {
9689    type Target = IpoptApplication;
9690    fn deref(&self) -> &IpoptApplication {
9691        self.app
9692    }
9693}
9694
9695impl std::ops::DerefMut for RetryOptionScope<'_> {
9696    fn deref_mut(&mut self) -> &mut IpoptApplication {
9697        self.app
9698    }
9699}
9700
9701impl Drop for RetryOptionScope<'_> {
9702    fn drop(&mut self) {
9703        if self.on_unwind_only && !std::thread::panicking() {
9704            return;
9705        }
9706        for (tag, snap) in self.saved.drain(..) {
9707            self.app.options.restore_entry(tag, snap);
9708        }
9709        self.app.retry_keeps_declared_box.set(false);
9710    }
9711}
9712
9713/// The `final_*` half of [`SolveStatistics`] — the numbers that describe the
9714/// answer and the certificate attached to it.
9715///
9716/// Deliberately **not** the whole struct. `SolveStatistics` mixes two kinds of
9717/// number and they float back differently when a second-opinion retry loses:
9718///
9719/// * the `final_*` fields describe *the point being reported*, so they have to
9720///   agree with the status reported beside them. A `Solved_To_Acceptable_Level`
9721///   carrying a `final_kkt_error` two orders above `acceptable_tol` is
9722///   self-contradictory, and that is pounce#870.
9723/// * the wall clock (`total_wallclock_time_secs`) and the cumulative
9724///   dual-divergence flags describe *what the invocation did*: both attempts
9725///   really ran, so rewinding them would under-report the work actually
9726///   spent.
9727///
9728/// Everything else a solve report reads beside the final residuals describes
9729/// the *run that produced the returned point* (gh#983 item 5): the iteration
9730/// count and rows, the evaluation counts, the restoration tallies and
9731/// `quality_escalations`. Before that fix `deb7` at `max_iter=100` reported the
9732/// declined retry's 100 iterations beside the first attempt's objective and
9733/// point, and `eigenb2` (limited memory) 86 objective evaluations beside the
9734/// first attempt's 47 iterations and 159 evaluations. The first attempt's own
9735/// counts (`deb7`: 84 outer + 32 restoration = 116) are the ones that belong
9736/// with its point. The console's per-attempt summaries still show each
9737/// attempt's own tally.
9738///
9739/// So the certificate and the run it came from are floored together; only the
9740/// wall clock is the invocation's.
9741#[derive(Debug, Clone)]
9742struct SolutionCertificate {
9743    objective: Number,
9744    scaled_objective: Number,
9745    dual_inf: Number,
9746    constr_viol: Number,
9747    compl: Number,
9748    kkt_error: Number,
9749    unscaled_dual_inf: Number,
9750    unscaled_constr_viol: Number,
9751    unscaled_compl: Number,
9752    unscaled_kkt_error: Number,
9753    kkt_error_above_noise: Number,
9754    mu: Number,
9755    /// How far the attempt's point sits outside the model as declared --
9756    /// rows and box. Both are read off the statistics beside the residuals
9757    /// above, and both describe the *point*; leaving them out meant a
9758    /// declined retry's measurement was reported beside the base attempt's
9759    /// point (`Variable bound violation` and `final_declared_box_viol` naming
9760    /// the discarded re-solve's `9.9e-9` next to a point that sits inside
9761    /// its box).
9762    declared_constr_viol: Number,
9763    declared_box_viol: Number,
9764    /// gh#983 item 5: the iteration count and per-iteration rows of the
9765    /// attempt being floored. A solve report reads both from the statistics,
9766    /// so restoring the certificate without them left a report whose
9767    /// numbers describe the returned point and whose iteration table
9768    /// describes the declined retry.
9769    iteration_count: Index,
9770    iterations: Vec<pounce_nlp::solve_statistics::IterRecord>,
9771    /// The per-run evaluation and restoration tallies of the attempt, for the
9772    /// same reason as the iteration table: they are read off the statistics
9773    /// beside the final residuals, and a declined retry used to leave its own
9774    /// (`eigenb2` limited-memory: 86 objective evaluations reported beside the
9775    /// base attempt's 47 iterations and 159 evaluations).
9776    evals: [Index; 5],
9777    restoration: (Index, Index, Index, Number),
9778    quality_escalations: Index,
9779    /// gh#983: the scale the stationarity residual is judged against, the
9780    /// objective scale the run ended with, and the warnings raised about the
9781    /// attempt. All three describe the *point being reported*.
9782    unscaled_dual_scale: Number,
9783    obj_scaling_factor: Number,
9784    total_obj_scaling_factor: Number,
9785    start_obj_grad_max: Number,
9786    warnings: Vec<String>,
9787    /// gh#983 review item 3: the detector's verdict on this run alone.
9788    returned_run_signature: bool,
9789}
9790
9791impl SolutionCertificate {
9792    fn of(s: &pounce_nlp::solve_statistics::SolveStatistics) -> Self {
9793        Self {
9794            objective: s.final_objective,
9795            scaled_objective: s.final_scaled_objective,
9796            dual_inf: s.final_dual_inf,
9797            constr_viol: s.final_constr_viol,
9798            compl: s.final_compl,
9799            kkt_error: s.final_kkt_error,
9800            unscaled_dual_inf: s.final_unscaled_dual_inf,
9801            unscaled_constr_viol: s.final_unscaled_constr_viol,
9802            unscaled_compl: s.final_unscaled_compl,
9803            unscaled_kkt_error: s.final_unscaled_kkt_error,
9804            kkt_error_above_noise: s.final_kkt_error_above_noise,
9805            mu: s.final_mu,
9806            declared_constr_viol: s.final_declared_constr_viol,
9807            declared_box_viol: s.final_declared_box_viol,
9808            iteration_count: s.iteration_count,
9809            iterations: s.iterations.clone(),
9810            evals: [
9811                s.num_obj_evals,
9812                s.num_constr_evals,
9813                s.num_obj_grad_evals,
9814                s.num_constr_jac_evals,
9815                s.num_hess_evals,
9816            ],
9817            restoration: (
9818                s.restoration_calls,
9819                s.restoration_inner_iters,
9820                s.restoration_outer_iters,
9821                s.restoration_wall_secs,
9822            ),
9823            quality_escalations: s.quality_escalations,
9824            unscaled_dual_scale: s.final_unscaled_dual_scale,
9825            obj_scaling_factor: s.final_obj_scaling_factor,
9826            total_obj_scaling_factor: s.final_total_obj_scaling_factor,
9827            start_obj_grad_max: s.start_obj_grad_max,
9828            warnings: s.warnings.clone(),
9829            returned_run_signature: s.returned_run_dual_divergence_signature,
9830        }
9831    }
9832
9833    fn restore_into(&self, s: &mut pounce_nlp::solve_statistics::SolveStatistics) {
9834        s.final_objective = self.objective;
9835        s.final_scaled_objective = self.scaled_objective;
9836        s.final_dual_inf = self.dual_inf;
9837        s.final_constr_viol = self.constr_viol;
9838        s.final_compl = self.compl;
9839        s.final_kkt_error = self.kkt_error;
9840        s.final_unscaled_dual_inf = self.unscaled_dual_inf;
9841        s.final_unscaled_constr_viol = self.unscaled_constr_viol;
9842        s.final_unscaled_compl = self.unscaled_compl;
9843        s.final_unscaled_kkt_error = self.unscaled_kkt_error;
9844        s.final_kkt_error_above_noise = self.kkt_error_above_noise;
9845        s.final_mu = self.mu;
9846        s.final_declared_constr_viol = self.declared_constr_viol;
9847        s.final_declared_box_viol = self.declared_box_viol;
9848        s.iteration_count = self.iteration_count;
9849        s.iterations = self.iterations.clone();
9850        s.num_obj_evals = self.evals[0];
9851        s.num_constr_evals = self.evals[1];
9852        s.num_obj_grad_evals = self.evals[2];
9853        s.num_constr_jac_evals = self.evals[3];
9854        s.num_hess_evals = self.evals[4];
9855        s.restoration_calls = self.restoration.0;
9856        s.restoration_inner_iters = self.restoration.1;
9857        s.restoration_outer_iters = self.restoration.2;
9858        s.restoration_wall_secs = self.restoration.3;
9859        s.quality_escalations = self.quality_escalations;
9860        s.final_unscaled_dual_scale = self.unscaled_dual_scale;
9861        s.final_obj_scaling_factor = self.obj_scaling_factor;
9862        s.final_total_obj_scaling_factor = self.total_obj_scaling_factor;
9863        s.start_obj_grad_max = self.start_obj_grad_max;
9864        s.warnings = self.warnings.clone();
9865        s.returned_run_dual_divergence_signature = self.returned_run_signature;
9866    }
9867}
9868
9869impl FinalizeSnapshot {
9870    /// Re-deliver this payload to `tnlp`, overwriting whatever a later attempt
9871    /// captured there.
9872    fn replay(&self, tnlp: &Rc<RefCell<dyn TNLP>>) {
9873        tnlp.borrow_mut().finalize_solution(
9874            Solution {
9875                status: self.status,
9876                x: &self.x,
9877                z_l: &self.z_l,
9878                z_u: &self.z_u,
9879                g: &self.g,
9880                lambda: &self.lambda,
9881                obj_value: self.obj_value,
9882            },
9883            &TnlpIpoptData::default(),
9884            &TnlpIpoptCq::default(),
9885        );
9886    }
9887}
9888
9889fn finalize_via_orig_nlp(
9890    nlp: &Rc<RefCell<dyn IpoptNlp>>,
9891    alg: &IpoptAlgorithm,
9892    solver_status: SolverReturn,
9893    _app_status: ApplicationReturnStatus,
9894    tnlp: &Rc<RefCell<dyn TNLP>>,
9895    sink: &RefCell<Option<FinalizeSnapshot>>,
9896    fixed_var_duals: bool,
9897) -> Result<Number, ()> {
9898    let curr = alg.data.borrow().curr.clone().ok_or(())?;
9899    // Lift compressed x_var → full-x (length `info.n`) so the user
9900    // TNLP receives the same shape it provided. With `make_parameter`
9901    // the fixed components are spliced back in by the IpoptNlp.
9902    let nlp_borrow = nlp.borrow();
9903    // `finalize_solution_x`, not `lift_x_to_full`: the reported point also
9904    // owes the user the `honor_original_bounds` projection. `f` and `g`
9905    // below are then evaluated at the point actually reported, so x/f/g
9906    // agree with each other.
9907    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&*curr.x);
9908    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
9909    let n = info.n as usize;
9910    let m = info.m as usize;
9911    debug_assert_eq!(x_vec.len(), n);
9912    // Lift algorithm-side multipliers back into user-space (pounce#11).
9913    // Use the `finalize_solution_*` family (not the `pack_*` family): the
9914    // final solution duals must be reported in the user's *unscaled-
9915    // Lagrangian* convention `∇f + λ·∇g + z = 0`, which divides out the
9916    // `obj_scale_factor` the algorithm threads through `eval_h`. The `pack_*`
9917    // family deliberately omits that division because it feeds the scaled
9918    // `eval_h`; calling it here left every dual scaled by `obj_scale_factor`
9919    // whenever gradient-based scaling triggered (pounce#11 F1).
9920    // Backends without overrides return empty; fall back to zero stubs so the
9921    // user sees a length-consistent vector.
9922    let mut z_l = nlp_borrow.finalize_solution_z_l(&*curr.z_l);
9923    if z_l.is_empty() {
9924        z_l = vec![0.0; n];
9925    }
9926    let mut z_u = nlp_borrow.finalize_solution_z_u(&*curr.z_u);
9927    if z_u.is_empty() {
9928        z_u = vec![0.0; n];
9929    }
9930    let mut lambda = nlp_borrow.finalize_solution_lambda(&*curr.y_c, &*curr.y_d);
9931    if lambda.is_empty() {
9932        lambda = vec![0.0; m];
9933    }
9934    if fixed_var_duals {
9935        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
9936    }
9937    drop(nlp_borrow);
9938    // Compute g(x) via the user TNLP so the final residual is
9939    // populated for the user.
9940    let mut g_final = vec![0.0; m];
9941    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
9942    let f_final = tnlp
9943        .borrow_mut()
9944        .eval_f(&x_vec, true)
9945        .unwrap_or(Number::NAN);
9946    let snap = FinalizeSnapshot {
9947        status: solver_status,
9948        x: x_vec,
9949        z_l,
9950        z_u,
9951        g: g_final,
9952        lambda,
9953        obj_value: f_final,
9954        on_converged_id: alg.data.borrow().on_converged_id,
9955    };
9956    snap.replay(tnlp);
9957    *sink.borrow_mut() = Some(snap);
9958    Ok(f_final)
9959}
9960
9961/// Bind SQP suboptions registered in `upstream_options.rs`
9962/// (`sqp_globalization`, `sqp_hessian`, `sqp_max_iter`, `sqp_tol`,
9963/// `sqp_constr_viol_tol`, `sqp_dual_inf_tol`, `sqp_l1_penalty`,
9964/// `sqp_bt_reduction`, `sqp_bt_min_alpha`, `sqp_print_level`,
9965/// `sqp_lbfgs_max_history`) onto
9966/// `opts`. Used by [`IpoptApplication::algorithm_builder_snapshot`]
9967/// before constructing an SQP algorithm.
9968fn apply_sqp_options(options: &OptionsList, opts: &mut crate::sqp::SqpOptions) {
9969    use crate::sqp::{SqpGlobalization, SqpHessianSource};
9970
9971    if let Ok((s, true)) = options.get_string_value("sqp_globalization", "") {
9972        opts.globalization = match s.as_str() {
9973            "filter" => SqpGlobalization::Filter,
9974            "l1-elastic" => SqpGlobalization::L1Elastic,
9975            _ => opts.globalization,
9976        };
9977    }
9978    // `hessian_approximation` is the upstream Ipopt option a frontend sets
9979    // when the caller supplies no second derivatives -- `pounce.minimize` does
9980    // it automatically, and warns that it is doing so. It was only ever read
9981    // on the IPM path, so an SQP solve ignored it and fell back to the
9982    // `Exact` default, asking the NLP for a Lagrangian Hessian that was never
9983    // provided. A zero Hessian turns the QP subproblem into an LP, which is
9984    // unbounded whenever the objective gradient has a component in the null
9985    // space of the active constraints -- so the solve died with
9986    // `Internal_Error` on problems the IPM handles without complaint:
9987    //
9988    //     min (x0-3)^2 + (x1-2)^2  s.t.  4 - x0 - x1 >= 0
9989    //
9990    // (IPM: x = [2.5, 1.5]. Active-set SQP before this: Internal_Error, or
9991    // with variable bounds, a run to the box corner along the null-space
9992    // direction.)
9993    //
9994    // The quasi-Newton source picked here is the *dense Powell-damped BFGS*,
9995    // not the limited-memory one, even though the requesting option is spelled
9996    // `limited-memory`. On this active-set-SQP path L-BFGS buys nothing: its
9997    // `as_triplet` materializes a full dense `n×n` Hessian for the QP
9998    // subproblem exactly as `DampedBfgs` does (the matrix-free product
9999    // interface that would make L-BFGS cheaper is not implemented yet), and it
10000    // is markedly less robust -- it stalls with
10001    // `Search_Direction_Becomes_Too_Small` (or reports the QP subproblem
10002    // `unbounded`) on easy, well-conditioned convex QPs whenever a general
10003    // inequality is active at the optimum, returning `success=False` with a
10004    // wrong `x` (issue #358). `DampedBfgs` solves those. So the automatic
10005    // approximation the facade injects when no analytic Hessian is available
10006    // maps to the robust dense update; a caller who genuinely wants
10007    // limited-memory storage can still request it explicitly with
10008    // `sqp_hessian = "lbfgs"` below (read after this, so it wins).
10009    //
10010    // ...up to `sqp_dense_hessian_max_n` variables (gh#1054). Above that the
10011    // dense update is not a robust choice but an impossible one -- `n²`
10012    // storage, and every QP factorization dense -- so `QuasiNewtonAuto`
10013    // resolves per solve, from the model's `n`, to L-BFGS in the lifted
10014    // low-rank form that keeps the QP sparse. The paragraph above still
10015    // governs every model at or below the ceiling.
10016    //
10017    // Read this before `sqp_hessian` so an explicit setting still wins.
10018    if let Ok((s, true)) = options.get_string_value("hessian_approximation", "") {
10019        if s == "limited-memory" {
10020            opts.hessian = SqpHessianSource::QuasiNewtonAuto;
10021        }
10022    }
10023    if let Ok((s, true)) = options.get_string_value("sqp_hessian", "") {
10024        opts.hessian = match s.as_str() {
10025            "exact" => SqpHessianSource::Exact,
10026            "damped-bfgs" => SqpHessianSource::DampedBfgs,
10027            "lbfgs" => SqpHessianSource::Lbfgs,
10028            _ => opts.hessian,
10029        };
10030    }
10031    if let Ok((v, true)) = options.get_integer_value("sqp_max_iter", "") {
10032        if v >= 0 {
10033            opts.max_iter = v as u32;
10034        }
10035    }
10036    if let Ok((v, true)) = options.get_numeric_value("sqp_tol", "") {
10037        opts.tol = v;
10038    }
10039    if let Ok((v, true)) = options.get_numeric_value("sqp_constr_viol_tol", "") {
10040        opts.constr_viol_tol = v;
10041    }
10042    if let Ok((v, true)) = options.get_numeric_value("sqp_dual_inf_tol", "") {
10043        opts.dual_inf_tol = v;
10044    }
10045    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty", "") {
10046        opts.l1_penalty = v;
10047    }
10048    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_safety", "") {
10049        opts.l1_penalty_safety = v;
10050    }
10051    if let Ok((v, true)) = options.get_numeric_value("sqp_l1_penalty_max", "") {
10052        opts.l1_penalty_max = v;
10053    }
10054    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_reduction", "") {
10055        opts.bt_reduction = v;
10056    }
10057    if let Ok((v, true)) = options.get_numeric_value("sqp_bt_min_alpha", "") {
10058        opts.bt_min_alpha = v;
10059    }
10060    if let Ok((v, true)) = options.get_integer_value("sqp_print_level", "") {
10061        opts.print_level = v.clamp(0, u8::MAX as i32) as u8;
10062    }
10063    if let Ok((v, true)) = options.get_integer_value("sqp_lbfgs_max_history", "") {
10064        if v >= 1 {
10065            opts.lbfgs_max_history = v as u32;
10066        }
10067    }
10068    // An explicit `sqp_qp_use_schur_updates` is the caller's choice and goes
10069    // to the QP options as given (`apply_qp_subproblem_options`); only an
10070    // unset one is left to the size rule.
10071    if let Ok((_, true)) = options.get_string_value("sqp_qp_use_schur_updates", "") {
10072        opts.qp_schur_min_dim = None;
10073    }
10074    if let Ok((v, true)) = options.get_integer_value("sqp_dense_hessian_max_n", "") {
10075        opts.dense_hessian_max_n = usize::try_from(v).unwrap_or(0);
10076    }
10077}
10078
10079/// Populate the active-set SQP **QP-subproblem** options
10080/// ([`pounce_qp::QpOptions`]) from the `sqp_qp_*` option family.
10081///
10082/// Sister to [`apply_sqp_options`], which handles the SQP *outer-loop*
10083/// options ([`crate::sqp::SqpOptions`]); this one feeds the inner QP
10084/// solver that `SqpAlgorithm` delegates each subproblem to. Consulted
10085/// only on the `ActiveSetSqp` path. Each knob is forwarded only when
10086/// the user explicitly set it, so the `pounce_qp` defaults stand
10087/// otherwise.
10088///
10089/// The reading itself is [`pounce_qp::ActiveSetOverrides`], shared with
10090/// `pounce_convex`'s direct active-set driver, which overlays the same
10091/// eight names onto the same `QpOptions` type. This function had its own
10092/// copy until then, and the two had drifted: this one silently ignored a
10093/// `sqp_qp_max_iter` of 0 and an unknown `sqp_qp_anti_cycling` value where
10094/// the other rejected them. Neither divergence was reachable — the
10095/// registry bounds `sqp_qp_max_iter` at 1 and restricts `anti_cycling` to
10096/// three values — but two readers of one option family is how a
10097/// reachable one starts.
10098fn apply_qp_subproblem_options(options: &OptionsList, opts: &mut pounce_qp::QpOptions) {
10099    match pounce_qp::ActiveSetOverrides::try_from_options_list(options) {
10100        Ok(overrides) => overrides.apply(opts),
10101        // Unreachable from here: this runs after `initialize()`, so every
10102        // value present has already been validated against the registered
10103        // bound that the reader re-checks. Say so out loud anyway rather
10104        // than solving with a configuration the user did not ask for —
10105        // silently dropping the whole family is exactly the failure mode
10106        // `tests/no_silent_options.rs` exists to prevent.
10107        Err(error) => tracing::error!(
10108            target: "pounce::options",
10109            %error,
10110            "sqp_qp_* options were rejected after the registry accepted them; \
10111             the QP subproblem is running on pounce-qp defaults"
10112        ),
10113    }
10114}
10115
10116/// The TNLP's own starting point as an SQP warm start, in algorithm space,
10117/// through the projections the IPM's warm initializer reads
10118/// (`prepare_warm_start`, `get_starting_x/y/z`). `None` when the NLP
10119/// declines. An unseeded bound multiplier (NaN, gh#622) counts as zero: the
10120/// SQP has no `bound_mult_init_val` of its own to resolve it to.
10121fn sqp_tnlp_warm_start(nlp_rc: &Rc<RefCell<dyn IpoptNlp>>) -> Option<crate::sqp::SqpIterates> {
10122    use pounce_linalg::dense_vector::DenseVectorSpace;
10123    let dense = |v: &dyn pounce_linalg::Vector| -> Vec<Number> {
10124        v.as_any()
10125            .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
10126            .map(|d| d.expanded_values().to_vec())
10127            .unwrap_or_default()
10128    };
10129    let (z_l, z_u, x, lambda_g) = {
10130        let mut nlp = nlp_rc.borrow_mut();
10131        if !nlp.prepare_warm_start() {
10132            return None;
10133        }
10134        let (n, m_eq, m_ineq) = (nlp.n(), nlp.m_eq(), nlp.m_ineq());
10135        let (n_xl, n_xu) = (nlp.x_l().dim(), nlp.x_u().dim());
10136        let (n_dl, n_du) = (nlp.d_l().dim(), nlp.d_u().dim());
10137        let mut x = DenseVectorSpace::new(n).make_new_dense();
10138        let mut y_c = DenseVectorSpace::new(m_eq).make_new_dense();
10139        let mut y_d = DenseVectorSpace::new(m_ineq).make_new_dense();
10140        let mut z_l = DenseVectorSpace::new(n_xl).make_new_dense();
10141        let mut z_u = DenseVectorSpace::new(n_xu).make_new_dense();
10142        let mut v_l = DenseVectorSpace::new(n_dl).make_new_dense();
10143        let mut v_u = DenseVectorSpace::new(n_du).make_new_dense();
10144        let ok = nlp.get_starting_x(&mut x)
10145            && nlp.get_starting_y(&mut y_c, &mut y_d)
10146            && nlp.get_starting_z(&mut z_l, &mut z_u, &mut v_l, &mut v_u);
10147        nlp.finish_warm_start();
10148        if !ok {
10149            return None;
10150        }
10151        let finite = |v: Vec<Number>| -> Vec<Number> {
10152            v.into_iter()
10153                .map(|a| if a.is_finite() { a } else { 0.0 })
10154                .collect()
10155        };
10156        let mut lambda_g = finite(dense(&y_c));
10157        lambda_g.extend(finite(dense(&y_d)));
10158        (
10159            finite(dense(&z_l)),
10160            finite(dense(&z_u)),
10161            dense(&x),
10162            lambda_g,
10163        )
10164    };
10165    let lambda_x = crate::sqp::ipopt_adapter::pack_bound_multipliers(nlp_rc, &z_l, &z_u);
10166    Some(crate::sqp::SqpIterates {
10167        x,
10168        lambda_g,
10169        lambda_x,
10170        working: None,
10171    })
10172}
10173
10174/// Map a staged SQP warm start from the caller's space into the algorithm's:
10175/// the exact inverse of what [`finalize_via_sqp`] / [`sqp_user_iterate`] do on
10176/// the way out, so that the multipliers a solve reports, fed back unchanged,
10177/// are the iterate the next solve starts from.
10178///
10179/// | field | user space (what callers stage) | algorithm space |
10180/// |---|---|---|
10181/// | `x` | full `n`, model units | fixed columns dropped, `x̃ = d ⊙ x` |
10182/// | `lambda_x` | full `n`, `z_L − z_U` | fixed dropped, `· obj_scal ⊘ d` |
10183/// | `lambda_g` | `m`, in `g` order | `[y_c; y_d]`, `y = λ · obj_scal / {c,d}_scale` |
10184/// | `working.constraints` | `m`, in `g` order | `[c; d]` order |
10185///
10186/// (`working.bounds` goes from full `n` to the reduced columns in the
10187/// caller, which also knows which elimination an already-reduced set came
10188/// from.)
10189///
10190/// `d` is the per-variable factor of a `ScalingTnlp` below the NLP (gh#486;
10191/// `z̃ = z ⊘ d`, its `get_starting_point` rule) and `obj_scal` includes the
10192/// sign of a maximize. The `λ` rule is `OrigIpoptNlp::initialize_starting_point`'s,
10193/// the IPM's inbound half of the same inverse.
10194///
10195/// Every frontend stages user space — the C API and `pounce-py` pass the
10196/// caller's `x` / `mult_g` / `z_L − z_U` through untouched. Before this they
10197/// went in as-is: on a model whose equality is not the first row, the two
10198/// constraint multipliers landed on each other's rows, and any
10199/// `obj_scaling_factor` ≠ 1 left them off by that factor.
10200///
10201/// An `x` / `lambda_x` already of the reduced length (a problem with fixed
10202/// variables) is taken as user-unit values of the surviving columns, in
10203/// order; any other length is left alone for the dimension check to reject.
10204fn sqp_warm_start_to_algorithm(nlp: &dyn IpoptNlp, w: &mut crate::sqp::SqpIterates) {
10205    let n_alg = nlp.n() as usize;
10206    let n_full = nlp.n_full_x() as usize;
10207    let m_full = nlp.n_full_g() as usize;
10208    let m_eq = nlp.m_eq() as usize;
10209    let obj_scal = nlp.obj_scaling_factor();
10210    let d = nlp.variable_scaling();
10211    // Algorithm column -> (user column, its x-scaling factor).
10212    let cols: Vec<(usize, Number)> = (0..n_alg)
10213        .map(|k| {
10214            let j = nlp.var_x_to_full_x(k as Index) as usize;
10215            let dj = d.as_ref().and_then(|d| d.get(j).copied()).unwrap_or(1.0);
10216            (j, dj)
10217        })
10218        .collect();
10219    let to_alg = |v: &[Number], f: &dyn Fn(Number, Number) -> Number| -> Option<Vec<Number>> {
10220        if v.len() == n_full {
10221            Some(cols.iter().map(|&(j, dj)| f(v[j], dj)).collect())
10222        } else if v.len() == n_alg {
10223            Some(cols.iter().zip(v).map(|(&(_, dj), &x)| f(x, dj)).collect())
10224        } else {
10225            None
10226        }
10227    };
10228    if let Some(x) = to_alg(&w.x, &|x, dj| x * dj) {
10229        w.x = x;
10230    }
10231    if let Some(lx) = to_alg(&w.lambda_x, &|z, dj| z * obj_scal / dj) {
10232        w.lambda_x = lx;
10233    }
10234    if w.lambda_g.len() == m_full {
10235        let cs = nlp.c_scale_vec();
10236        let ds = nlp.d_scale_vec();
10237        let mut y = vec![0.0; m_full];
10238        for (i, &lam) in w.lambda_g.iter().enumerate() {
10239            let i = i as Index;
10240            if let Some(k) = nlp.full_g_to_c_block(i) {
10241                let k = k as usize;
10242                let s = cs.as_ref().map_or(1.0, |v| v[k]);
10243                y[k] = lam / s * obj_scal;
10244            } else if let Some(k) = nlp.full_g_to_d_block(i) {
10245                let k = k as usize;
10246                let s = ds.as_ref().map_or(1.0, |v| v[k]);
10247                y[m_eq + k] = lam / s * obj_scal;
10248            }
10249        }
10250        w.lambda_g = y;
10251    }
10252    if let Some(ws) = w.working.as_mut() {
10253        ws.constraints = working_set_rows_to_algorithm(nlp, std::mem::take(&mut ws.constraints));
10254    }
10255}
10256
10257/// Algorithm row `k` of the `[c; d]` constraint vector → user `g` row, or
10258/// `None` when the NLP's row count does not describe a full split.
10259fn algorithm_rows_to_user(nlp: &dyn IpoptNlp) -> Option<Vec<usize>> {
10260    let m_full = nlp.n_full_g() as usize;
10261    let m_eq = nlp.m_eq() as usize;
10262    let m_alg = m_eq + nlp.m_ineq() as usize;
10263    if m_full != m_alg {
10264        return None;
10265    }
10266    let mut map = vec![usize::MAX; m_alg];
10267    for i in 0..m_full {
10268        let k = if let Some(k) = nlp.full_g_to_c_block(i as Index) {
10269            k as usize
10270        } else if let Some(k) = nlp.full_g_to_d_block(i as Index) {
10271            m_eq + k as usize
10272        } else {
10273            return None;
10274        };
10275        if k >= m_alg || map[k] != usize::MAX {
10276            return None;
10277        }
10278        map[k] = i;
10279    }
10280    Some(map)
10281}
10282
10283/// Constraint statuses of a working set, algorithm `[c; d]` order → user
10284/// `g` order. The SQP stacks equalities first, so on a model whose first
10285/// row is an inequality the statuses published positionally landed on the
10286/// wrong rows (`[Equality, AtUpper]` for `g = [ineq, eq]`). A vector of
10287/// any other length is returned unchanged for the dimension check to judge.
10288fn working_set_rows_to_user(
10289    nlp: &dyn IpoptNlp,
10290    rows: Vec<pounce_qp::ConsStatus>,
10291) -> Vec<pounce_qp::ConsStatus> {
10292    match algorithm_rows_to_user(nlp) {
10293        Some(map) if map.len() == rows.len() => {
10294            let mut user = vec![pounce_qp::ConsStatus::Inactive; rows.len()];
10295            for (k, &i) in map.iter().enumerate() {
10296                user[i] = rows[k];
10297            }
10298            user
10299        }
10300        _ => rows,
10301    }
10302}
10303
10304/// Inverse of [`working_set_rows_to_user`]: user `g` order → `[c; d]`.
10305fn working_set_rows_to_algorithm(
10306    nlp: &dyn IpoptNlp,
10307    rows: Vec<pounce_qp::ConsStatus>,
10308) -> Vec<pounce_qp::ConsStatus> {
10309    match algorithm_rows_to_user(nlp) {
10310        Some(map) if map.len() == rows.len() => map.iter().map(|&i| rows[i]).collect(),
10311        _ => rows,
10312    }
10313}
10314
10315/// The SQP iterate in the user's index spaces, for the live-inspector window
10316/// (gh#1015). Same conversions as [`finalize_via_sqp`] — `λ_x` is packed
10317/// signed (`z_L − z_U`) and is split by sign — minus the user-callback
10318/// evaluations: `g` comes from the loop's own `[c; d]` values.
10319fn sqp_user_iterate(
10320    nlp: &Rc<RefCell<dyn IpoptNlp>>,
10321    x: &[Number],
10322    lambda_g: &[Number],
10323    lambda_x: &[Number],
10324    c_vals: &[Number],
10325    grad_lag_x: &[Number],
10326    fixed_var_duals: bool,
10327) -> crate::intermediate::UserIterate {
10328    use pounce_linalg::dense_vector::DenseVectorSpace;
10329
10330    // `finalize_solution_z_*` read the compressed x_l / x_u spaces (one
10331    // entry per finite bound, via `x_l_map`), not one entry per variable;
10332    // `split_bound_multipliers` does that split, as crossover does.
10333    let (zl, zu) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, lambda_x);
10334    let nlp = nlp.borrow();
10335    let n_alg = nlp.n() as usize;
10336    let m_eq = nlp.m_eq() as usize;
10337    let m_ineq = nlp.m_ineq() as usize;
10338    let n_user = nlp.n_full_x() as usize;
10339    let m_user = nlp.n_full_g() as usize;
10340
10341    let x_space = DenseVectorSpace::new(n_alg as Index);
10342    let c_space = DenseVectorSpace::new(m_eq as Index);
10343    let d_space = DenseVectorSpace::new(m_ineq as Index);
10344    let dv = |space: &Rc<DenseVectorSpace>, v: &[Number]| {
10345        let mut d = space.make_new_dense();
10346        if !v.is_empty() {
10347            d.set_values(v);
10348        }
10349        d
10350    };
10351
10352    let x_full = nlp.finalize_solution_x(&dv(&x_space, x));
10353    let mut z_l = nlp.finalize_solution_z_l(&dv(&DenseVectorSpace::new(zl.len() as Index), &zl));
10354    if z_l.is_empty() {
10355        z_l = vec![0.0; n_user];
10356    }
10357    let mut z_u = nlp.finalize_solution_z_u(&dv(&DenseVectorSpace::new(zu.len() as Index), &zu));
10358    if z_u.is_empty() {
10359        z_u = vec![0.0; n_user];
10360    }
10361    let (y_c, y_d) = lambda_g.split_at(m_eq.min(lambda_g.len()));
10362    let mut lambda = nlp.finalize_solution_lambda(&dv(&c_space, y_c), &dv(&d_space, y_d));
10363    if lambda.is_empty() {
10364        lambda = vec![0.0; m_user];
10365    }
10366    if fixed_var_duals {
10367        nlp.complete_fixed_var_bound_multipliers(&x_full, &lambda, &mut z_l, &mut z_u);
10368    }
10369    // Everything here is in the space of the TNLP the NLP wraps, which
10370    // under per-variable `user-scaling` is a `ScalingTnlp` seeing
10371    // `x̃ = d ⊙ x`; that wrapper undoes the substitution on the iterate's
10372    // way through its `intermediate_callback`, by its `finalize_solution`'s
10373    // rule (`x = x̃ ⊘ d`, `z = d ⊙ z̃`).
10374    let (c, d) = c_vals.split_at(m_eq.min(c_vals.len()));
10375    let g = nlp.pack_g_for_user(&dv(&c_space, c), &dv(&d_space, d));
10376    // The SQP iterates against the same live bounds (widened only when
10377    // `bound_relax_factor` is set by name on this arm).
10378    let (x_l_alg, x_u_alg) = crate::intermediate::algorithm_x_bounds(&*nlp, &x_full);
10379    crate::intermediate::UserIterate {
10380        x: x_full,
10381        z_l,
10382        z_u,
10383        g,
10384        lambda,
10385        scaling: Some(crate::intermediate::iterate_scaling(&*nlp)),
10386        x_l_alg,
10387        x_u_alg,
10388        grad_lag_x: crate::intermediate::user_grad_lag(&*nlp, grad_lag_x),
10389    }
10390}
10391
10392/// SQP-side analog of [`finalize_via_orig_nlp`]. Hands the SQP
10393/// solution iterate to the user TNLP via the standard
10394/// `finalize_solution` callback. Multiplier lifting goes through
10395/// the same OrigIpoptNlp hooks so the user sees the same shape
10396/// regardless of which algorithm produced the iterate.
10397///
10398/// Returns the user-space objective value on success.
10399fn finalize_via_sqp(
10400    nlp: &Rc<RefCell<dyn IpoptNlp>>,
10401    res: &crate::sqp::SqpResult,
10402    solver_status: pounce_nlp::SolverReturn,
10403    tnlp: &Rc<RefCell<dyn TNLP>>,
10404    sink: &RefCell<Option<FinalizeSnapshot>>,
10405    fixed_var_duals: bool,
10406) -> Result<Number, ()> {
10407    use pounce_linalg::dense_vector::DenseVectorSpace;
10408
10409    let info = tnlp.borrow_mut().get_nlp_info().ok_or(())?;
10410    let n = info.n as usize;
10411    let m = info.m as usize;
10412
10413    // Wrap SQP slices in DenseVectors so we can pass them through
10414    // the OrigIpoptNlp lift_x_to_full / pack_*_for_user hooks.
10415    let nlp_borrow = nlp.borrow();
10416    let n_alg = nlp_borrow.n() as usize;
10417    let m_eq = nlp_borrow.m_eq() as usize;
10418    let m_ineq = nlp_borrow.m_ineq() as usize;
10419    debug_assert_eq!(res.x.len(), n_alg);
10420    debug_assert_eq!(res.lambda_g.len(), m_eq + m_ineq);
10421    debug_assert_eq!(res.lambda_x.len(), n_alg);
10422
10423    let x_space = DenseVectorSpace::new(n_alg as Index);
10424    let c_space = DenseVectorSpace::new(m_eq as Index);
10425    let d_space = DenseVectorSpace::new(m_ineq as Index);
10426
10427    let mut x_dv = x_space.make_new_dense();
10428    x_dv.set_values(&res.x);
10429    let x_vec: Vec<Number> = nlp_borrow.finalize_solution_x(&x_dv);
10430    debug_assert_eq!(x_vec.len(), n);
10431
10432    // λ_x is packed signed (z_l − z_u), one entry per variable. Split it
10433    // into the compressed x_l / x_u spaces `finalize_solution_z_*` read
10434    // (one entry per finite bound): splitting per variable put each
10435    // multiplier on the wrong variable whenever an unbounded one came
10436    // first, as crossover's `split_bound_multipliers` call already avoids.
10437    let (zl_vals, zu_vals) = crate::sqp::ipopt_adapter::split_bound_multipliers(nlp, &res.lambda_x);
10438    let mut z_l_compressed = DenseVectorSpace::new(zl_vals.len() as Index).make_new_dense();
10439    let mut z_u_compressed = DenseVectorSpace::new(zu_vals.len() as Index).make_new_dense();
10440    if !zl_vals.is_empty() {
10441        z_l_compressed.set_values(&zl_vals);
10442    }
10443    if !zu_vals.is_empty() {
10444        z_u_compressed.set_values(&zu_vals);
10445    }
10446    // `finalize_solution_*` (not `pack_*`): report unscaled-Lagrangian duals,
10447    // dividing out `obj_scale_factor` — see `finalize_via_orig_nlp` (F1).
10448    let mut z_l = nlp_borrow.finalize_solution_z_l(&z_l_compressed);
10449    if z_l.is_empty() {
10450        z_l = vec![0.0; n];
10451    }
10452    let mut z_u = nlp_borrow.finalize_solution_z_u(&z_u_compressed);
10453    if z_u.is_empty() {
10454        z_u = vec![0.0; n];
10455    }
10456
10457    // λ_g is [y_c; y_d]; split into the c/d blocks for lift.
10458    let mut y_c_dv = c_space.make_new_dense();
10459    let mut y_d_dv = d_space.make_new_dense();
10460    if m_eq > 0 {
10461        y_c_dv.set_values(&res.lambda_g[..m_eq]);
10462    }
10463    if m_ineq > 0 {
10464        y_d_dv.set_values(&res.lambda_g[m_eq..]);
10465    }
10466    let mut lambda = nlp_borrow.finalize_solution_lambda(&y_c_dv, &y_d_dv);
10467    if lambda.is_empty() {
10468        lambda = vec![0.0; m];
10469    }
10470    if fixed_var_duals {
10471        nlp_borrow.complete_fixed_var_bound_multipliers(&x_vec, &lambda, &mut z_l, &mut z_u);
10472    }
10473    drop(nlp_borrow);
10474
10475    let mut g_final = vec![0.0; m];
10476    let _ = tnlp.borrow_mut().eval_g(&x_vec, true, &mut g_final);
10477    let f_final = tnlp
10478        .borrow_mut()
10479        .eval_f(&x_vec, true)
10480        .unwrap_or(Number::NAN);
10481    let snap = FinalizeSnapshot {
10482        status: solver_status,
10483        x: x_vec,
10484        z_l,
10485        z_u,
10486        g: g_final,
10487        lambda,
10488        obj_value: f_final,
10489        // The SQP arm has no `on_converged` firing.
10490        on_converged_id: None,
10491    };
10492    snap.replay(tnlp);
10493    *sink.borrow_mut() = Some(snap);
10494    Ok(f_final)
10495}
10496
10497/// Whether `options` resolve to the adaptive μ strategy, by the rules
10498/// `IpoptApplication::algorithm_builder_from_options` applies:
10499/// `mehrotra_algorithm=yes` forces adaptive; otherwise an explicit
10500/// `mu_strategy` wins; otherwise a limited-memory Hessian takes upstream's
10501/// quasi-Newton default, adaptive (gh#746), and anything else the registered
10502/// `monotone`.
10503///
10504/// Anything that asks "would this solve already run adaptive?" must ask this,
10505/// not read the raw `mu_strategy` string: under L-BFGS the string is unset and
10506/// the solve is adaptive. The second-opinion ladder read the string, so its
10507/// `mu_strategy=adaptive` rung re-ran a limited-memory base solve
10508/// byte-for-byte (`deb7`, 1610 iterations and `f = 99.636943584` both times).
10509pub fn mu_strategy_resolves_to_adaptive(options: &OptionsList) -> bool {
10510    if matches!(
10511        options.get_string_value("mehrotra_algorithm", ""),
10512        Ok((ref v, true)) if v == "yes"
10513    ) {
10514        return true;
10515    }
10516    if let Ok((v, true)) = options.get_string_value("mu_strategy", "") {
10517        return v == "adaptive";
10518    }
10519    matches!(
10520        options.get_string_value("hessian_approximation", ""),
10521        Ok((ref v, true)) if v == "limited-memory"
10522    )
10523}
10524
10525#[cfg(test)]
10526mod block_structure_tests {
10527    use super::map_block_structure_to_kkt;
10528    use pounce_nlp::tnlp_adapter::BoundClassification;
10529
10530    /// Three variables (the middle one fixed out) and four constraints: two
10531    /// equalities (rows 0 and 3) and two inequalities (rows 1 and 2).
10532    fn classification() -> BoundClassification {
10533        BoundClassification {
10534            n_full_x: 3,
10535            n_full_g: 4,
10536            n_x_fixed: 1,
10537            x_not_fixed_map: vec![0, 2],
10538            x_fixed_map: vec![1],
10539            x_fixed_vals: vec![0.0],
10540            full_to_var: vec![0, -1, 1],
10541            x_l_map: vec![],
10542            x_u_map: vec![],
10543            n_c: 2,
10544            c_map: vec![0, 3],
10545            n_d: 2,
10546            d_map: vec![1, 2],
10547            d_l_map: vec![],
10548            d_u_map: vec![],
10549            full_to_c: vec![0, -1, -1, 1],
10550            full_to_d: vec![-1, 0, 1, -1],
10551        }
10552    }
10553
10554    /// The KKT is `[x | slacks | equality duals | inequality duals]`, so a
10555    /// declaration in the model's terms lands as: the surviving variables'
10556    /// labels, then each inequality's label twice (slack and dual) around the
10557    /// equalities' labels. A variable fixed out of the problem contributes
10558    /// nothing — reading its label anyway would shift every later one.
10559    #[test]
10560    fn model_labels_map_onto_the_kkt_layout() {
10561        let cls = classification();
10562        let var_blocks = vec![7, 99, -1]; // x0 -> block 7, x1 fixed, x2 shared
10563        let con_blocks = vec![5, 6, -1, 8]; // eq 5, ineq 6, ineq shared, eq 8
10564        let labels = map_block_structure_to_kkt(&cls, &var_blocks, &con_blocks).unwrap();
10565        assert_eq!(
10566            labels,
10567            vec![
10568                7, -1, // x: the two unfixed variables
10569                6, -1, // slacks, in d order (rows 1 and 2)
10570                5, 8, // equality duals, in c order (rows 0 and 3)
10571                6, -1, // inequality duals, same order as their slacks
10572            ]
10573        );
10574    }
10575
10576    /// A length that does not match the problem is refused rather than
10577    /// truncated: a structure off by one row declares blocks the matrix does
10578    /// not have, and the solver would only notice as a wrong answer or a
10579    /// rejected partition.
10580    #[test]
10581    fn a_mismatched_declaration_is_refused() {
10582        let cls = classification();
10583        assert!(map_block_structure_to_kkt(&cls, &[1, 2], &[1, 2, 3, 4]).is_err());
10584        assert!(map_block_structure_to_kkt(&cls, &[1, 2, 3], &[1, 2, 3]).is_err());
10585    }
10586}
10587
10588#[cfg(test)]
10589mod tests {
10590    use super::*;
10591
10592    /// pounce#748 — the flipped default is conditional on the caller not
10593    /// having named a `mu_strategy`. All four combinations, because the
10594    /// point of the condition is that an explicit strategy suppresses the
10595    /// automatic retry while an explicit `mu_strategy_fallback` does not.
10596    #[test]
10597    fn mu_strategy_fallback_default_defers_to_an_explicit_strategy() {
10598        // Nothing set: the retry is on.
10599        let app = IpoptApplication::new();
10600        assert!(app.is_mu_strategy_fallback_enabled());
10601
10602        // Caller named a strategy: the automatic retry stands down.
10603        let mut app = IpoptApplication::new();
10604        app.options_mut()
10605            .set_string_value("mu_strategy", "monotone", true, false)
10606            .unwrap();
10607        assert!(!app.is_mu_strategy_fallback_enabled());
10608
10609        // ... unless they also asked for the retry explicitly.
10610        app.options_mut()
10611            .set_string_value("mu_strategy_fallback", "yes", true, false)
10612            .unwrap();
10613        assert!(app.is_mu_strategy_fallback_enabled());
10614
10615        // An explicit "no" is honoured with no strategy set.
10616        let mut app = IpoptApplication::new();
10617        app.options_mut()
10618            .set_string_value("mu_strategy_fallback", "no", true, false)
10619            .unwrap();
10620        assert!(!app.is_mu_strategy_fallback_enabled());
10621    }
10622
10623    /// gh#990: a `mu_strategy` a POUNCE frontend pinned (the Python
10624    /// no-`hessian` path's `monotone`) is not the caller naming a strategy,
10625    /// so the default-on stall retry stays on; an explicit `no` still wins.
10626    #[test]
10627    fn a_pounce_chosen_mu_strategy_keeps_the_fallback_on() {
10628        let mut app = IpoptApplication::new();
10629        app.options_mut()
10630            .set_string_value("hessian_approximation", "limited-memory", true, false)
10631            .unwrap();
10632        app.options_mut()
10633            .set_string_value("mu_strategy", "monotone", true, false)
10634            .unwrap();
10635        assert!(!app.is_mu_strategy_fallback_enabled());
10636        app.mark_mu_strategy_pounce_chosen();
10637        assert!(app.is_mu_strategy_fallback_enabled());
10638        // The pin still decides the schedule: no limited-memory -> adaptive.
10639        assert!(!app.effective_mu_strategy_is_adaptive());
10640        app.options_mut()
10641            .set_string_value("mu_strategy_fallback", "no", true, false)
10642            .unwrap();
10643        assert!(!app.is_mu_strategy_fallback_enabled());
10644    }
10645
10646    use pounce_nlp::tnlp::{
10647        BoundsInfo, IndexStyle, IpoptCq, IpoptData, NlpInfo, ScalingRequest, Solution,
10648        SparsityRequest, StartingPoint,
10649    };
10650
10651    struct Hs071Stub;
10652    impl TNLP for Hs071Stub {
10653        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10654            // HS071 dimensions: n=4, m=2, dense Jacobian (8 nz),
10655            // dense lower-triangular Hessian (10 nz).
10656            Some(NlpInfo {
10657                n: 4,
10658                m: 2,
10659                nnz_jac_g: 8,
10660                nnz_h_lag: 10,
10661                index_style: IndexStyle::C,
10662            })
10663        }
10664        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10665            b.x_l.copy_from_slice(&[1.0; 4]);
10666            b.x_u.copy_from_slice(&[5.0; 4]);
10667            b.g_l.copy_from_slice(&[25.0, 40.0]);
10668            b.g_u.copy_from_slice(&[2.0e19, 40.0]);
10669            true
10670        }
10671        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10672            sp.x.copy_from_slice(&[1.0, 5.0, 5.0, 1.0]);
10673            true
10674        }
10675        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
10676            Some(x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2])
10677        }
10678        fn eval_grad_f(&mut self, _x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10679            grad.fill(0.0);
10680            true
10681        }
10682        fn eval_g(&mut self, _x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10683            g.fill(0.0);
10684            true
10685        }
10686        fn eval_jac_g(
10687            &mut self,
10688            _x: Option<&[Number]>,
10689            _new_x: bool,
10690            mode: SparsityRequest<'_>,
10691        ) -> bool {
10692            if let SparsityRequest::Structure { irow, jcol } = mode {
10693                irow.copy_from_slice(&[0, 0, 0, 0, 1, 1, 1, 1]);
10694                jcol.copy_from_slice(&[0, 1, 2, 3, 0, 1, 2, 3]);
10695            }
10696            true
10697        }
10698        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
10699    }
10700
10701    #[test]
10702    fn application_default_does_not_select_sqp() {
10703        let mut app = IpoptApplication::new();
10704        app.initialize().unwrap();
10705        assert!(!app.is_sqp_algorithm_selected());
10706    }
10707
10708    /// gh#1061: `algorithm=active-set-sqp` starts from the interior point at
10709    /// `n + m ≥ AUTO_HANDOVER_MIN_DIM` — and only there, only when the user
10710    /// asked for the active-set SQP, and never when they set
10711    /// `ipm_sqp_handover` themselves.
10712    #[test]
10713    fn active_set_sqp_hands_over_from_the_interior_point_at_size() {
10714        let big = (AUTO_HANDOVER_MIN_DIM - 1000, 1000);
10715        let small = (AUTO_HANDOVER_MIN_DIM - 1000, 999);
10716        let with = |opts: &str| {
10717            let mut app = IpoptApplication::new();
10718            app.initialize().unwrap();
10719            app.initialize_with_options_str(opts).unwrap();
10720            app
10721        };
10722        let sqp = with("algorithm active-set-sqp\n");
10723        assert!(sqp.sqp_auto_handover(big.0, big.1));
10724        assert!(!sqp.sqp_auto_handover(small.0, small.1));
10725        assert!(with("solver_selection qp-active-set\n").sqp_auto_handover(big.0, big.1));
10726        let ipm = with("");
10727        assert!(
10728            !ipm.sqp_auto_handover(big.0, big.1),
10729            "the IPM is not rerouted"
10730        );
10731        for set in ["no", "yes"] {
10732            let app = with(&format!(
10733                "algorithm active-set-sqp\nipm_sqp_handover {set}\n"
10734            ));
10735            assert!(
10736                !app.sqp_auto_handover(big.0, big.1),
10737                "ipm_sqp_handover={set} was set, so the user decides"
10738            );
10739        }
10740    }
10741
10742    #[test]
10743    fn application_routes_to_sqp_when_algorithm_option_set() {
10744        let mut app = IpoptApplication::new();
10745        app.initialize().unwrap();
10746        app.initialize_with_options_str("algorithm active-set-sqp\n")
10747            .unwrap();
10748        assert!(app.is_sqp_algorithm_selected());
10749    }
10750
10751    #[test]
10752    fn feral_min_par_flops_option_reaches_config() {
10753        let mut app = IpoptApplication::new();
10754        app.initialize().unwrap();
10755        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10756        // which leaves it None (inherit feral's built-in default) when the
10757        // POUNCE_FERAL_MIN_PAR_FLOPS env var is also absent.
10758        assert_eq!(
10759            feral_config_from_options(app.options()).min_par_flops,
10760            None,
10761            "unset feral_min_par_flops should not force an override"
10762        );
10763        // Explicit set is mapped through, cast to u64. `0` is the "dispatch
10764        // on every eligible tree" setting and must survive the cast.
10765        app.initialize_with_options_str("feral_min_par_flops 0\n")
10766            .unwrap();
10767        assert_eq!(
10768            feral_config_from_options(app.options()).min_par_flops,
10769            Some(0)
10770        );
10771        // A large finite value passes through intact (5e8 > i32::MAX, which
10772        // is why this is a number option, not an integer one).
10773        app.initialize_with_options_str("feral_min_par_flops 5e8\n")
10774            .unwrap();
10775        assert_eq!(
10776            feral_config_from_options(app.options()).min_par_flops,
10777            Some(500_000_000)
10778        );
10779    }
10780
10781    #[test]
10782    fn feral_refine_steps_option_reaches_config() {
10783        let mut app = IpoptApplication::new();
10784        app.initialize().unwrap();
10785        // Unset: falls through to FeralConfig::from_env, which resolves to
10786        // feral's own DEFAULT_REFINE_MAX_STEPS. The bump to feral 0.17.0 is
10787        // deliberately behaviour-preserving here — the cap that gh#710 wants
10788        // to measure (1) is not yet the default.
10789        assert_eq!(
10790            feral_config_from_options(app.options()).refine_max_steps,
10791            pounce_feral::FeralConfig::default().refine_max_steps,
10792            "unset feral_refine_steps must keep feral's own default"
10793        );
10794        // The setting gh#710 exists to evaluate.
10795        app.initialize_with_options_str("feral_refine_steps 1\n")
10796            .unwrap();
10797        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 1);
10798        // `0` is a legal cap (zero corrections, refined entry point still
10799        // taken) and must not be read as "unset".
10800        app.initialize_with_options_str("feral_refine_steps 0\n")
10801            .unwrap();
10802        assert_eq!(feral_config_from_options(app.options()).refine_max_steps, 0);
10803    }
10804
10805    #[test]
10806    fn feral_static_pivoting_option_reaches_config() {
10807        let mut app = IpoptApplication::new();
10808        app.initialize().unwrap();
10809        // Unset on the OptionsList: falls through to FeralConfig::from_env,
10810        // which leaves it None (inherit feral's delayed-pivot default) when
10811        // the POUNCE_FERAL_STATIC_PIVOTING env var is also absent — so the
10812        // default numeric path is unchanged.
10813        assert_eq!(
10814            feral_config_from_options(app.options()).static_pivoting,
10815            None,
10816            "unset feral_static_pivoting must not force a numeric override"
10817        );
10818        // Explicit `yes` maps to Some(true): every supernode factors with
10819        // delayed pivoting disabled (feral#8 cascade breaker).
10820        app.initialize_with_options_str("feral_static_pivoting yes\n")
10821            .unwrap();
10822        assert_eq!(
10823            feral_config_from_options(app.options()).static_pivoting,
10824            Some(true)
10825        );
10826        // Explicit `no` maps to Some(false): keep delayed pivoting on
10827        // (distinct from unset, which merely inherits the default).
10828        app.initialize_with_options_str("feral_static_pivoting no\n")
10829            .unwrap();
10830        assert_eq!(
10831            feral_config_from_options(app.options()).static_pivoting,
10832            Some(false)
10833        );
10834    }
10835
10836    /// Convex equality NLP fixture for end-to-end SQP testing
10837    /// through `IpoptApplication`:
10838    ///
10839    ///     min ½(x₁² + x₂²) − x₁ − 2x₂  s.t.  x₁ + x₂ = 1
10840    ///
10841    /// Closed form: x* = (0, 1), obj = -1.5, λ_g = 1.
10842    struct ConvexEqTnlp {
10843        finalize_called: std::rc::Rc<std::cell::RefCell<Option<(Vec<Number>, Number)>>>,
10844    }
10845    impl TNLP for ConvexEqTnlp {
10846        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10847            Some(NlpInfo {
10848                n: 2,
10849                m: 1,
10850                nnz_jac_g: 2,
10851                nnz_h_lag: 2,
10852                index_style: IndexStyle::C,
10853            })
10854        }
10855        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10856            b.x_l.copy_from_slice(&[-2.0e19; 2]);
10857            b.x_u.copy_from_slice(&[2.0e19; 2]);
10858            b.g_l.copy_from_slice(&[1.0]);
10859            b.g_u.copy_from_slice(&[1.0]);
10860            true
10861        }
10862        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10863            sp.x.copy_from_slice(&[0.0, 0.0]);
10864            true
10865        }
10866        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
10867            Some(0.5 * (x[0] * x[0] + x[1] * x[1]) - x[0] - 2.0 * x[1])
10868        }
10869        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
10870            grad[0] = x[0] - 1.0;
10871            grad[1] = x[1] - 2.0;
10872            true
10873        }
10874        fn eval_g(&mut self, x: &[Number], _new_x: bool, g: &mut [Number]) -> bool {
10875            g[0] = x[0] + x[1];
10876            true
10877        }
10878        fn eval_jac_g(
10879            &mut self,
10880            _x: Option<&[Number]>,
10881            _new_x: bool,
10882            mode: SparsityRequest<'_>,
10883        ) -> bool {
10884            match mode {
10885                SparsityRequest::Structure { irow, jcol } => {
10886                    irow.copy_from_slice(&[0, 0]);
10887                    jcol.copy_from_slice(&[0, 1]);
10888                }
10889                SparsityRequest::Values { values, .. } => {
10890                    values.copy_from_slice(&[1.0, 1.0]);
10891                }
10892            }
10893            true
10894        }
10895        fn eval_h(
10896            &mut self,
10897            _x: Option<&[Number]>,
10898            _new_x: bool,
10899            _obj_factor: Number,
10900            _lambda: Option<&[Number]>,
10901            _new_lambda: bool,
10902            mode: SparsityRequest<'_>,
10903        ) -> bool {
10904            match mode {
10905                SparsityRequest::Structure { irow, jcol } => {
10906                    irow.copy_from_slice(&[0, 1]);
10907                    jcol.copy_from_slice(&[0, 1]);
10908                }
10909                SparsityRequest::Values { values, .. } => {
10910                    values.copy_from_slice(&[1.0, 1.0]);
10911                }
10912            }
10913            true
10914        }
10915        fn finalize_solution(&mut self, sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {
10916            *self.finalize_called.borrow_mut() = Some((sol.x.to_vec(), sol.obj_value));
10917        }
10918    }
10919
10920    /// A TNLP that solves normally once, then declines to supply bounds.
10921    ///
10922    /// The second `optimize_constrained` therefore bails long before the
10923    /// statistics block that records `row_scaling_active`, which is the
10924    /// path the fail-closed reset exists for.
10925    struct DescribesItselfOnce {
10926        /// Flipped by the test between the two solves. A call counter
10927        /// would not work: these hooks are called more than once per
10928        /// solve, so it would trip inside the first one.
10929        refuse: std::rc::Rc<std::cell::Cell<bool>>,
10930        inner: ExactQuadratic,
10931    }
10932    impl TNLP for DescribesItselfOnce {
10933        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
10934            self.inner.get_nlp_info()
10935        }
10936        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
10937            // Declining here is a documented TNLP outcome and unwinds
10938            // cleanly; declining `get_nlp_info` mid-flight panics instead,
10939            // which would test the panic path rather than the reset.
10940            if self.refuse.get() {
10941                return false;
10942            }
10943            self.inner.get_bounds_info(b)
10944        }
10945        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
10946            self.inner.get_starting_point(sp)
10947        }
10948        fn eval_f(&mut self, x: &[Number], n: bool) -> Option<Number> {
10949            self.inner.eval_f(x, n)
10950        }
10951        fn eval_grad_f(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10952            self.inner.eval_grad_f(x, n, g)
10953        }
10954        fn eval_g(&mut self, x: &[Number], n: bool, g: &mut [Number]) -> bool {
10955            self.inner.eval_g(x, n, g)
10956        }
10957        fn eval_jac_g(&mut self, x: Option<&[Number]>, n: bool, mode: SparsityRequest<'_>) -> bool {
10958            self.inner.eval_jac_g(x, n, mode)
10959        }
10960        fn eval_h(
10961            &mut self,
10962            x: Option<&[Number]>,
10963            n: bool,
10964            o: Number,
10965            l: Option<&[Number]>,
10966            nl: bool,
10967            mode: SparsityRequest<'_>,
10968        ) -> bool {
10969            self.inner.eval_h(x, n, o, l, nl, mode)
10970        }
10971        fn finalize_solution(&mut self, s: Solution<'_>, d: &IpoptData, c: &IpoptCq) {
10972            self.inner.finalize_solution(s, d, c)
10973        }
10974    }
10975
10976    /// gh#794 review round 2: `row_scaling_active` must be fail-closed.
10977    ///
10978    /// It is written near the end of `optimize_constrained`, from the NLP
10979    /// that solve built. A solve that bails before that point used to
10980    /// leave the *previous* solve's value in place — and the ℓ₁ outer
10981    /// loop calls `optimize_constrained` repeatedly and reads the flag
10982    /// after each call, so a stale `Some(false)` would let it mirror an
10983    /// original-units violation into the scaled family. That is exactly
10984    /// the units contract the flag was added to protect.
10985    ///
10986    /// The two solves here are the shape that matters: the first records
10987    /// a verdict, the second never gets far enough to record one.
10988    /// Removing the reset at the top of `optimize_constrained` makes this
10989    /// fail with `Some(false)` where `None` is required — checked, not
10990    /// assumed.
10991    #[test]
10992    fn row_scaling_active_is_cleared_when_a_later_solve_bails_early() {
10993        let mut app = IpoptApplication::new();
10994        app.initialize().unwrap();
10995
10996        // Solve 1: reaches the statistics block and records a verdict.
10997        // `ExactQuadratic` supplies `eval_h`, so the solve stays on the
10998        // exact-Hessian NLP path that writes this flag; a fixture without
10999        // one lands on L-BFGS instead.
11000        let refuse = std::rc::Rc::new(std::cell::Cell::new(false));
11001        let first = std::rc::Rc::new(std::cell::RefCell::new(DescribesItselfOnce {
11002            refuse: std::rc::Rc::clone(&refuse),
11003            inner: ExactQuadratic,
11004        }));
11005        let _ = app
11006            .optimize_tnlp(std::rc::Rc::clone(&first) as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
11007        assert!(
11008            app.row_scaling_active.get().is_some(),
11009            "the first solve did not record a row-scaling verdict, so this \
11010             test cannot show the second one clearing it",
11011        );
11012
11013        // Solve 2, same application: bails before recording anything.
11014        refuse.set(true);
11015        let _ = app.optimize_tnlp(first as std::rc::Rc<std::cell::RefCell<dyn TNLP>>);
11016
11017        assert_eq!(
11018            app.row_scaling_active.get(),
11019            None,
11020            "a solve that bailed before recording row scaling left the \
11021             previous solve's verdict in place; the ℓ₁ outer loop would \
11022             read it as fact and mirror an original-units violation into \
11023             the scaled family (gh#794 review round 2)",
11024        );
11025    }
11026
11027    #[test]
11028    fn application_sqp_path_solves_convex_eq_nlp_and_finalizes() {
11029        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
11030        let tnlp = std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
11031            finalize_called: std::rc::Rc::clone(&finalize_slot),
11032        }));
11033
11034        let mut app = IpoptApplication::new();
11035        app.initialize().unwrap();
11036        app.initialize_with_options_str("algorithm active-set-sqp\n")
11037            .unwrap();
11038        let status = app.optimize_tnlp(tnlp);
11039        assert_eq!(status, ApplicationReturnStatus::SolveSucceeded);
11040
11041        // The TNLP's finalize_solution must have been invoked.
11042        let recv = finalize_slot.borrow().clone();
11043        let (x_recv, obj_recv) = recv.expect("finalize_solution was not called");
11044        assert_eq!(x_recv.len(), 2);
11045        assert!((x_recv[0] - 0.0).abs() < 1e-6, "x[0] = {}", x_recv[0]);
11046        assert!((x_recv[1] - 1.0).abs() < 1e-6, "x[1] = {}", x_recv[1]);
11047        assert!(
11048            (obj_recv - (-1.5)).abs() < 1e-6,
11049            "obj = {} but expected -1.5",
11050            obj_recv
11051        );
11052    }
11053
11054    #[test]
11055    fn application_routes_to_sqp_case_insensitively() {
11056        let mut app = IpoptApplication::new();
11057        app.initialize().unwrap();
11058        app.initialize_with_options_str("algorithm Active-Set-SQP\n")
11059            .unwrap();
11060        // get_string_value may return the value as-stored (no
11061        // normalization); the dispatch must handle case
11062        // insensitively per the c11 design choice.
11063        assert!(app.is_sqp_algorithm_selected());
11064    }
11065
11066    #[test]
11067    fn application_constructs_and_loads_options() {
11068        let mut app = IpoptApplication::new();
11069        app.initialize().unwrap();
11070        // ipopt.opt-style file: an integer-typed option registered by
11071        // the Interfaces layer.
11072        app.initialize_with_options_str("print_level 5\nfile_print_level 7\n")
11073            .unwrap();
11074        let (level, found) = app.options().get_integer_value("print_level", "").unwrap();
11075        assert!(found);
11076        assert_eq!(level, 5);
11077    }
11078
11079    #[test]
11080    fn application_sqp_suboptions_propagate_to_builder() {
11081        // All SQP suboptions are read by algorithm_builder_snapshot
11082        // and baked into the builder's `sqp` field.
11083        let mut app = IpoptApplication::new();
11084        app.initialize().unwrap();
11085        app.initialize_with_options_str(
11086            "algorithm active-set-sqp\n\
11087             sqp_globalization l1-elastic\n\
11088             sqp_hessian lbfgs\n\
11089             sqp_max_iter 17\n\
11090             sqp_tol 1e-7\n\
11091             sqp_constr_viol_tol 1e-5\n\
11092             sqp_dual_inf_tol 1e-3\n\
11093             sqp_l1_penalty 2.5\n\
11094             sqp_bt_reduction 0.25\n\
11095             sqp_bt_min_alpha 1e-10\n\
11096             sqp_print_level 2\n\
11097             sqp_lbfgs_max_history 12\n",
11098        )
11099        .unwrap();
11100        let snap = app.algorithm_builder_snapshot();
11101        assert_eq!(
11102            snap.sqp.globalization,
11103            crate::sqp::SqpGlobalization::L1Elastic
11104        );
11105        assert_eq!(snap.sqp.hessian, crate::sqp::SqpHessianSource::Lbfgs);
11106        assert_eq!(snap.sqp.max_iter, 17);
11107        assert!((snap.sqp.tol - 1e-7).abs() < 1e-18);
11108        assert!((snap.sqp.constr_viol_tol - 1e-5).abs() < 1e-18);
11109        assert!((snap.sqp.dual_inf_tol - 1e-3).abs() < 1e-18);
11110        assert!((snap.sqp.l1_penalty - 2.5).abs() < 1e-18);
11111        assert!((snap.sqp.bt_reduction - 0.25).abs() < 1e-18);
11112        assert!((snap.sqp.bt_min_alpha - 1e-10).abs() < 1e-18);
11113        assert_eq!(snap.sqp.print_level, 2);
11114        assert_eq!(snap.sqp.lbfgs_max_history, 12);
11115    }
11116
11117    /// Every `sqp_qp_*` key that [`apply_qp_subproblem_options`] reads must
11118    /// actually be *registered*, and must reach `pounce_qp::QpOptions`.
11119    ///
11120    /// The whole family was readable-but-unregistered (gh #360): the options
11121    /// registry rejected each one with OPTION_INVALID, so the reader was
11122    /// unreachable and the documented knobs were unusable. This is the guard
11123    /// that class of omission needs — it fails both if a key stops being
11124    /// registered and if a newly-read key is never registered at all.
11125    #[test]
11126    fn issue_1054_schur_updates_follow_size_unless_set() {
11127        let mut app = IpoptApplication::new();
11128        app.initialize().unwrap();
11129        app.initialize_with_options_str("algorithm active-set-sqp\n")
11130            .unwrap();
11131        assert_eq!(
11132            app.algorithm_builder_snapshot().sqp.qp_schur_min_dim,
11133            Some(crate::sqp::options::DEFAULT_QP_SCHUR_MIN_DIM)
11134        );
11135        for v in ["yes", "no"] {
11136            let mut app = IpoptApplication::new();
11137            app.initialize().unwrap();
11138            app.initialize_with_options_str(&format!(
11139                "algorithm active-set-sqp\nsqp_qp_use_schur_updates {v}\n"
11140            ))
11141            .unwrap();
11142            let snap = app.algorithm_builder_snapshot();
11143            assert_eq!(snap.sqp.qp_schur_min_dim, None, "{v}: explicit wins");
11144            assert_eq!(snap.sqp_qp.use_schur_updates, v == "yes");
11145        }
11146    }
11147
11148    #[test]
11149    fn application_sqp_qp_subproblem_options_are_registered_and_propagate() {
11150        use pounce_qp::AntiCyclingChoice;
11151
11152        // Source of truth: the keys `apply_qp_subproblem_options` reads.
11153        // Kept in step with that function by the round-trip assertions below.
11154        let mut app = IpoptApplication::new();
11155        app.initialize().unwrap();
11156        app.initialize_with_options_str(
11157            "algorithm active-set-sqp\n\
11158             sqp_qp_max_iter 37\n\
11159             sqp_qp_feas_tol 1e-7\n\
11160             sqp_qp_opt_tol 2e-7\n\
11161             sqp_qp_elastic_gamma 1e4\n\
11162             sqp_qp_anti_cycling bland\n\
11163             sqp_qp_use_schur_updates yes\n\
11164             sqp_qp_max_schur_updates_before_refactor 12\n\
11165             sqp_qp_use_homotopy yes\n\
11166             sqp_qp_certify_second_order yes\n",
11167        )
11168        .expect("every sqp_qp_* option must be registered (gh #360)");
11169
11170        let qp = &app.algorithm_builder_snapshot().sqp_qp;
11171        assert_eq!(qp.max_iter, 37);
11172        assert!((qp.feas_tol - 1e-7).abs() < 1e-20);
11173        assert!((qp.opt_tol - 2e-7).abs() < 1e-20);
11174        assert!((qp.elastic_gamma - 1e4).abs() < 1e-9);
11175        assert_eq!(qp.anti_cycling, AntiCyclingChoice::Bland);
11176        // The Schur update path was implemented but reachable only through
11177        // `SqpAlgorithm::with_qp_options`, so no CLI/library user could turn
11178        // it on — the same unreachable-knob defect gh #360 fixed for the rest
11179        // of this family.
11180        assert!(qp.use_schur_updates);
11181        assert_eq!(qp.max_schur_updates_before_refactor, 12);
11182        assert!(qp.use_homotopy);
11183        // gh #848. Off by default on this path (see
11184        // `QpOptions::sqp_subproblem`), so the value that proves the wire is
11185        // live is `yes` — asserting the default would pass on a reader that
11186        // never ran.
11187        assert!(qp.certify_second_order);
11188
11189        // Untouched options must keep the SQP subproblem base, not be
11190        // overwritten with zeros by the "explicitly set" gate. That base is
11191        // `QpOptions::default()` in every field but one; the exception is
11192        // asserted below.
11193        let mut app = IpoptApplication::new();
11194        app.initialize().unwrap();
11195        app.initialize_with_options_str("algorithm active-set-sqp\n")
11196            .unwrap();
11197        let defaults = pounce_qp::QpOptions::default();
11198        let qp = &app.algorithm_builder_snapshot().sqp_qp;
11199        assert_eq!(qp.max_iter, defaults.max_iter);
11200        assert!((qp.feas_tol - defaults.feas_tol).abs() < 1e-20);
11201        assert!((qp.opt_tol - defaults.opt_tol).abs() < 1e-20);
11202        assert_eq!(qp.anti_cycling, defaults.anti_cycling);
11203        // Off in the base QP options: the SQP driver turns it on per solve
11204        // from `n + m >= 500` (gh#1054; measured on Maros-Meszaros, see the
11205        // option text). Do not move that threshold without re-running the
11206        // comparison.
11207        assert!(!qp.use_schur_updates);
11208        assert_eq!(
11209            qp.max_schur_updates_before_refactor,
11210            defaults.max_schur_updates_before_refactor
11211        );
11212        // Off by default *on the SQP path*, and deliberately different from
11213        // `QpOptions::default()` — which is what a standalone `solve_qp`
11214        // gets, and where it is on. gh #848 / gh #856.
11215        assert!(!qp.certify_second_order);
11216        assert!(pounce_qp::QpOptions::default().certify_second_order);
11217    }
11218
11219    /// The other direction of the gh #360 guard: every **registered**
11220    /// `sqp_qp_*` option must be one `apply_qp_subproblem_options` actually
11221    /// reads.
11222    ///
11223    /// The sister test above checks read-keys-are-registered. It cannot catch
11224    /// the inverse, and the inverse happened: `sqp_qp_use_homotopy` was
11225    /// registered with the homotopy work and never wired into the reader, so
11226    /// setting it on the SQP path silently did nothing while the option's own
11227    /// documentation described what it would do. A registered knob that no
11228    /// code reads is worse than a missing one — it validates, it accepts a
11229    /// value, and it lies.
11230    ///
11231    /// Adding a new `sqp_qp_*` option therefore fails here until it is both
11232    /// read by `apply_qp_subproblem_options` and asserted in the round-trip
11233    /// test above.
11234    #[test]
11235    fn application_every_registered_sqp_qp_option_is_read_by_the_subproblem_reader() {
11236        let mut app = IpoptApplication::new();
11237        app.initialize().unwrap();
11238
11239        let mut registered: Vec<String> = app
11240            .registered_options()
11241            .registered_options_in_order()
11242            .iter()
11243            .map(|o| o.name.clone())
11244            .filter(|n| n.starts_with("sqp_qp_"))
11245            .collect();
11246        registered.sort();
11247
11248        // Kept in step by hand with the `options.get_*_value("sqp_qp_…")`
11249        // calls in `apply_qp_subproblem_options`, and cross-checked by the
11250        // round-trip assertions in the sister test.
11251        let mut read_by_the_reader = vec![
11252            "sqp_qp_anti_cycling".to_string(),
11253            "sqp_qp_certify_second_order".to_string(),
11254            "sqp_qp_elastic_gamma".to_string(),
11255            "sqp_qp_feas_tol".to_string(),
11256            "sqp_qp_max_iter".to_string(),
11257            "sqp_qp_max_schur_updates_before_refactor".to_string(),
11258            "sqp_qp_opt_tol".to_string(),
11259            "sqp_qp_use_homotopy".to_string(),
11260            "sqp_qp_use_schur_updates".to_string(),
11261        ];
11262        read_by_the_reader.sort();
11263
11264        assert_eq!(
11265            registered, read_by_the_reader,
11266            "registered sqp_qp_* options and the ones \
11267             `apply_qp_subproblem_options` reads have diverged. A key that is \
11268             registered but unread is a no-op knob with working documentation \
11269             (that is how `sqp_qp_use_homotopy` shipped); a key read but not \
11270             registered is gh #360. Wire it up in both places, assert it in \
11271             `application_sqp_qp_subproblem_options_are_registered_and_propagate`, \
11272             then add it here."
11273        );
11274    }
11275
11276    #[test]
11277    fn application_sqp_hessian_approximation_maps_to_damped_bfgs() {
11278        // The frontend sets `hessian_approximation = limited-memory` when no
11279        // exact Lagrangian Hessian is available (e.g. `pounce.minimize` with
11280        // no `hess`). On the active-set-SQP path that must resolve to the
11281        // dense Powell-damped BFGS, NOT the limited-memory update: L-BFGS
11282        // materializes the same dense Hessian for the QP subproblem yet stalls
11283        // (`Search_Direction_Becomes_Too_Small` / wrong `x`) on convex QPs with
11284        // an active inequality (issue #358); damped-BFGS solves them.
11285        let mut app = IpoptApplication::new();
11286        app.initialize().unwrap();
11287        app.initialize_with_options_str(
11288            "algorithm active-set-sqp\n\
11289             hessian_approximation limited-memory\n",
11290        )
11291        .unwrap();
11292        let snap = app.algorithm_builder_snapshot().sqp;
11293        assert_eq!(snap.hessian, crate::sqp::SqpHessianSource::QuasiNewtonAuto);
11294        // ...which is the dense update at or below the ceiling, and the
11295        // lifted limited-memory one above it (gh#1054).
11296        assert_eq!(
11297            snap.hessian
11298                .resolve(snap.dense_hessian_max_n, snap.dense_hessian_max_n),
11299            crate::sqp::SqpHessianSource::DampedBfgs
11300        );
11301        assert_eq!(
11302            snap.hessian
11303                .resolve(snap.dense_hessian_max_n + 1, snap.dense_hessian_max_n),
11304            crate::sqp::SqpHessianSource::Lbfgs
11305        );
11306
11307        // An explicit `sqp_hessian = lbfgs` is still honored (it is read after
11308        // `hessian_approximation`, so it wins): callers who genuinely want the
11309        // limited-memory update can still ask for it.
11310        let mut app = IpoptApplication::new();
11311        app.initialize().unwrap();
11312        app.initialize_with_options_str(
11313            "algorithm active-set-sqp\n\
11314             hessian_approximation limited-memory\n\
11315             sqp_hessian lbfgs\n",
11316        )
11317        .unwrap();
11318        assert_eq!(
11319            app.algorithm_builder_snapshot().sqp.hessian,
11320            crate::sqp::SqpHessianSource::Lbfgs
11321        );
11322    }
11323
11324    /// `builder.linear_solver` must name the backend that will actually be
11325    /// built, not the one the option string asked for.
11326    ///
11327    /// MA57 is behind the optional `ma57` cargo feature; without it
11328    /// `default_backend_factory` silently substitutes FERAL. Recording `Ma57`
11329    /// anyway made the field disagree with reality, and the Schur KKT gate in
11330    /// `alg_builder::build_with_backend` (which tests `== Feral`) consumed that
11331    /// disagreement — so `set_kkt_schur_block()` never engaged on the default
11332    /// pure-Rust build for any user, while the transparent fallback kept every
11333    /// answer correct and every test green.
11334    #[test]
11335    fn application_linear_solver_records_the_effective_backend() {
11336        // Default options resolve to FERAL in *every* build. The registry
11337        // used to default to upstream's "ma57", which meant an HSL build
11338        // silently ran MA57 without being asked and a pure-Rust build
11339        // advertised a backend it did not contain; the default now names
11340        // pounce's own solver and HSL is opt-in (gh#483 follow-up).
11341        let mut app = IpoptApplication::new();
11342        app.initialize().unwrap();
11343        assert_eq!(
11344            app.algorithm_builder_from_options().linear_solver,
11345            LinearSolverChoice::Feral,
11346            "the registered default is `feral`, in an ma57 build too"
11347        );
11348
11349        // An explicit ma57 request resolves the same way.
11350        let mut app = IpoptApplication::new();
11351        app.initialize().unwrap();
11352        app.initialize_with_options_str("linear_solver ma57\n")
11353            .unwrap();
11354        let got = app.algorithm_builder_from_options().linear_solver;
11355        if cfg!(feature = "ma57") {
11356            assert_eq!(got, LinearSolverChoice::Ma57);
11357        } else {
11358            assert_eq!(got, LinearSolverChoice::Feral);
11359        }
11360
11361        // An explicit feral request is honored in every build.
11362        let mut app = IpoptApplication::new();
11363        app.initialize().unwrap();
11364        app.initialize_with_options_str("linear_solver feral\n")
11365            .unwrap();
11366        assert_eq!(
11367            app.algorithm_builder_from_options().linear_solver,
11368            LinearSolverChoice::Feral
11369        );
11370    }
11371
11372    /// gh#746. `IpAlgBuilder.cpp:1059` substitutes `adaptive` for the
11373    /// registered `monotone` when `hessian_approximation` is
11374    /// limited-memory and the caller left `mu_strategy` alone. pounce
11375    /// read the registered default unconditionally, which is a
11376    /// different barrier schedule on the whole quasi-Newton arm.
11377    #[test]
11378    fn limited_memory_defaults_mu_strategy_to_adaptive() {
11379        // Exact Hessian, nothing set: monotone, as registered.
11380        let mut app = IpoptApplication::new();
11381        app.initialize().unwrap();
11382        assert_eq!(
11383            app.algorithm_builder_from_options().mu_strategy,
11384            MuStrategyChoice::Monotone,
11385            "the exact arm must keep the registered default"
11386        );
11387
11388        // Limited memory, nothing set: adaptive.
11389        let mut app = IpoptApplication::new();
11390        app.initialize().unwrap();
11391        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11392            .unwrap();
11393        assert_eq!(
11394            app.algorithm_builder_from_options().mu_strategy,
11395            MuStrategyChoice::Adaptive,
11396            "limited-memory must take upstream's quasi-Newton default"
11397        );
11398
11399        // An explicit `monotone` still wins — the substitution is only
11400        // for an absent option.
11401        let mut app = IpoptApplication::new();
11402        app.initialize().unwrap();
11403        app.initialize_with_options_str(
11404            "hessian_approximation limited-memory\n\
11405             mu_strategy monotone\n",
11406        )
11407        .unwrap();
11408        assert_eq!(
11409            app.algorithm_builder_from_options().mu_strategy,
11410            MuStrategyChoice::Monotone,
11411            "an explicit mu_strategy must not be overridden"
11412        );
11413    }
11414
11415    /// The μ-strategy auto-fallback retries with the *other* strategy.
11416    /// Under limited-memory the first attempt is adaptive, so the flip
11417    /// has to be monotone — reading the registered default there would
11418    /// re-run the strategy that just stalled (gh#746).
11419    #[test]
11420    fn fallback_flip_follows_the_resolved_mu_strategy() {
11421        let mut app = IpoptApplication::new();
11422        app.initialize().unwrap();
11423        assert!(
11424            !app.effective_mu_strategy_is_adaptive(),
11425            "unset + exact resolves to monotone"
11426        );
11427
11428        let mut app = IpoptApplication::new();
11429        app.initialize().unwrap();
11430        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11431            .unwrap();
11432        assert!(
11433            app.effective_mu_strategy_is_adaptive(),
11434            "unset + limited-memory resolves to adaptive"
11435        );
11436
11437        let mut app = IpoptApplication::new();
11438        app.initialize().unwrap();
11439        app.initialize_with_options_str(
11440            "hessian_approximation limited-memory\n\
11441             mu_strategy monotone\n",
11442        )
11443        .unwrap();
11444        assert!(
11445            !app.effective_mu_strategy_is_adaptive(),
11446            "an explicit monotone under limited-memory resolves to monotone"
11447        );
11448    }
11449
11450    #[test]
11451    fn application_limited_memory_options_propagate_to_builder() {
11452        use crate::hess::lim_mem_quasi_newton::UpdateType;
11453
11454        // Default: no options set -> bit-exact with Ipopt's default
11455        // (bfgs, history 6). This is what the IPM path runs unless the
11456        // user opts in, so it must not drift.
11457        let mut app = IpoptApplication::new();
11458        app.initialize().unwrap();
11459        let def = app.algorithm_builder_from_options();
11460        assert_eq!(def.limited_memory_update_type, UpdateType::Bfgs);
11461        assert_eq!(def.limited_memory_max_history, 6);
11462
11463        // `limited_memory_update_type=sr1` and a custom history length
11464        // must reach the builder (these were registered upstream but
11465        // read nowhere on the IPM path before — see #131). Honoring
11466        // them is what lets SR1 break the monotone L-BFGS stall.
11467        let mut app = IpoptApplication::new();
11468        app.initialize().unwrap();
11469        app.initialize_with_options_str(
11470            "hessian_approximation limited-memory\n\
11471             limited_memory_update_type sr1\n\
11472             limited_memory_max_history 9\n",
11473        )
11474        .unwrap();
11475        let snap = app.algorithm_builder_from_options();
11476        assert_eq!(snap.limited_memory_update_type, UpdateType::Sr1);
11477        assert_eq!(snap.limited_memory_max_history, 9);
11478    }
11479
11480    #[test]
11481    fn application_recalc_y_is_wired_and_defaults_off() {
11482        // #677. Upstream registers `recalc_y` as `no`, but its option
11483        // text ends "If a limited memory quasi-Newton option is chosen,
11484        // this is used by default" — the effective default is
11485        // conditional on the Hessian approximation. pounce refused the
11486        // option outright before this, so an L-BFGS user had no way to
11487        // reach Ipopt's behaviour.
11488
11489        // Exact Hessian: off, matching the registered default.
11490        let mut app = IpoptApplication::new();
11491        app.initialize().unwrap();
11492        let b = app.algorithm_builder_from_options();
11493        assert!(!b.recalc_y, "exact-Hessian default must stay off");
11494        assert_eq!(b.recalc_y_feas_tol, 1e-6, "default changed");
11495
11496        // Limited memory: also off. Upstream's option text says it is
11497        // used by default there; pounce deliberately does not, because
11498        // auto-enabling took 7 of 57 fixtures from solved to not solved
11499        // on the L-BFGS leg with nothing moving the other way. See the
11500        // read site in `algorithm_builder_from_options`. If this
11501        // assertion is what fails, the auto-enable is being restored —
11502        // re-run `scripts/sweep-fixtures.sh` and explain those 7 first.
11503        let mut app = IpoptApplication::new();
11504        app.initialize().unwrap();
11505        app.initialize_with_options_str("hessian_approximation limited-memory\n")
11506            .unwrap();
11507        assert!(
11508            !app.algorithm_builder_from_options().recalc_y,
11509            "limited-memory must not silently enable recalc_y"
11510        );
11511
11512        // An explicit `yes` reaches the exact-Hessian path, which
11513        // used to be refused as unimplemented.
11514        let mut app = IpoptApplication::new();
11515        app.initialize().unwrap();
11516        app.initialize_with_options_str("recalc_y yes\nrecalc_y_feas_tol 1e-3\n")
11517            .unwrap();
11518        let b = app.algorithm_builder_from_options();
11519        assert!(b.recalc_y);
11520        assert_eq!(b.recalc_y_feas_tol, 1e-3);
11521    }
11522
11523    #[test]
11524    fn application_limited_memory_initialization_propagates_to_builder() {
11525        use crate::hess::lim_mem_quasi_newton::InitialApprox;
11526
11527        // #677: registered with upstream's `scalar1` default and read
11528        // nowhere, so every limited-memory solve ran `scalar2` and
11529        // setting the option was a silent no-op. Each keyword must now
11530        // reach the builder.
11531        for (kw, want) in [
11532            ("scalar1", InitialApprox::Scalar1),
11533            ("scalar2", InitialApprox::Scalar2),
11534            ("scalar3", InitialApprox::Scalar3),
11535            ("scalar4", InitialApprox::Scalar4),
11536            ("constant", InitialApprox::Constant),
11537            ("history-max", InitialApprox::HistoryMax),
11538        ] {
11539            let mut app = IpoptApplication::new();
11540            app.initialize().unwrap();
11541            app.initialize_with_options_str(&format!(
11542                "hessian_approximation limited-memory\n\
11543                 limited_memory_initialization {kw}\n"
11544            ))
11545            .unwrap();
11546            assert_eq!(
11547                app.algorithm_builder_from_options()
11548                    .limited_memory_initialization,
11549                want,
11550                "limited_memory_initialization={kw} did not reach the builder"
11551            );
11552        }
11553
11554        // `limited_memory_init_val` was unread too — the empty-history
11555        // branch hard-coded the same 1.0, so the miss was invisible.
11556        let mut app = IpoptApplication::new();
11557        app.initialize().unwrap();
11558        app.initialize_with_options_str(
11559            "hessian_approximation limited-memory\n\
11560             limited_memory_init_val 4.5\n",
11561        )
11562        .unwrap();
11563        assert_eq!(
11564            app.algorithm_builder_from_options().limited_memory_init_val,
11565            4.5
11566        );
11567
11568        // The effective default matches the registry and Ipopt
11569        // (`scalar1`). This is the assertion that would have caught #677
11570        // when the option was first registered: it pins the *selection*,
11571        // which the per-formula tests in `lim_mem_quasi_newton` cannot
11572        // see. Do not relax it to make an unrelated change pass.
11573        let mut app = IpoptApplication::new();
11574        app.initialize().unwrap();
11575        let def = app.algorithm_builder_from_options();
11576        assert_eq!(def.limited_memory_initialization, InitialApprox::Scalar1);
11577        assert_eq!(def.limited_memory_init_val, 1.0);
11578    }
11579
11580    #[test]
11581    fn application_sqp_warm_start_round_trip() {
11582        // Drive the convex-equality TNLP through the SQP path
11583        // twice. The first solve produces a working set; the
11584        // second is warm-started from it. The second must converge
11585        // with zero QP solves (the first KKT check declares
11586        // optimality immediately).
11587        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
11588        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
11589            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
11590                finalize_called: std::rc::Rc::clone(&finalize_slot),
11591            }));
11592
11593        let mut app = IpoptApplication::new();
11594        app.initialize().unwrap();
11595        app.initialize_with_options_str("algorithm active-set-sqp\n")
11596            .unwrap();
11597
11598        // Cold solve.
11599        let status_a = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11600        assert_eq!(status_a, ApplicationReturnStatus::SolveSucceeded);
11601        let ws = app.last_sqp_working_set().cloned();
11602        assert!(ws.is_some(), "cold solve must yield a working set");
11603
11604        // Build the warm-start iterate from the converged finalize
11605        // payload (just x; pad multipliers to 0 since the test
11606        // problem is convex).
11607        let (x_recv, _) = finalize_slot.borrow().clone().unwrap();
11608        let warm = crate::sqp::SqpIterates {
11609            x: x_recv,
11610            lambda_g: vec![1.0],
11611            lambda_x: vec![0.0, 0.0],
11612            working: ws,
11613        };
11614        app.set_sqp_warm_start(warm);
11615
11616        // Warm solve.
11617        let status_b = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11618        assert_eq!(status_b, ApplicationReturnStatus::SolveSucceeded);
11619        assert!(app.last_sqp_working_set().is_some());
11620    }
11621
11622    #[test]
11623    fn application_sqp_warm_start_auto_clears_after_use() {
11624        let finalize_slot = std::rc::Rc::new(std::cell::RefCell::new(None));
11625        let tnlp_rc: std::rc::Rc<std::cell::RefCell<dyn TNLP>> =
11626            std::rc::Rc::new(std::cell::RefCell::new(ConvexEqTnlp {
11627                finalize_called: std::rc::Rc::clone(&finalize_slot),
11628            }));
11629        let mut app = IpoptApplication::new();
11630        app.initialize().unwrap();
11631        app.initialize_with_options_str("algorithm active-set-sqp\n")
11632            .unwrap();
11633        app.set_sqp_warm_start(crate::sqp::SqpIterates {
11634            x: vec![0.0, 1.0],
11635            lambda_g: vec![1.0],
11636            lambda_x: vec![0.0, 0.0],
11637            working: None,
11638        });
11639        assert!(app.sqp_warm_start.is_some());
11640        let _ = app.optimize_tnlp(std::rc::Rc::clone(&tnlp_rc));
11641        assert!(
11642            app.sqp_warm_start.is_none(),
11643            "warm-start input must be auto-cleared after use"
11644        );
11645    }
11646
11647    #[test]
11648    fn application_sqp_suboptions_default_when_unset() {
11649        // Without any sqp_* settings, the snapshot should equal
11650        // SqpOptions::default().
11651        let mut app = IpoptApplication::new();
11652        app.initialize().unwrap();
11653        let snap = app.algorithm_builder_snapshot();
11654        let d = crate::sqp::SqpOptions::default();
11655        assert_eq!(snap.sqp.globalization, d.globalization);
11656        assert_eq!(snap.sqp.hessian, d.hessian);
11657        assert_eq!(snap.sqp.max_iter, d.max_iter);
11658        assert!((snap.sqp.tol - d.tol).abs() < 1e-18);
11659        assert!((snap.sqp.constr_viol_tol - d.constr_viol_tol).abs() < 1e-18);
11660        assert!((snap.sqp.dual_inf_tol - d.dual_inf_tol).abs() < 1e-18);
11661        assert!((snap.sqp.l1_penalty - d.l1_penalty).abs() < 1e-18);
11662        assert!((snap.sqp.bt_reduction - d.bt_reduction).abs() < 1e-18);
11663        assert!((snap.sqp.bt_min_alpha - d.bt_min_alpha).abs() < 1e-18);
11664        assert_eq!(snap.sqp.print_level, d.print_level);
11665        assert_eq!(snap.sqp.lbfgs_max_history, d.lbfgs_max_history);
11666    }
11667
11668    #[test]
11669    fn application_reports_problem_dimensions() {
11670        let app = IpoptApplication::new();
11671        let mut tnlp = Hs071Stub;
11672        let info = app.problem_dimensions(&mut tnlp).unwrap();
11673        assert_eq!(info.n, 4);
11674        assert_eq!(info.m, 2);
11675        assert_eq!(info.nnz_jac_g, 8);
11676        assert_eq!(info.nnz_h_lag, 10);
11677    }
11678
11679    /// Each of the four constant-derivative hints reaches the algorithm,
11680    /// and reaches its *own* slot (#551 / #677).
11681    ///
11682    /// All four were wired and consumed — gh#588 Q6 made pounce exploit
11683    /// them — but the read site looped over
11684    /// `constant_derivatives::HINT_OPTIONS`, so the registered-but-unread
11685    /// scan saw a loop variable where it needs a literal key and reported
11686    /// all four as silent no-ops. They are literals now, and this pins
11687    /// what a literal-per-name rewrite can get wrong that a loop could
11688    /// not: setting one hint must light up that hint's slot and no other,
11689    /// because `reconcile` pairs `asserted[k]` with the model's proof for
11690    /// `HINT_OPTIONS[k]` and a transposed pair would reuse the wrong
11691    /// derivative.
11692    #[test]
11693    fn each_constant_derivative_hint_lights_up_its_own_slot() {
11694        use pounce_nlp::constant_derivatives::HINT_OPTIONS;
11695
11696        let app = IpoptApplication::new();
11697        assert_eq!(
11698            app.asserted_constant_derivative_hints(),
11699            [false; 4],
11700            "no hint is asserted on a fresh options list",
11701        );
11702
11703        for (k, name) in HINT_OPTIONS.iter().enumerate() {
11704            let mut app = IpoptApplication::new();
11705            app.initialize().unwrap();
11706            app.initialize_with_options_str(&format!("{name} yes\n"))
11707                .unwrap();
11708            let mut expected = [false; 4];
11709            expected[k] = true;
11710            assert_eq!(
11711                app.asserted_constant_derivative_hints(),
11712                expected,
11713                "`{name}=yes` must set slot {k} and nothing else",
11714            );
11715
11716            // …and the registered default asks for nothing, so an
11717            // `ipopt.opt` that spells it out changes no derivative reuse.
11718            let mut app = IpoptApplication::new();
11719            app.initialize().unwrap();
11720            app.initialize_with_options_str(&format!("{name} no\n"))
11721                .unwrap();
11722            assert_eq!(
11723                app.asserted_constant_derivative_hints(),
11724                [false; 4],
11725                "`{name}=no` is the registered default and asserts nothing",
11726            );
11727        }
11728    }
11729
11730    /// `min x²` on `[-10, 10]` from `x = 1`, with an *exactly correct*
11731    /// gradient `2x`. Unconstrained and one-dimensional so the only
11732    /// thing the derivative checker can react to is its own step size
11733    /// and threshold.
11734    ///
11735    /// The forward difference at step `h` is `((1+h)² − 1)/h = 2 + h`,
11736    /// so the deviation from the analytic `2` is exactly `h`, and the
11737    /// relative test flags it when `h > tol·(2 + h)`. That makes the
11738    /// verdict a closed-form function of the two knobs under test.
11739    struct ExactQuadratic;
11740    impl TNLP for ExactQuadratic {
11741        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
11742            Some(NlpInfo {
11743                n: 1,
11744                m: 0,
11745                nnz_jac_g: 0,
11746                nnz_h_lag: 0,
11747                index_style: IndexStyle::C,
11748            })
11749        }
11750        fn get_bounds_info(&mut self, b: BoundsInfo<'_>) -> bool {
11751            b.x_l.copy_from_slice(&[-10.0]);
11752            b.x_u.copy_from_slice(&[10.0]);
11753            true
11754        }
11755        fn get_starting_point(&mut self, sp: StartingPoint<'_>) -> bool {
11756            sp.x.copy_from_slice(&[1.0]);
11757            true
11758        }
11759        fn eval_f(&mut self, x: &[Number], _new_x: bool) -> Option<Number> {
11760            Some(x[0] * x[0])
11761        }
11762        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11763            grad[0] = 2.0 * x[0];
11764            true
11765        }
11766        fn eval_g(&mut self, _x: &[Number], _new_x: bool, _g: &mut [Number]) -> bool {
11767            true
11768        }
11769        fn eval_jac_g(
11770            &mut self,
11771            _x: Option<&[Number]>,
11772            _new_x: bool,
11773            _mode: SparsityRequest<'_>,
11774        ) -> bool {
11775            true
11776        }
11777        fn eval_h(
11778            &mut self,
11779            _x: Option<&[Number]>,
11780            _new_x: bool,
11781            _obj_factor: Number,
11782            _lambda: Option<&[Number]>,
11783            _new_lambda: bool,
11784            _mode: SparsityRequest<'_>,
11785        ) -> bool {
11786            true
11787        }
11788        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11789    }
11790
11791    struct RecordingQuadratic {
11792        gradient_points: Rc<RefCell<Vec<Number>>>,
11793        objective_points: Rc<RefCell<Vec<Number>>>,
11794        x_scaling: Number,
11795    }
11796
11797    impl TNLP for RecordingQuadratic {
11798        fn get_nlp_info(&mut self) -> Option<NlpInfo> {
11799            ExactQuadratic.get_nlp_info()
11800        }
11801
11802        fn get_bounds_info(&mut self, bounds: BoundsInfo<'_>) -> bool {
11803            ExactQuadratic.get_bounds_info(bounds)
11804        }
11805
11806        fn get_starting_point(&mut self, start: StartingPoint<'_>) -> bool {
11807            ExactQuadratic.get_starting_point(start)
11808        }
11809
11810        fn eval_f(&mut self, x: &[Number], new_x: bool) -> Option<Number> {
11811            self.objective_points.borrow_mut().push(x[0]);
11812            ExactQuadratic.eval_f(x, new_x)
11813        }
11814
11815        fn eval_grad_f(&mut self, x: &[Number], _new_x: bool, grad: &mut [Number]) -> bool {
11816            self.gradient_points.borrow_mut().push(x[0]);
11817            grad[0] = 2.0 * x[0];
11818            true
11819        }
11820
11821        fn eval_g(&mut self, x: &[Number], new_x: bool, g: &mut [Number]) -> bool {
11822            ExactQuadratic.eval_g(x, new_x, g)
11823        }
11824
11825        fn eval_jac_g(
11826            &mut self,
11827            x: Option<&[Number]>,
11828            new_x: bool,
11829            mode: SparsityRequest<'_>,
11830        ) -> bool {
11831            ExactQuadratic.eval_jac_g(x, new_x, mode)
11832        }
11833
11834        fn get_scaling_parameters(&mut self, req: ScalingRequest<'_>) -> bool {
11835            *req.obj_scaling = 1.0;
11836            *req.use_x_scaling = true;
11837            req.x_scaling[0] = self.x_scaling;
11838            *req.use_g_scaling = false;
11839            true
11840        }
11841
11842        fn finalize_solution(&mut self, _sol: Solution<'_>, _d: &IpoptData, _q: &IpoptCq) {}
11843    }
11844
11845    /// A floor replay makes the floor the recorded answer again, firing id
11846    /// included. The retries nest and each floors to `last_finalize`, so a
11847    /// replay that only re-delivered the payload left the inner retry's
11848    /// discarded payload there for an outer wrapper to floor to, and for
11849    /// `reported_on_converged_id` to name.
11850    #[test]
11851    fn restoring_a_floor_records_it_as_the_answer() {
11852        let snap = |x: Number, id: Option<u64>| FinalizeSnapshot {
11853            status: SolverReturn::Success,
11854            x: vec![x],
11855            z_l: vec![0.0],
11856            z_u: vec![0.0],
11857            g: vec![],
11858            lambda: vec![],
11859            obj_value: x * x,
11860            on_converged_id: id,
11861        };
11862        let app = IpoptApplication::new();
11863        let tnlp: Rc<RefCell<dyn TNLP>> = Rc::new(RefCell::new(ExactQuadratic));
11864        let base = snap(1.0, Some(1));
11865        // The retry's payload is the last one written, as after an inner
11866        // retry that lost.
11867        *app.last_finalize.borrow_mut() = Some(snap(2.0, Some(2)));
11868        assert_eq!(app.reported_on_converged_id(), Some(2));
11869
11870        app.restore_floor(&base, &tnlp);
11871        assert!(app.answer_restored_from_floor());
11872        assert_eq!(app.reported_on_converged_id(), Some(1));
11873        // What an outer wrapper would take as its own floor.
11874        let outer_floor = app.last_finalize.borrow().clone().unwrap();
11875        assert_eq!(outer_floor.x, base.x);
11876    }
11877
11878    fn derivative_test_verdict(extra: &str) -> pounce_nlp::derivative_test::DerivativeTestReport {
11879        let mut app = IpoptApplication::new();
11880        app.initialize().unwrap();
11881        app.initialize_with_options_str(&format!("derivative_test first-order\n{extra}"))
11882            .unwrap();
11883        let opts = app.derivative_test_options();
11884        pounce_nlp::derivative_test::run(&mut ExactQuadratic, &opts).expect("a report")
11885    }
11886
11887    /// `derivative_test_perturbation` and `derivative_test_tol` were
11888    /// registered, read into [`DerivativeTestOptions`], and consumed by
11889    /// the checker — but nothing proved a *set value* reached it, which
11890    /// is the only assertion that distinguishes a read site from a
11891    /// parse-and-discard (#677, #551).
11892    ///
11893    /// Each of the three verdicts below differs from the one above it by
11894    /// exactly one option, so a knob that stopped reaching the checker
11895    /// would collapse two of them together and fail here.
11896    #[test]
11897    fn the_derivative_checker_knobs_change_the_verdict() {
11898        // Registered defaults (1e-8 / 1e-4), which are also the read
11899        // site's fallbacks: a correct gradient looks correct.
11900        let clean = derivative_test_verdict("");
11901        assert_eq!(clean.checked, 1);
11902        assert_eq!(clean.suspicious, 0, "{:#?}", clean.lines);
11903
11904        // A coarse step makes the *same correct gradient* look wrong:
11905        // deviation 0.5 > 1e-4·2.5. Only `derivative_test_perturbation`
11906        // changed, so this is that option and nothing else.
11907        let coarse = derivative_test_verdict("derivative_test_perturbation 0.5\n");
11908        assert_eq!(coarse.checked, 1);
11909        assert_eq!(
11910            coarse.suspicious, 1,
11911            "derivative_test_perturbation never reached the checker: {:#?}",
11912            coarse.lines,
11913        );
11914
11915        // …and loosening the threshold at that same coarse step clears
11916        // it again: 0.5 < 0.5·2.5. Only `derivative_test_tol` changed.
11917        let tolerant =
11918            derivative_test_verdict("derivative_test_perturbation 0.5\nderivative_test_tol 0.5\n");
11919        assert_eq!(tolerant.checked, 1);
11920        assert_eq!(
11921            tolerant.suspicious, 0,
11922            "derivative_test_tol never reached the checker: {:#?}",
11923            tolerant.lines,
11924        );
11925
11926        // The report also prints what it used, so a user reading the
11927        // output can tell which step and threshold produced the verdict.
11928        assert!(
11929            tolerant.lines[0].contains("5.0e-1"),
11930            "{:#?}",
11931            tolerant.lines,
11932        );
11933    }
11934
11935    #[test]
11936    fn ordinary_derivative_test_keeps_the_conditioned_start() {
11937        let gradient_points = Rc::new(RefCell::new(Vec::new()));
11938        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11939            gradient_points: Rc::clone(&gradient_points),
11940            objective_points: Rc::new(RefCell::new(Vec::new())),
11941            x_scaling: 1.0,
11942        })) as Rc<RefCell<dyn TNLP>>;
11943        let mut app = IpoptApplication::new();
11944        app.initialize().unwrap();
11945        app.initialize_with_options_str(
11946            "derivative_test first-order\n\
11947             start_point_perturbation 0.5\n\
11948             hessian_approximation limited-memory\n\
11949             max_iter 0\n\
11950             print_level 0\n",
11951        )
11952        .unwrap();
11953
11954        let _ = app.optimize_tnlp(tnlp);
11955
11956        let first = gradient_points.borrow()[0];
11957        assert!((first - 1.7666216164272852).abs() < 1e-12, "{first}");
11958    }
11959
11960    #[test]
11961    fn ordinary_derivative_test_keeps_variable_scaling() {
11962        let objective_points = Rc::new(RefCell::new(Vec::new()));
11963        let tnlp = Rc::new(RefCell::new(RecordingQuadratic {
11964            gradient_points: Rc::new(RefCell::new(Vec::new())),
11965            objective_points: Rc::clone(&objective_points),
11966            x_scaling: 0.5,
11967        })) as Rc<RefCell<dyn TNLP>>;
11968        let mut app = IpoptApplication::new();
11969        app.initialize().unwrap();
11970        app.initialize_with_options_str(
11971            "derivative_test first-order\n\
11972             derivative_test_perturbation 0.5\n\
11973             nlp_scaling_method user-scaling\n\
11974             hessian_approximation limited-memory\n\
11975             max_iter 0\n\
11976             print_level 0\n",
11977        )
11978        .unwrap();
11979
11980        let _ = app.optimize_tnlp(tnlp);
11981
11982        assert_eq!(&objective_points.borrow()[..2], &[1.0, 2.0]);
11983    }
11984
11985    // ---- gh#887: the dominance gate ------------------------------------
11986    //
11987    // These pin the rule directly, on numbers measured off real runs,
11988    // because the fixture that motivated the gate turned out not to be a
11989    // portable witness for it. `deb7` on the L-BFGS leg with
11990    // `limited_memory_ls_failure_restarts=1` reaches a *materially
11991    // different answer* on macOS and on Linux -- different objective
11992    // (99.677 vs 99.651) and, decisively, a different shape:
11993    //
11994    //   | run                 | unscaled dual | viol    | compl   | ratio   |
11995    //   | reproducer, .nl     | 7.90e4        | 1.1e-16 | 1.1e-9  | 1.5e-14 |
11996    //   | reproducer, TNLP    | 3.25e11       | 2.5e-16 | 2.8e-3  | 8.7e-15 |
11997    //   | deb7 + rung, macOS  | 9.90e1        | 8.0e-13 | 4.65e0  | 4.7e-2  |
11998    //   | deb7 + rung, Linux  | 5.5743e3      | 5.6e-14 | 2.08e-5 | 3.7e-9  |
11999    //
12000    // The Linux row is the one worth reading twice: that answer really is
12001    // gh#884's shape (scaled overall error 5.28e-1 against unscaled
12002    // 5.57e3, which is the `s_d` normalisation hiding a runaway exactly
12003    // as it did on `qpec_small`), so the retry there is the designed cost
12004    // and not the waste gh#887 filed. A CLI assertion of "deb7 declines"
12005    // is therefore false on Linux no matter what the threshold is, which
12006    // is why the pin lives here instead.
12007
12008    /// The dominance rule on its own, with the absolute floor switched
12009    /// off (`du_floor = 0`), so each of these tests is about one rule.
12010    fn ratio_only(dual_inf: Number, viol: Number, compl: Number) -> bool {
12011        runaway_is_the_whole_residual(dual_inf, viol, compl, 0.0)
12012    }
12013
12014    /// The gate as it actually runs: dominance *and* the detector's own
12015    /// absolute floor.
12016    fn runaway(dual_inf: Number, viol: Number, compl: Number) -> bool {
12017        runaway_is_the_whole_residual(dual_inf, viol, compl, DUAL_DIV_RETRY_DU_FLOOR)
12018    }
12019
12020    #[test]
12021    fn a_converged_point_with_a_runaway_multiplier_opens_the_retry() {
12022        // The gh#884 reproducer, both routes it reaches the gate by.
12023        assert!(runaway(7.90e4, 1.1e-16, 1.1e-9));
12024        assert!(runaway(3.25e11, 2.5e-16, 2.8e-3));
12025        // deb7 under the rung on Linux: primal exact, complementarity
12026        // eight orders under its own dual residual. Same shape.
12027        assert!(runaway(5.5743e3, 5.6e-14, 2.08e-5));
12028    }
12029
12030    #[test]
12031    fn an_unconverged_point_does_not_open_the_retry() {
12032        // deb7 under the rung on macOS: complementarity 4.65, five
12033        // percent of its own KKT error. Not a runaway multiplier on an
12034        // otherwise-converged point -- just an unconverged point.
12035        assert!(!ratio_only(9.90e1, 8.0e-13, 4.65e0));
12036        // Either residual alone is enough to close it: the gate takes the
12037        // max, so a clean complementarity does not excuse a violated
12038        // constraint. (`1.0e1` against `1.0e6` is a ratio of `1e-5`; note
12039        // that `1.0e0` there would be `1e-6` exactly, i.e. inside.)
12040        assert!(!ratio_only(1.0e6, 1.0e1, 1.0e-16));
12041        assert!(!ratio_only(1.0e6, 1.0e-16, 1.0e1));
12042    }
12043
12044    /// The dominance ratio is scale-free, and that is exactly why it
12045    /// cannot be the whole gate: a point converged to `1e-30` primal with
12046    /// a dual residual of `4.4e-1` satisfies it as comfortably as
12047    /// gh#884's `7.9e+04` does, and `4.4e-1` is not a runaway by any
12048    /// reading of the issue. Measured on the 400-model QPEC family, the
12049    /// floor alone removes 7 of 68 promotions, every one of them on an
12050    /// answer whose reported dual residual was below `1e2`.
12051    ///
12052    /// The floor is the *detector's*, so this is the answer-level gate
12053    /// asking about the same magnitude the iterate-level one did rather
12054    /// than being a strictly looser copy of it.
12055    #[test]
12056    fn a_small_dual_residual_is_not_a_runaway_however_dominant() {
12057        // Passes the ratio comfortably (1e-30 / 4.4e-1 = 2.3e-30) ...
12058        assert!(ratio_only(4.4e-1, 1.0e-30, 1.0e-30));
12059        // ... and is still refused, because it is not a runaway.
12060        assert!(!runaway(4.4e-1, 1.0e-30, 1.0e-30));
12061        // The two real `r`-family answers that reached the gate this way.
12062        assert!(!runaway(4.397e-1, 1.0e-16, 1.0e-16));
12063        assert!(!runaway(2.026e1, 1.0e-16, 1.0e-16));
12064        // Exactly at the floor is inside; a hair under is outside.
12065        assert!(runaway(DUAL_DIV_RETRY_DU_FLOOR, 0.0, 0.0));
12066        assert!(!runaway(DUAL_DIV_RETRY_DU_FLOOR * 0.999, 0.0, 0.0));
12067    }
12068
12069    #[test]
12070    fn the_threshold_is_where_the_constant_says_it_is() {
12071        // Exactly at the ratio is inside; a hair past it is outside.
12072        assert!(ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE, 0.0));
12073        assert!(!ratio_only(1.0, DUAL_DIV_RETRY_DOMINANCE * 1.001, 0.0));
12074    }
12075
12076    #[test]
12077    fn what_we_cannot_measure_does_not_buy_a_retry() {
12078        // A NaN compares false everywhere, so the condition is written so
12079        // that "we cannot tell" declines rather than retries. Each
12080        // argument in turn.
12081        assert!(!ratio_only(Number::NAN, 0.0, 0.0));
12082        assert!(!ratio_only(1.0e6, Number::NAN, 0.0));
12083        assert!(!ratio_only(1.0e6, 0.0, Number::NAN));
12084        assert!(!ratio_only(Number::INFINITY, 0.0, 0.0));
12085        // And a dual residual that is not a runaway at all: the ratio
12086        // would be meaningless, and a zero-dual point is not gh#884.
12087        assert!(!ratio_only(0.0, 0.0, 0.0));
12088        assert!(!ratio_only(-1.0, 0.0, 0.0));
12089    }
12090
12091    // ---- the promotion gate reads the ANSWER, not only the certificate --
12092    //
12093    // gh#884 ranked the two attempts on unscaled KKT error alone and
12094    // argued that this could not return a different local solution,
12095    // because "conjunct 4 requires the promoted answer to satisfy the KKT
12096    // conditions in the model's own units". Any other KKT point does too.
12097    // Measured on 400 random QPECs under the `prod_eq` lowering
12098    // (`bound_relax_factor=0 mu_strategy_fallback=no tol=1e-8`): 68
12099    // promotions, 42 of which moved the objective materially, and three
12100    // of which returned a strictly worse *feasible* point.
12101    //
12102    // Every number below is off a real run, and the two branches are
12103    // separated on purpose -- a rule that branches needs a case on each
12104    // side or the untaken one stays broken while the test is green.
12105    //
12106    //   | model      | base f      | base viol | retry f     | retry viol | branch |
12107    //   |------------|-------------|-----------|-------------|------------|--------|
12108    //   | qpec_small | +3.586e-28  | 1.11e-16  | +5.835e-11  | 5.47e-12   | admit  |
12109    //   | r116       | -1.3006e+01 | 2.22e-16  | -1.2072e+00 | 4.55e-13   | rule 1 |
12110    //   | r261       | -4.7919e+00 | 1.07e-14  | -9.8563e-01 | 7.99e-14   | rule 1 |
12111    //   | r201       | -2.9559e-01 | 6.25e-17  | -9.7321e-02 | 6.21e-13   | rule 1 |
12112    //   | scholtes4  | +1.8176e-09 | 2.07e-25  | -6.6088e-05 | 1.09e-09   | rule 2 |
12113
12114    const ACCEPT: Number = 1e-6;
12115    /// Minimization, which is every row of the table above.
12116    const MIN: Number = 1.0;
12117    /// Maximization, i.e. `obj_scaling_factor < 0`.
12118    const MAX: Number = -1.0;
12119
12120    fn admissible(bo: Number, bv: Number, ro: Number, rv: Number) -> bool {
12121        retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN)
12122    }
12123
12124    #[test]
12125    fn the_reproducers_promotion_is_still_admissible() {
12126        // `qpec_small`: the retry's objective is *worse*, by 5.8e-11 --
12127        // deliberately, since it buys nine orders of unscaled dual
12128        // residual. Five orders inside the tolerance, so rule 1 admits
12129        // it, which is the whole point of having a tolerance at all.
12130        assert!(admissible(3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12));
12131    }
12132
12133    /// Rule 1: a strictly worse feasible point is never an upgrade.
12134    #[test]
12135    fn a_worse_feasible_objective_is_refused_however_clean_the_certificate() {
12136        // r116: -13.0057 -> -1.2072, both independently verified feasible
12137        // by `pounce verify`. The retry's unscaled KKT error is 2.9e-11
12138        // against the base attempt's 3.0e+03, so every certificate
12139        // conjunct passes and only this one refuses it.
12140        assert!(!admissible(
12141            -1.3005680756e1,
12142            2.22e-16,
12143            -1.2072337962e0,
12144            4.55e-13
12145        ));
12146        assert!(!admissible(
12147            -4.7919265770e0,
12148            1.07e-14,
12149            -9.8562977711e-1,
12150            7.99e-14
12151        ));
12152        assert!(!admissible(
12153            -2.9558632401e-1,
12154            6.25e-17,
12155            -9.7321185691e-2,
12156            6.21e-13
12157        ));
12158    }
12159
12160    /// The declared-box conjunct is scale-safe: at a bound of `1e6`, two
12161    /// points pinned to the same widened bound differ by an ulp (`1.2e-10`),
12162    /// which an absolute `1e-12` floor read as the re-solve using more of the
12163    /// widening; relative to the bound it is rounding. A genuine excess at
12164    /// that magnitude -- the bound-magnitude probe's `2.5e-6`, i.e. `2.5e-12`
12165    /// relative -- is still refused, and at a unit bound `1e-8` is.
12166    #[test]
12167    fn the_declared_box_conjunct_is_relative_to_each_bounds_magnitude() {
12168        let (lo, up) = (-1e19, 1e19);
12169        let rel = |x: &[Number], l: &[Number], u: &[Number]| {
12170            declared_box_relative_violation(x, l, u, lo, up)
12171        };
12172        let ub: Number = 1e6;
12173        let pinned: Number = ub + 1e-4; // on the widened bound (`constr_viol_tol` cap)
12174        let one_ulp_out = f64::from_bits(pinned.to_bits() + 1);
12175        assert!(
12176            one_ulp_out - pinned > 1e-12,
12177            "premise: an ulp of 1e6 exceeds 1e-12"
12178        );
12179        let (l, u) = (vec![0.0], vec![ub]);
12180        let base = rel(&[pinned], &l, &u);
12181        assert!(retry_keeps_declared_box(base, rel(&[one_ulp_out], &l, &u)));
12182        // The absolute rule this replaces declined exactly that pair.
12183        assert!(one_ulp_out - ub > (pinned - ub) + 1e-12);
12184        let genuine = rel(&[ub + 9.9995e-5], &l, &u);
12185        let base_genuine = rel(&[ub + 9.7494e-5], &l, &u);
12186        assert!(!retry_keeps_declared_box(base_genuine, genuine));
12187        // Unit bound: the widening's own size is refused, rounding is not.
12188        let (l1, u1) = (vec![0.0], vec![1.0]);
12189        assert!(!retry_keeps_declared_box(0.0, rel(&[1.0 + 1e-8], &l1, &u1)));
12190        assert!(retry_keeps_declared_box(
12191            0.0,
12192            rel(&[f64::from_bits(1.0f64.to_bits() + 1)], &l1, &u1)
12193        ));
12194        // Lower bounds, sentinels, and single-point boxes.
12195        assert_eq!(rel(&[-2e-4], &[-1e4], &[1e19]), 0.0);
12196        assert!(rel(&[-1e4 - 1e-4], &[-1e4], &[1e19]) > 0.0);
12197        assert_eq!(rel(&[5.0], &[-1e19], &[1e19]), 0.0);
12198        assert_eq!(rel(&[0.5 + 1e-8], &[0.5], &[0.5]), 0.0);
12199        assert!(rel(&[1.0], &[0.0, 0.0], &[1.0, 1.0]).is_nan());
12200        // `NaN` is "not measured".
12201        assert!(retry_keeps_declared_box(Number::NAN, Number::NAN));
12202        assert!(!retry_keeps_declared_box(0.0, Number::NAN));
12203    }
12204
12205    /// Rule 2: an objective *improvement* bought with primal slack.
12206    ///
12207    /// `scholtes4` (`benchmarks/mpcc/cases.py`, and now a CLI fixture) has
12208    /// `f* = 0` exactly -- for the MPCC and for the smooth lowering alike,
12209    /// since `x1*x2 = 0` forces one of them to zero, hence `x3 <= 0`, hence
12210    /// `f = x1 - x3 >= 0`. The retry reports `-6.61e-05`, which no feasible
12211    /// point reaches, by moving the complementarity row 16 orders further
12212    /// out. Rule 1 cannot see it: the objective got *better*.
12213    #[test]
12214    fn an_improvement_bought_with_primal_slack_is_refused() {
12215        assert!(!admissible(
12216            1.8175997416e-9,
12217            2.07e-25,
12218            -6.6088333055e-5,
12219            1.09e-9
12220        ));
12221        // The same numbers with the primal *held* would be admissible --
12222        // this is the conjunct that refuses it, not the objective move.
12223        assert!(admissible(
12224            1.8175997416e-9,
12225            2.07e-25,
12226            -6.6088333055e-5,
12227            2.07e-25
12228        ));
12229    }
12230
12231    /// The window the tolerance sits in, from both sides, so it is a
12232    /// checkable claim rather than a fitted constant: the smallest move
12233    /// that must be admitted is `qpec_small`'s `5.8e-11` and the smallest
12234    /// that must be refused is `r201`'s `0.198`, four and five orders
12235    /// away from `acceptable_tol` on either side.
12236    #[test]
12237    fn the_objective_tolerance_is_not_fitted_to_one_model() {
12238        let admit = 5.835e-11;
12239        let refuse = 0.198;
12240        assert!(admit < ACCEPT / 1.0e4, "{admit} is not well inside");
12241        assert!(refuse > ACCEPT * 1.0e4, "{refuse} is not well outside");
12242        // Scale-relative above 1, absolute below it -- the same
12243        // convention `sigma_forward_error_is_small` uses for `norm(x)`.
12244        assert!(admissible(1.0e6, 0.0, 1.0e6 + 0.5, 0.0));
12245        assert!(!admissible(1.0e6, 0.0, 1.0e6 + 5.0, 0.0));
12246    }
12247
12248    /// gh#983 item 4: `x*y == 0` from `(0.3, 0.3)`. The base attempt sits at
12249    /// `f = 2` with a violation of `3e-38` and an unscaled dual infeasibility
12250    /// of `1.4e9`; the retry reaches `f = 1` at `1.96e-13`, six orders inside
12251    /// `constr_viol_tol`. Rule 2 compared the two violations bare and refused
12252    /// it. The floor admits arithmetic noise and nothing above it: the
12253    /// scholtes4 row (`1.09e-9`) is refused in the same breath.
12254    #[test]
12255    fn a_retry_violation_at_the_noise_floor_does_not_block_an_improvement() {
12256        assert!(retry_answer_is_admissible(
12257            2.0, 3.037e-38, 1.0, 1.9584e-13, ACCEPT, MIN
12258        ));
12259        assert!(retry_answer_is_admissible(
12260            -2.0, 3.037e-38, -1.0, 1.9584e-13, ACCEPT, MAX
12261        ));
12262        // Just above the floor is still slack.
12263        assert!(!retry_answer_is_admissible(
12264            2.0,
12265            3.037e-38,
12266            1.0,
12267            RETRY_VIOL_NOISE_FLOOR * 10.0,
12268            ACCEPT,
12269            MIN
12270        ));
12271        // ... and rule 1 is untouched by the floor.
12272        assert!(!retry_answer_is_admissible(
12273            1.0, 3.037e-38, 2.0, 1.0e-13, ACCEPT, MIN
12274        ));
12275        // MacMPEC pack-comp1p-32's exact finish: the retry reaches the
12276        // published optimum at a violation three orders inside `tol`, next to
12277        // a base at 2.5e-12. Admitted.
12278        assert!(retry_answer_is_admissible(
12279            0.704, 2.5e-12, 0.652997, 2.6e-11, ACCEPT, MIN
12280        ));
12281        // scholtes4: f* = 0 exactly, and the retry buys -6.6e-5 with a
12282        // violation of 1.09e-9. Still refused.
12283        assert!(!retry_answer_is_admissible(
12284            1.82e-9, 2.07e-25, -6.61e-5, 1.09e-9, ACCEPT, MIN
12285        ));
12286    }
12287
12288    /// The audit input with every measurement given and the defaults for
12289    /// the rest (`tol 1e-8`, `acceptable_tol 1e-6`, threshold `1e-4`).
12290    #[allow(clippy::too_many_arguments)]
12291    fn audit_in(
12292        tol: Number,
12293        obj_scale: Number,
12294        rescaled: Number,
12295        start_grad: Number,
12296        final_grad: Number,
12297        kkt: Number,
12298        compl: Number,
12299        th: Number,
12300    ) -> ScaleAuditInput {
12301        ScaleAuditInput {
12302            tol,
12303            obj_scale,
12304            rescaled_obj_scale: rescaled,
12305            start_grad_max: start_grad,
12306            final_grad_max: final_grad,
12307            unscaled_kkt: kkt,
12308            unscaled_compl: compl,
12309            acceptable_tol: 1e-6,
12310            masked_threshold: th,
12311            warm_start: false,
12312        }
12313    }
12314
12315    /// `audit_in` for a warm start (`warm_start_init_point=yes`).
12316    #[allow(clippy::too_many_arguments)]
12317    fn audit_in_warm(
12318        tol: Number,
12319        obj_scale: Number,
12320        rescaled: Number,
12321        start_grad: Number,
12322        final_grad: Number,
12323        kkt: Number,
12324        compl: Number,
12325        th: Number,
12326    ) -> ScaleAuditInput {
12327        ScaleAuditInput {
12328            warm_start: true,
12329            ..audit_in(
12330                tol, obj_scale, rescaled, start_grad, final_grad, kkt, compl, th,
12331            )
12332        }
12333    }
12334
12335    /// gh#983 / CI: a warm start is an answer, so its gradient -- and the
12336    /// returned point's -- carry the model's scale only above the barrier
12337    /// level. Both branches of the warm rule need a row: the session's
12338    /// interior optimum (gradient at the complementarity) stays out, and the
12339    /// reactor warm-started at its answer (gradient `4e3` times it) is still
12340    /// up-scaled.
12341    #[test]
12342    fn a_warm_start_at_an_answer_is_not_read_as_a_tiny_objective() {
12343        let th = 1e-4;
12344        let t = |inp| scale_audit_trigger(inp);
12345        // `cold_then_warm_through_presolve`'s warm re-solve, measured.
12346        assert_eq!(
12347            t(audit_in_warm(
12348                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
12349            )),
12350            None
12351        );
12352        // The same numbers on a cold start are the tiny-objective signature:
12353        // the rule is the warm start's, not a change to the cold branch.
12354        assert!(matches!(
12355            t(audit_in(
12356                1e-8, 1.0, 1.0, 1.0e-11, 3.726e-9, 3.72e-9, 3.72e-9, th
12357            )),
12358            Some(ScaleAudit::Upscale(_))
12359        ));
12360        // The reactor (fs = 1e-6) warm-started from its answer: the active
12361        // bound's multiplier keeps the gradient at 1e-5, the model's scale.
12362        match t(audit_in_warm(
12363            1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th,
12364        )) {
12365            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
12366            other => panic!("{other:?}"),
12367        }
12368        // A barrier-level seed does not mask an answer that carries scale.
12369        assert!(matches!(
12370            t(audit_in_warm(
12371                1e-8, 1.0, 1.0, 1e-11, 1e-5, 2.5e-9, 2.5e-9, th
12372            )),
12373            Some(ScaleAudit::Upscale(_))
12374        ));
12375        // The re-scale branch does not read the gradient scale at all.
12376        assert_eq!(
12377            t(audit_in_warm(
12378                1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th
12379            )),
12380            Some(ScaleAudit::Rescale)
12381        );
12382    }
12383
12384    /// gh#983: the audit's trigger branches on *which* scaling defect shows,
12385    /// and each branch needs its own row.
12386    #[test]
12387    fn the_scale_audit_trigger_takes_each_branch_and_neither_by_default() {
12388        let th = 1e-4;
12389        let t = |inp| scale_audit_trigger(inp);
12390        // Frozen factor, non-stationary in the model's own units, and the
12391        // factor re-evaluated at the returned point (gradient 2.9e-2 -> 1) is
12392        // seven orders from the frozen one: re-scale.
12393        assert_eq!(
12394            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, th)),
12395            Some(ScaleAudit::Rescale)
12396        );
12397        // gh#983 review item 2(b): the same masked certificate on a
12398        // legitimately large objective (`hs71 x 1e8`) re-evaluates to the
12399        // factor it already has -- the re-solve would be the same solve.
12400        assert_eq!(
12401            t(audit_in(1e-8, 2.2e-7, 2.4e-7, 4.6e8, 4.2e8, 3e-6, 1e-9, th)),
12402            None
12403        );
12404        // Tiny gradient, complementarity 2.5e-4 of it (the reactor, fs = 1e-6).
12405        match t(audit_in(1e-8, 1.0, 1.0, 1e-5, 1e-5, 2.5e-9, 2.5e-9, th)) {
12406            Some(ScaleAudit::Upscale(k)) => assert!((k - 1e5).abs() < 1.0),
12407            other => panic!("{other:?}"),
12408        }
12409        // gh#983 review item 4: no band without a signal. fs = 3e-5 (gradient
12410        // 3e-4, relative complementarity 8.4e-6) and fs = 1e-3 (2.5e-7) are
12411        // both re-solved now; fs = 1 is left alone.
12412        assert!(matches!(
12413            t(audit_in(1e-8, 1.0, 1.0, 3e-4, 3e-4, 2.5e-9, 2.5e-9, th)),
12414            Some(ScaleAudit::Upscale(_))
12415        ));
12416        assert!(matches!(
12417            t(audit_in(1e-8, 1.0, 1.0, 1e-2, 1e-2, 2.5e-9, 2.5e-9, th)),
12418            Some(ScaleAudit::Upscale(_))
12419        ));
12420        assert_eq!(
12421            t(audit_in(1e-8, 1.0, 1.0, 10.0, 10.0, 2.5e-9, 2.5e-9, th)),
12422            None
12423        );
12424        // A gradient in [0.1, 1): the signature, but an up-scale below the
12425        // material factor -- warn, do not re-solve.
12426        assert_eq!(
12427            t(audit_in(1e-8, 1.0, 1.0, 0.5, 0.5, 1e-6, 1e-6, th)),
12428            Some(ScaleAudit::SmallObjective)
12429        );
12430        // gh#983 review item 2(a): a start near a stationary point
12431        // (`grad f(x0) = 2e-7`) is not a tiny objective when the gradient at
12432        // the answer is 1.
12433        assert_eq!(
12434            t(audit_in(1e-8, 1.0, 1.0, 2e-7, 1.0, 2.5e-9, 2.5e-9, th)),
12435            None
12436        );
12437        // A start measured at a stationary point (gradient exactly 0) carries
12438        // no scale: the audit stays out however small the answer's gradient.
12439        assert_eq!(
12440            t(audit_in(1e-8, 1.0, 1.0, 0.0, 2e-4, 6e-3, 2.5e-9, th)),
12441            None
12442        );
12443        // An unmeasured start (caller-owned scaling) defers to the answer.
12444        assert!(matches!(
12445            t(audit_in(
12446                1e-8,
12447                f64::NAN,
12448                f64::NAN,
12449                f64::NAN,
12450                1e-5,
12451                2.5e-9,
12452                2.5e-9,
12453                th
12454            )),
12455            Some(ScaleAudit::Upscale(_))
12456        ));
12457        // A big gradient never up-scales, whatever the complementarity.
12458        assert_eq!(
12459            t(audit_in(1e-8, 1.0, 1.0, 50.0, 50.0, 1e-3, 1e-3, th)),
12460            None
12461        );
12462        // An extreme factor at a stationary point is the honest case.
12463        assert_eq!(
12464            t(audit_in(1e-8, 1e-8, 1e-8, 1e9, 1e9, 1e-9, 1e-12, th)),
12465            None
12466        );
12467        // The masked opt-out (threshold 0) disables the re-scale branch.
12468        assert_eq!(
12469            t(audit_in(1e-8, 3e-7, 1.0, 3e8, 2.9e-2, 2.9e-2, 1e-9, 0.0)),
12470            None
12471        );
12472        // A caller who loosened tol asked for the complementarity they got.
12473        assert_eq!(
12474            t(audit_in(5e-2, 1.0, 1.0, 1e-5, 1e-5, 1e-2, 1e-2, th)),
12475            None
12476        );
12477        // NaN stays quiet.
12478        let nan = f64::NAN;
12479        assert_eq!(t(audit_in(1e-8, nan, nan, nan, nan, nan, nan, th)), None);
12480        // The upscale is capped.
12481        match t(audit_in(1e-8, 1.0, 1.0, 1e-14, 1e-14, 1.0, 1.0, th)) {
12482            Some(ScaleAudit::Upscale(k)) => assert_eq!(k, SCALE_AUDIT_MAX_UPSCALE),
12483            other => panic!("{other:?}"),
12484        }
12485    }
12486
12487    /// gh#1000 (II.22): the roundoff exemption, on the measured population
12488    /// named in `UNSCALED_DUAL_ROUNDOFF_ULPS`'s doc.
12489    #[test]
12490    fn a_residual_at_the_roundoff_floor_of_its_terms_is_not_a_miss() {
12491        // Pump network at H0_max 148: 1.6 ulps of its terms.
12492        assert!(unscaled_dual_inf_is_roundoff(5.54e-3, 1.57e13));
12493        assert!(unscaled_dual_inf_is_roundoff(7.39e-3, 2.66e13));
12494        // The downgrades that are right keep it: Haverly, the process
12495        // network's T2 and S2+T2 subproblems, the eps-perspective root, and
12496        // the gh#983 cusp.
12497        assert!(!unscaled_dual_inf_is_roundoff(1.33e-2, 6.6e10));
12498        assert!(!unscaled_dual_inf_is_roundoff(0.5, 7.55e11));
12499        assert!(!unscaled_dual_inf_is_roundoff(6.25e-2, 3.21e11));
12500        assert!(!unscaled_dual_inf_is_roundoff(3.92e-3, 5.03e9));
12501        assert!(!unscaled_dual_inf_is_roundoff(0.144, 3.55e9));
12502        // No scale measured: keep the downgrade.
12503        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, f64::NAN));
12504        assert!(!unscaled_dual_inf_is_roundoff(5.54e-3, 0.0));
12505        assert!(!unscaled_dual_inf_is_roundoff(f64::NAN, 1e13));
12506    }
12507
12508    /// gh#983 review item 7: one warning per code.
12509    #[test]
12510    fn a_warning_code_is_attached_at_most_once() {
12511        let mut w = vec!["unscaled_dual_inf_above_acceptable: downgraded".to_string()];
12512        push_warning_once(
12513            &mut w,
12514            "unscaled_dual_inf_above_acceptable: verify in your units".to_string(),
12515        );
12516        push_warning_once(&mut w, "large_dual_scale: terms of 1e9".to_string());
12517        assert_eq!(w.len(), 2, "{w:?}");
12518        assert!(w[0].ends_with("downgraded"));
12519    }
12520
12521    /// gh#983: the structured warnings, by code, on success verdicts only.
12522    #[test]
12523    fn quality_warnings_carry_a_code_and_only_on_success_verdicts() {
12524        use ApplicationReturnStatus::*;
12525        // The cusp: multipliers 3.5e9, residual 0.144.
12526        let w = quality_warnings(SolveSucceeded, 0.144, 3.55e9, 1.0, 1e-6, false);
12527        assert!(
12528            w.iter().any(|m| m.starts_with("large_dual_scale:")),
12529            "{w:?}"
12530        );
12531        assert!(
12532            w.iter()
12533                .any(|m| m.starts_with("unscaled_dual_inf_above_acceptable:")),
12534            "{w:?}"
12535        );
12536        // orthrds2-like: scale 1.6e10, residual 89.7 -> only the scale caveat
12537        // and the absolute one; never a status change (the function returns
12538        // text, not a verdict).
12539        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, false);
12540        assert!(w.iter().any(|m| m.starts_with("large_dual_scale:")));
12541        assert!(!w.iter().any(|m| m.contains("bound_relax_factor")), "{w:?}");
12542        // gh#1000: under bound_relax_factor = 0 the caveat names the option.
12543        let w = quality_warnings(SolveSucceeded, 89.7, 1.6e10, 1.0, 1e-6, true);
12544        assert!(
12545            w.iter()
12546                .any(|m| m.starts_with("large_dual_scale:") && m.contains("bound_relax_factor = 0")),
12547            "{w:?}"
12548        );
12549        // A clean point has none.
12550        assert!(quality_warnings(SolveSucceeded, 1e-9, 5.0, 1.0, 1e-6, false).is_empty());
12551        // A large objective with a stationary residual is not a failed CQ.
12552        assert!(quality_warnings(SolveSucceeded, 2.9e-7, 1.46e9, 1.0, 1e-6, false).is_empty());
12553        // 5e-4 is below the warning bar even though it exceeds acceptable_tol.
12554        assert!(quality_warnings(SolveSucceeded, 5e-4, 5.0, 1.0, 1e-6, false).is_empty());
12555        // Failures carry no success caveat.
12556        assert!(quality_warnings(RestorationFailed, 0.144, 3.55e9, 1.0, 1e-6, false).is_empty());
12557        assert!(quality_warnings(SolveSucceeded, f64::NAN, f64::NAN, 1.0, 1e-6, false).is_empty());
12558    }
12559
12560    /// gh#983 item 5: flooring an attempt must floor everything a solve
12561    /// report reads off the statistics, the iteration count and the row table
12562    /// included, or the report describes the declined retry.
12563    #[test]
12564    fn the_certificate_floor_carries_the_iteration_trace() {
12565        use pounce_nlp::solve_statistics::{IterRecord, SolveStatistics};
12566        let mut base = SolveStatistics::new();
12567        base.iteration_count = 64;
12568        base.iterations = vec![IterRecord::default(); 3];
12569        base.num_obj_evals = 159;
12570        base.restoration_calls = 2;
12571        let floor = SolutionCertificate::of(&base);
12572        let mut retry = SolveStatistics::new();
12573        retry.iteration_count = 15;
12574        retry.iterations = vec![IterRecord::default(); 15];
12575        retry.num_obj_evals = 86;
12576        floor.restore_into(&mut retry);
12577        assert_eq!(retry.num_obj_evals, 159);
12578        assert_eq!(retry.restoration_calls, 2);
12579        assert_eq!(retry.iteration_count, 64);
12580        assert_eq!(retry.iterations.len(), 3);
12581    }
12582
12583    /// An infeasible base attempt is not a point worth protecting, so
12584    /// both rules stand down and the certificate conjuncts decide alone.
12585    /// R2: `obj_scaling_factor < 0` poses a maximization, and
12586    /// `final_objective` is the user's **signed** objective, so both rules
12587    /// have to follow the sense. This is the table above with every
12588    /// objective negated: the same three answers must be refused and the
12589    /// same one admitted, with `MAX` instead of `MIN`.
12590    ///
12591    /// Without the normalization each row flips — rule 1 starts refusing
12592    /// genuine improvements (a regression against the behaviour before the
12593    /// conjunct existed) and rule 2 starts admitting strictly worse
12594    /// answers, which is the class it was added to block.
12595    #[test]
12596    fn the_rules_follow_the_objective_sense() {
12597        // qpec_small, mirrored: the retry is worse by 5.8e-11, well inside
12598        // the tolerance, so it is still admitted.
12599        assert!(retry_answer_is_admissible(
12600            -3.586e-28, 1.11e-16, -5.835e-11, 5.47e-12, ACCEPT, MAX
12601        ));
12602        // r116, mirrored: +13.0057 given up for +1.2072 is now a *worse*
12603        // maximum, and rule 1 must still refuse it.
12604        assert!(!retry_answer_is_admissible(
12605            1.3005680756e1,
12606            2.22e-16,
12607            1.2072337962e0,
12608            4.55e-13,
12609            ACCEPT,
12610            MAX
12611        ));
12612        // scholtes4, mirrored: +6.6088e-05 is now an improvement bought
12613        // with primal slack, and rule 2 must still refuse it.
12614        assert!(!retry_answer_is_admissible(
12615            -1.8175997416e-9,
12616            2.07e-25,
12617            6.6088333055e-5,
12618            1.09e-9,
12619            ACCEPT,
12620            MAX
12621        ));
12622        // ... and the same improvement with the primal held is admitted.
12623        assert!(retry_answer_is_admissible(
12624            -1.8175997416e-9,
12625            2.07e-25,
12626            6.6088333055e-5,
12627            2.07e-25,
12628            ACCEPT,
12629            MAX
12630        ));
12631    }
12632
12633    /// The mirror of the above, stated as the property rather than the
12634    /// rows: negating both objectives and flipping the sense must leave
12635    /// every verdict unchanged.
12636    #[test]
12637    fn negating_the_objective_and_the_sense_is_inert() {
12638        for &(bo, bv, ro, rv) in &[
12639            (3.586e-28, 1.11e-16, 5.835e-11, 5.47e-12),
12640            (-1.3005680756e1, 2.22e-16, -1.2072337962e0, 4.55e-13),
12641            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 1.09e-9),
12642            (1.8175997416e-9, 2.07e-25, -6.6088333055e-5, 2.07e-25),
12643            (-1.0e3, 1.0e-2, 0.0, 1.0e-12),
12644        ] {
12645            assert_eq!(
12646                retry_answer_is_admissible(bo, bv, ro, rv, ACCEPT, MIN),
12647                retry_answer_is_admissible(-bo, bv, -ro, rv, ACCEPT, MAX),
12648                "verdict moved under (obj, sense) -> (-obj, -sense) at {bo:e}/{ro:e}"
12649            );
12650        }
12651    }
12652
12653    #[test]
12654    fn an_infeasible_base_attempt_protects_nothing() {
12655        assert!(admissible(-1.0e3, 1.0e-2, 0.0, 1.0e-12));
12656        // ... and what cannot be measured is refused, not admitted, the
12657        // same way `runaway_is_the_whole_residual` treats a NaN.
12658        assert!(admissible(Number::NAN, 0.0, 0.0, 0.0));
12659        assert!(!admissible(0.0, 0.0, Number::NAN, 0.0));
12660        assert!(!admissible(0.0, 0.0, -1.0, Number::NAN));
12661    }
12662}