Skip to main content

pounce_algorithm/
ipopt_alg.rs

1//! Main optimization loop — port of
2//! `Algorithm/IpIpoptAlg.{hpp,cpp}`.
3//!
4//! Phase 7 ships the loop scaffold matching `Optimize()` lines
5//! 292-563 in upstream. The body invokes:
6//!
7//!   1. `IterateInitializer::set_initial_iterates`
8//!   2. (loop) `OutputIteration` → `CheckConvergence` →
9//!      `UpdateBarrierParameter` → `UpdateHessian` →
10//!      `ComputeSearchDirection` → `ComputeAcceptableTrialPoint` →
11//!      `AcceptTrialPoint`
12//!   3. `correct_bound_multiplier` (kappa_sigma) per `MAIN_LOOP.md`
13//!      §"Bound multiplier reset" lines 1055-1134
14//!   4. exception → `SolverReturn` mapping per the table in
15//!      `MAIN_LOOP.md`.
16//!
17//! The NLP handle and search-direction calculator are optional:
18//! when both are present, `iterate()` computes a real Newton step and
19//! drives the line search. Without them, `iterate()` runs the bookkeeping
20//! pieces (mu update, hessian update, conv check, kappa_sigma reset)
21//! and is exercised by structural unit tests. The full path lights up
22//! once `pounce-nlp::OrigIpoptNLP` lands.
23
24use crate::alg_builder::AlgorithmBundle;
25use crate::conv_check::r#trait::ConvergenceStatus;
26use crate::intermediate::{CtxGuard, IntermediateContext};
27use crate::ipopt_cq::IpoptCqHandle;
28use crate::ipopt_data::IpoptDataHandle;
29use crate::ipopt_nlp::IpoptNlp;
30use crate::iter_dump::IterDumper;
31use crate::iterate_dump::emit_record as emit_iterate_record;
32use crate::kkt::pd_search_dir_calc::PdSearchDirCalc;
33use crate::line_search::backtracking::Outcome;
34use crate::restoration::{RestorationOutcome, RestorationPhase};
35use pounce_common::diagnostics::DiagnosticsState;
36use pounce_common::types::{Index, Number};
37use pounce_linalg::Vector;
38use pounce_nlp::alg_types::SolverReturn;
39use pounce_nlp::return_codes::AlgorithmMode;
40use pounce_nlp::tnlp::{IpoptCq as TnlpIpoptCq, IpoptData as TnlpIpoptData, IterStats, TNLP};
41use std::cell::RefCell;
42use std::rc::Rc;
43
44/// Dual-divergence guard (pounce#246): only dual-infeasibility growth in the
45/// *elevated* regime (`inf_du` above this) counts toward the streak, so the
46/// noisy early iterations of a normal solve never build one.
47const DUAL_DIV_COUNT_FLOOR: Number = 1e2;
48/// Dual-divergence guard: the guard fires only once `inf_du` is this large in
49/// absolute terms — well above the transient peaks a converging solve reaches
50/// (e.g. the least-square-init path recovers from ~6e9 on emfl050), and below
51/// the ~1e10 where the KKT factorizations begin to choke, so the diversion to
52/// restoration happens *before* the seconds-long factorizations start.
53const DUAL_DIV_FIRE_TOL: Number = 1e8;
54
55/// gh#884 — the scale-relative search direction below which the iterate
56/// counts as **settled** for the dual-divergence-retry signature.
57///
58/// Measured on `d89771bc`, minimum over the iterates where the primal is
59/// already converged: `qpec_small`/`ncp_eq`/origin reaches `8.6e-14`
60/// through the `.nl` path and `4.3e-8` through a Rust TNLP, while
61/// `ralph1`/`direct`/origin — which *must not* fire, because no
62/// sign-feasible multiplier exists at its origin and failing there is
63/// correct — bottoms out at `7.2e-3`. Five orders of separation; `1e-5`
64/// sits near the middle of it in log terms. The census behind this, and
65/// the corpus fixtures that come closest on either side, are in
66/// `dev-notes/mpcc-biactive-dual-divergence.md`.
67const DUAL_DIV_RETRY_STEP_TOL: Number = 1e-5;
68
69/// gh#884 — the unscaled `‖∇L‖∞` floor for that signature.
70///
71/// Deliberately the same `1e2` as [`DUAL_DIV_COUNT_FLOOR`], and for the
72/// same reason: below it a solve is merely mid-flight. It is what
73/// excludes `eigena2` on the L-BFGS leg, which reaches a settled step of
74/// `7.9e-9` but at an unscaled dual of only `37`.
75pub(crate) const DUAL_DIV_RETRY_DU_FLOOR: Number = 1e2;
76
77/// gh#884 — primal infeasibility below which the primal counts as
78/// converged for that signature. The failure mode is defined by the
79/// primal being *done* while the duals run away, so this conjunct is
80/// what separates it from an ordinary struggling solve.
81const DUAL_DIV_RETRY_PRIMAL_TOL: Number = 1e-8;
82
83/// gh #534 — how many consecutive outer NLP errors the progress test reads.
84/// Four samples give three ratios: enough that a single lucky step cannot pass
85/// the test, short enough to still be inside the endgame it is meant to
86/// recognise. `eigena2`'s quoted tail is exactly four iterations long
87/// (`1.19e-5 → 2.96e-6 → 7.38e-7 → 1.84e-7`).
88const DECLINE_PROGRESS_SAMPLES: usize = 4;
89/// gh #534 — default `resto_decline_progress_ratio`: every one of those ratios
90/// must be at least this contraction for the decline to be deferred. `eigena2`
91/// quarters (ratio `0.249`) and passes; `eigenb2`'s tail *rises*
92/// (`1.88e-7, 2.69e-7, 2.89e-7, 2.93e-7`) and fails, which is the intended
93/// split — the issue calls `eigenb2` a plausible genuine stall and the guard
94/// plausibly right there.
95const DEFAULT_DECLINE_PROGRESS_RATIO: Number = 0.5;
96/// gh #534 — outer iterations a deferred continuation gets to produce a strict
97/// certificate before it is cut and the floor reported. `eigena2`'s
98/// extrapolation needs three; ten leaves room for a slower but still genuine
99/// endgame while keeping the cost of a lost bet bounded and small.
100const DECLINE_CONTINUATION_BUDGET: Index = 10;
101/// gh #534 — default for `resto_decline_deferrals`. One deferral is enough for
102/// the reported case (the continuation either converges within the budget or it
103/// does not); more entries would mostly re-bet on a point the first bet already
104/// failed to improve.
105const DEFAULT_RESTO_DECLINE_DEFERRALS: usize = 1;
106/// gh #797 — default for `neg_curv_escapes`. One is enough for the reported
107/// shape: the escape lands on a point whose reduced Hessian *is* positive
108/// definite, so the probe declines there and a second escape would have nothing
109/// to spend itself on. It is also the conservative default — each escape is a
110/// separate bet, and while none of them can return a worse point than the
111/// certificate it left, each costs its own continuation budget.
112/// Default `limited_memory_ls_failure_restarts` (gh #818): **off**. The
113/// rung is available, and it is not what fixes gh #818.
114///
115/// It shipped in the first draft of this work defaulted to one, on a
116/// measurement taken before `ALPHA_INTERP_MIN_TRIALS` existed: with the
117/// interpolation firing on every trial, a line search failed often
118/// enough that standing in front of the restoration hand-off was worth
119/// something. Gating the interpolation removed most of those failures,
120/// and re-measuring the rung on top of the gate turned the trade
121/// negative. `scripts/sweep-fixtures.sh` against `a5e0a837`, both with
122/// the gate, rung off against rung on:
123///
124/// | fixture | rung off | rung on |
125/// |---|---|---|
126/// | `pooling_rt2stp` | `ErrorInStepComputation`/716 — *unmoved from `main`* | `ErrorInStepComputation`/**744** |
127/// | `infeasible_square_scaled_1em4` | `InfeasibleProblemDetected`/24 — *unmoved from `main`* | **26** |
128/// | `deb7` | `ErrorInStepComputation`/1010 | **`RestorationFailed`**/460 |
129/// | `eigena2` | `ErrorInStepComputation`/201 | **`SolvedToAcceptableLevel`**/174 |
130/// | `issue_508_infeasible_gap_1em4` | `InfeasibleProblemDetected`/79 | 76 |
131///
132/// **This ledger is not the one that set the default.** At the gate of
133/// 5 an earlier revision shipped, the rung cost iterations on both
134/// `eigena2` and `infeasible_square_scaled_1em4` to the same verdict,
135/// and that pair is what kept it off. At 6, `eigena2` *gains* a
136/// reportable point. What still argues for off is narrower: the rung
137/// moves two fixtures off the numbers they have on `main` at no benefit
138/// (`pooling_rt2stp`, `infeasible_square_scaled_1em4`), and it changes
139/// `deb7`'s verdict rather than shortening it — a different answer, not
140/// a faster one. Turning it on is a trajectory change over the whole
141/// corpus and needs its own `scripts/sweep-fixtures.sh` run to justify;
142/// **that case has improved and is worth re-opening.** Every
143/// `issue_818_*` test in `pounce-rs` passes with the rung compiled out
144/// — the interpolation is the fix, not this.
145///
146/// Left in the tree rather than deleted because the reasoning behind it
147/// is sound and unaddressed elsewhere: a restoration phase entered at a
148/// feasible point has no constraint violation to minimize and cannot
149/// help. Some model will want it. Setting the option to a positive value
150/// enables it — and note that setting it *at all*, including to 0, opts
151/// out of the `Solved_To_Acceptable_Level` re-solve, because it is a
152/// [`TERMINATION_POLICY_OPTIONS`](crate::application) key.
153const DEFAULT_LBFGS_LS_FAILURE_RESTARTS: usize = 0;
154
155const DEFAULT_NEG_CURV_ESCAPES: usize = 1;
156/// gh #797 — outer iterations a negative-curvature escape gets to produce a
157/// certificate of its own before it is cut and the stationary point reported.
158/// Generous relative to gh #534's ten, because the escape deliberately lands
159/// far from the point it left (a full fraction-to-the-boundary step) and the
160/// continuation is a fresh endgame rather than the tail of one already in
161/// progress.
162const NEG_CURV_CONTINUATION_BUDGET: Index = 30;
163/// gh #797 — cap on the escape step as a multiple of `1 + ‖(x, s)‖∞`. The
164/// probe's direction has unit infinity-norm, so this bounds the escape by the
165/// iterate's own scale; an absolute cap would mean different things on
166/// differently scaled models. Only binds when the fraction-to-the-boundary rule
167/// does not, i.e. when nothing in the direction runs into a bound.
168const NEG_CURV_MAX_STEP_FACTOR: Number = 10.0;
169/// gh #797 — backtracking steps available to the escape, and the ratio between
170/// them. `0.5^12 ≈ 2.4e-4` of the boundary step, past which a direction that
171/// still fails the decrease test is not one worth taking.
172const NEG_CURV_BACKTRACKS: usize = 12;
173const NEG_CURV_BACKTRACK_FACTOR: Number = 0.5;
174/// gh #797 — Armijo factor on the escape's *second-order* decrease model. The
175/// gradient is (near) zero at a stationary point, so the model is
176/// `½α²dᵀ(W + Σ)d` and this is the fraction of it the trial must actually
177/// realise. Mirrors the line search's `eta_phi` in role, not in value: the
178/// quantity being tested is curvature, and a nonlinear objective gives back
179/// less of a quadratic model's prediction than a linear one gives of a
180/// first-order model's.
181const NEG_CURV_ARMIJO: Number = 0.1;
182
183/// See [`IpoptAlgorithm::handover`].
184/// Arguments: the current iterate, the iteration count, the overall NLP
185/// error and the barrier parameter.
186pub type HandoverHook = Box<
187    dyn FnMut(
188        &crate::iterates_vector::IteratesVector,
189        Index,
190        Number,
191        Number,
192    ) -> Option<crate::iterates_vector::IteratesVector>,
193>;
194
195pub struct IpoptAlgorithm {
196    pub data: IpoptDataHandle,
197    pub cq: IpoptCqHandle,
198    pub bundle: AlgorithmBundle,
199    /// Optional NLP handle. Required for any step that evaluates
200    /// problem functions or pulls bound expansion matrices (init,
201    /// search direction, line-search trial-point evaluation). Absent
202    /// in the structural unit tests of Phases 5-6.
203    pub nlp: Option<Rc<RefCell<dyn IpoptNlp>>>,
204    /// Optional TNLP handle — the user-facing problem. When present,
205    /// `iterate()` fires `TNLP::intermediate_callback` once per outer
206    /// iteration so callers can monitor progress or request early
207    /// termination (returning `false` from the callback surfaces as
208    /// `SolverReturn::UserRequestedStop`). Kept separate from `nlp`
209    /// because the algorithm-side NLP is the *compressed* `OrigIpoptNlp`
210    /// view (fixed-variable elimination, c/d split) while the callback
211    /// payload needs to expose the original-coordinate iterate.
212    pub tnlp: Option<Rc<RefCell<dyn TNLP>>>,
213    /// Set on the *restoration* inner IPM so its callback fires report
214    /// `AlgorithmMode::RestorationPhaseMode` (gh#645). Two things hang
215    /// off it, both in [`Self::fire_intermediate`]:
216    ///
217    /// 1. the mode field of the [`IterStats`] payload, which is what
218    ///    tells a caller the numbers beside it (`obj`, `inf_pr`,
219    ///    `inf_du`, `alpha_*`) describe the min-C1-norm feasibility
220    ///    subproblem rather than the user's NLP;
221    /// 2. whether the live-inspector `IntermediateContext` is installed
222    ///    — and for a restoration fire it deliberately is **not**. The
223    ///    inner iterate is a `CompoundVector` over `(x_orig, n, p)`, so
224    ///    it does not even have the user's `n`, and the C API's
225    ///    `GetIpoptCurrent*` family checks the caller's `n`/`m` against
226    ///    the *problem's* registered dimensions rather than the
227    ///    context's. Installing this context would sail past that check
228    ///    and read a differently-shaped `cq`. The live accessors
229    ///    therefore report "no data" during restoration, which is the
230    ///    truth: there is no current iterate of the user's problem
231    ///    while the subproblem is being solved.
232    pub fires_as_restoration: bool,
233    /// Interior-point → active-set handover (gh#1054), installed by the
234    /// driver when `ipm_sqp_handover=yes`. Called at every convergence
235    /// check that did not converge, with the current iterate, the
236    /// iteration count, the overall NLP error and `μ`; it decides itself
237    /// whether to try (see `crate::handover`). `Some(point)` is an iterate
238    /// that already meets the stopping tolerances: it replaces `curr` and
239    /// the solve ends `Success`. `None` leaves the interior iteration
240    /// exactly as it was, which is the fallback the request asked for.
241    pub handover: Option<HandoverHook>,
242    /// Whether the live iterate handed to the intermediate callback
243    /// recovers the bound multipliers of fixed variables, as the final
244    /// solution does. Set from `fixed_variable_treatment` by the driver
245    /// (`IpoptApplication::reports_fixed_var_duals`); see
246    /// [`crate::intermediate::ipm_user_iterate`].
247    pub live_iterate_fixed_var_duals: bool,
248    /// Search-direction calculator (`PdSearchDirCalc`). Lands once a
249    /// concrete `SymLinearSolver` backend (MUMPS / FERAL) is wired
250    /// through `AlgBuilder` in Phase 7's tail.
251    pub search_dir: Option<PdSearchDirCalc>,
252    /// Restoration-phase strategy. Invoked when the line search
253    /// returns [`Outcome::Failed`] (port of upstream
254    /// `IpBacktrackingLineSearch::ActivateLineSearch`'s resto
255    /// fallback). Optional: in its absence, line-search failure maps
256    /// directly to [`SolverReturn::RestorationFailure`] so the main
257    /// loop's exit-code semantics match upstream's "no resto built"
258    /// case.
259    pub restoration: Option<Box<dyn RestorationPhase>>,
260
261    /// `kappa_sigma` for the post-AcceptTrialPoint multiplier reset
262    /// (`IpIpoptAlg.cpp:correct_bound_multiplier`, line 1055-1134).
263    pub kappa_sigma: Number,
264    /// `recalc_y` — recompute `y_c`/`y_d` as least-square estimates
265    /// once the iterate is feasible enough, instead of carrying the
266    /// multipliers the Newton step produced. Upstream registers this
267    /// `no`, but its own option text says "If a limited memory
268    /// quasi-Newton option is chosen, this is used by default", so the
269    /// L-BFGS path auto-enables it (see
270    /// `application.rs`). Costs one extra augmented-system solve on
271    /// every iteration where it fires.
272    ///
273    /// It exists because a quasi-Newton model's multipliers are only as
274    /// good as the Hessian approximation behind them: L-BFGS can reach
275    /// a feasible primal and still fail to drive `inf_du` down, because
276    /// the dual step is computed from an approximate `W`. Re-estimating
277    /// `y` by least squares side-steps the approximation entirely.
278    /// `linear_system_scaling=slack-based` is active, so the
279    /// iterate-dependent `s`-block scaling must be refreshed each
280    /// iteration. See [`Self::push_slack_scaling`].
281    pub slack_based_scaling: bool,
282    pub recalc_y: bool,
283    /// `recalc_y_feas_tol` — the constraint-violation threshold below
284    /// which [`Self::recalc_y`] fires. Upstream default `1e-6`.
285    pub recalc_y_feas_tol: Number,
286    pub max_iter: Index,
287    /// `start_with_resto` — force the feasibility restoration phase in
288    /// the first iteration.
289    ///
290    /// This is an **outer**-loop behaviour, which is where it went wrong
291    /// before: the option was threaded from the `OptionsList` through
292    /// `AlgorithmBuilder::resto` into `RestoAlgorithmBuilder` and on into
293    /// `MinC1NrmDriver`, a field on the *inner* restoration solver, where
294    /// there is no first iteration of the outer algorithm to act on. It
295    /// was set by everything and read by nothing, so `start_with_resto
296    /// yes` was a silent no-op. `unimplemented_options.rs`'s
297    /// `the_restoration_switches_reach_the_builder` asserted only that the
298    /// value reached the builder — the very "read site populating a field
299    /// nobody consumes" its own comment names as the defect to avoid.
300    pub start_with_resto: bool,
301    /// Initial primal step length offered to the line search at the
302    /// top of each iteration. Mirrors `IpBacktrackingLineSearch`'s
303    /// fraction-to-the-boundary primal step (with τ = `data.curr_tau`).
304    /// In v1.0 the structural value here is 1.0 and the FTB cap is
305    /// applied per-component when the line-search driver computes
306    /// trial slacks; the simplification holds for non-degenerate runs.
307    pub alpha_init: Number,
308    /// Tiny-step relative tolerance — port of upstream
309    /// `IpBacktrackingLineSearch::tiny_step_tol_` (default `10·EPSILON`).
310    /// Step is "tiny" when `max_i |δx_i|/(1+|x_i|) ≤ tiny_step_tol`
311    /// (and same for s, and `c_viol ≤ 1e-4`).
312    pub tiny_step_tol: Number,
313    /// Port of upstream `IpIpoptAlg.cpp` divergence guard: when
314    /// `max_i |x_i|` exceeds this threshold the optimization aborts with
315    /// `SolverReturn::DivergingIterates`. Default `1e20` matches the
316    /// registered `diverging_iterates_tol` option. Catches MESH and
317    /// similar cases where the normal-mode IPM heads off to infinity
318    /// (orig `f` to ±1e33 by iter 90) before line-search failure forces
319    /// a degenerate restoration entry.
320    pub diverging_iterates_tol: Number,
321    /// #248 divergence persistence — consecutive iterations the primal
322    /// iterate has kept *growing* while past `diverging_iterates_tol` on a
323    /// structurally unbounded side. A genuine recession ray sustains this;
324    /// a transient ill-scaling excursion on a bounded-below problem peaks
325    /// and recedes (MINLPLib `jit1`: `|x|` climbs to ~16 then falls back to
326    /// ~2.9 at the finite optimum). Reset to zero whenever the iterate is
327    /// within the threshold or is not growing.
328    divergence_streak: u32,
329    /// Consecutive iterations for which the primal divergence guard has
330    /// been suppressed because the line search reported
331    /// [`crate::line_search::backtracking::BacktrackingLineSearch::in_watchdog`].
332    ///
333    /// The suppression is a *deferral*, and this is what bounds it. A
334    /// watchdog sequence is supposed to end within
335    /// `watchdog_trial_iter_max` (default 3) iterations, but the flag can
336    /// outlive one: `run_filter_line_search`'s `TinyStep` arm returns
337    /// without consulting `in_watchdog`, so a tiny step taken mid-watchdog
338    /// hands off to restoration with the flag still set, and
339    /// `reset_after_restoration` clears `watchdog_shortened_iter` but not
340    /// `in_watchdog`. Rather than change the line search's state machine
341    /// (a trajectory change, for a hole this guard need not depend on),
342    /// the guard simply stops deferring past
343    /// [`Self::WATCHDOG_DEFER_MAX`] and checks the iterate anyway. Reset
344    /// to zero on any iteration the guard actually runs.
345    watchdog_defer_streak: u32,
346    /// Largest `|x|` seen in the current growth run (companion to
347    /// [`Self::divergence_streak`]). Zero when no run is active.
348    divergence_prev_amax: Number,
349    /// #252 objective at the previous over-threshold iterate of the current
350    /// growth run (companion to [`Self::divergence_streak`]). A genuine
351    /// recession ray drives the (minimized) objective toward `−∞`, so a
352    /// diverging iterate only counts toward the streak when the objective is
353    /// *still descending* against this reference. A transient ill-scaling
354    /// excursion past a finite optimum grows `|x|` while the objective
355    /// *worsens* (the linear tail dominates), so it never accumulates the
356    /// streak — this is the fix for the unbounded-box (`ub = +∞`) B&B node
357    /// subproblems of jit1 that #248's growth-only check still mislabelled
358    /// `UNBOUNDED`. `+∞` when no run is active.
359    divergence_prev_f: Number,
360    /// #252 objective *decrease* at the previous step of the current growth
361    /// run (`prev_prev_f − prev_f`), the companion that lets the streak
362    /// require the descent to be *non-decelerating*. A recession ray's
363    /// per-step objective drop keeps up or accelerates as `|x|` grows
364    /// geometrically (`f` is at least linear along the ray); an excursion
365    /// converging to a finite optimum has a per-step drop that shrinks
366    /// toward zero. `NaN` (non-finite) until the run has a first finite
367    /// decrease to compare against, which bootstraps the check.
368    divergence_prev_decrease: Number,
369    /// #285 recession-ray persistence — consecutive iterations for which the
370    /// *checked recession-ray proof* ([`Self::curr_is_recession_ray`]) held
371    /// while the primal iterate kept growing. This is a second, independent
372    /// unboundedness path that catches a genuine recession ray in
373    /// `null(A_eq)` over free variables whose `|x|` grows only *linearly*
374    /// (the regularized zero-Hessian step in an equality null space marches
375    /// out at a bounded rate), so it never crosses `diverging_iterates_tol`
376    /// (`1e20`) within `max_iter` and the geometric-growth
377    /// [`Self::divergence_streak`] never accumulates. Reset to zero whenever
378    /// the proof fails or the iterate stops growing.
379    recession_streak: u32,
380    /// Largest `|x|` seen in the current recession-ray run (companion to
381    /// [`Self::recession_streak`]). Zero when no run is active.
382    recession_prev_amax: Number,
383    /// Companion threshold on the dual step — when both primal and dual
384    /// steps are tiny in two consecutive iterations the algorithm
385    /// declares convergence at the best attainable accuracy. Default
386    /// `1e-2` matches upstream.
387    pub tiny_step_y_tol: Number,
388    /// `dual_diverging_streak` (pounce#246) — number of consecutive
389    /// iterations of *growing* dual infeasibility (in the elevated regime,
390    /// `inf_du > `[`DUAL_DIV_COUNT_FLOOR`]) that must accumulate before the
391    /// dual-divergence guard fires. When the streak reaches the limit and
392    /// `inf_du > `[`DUAL_DIV_FIRE_TOL`], the outer routes to restoration.
393    ///
394    /// **`0` (off) is the default**, set from the option of the same name
395    /// (`application.rs`). It defaulted to `15` when introduced; see the option
396    /// help in `upstream_options.rs` for why that changed, and
397    /// [`Self::honour_best_acceptable_after_dual_guard`] for what protects a
398    /// solve when it is enabled. See the guard itself in [`Self::iterate`].
399    pub dual_diverging_streak: usize,
400    dual_inf_prev: Number,
401    dual_growth_streak: usize,
402    /// gh#884 — thresholds for the dual-divergence *retry* signature.
403    /// Distinct from the pounce#246 guard above in both mechanism and
404    /// consequence: that one diverts a running solve to restoration, this
405    /// one only *records* that a cold retry is worth attempting after the
406    /// solve has already given up. Set from options of the same name; see
407    /// [`DUAL_DIV_RETRY_STEP_TOL`] for the measured populations.
408    pub dual_divergence_retry_step_tol: Number,
409    /// Companion floor on the unscaled dual — see
410    /// [`DUAL_DIV_RETRY_DU_FLOOR`].
411    pub dual_divergence_retry_du_floor: Number,
412    /// Scale-relative magnitude of the most recent search direction,
413    /// `max(max_i |δx_i|/(1+|x_i|), max_i |δs_i|/(1+|s_i|))` — the
414    /// `detect_tiny_step` measure, kept as a number rather than a
415    /// predicate. `INFINITY` before the first direction is computed, so
416    /// the signature cannot fire on iteration 0.
417    last_step_rel: Number,
418    /// gh#884 — sticky: set once the four-conjunct signature is seen at a
419    /// single iterate, never cleared. Read by the application layer after
420    /// the solve to decide whether a cold retry is authorized. It never
421    /// changes a verdict by itself.
422    dual_divergence_signature: bool,
423    /// Set true when the previous iterate was tagged tiny; on the
424    /// second consecutive tiny step the loop sets `data.tiny_step_flag`
425    /// so the mu update can attempt to terminate. Mirrors
426    /// `IpBacktrackingLineSearch::tiny_step_last_iteration_`.
427    pub tiny_step_last_iteration: bool,
428    /// Cycle-detection state for [`Self::invoke_restoration`]: the
429    /// outer `(x, s)` snapshot from the previous restoration entry,
430    /// cleared on any iteration that exits via a normal line-search
431    /// accept. When restoration is invoked twice in a row and the
432    /// outer iterate has not moved between entries (relative
433    /// 2-norm < 1e-10 on both `x` and `s`), the inner resto-IPM is
434    /// returning Recovered points indistinguishable from `curr` — a
435    /// cycle. Surfaces as `ErrorInStepComputation`. Mirrors the
436    /// *intent* of upstream `IpBacktrackingLineSearch.cpp:580-600`'s
437    /// almost-feasible-resto guard while staying robust against the
438    /// `inf_pr` micro-drift seen on ACOPR14 (delta ~3e-12 per entry,
439    /// inf_du essentially constant) where a scalar-`inf_pr` heuristic
440    /// fails. Productive single-restoration sequences (BT8, HIMMELBJ,
441    /// LINSPANH, LSNNODOC, ODFITS, OET3) clear the snapshot via
442    /// `Outcome::Accepted` between entries and are unaffected.
443    last_resto_entry_x: Option<Box<dyn Vector>>,
444    last_resto_entry_s: Option<Box<dyn Vector>>,
445    /// Snapshot of the *recovery* iterate from the previous
446    /// restoration. Compared against the next entry's `(x, s)` to
447    /// detect "outer made no progress between consecutive resto
448    /// invocations". When this distance is below threshold for
449    /// several consecutive entries, terminate — catching
450    /// slow-non-convergence cycles (ACOPR14, TRO3X3, ACOPR30) where
451    /// resto's *inner* moves substantively each call but the *outer*
452    /// makes no progress between calls. Cleared on any LS-accepted
453    /// step.
454    last_resto_recovery_x: Option<Box<dyn Vector>>,
455    last_resto_recovery_s: Option<Box<dyn Vector>>,
456    /// The most recent restoration recovery, kept only when it was a point
457    /// restoration handed back without releasing it — layer 2's
458    /// converged-to-feasible-point verdict, which upstream treats as a
459    /// restoration failure (gh#1042, see
460    /// [`RestorationPhase::last_recovery_unreleased`]). Unlike
461    /// [`Self::last_resto_recovery_x`] it is **not** cleared by an accepted
462    /// step: a watchdog that tries steps from the handed-back point and
463    /// rolls back to it has not left it either. Replaced at every recovery.
464    last_resto_unreleased_x: Option<Box<dyn Vector>>,
465    last_resto_unreleased_s: Option<Box<dyn Vector>>,
466    /// Unscaled max-norm violation of the original NLP at
467    /// [`Self::last_resto_unreleased_x`] — what the gh#1042 exit judges its
468    /// verdict on (gh#1076). Meaningful only while that point is held.
469    last_resto_unreleased_theta_unscaled: Number,
470    /// An unreleased hand-back whose shot the outer has not yet taken
471    /// (gh#1076). Set by every unreleased recovery; cleared by the first
472    /// step the line search accepts on the *original* criterion — anything
473    /// but a soft-restoration `s` step, which is accepted precisely because
474    /// the original filter would not take it. Consumed at the next
475    /// restoration entry.
476    unreleased_shot_pending: bool,
477    /// Consecutive restoration entries at which
478    /// [`Self::unreleased_shot_pending`] was still set (gh#1076). Cleared
479    /// by any step the original globalization accepts and by a released
480    /// recovery.
481    unreleased_shot_strikes: u32,
482    /// Set when the gh#1042 exit below ended this solve (see
483    /// [`Self::unreleased_handback_exit`]). Never cleared within a solve.
484    unreleased_handback_exit: bool,
485    /// Count of consecutive restoration entries on which the outer
486    /// step (recovery → next-entry) was below the iterate-distance
487    /// threshold. Cleared on any LS-accepted step. Limit chosen to
488    /// let MAKELA3, HAIFAM, HALDMADS, ROBOT, TENBARS2 — which need
489    /// 2-3 consecutive resto entries to recover — pass through.
490    resto_no_outer_progress_count: usize,
491    /// `resto_decline_deferrals` (gh #534) — how many times the
492    /// acceptable-point restoration decline in [`Self::invoke_restoration`] may
493    /// be *deferred* on a solve whose NLP error is still contracting. `0`
494    /// restores the pre-#534 behaviour (decline immediately, always).
495    ///
496    /// See [`Self::may_defer_acceptable_decline`] for the progress test and
497    /// [`Self::honour_decline_floor`] for what makes a spent deferral harmless.
498    pub resto_decline_deferrals: usize,
499    /// `resto_decline_progress_ratio` (gh #534) — the contraction each of the
500    /// last [`DECLINE_PROGRESS_SAMPLES`]` - 1` iterations must have achieved for
501    /// the decline to be deferred. Default
502    /// [`DEFAULT_DECLINE_PROGRESS_RATIO`]. A value of `1` admits any
503    /// non-increasing window and a large one drops the progress requirement
504    /// altogether, which is the "patch the guard and see" experiment the issue
505    /// asks for, available without patching.
506    pub resto_decline_progress_ratio: Number,
507    /// The most recent outer-iteration NLP errors, oldest first, with
508    /// [`Self::nlp_err_recent_len`] entries live. Feeds the gh #534 progress
509    /// test and nothing else.
510    nlp_err_recent: [Number; DECLINE_PROGRESS_SAMPLES],
511    nlp_err_recent_len: usize,
512    /// gh #534 — deferrals of the acceptable-point decline spent so far.
513    decline_deferrals_used: usize,
514    /// gh #534 — the iterate the guard would have returned had it not been
515    /// deferred. Captured at the *first* deferral only, because that point is
516    /// precisely the answer the pre-#534 build reports; it is the floor the
517    /// continuation is never allowed to fall below.
518    decline_floor: Option<VetoSnapshot>,
519    /// gh #534 — outer iteration by which the deferred continuation must have
520    /// produced a strict certificate. Past it the continuation is cut and the
521    /// floor is reported, so the bet costs a bounded number of iterations.
522    decline_deadline_iter: Option<Index>,
523    /// `neg_curv_escapes` (gh #797) — how many times a certified stationary
524    /// point whose reduced Hessian is not positive semidefinite may be *left*
525    /// along a direction of negative curvature instead of reported. `0` restores
526    /// the pre-#797 behaviour (report the first-order certificate, whatever its
527    /// curvature).
528    ///
529    /// See [`Self::try_neg_curv_escape`] for the test and the step, and
530    /// [`Self::honour_neg_curv_floor`] for what makes a lost bet harmless.
531    pub neg_curv_escapes: usize,
532    /// `limited_memory_ls_failure_restarts` (gh #818) — how many times a
533    /// line-search failure at an *already feasible* point may re-anchor
534    /// the quasi-Newton model and retry, instead of handing off to a
535    /// restoration phase that has no constraint violation to reduce.
536    /// `0` restores the pre-#818 behaviour (always hand off).
537    ///
538    /// See [`Self::try_reanchor_before_restoration`] for the rung and
539    /// what bounds it.
540    pub lbfgs_ls_failure_restarts: usize,
541    /// gh #818 — re-anchors spent so far this solve.
542    lbfgs_ls_restarts_used: usize,
543    /// gh #797 — escapes spent so far this solve.
544    neg_curv_escapes_used: usize,
545    /// Sink for the last `IterStats` handed to the user's
546    /// `intermediate_callback` (pounce#870). A second-opinion retry that loses
547    /// needs it, so that the trace a consumer accumulated can be made to end
548    /// on the iterate actually reported. Set by `IpoptApplication`; `None`
549    /// everywhere else.
550    pub last_iter_stats_sink: Option<Rc<RefCell<Option<IterStats>>>>,
551    /// gh #797 — the certified stationary point the escape left. It is a strict
552    /// certificate, so it is the floor the continuation must beat *with a
553    /// certificate of its own* to be preferred.
554    ///
555    /// With more than one escape available this holds the **best** of the
556    /// certificates left so far, not the most recent (gh #805). The first entry
557    /// is the answer a `neg_curv_escapes = 0` build returns, and it is only
558    /// ever displaced by a point that outranks it, so the guarantee holds at
559    /// any number of escapes and the floor never moves backwards.
560    neg_curv_floor: Option<VetoSnapshot>,
561    /// gh #797 — outer iteration by which the escape's continuation must have
562    /// produced a certificate. Past it the continuation is cut and the floor
563    /// reported, so the bet costs a bounded number of iterations.
564    neg_curv_deadline_iter: Option<Index>,
565    /// Count of consecutive restoration entries on which the outer
566    /// constraint violation at entry was already below `tol` (the
567    /// outer optimality tolerance). Matches the *intent* of upstream
568    /// `IpBacktrackingLineSearch.cpp:580-600`'s almost-feasible-resto
569    /// guard while using a looser cv threshold (`tol` vs `1e-2·tol`)
570    /// — catches DECONVBNE's resto-thrash where each cycle re-enters
571    /// at cv ≈ 3e-10 < tol with bound multipliers reset to 1, the
572    /// outer's σ-blowup explodes inf_du to 1.9e7, alpha-min triggers
573    /// resto re-entry, and the (inf_pr, inf_du) post-recovery state
574    /// is essentially identical across cycles but `x` drifts enough
575    /// that [`Self::last_resto_recovery_x`]-based detection misses.
576    /// Cumulative (never cleared on LS-accept), since DECONVBNE's
577    /// cycle interleaves R-recoveries with sub-tol accepts that
578    /// accomplish no real outer progress. Fires after 3 near-feasible
579    /// entries — surfaces as `StopAtAcceptablePoint` since the
580    /// recovered point already satisfies constraint feasibility
581    /// within `tol`.
582    resto_near_feasible_count: usize,
583    /// The pending restoration entry was forced by a non-finite Hessian
584    /// (the factorization rejected the KKT before inertia was read), so it
585    /// is not a `resto_near_feasible_count` strike. Set at the
586    /// step-computation-failure hand-off, consumed by `invoke_restoration`.
587    resto_entry_nonfinite_w: bool,
588    /// Snapshot of the most recent iterate that the convergence check
589    /// flagged "acceptable" (NLP error ≤ `acceptable_tol`). Mirrors
590    /// upstream `IpBacktrackingLineSearch::acceptable_iterate_`
591    /// (`IpBacktrackingLineSearch.cpp:1286-1310`). Used by
592    /// [`Self::restore_acceptable_point`] to roll back when restoration
593    /// fails — if such an iterate exists, the algorithm exits with
594    /// `SolverReturn::StopAtAcceptablePoint` rather than
595    /// `RestorationFailure`. Cleared/refreshed on every iteration that
596    /// satisfies the acceptable predicate.
597    acceptable_iterate: Option<crate::iterates_vector::IteratesVector>,
598    /// The first iterate whose *strict* certificate the masked-scale veto
599    /// refused (gh #200), kept so the refusal can be undone verbatim if the
600    /// continued run does not do better. Deliberately not the acceptable
601    /// snapshot: that one is overwritten unconditionally and drifts.
602    vetoed: Option<VetoSnapshot>,
603    /// The iterate at which a refused *acceptable-level* termination would have
604    /// fired. Held separately from `vetoed` because it restores under a weaker
605    /// status, and claiming `Success` for it would over-report.
606    vetoed_acceptable: Option<VetoSnapshot>,
607    /// Whether a strict refusal has already been *seen*, independent of whether
608    /// a snapshot was successfully captured for it.
609    ///
610    /// This is the first-only latch, held apart from `vetoed` on purpose.
611    /// Testing `vetoed.is_none()` instead would let a refusal whose capture
612    /// failed be "completed" at a later iterate — the veto flag on the
613    /// convergence check is sticky, so it still reads true next pass, and the
614    /// fallback would then restore a point that never passed the strict test.
615    /// With the latch, a failed capture stays failed and the fallback declines.
616    ///
617    /// Declining is *not* the baseline outcome — the baseline stopped and
618    /// reported a certificate at the uncaptured iterate, and declining fails to
619    /// reproduce it. It is the least-bad handling of an unidentifiable baseline,
620    /// not a faithful one.
621    vetoed_seen: bool,
622    /// Same latch for the acceptable-level refusal.
623    vetoed_acceptable_seen: bool,
624    /// Whether the dual-divergence guard (pounce#246) actually fired this
625    /// solve. Gates the *use* of [`Self::best_acceptable`], so solves the guard
626    /// never touches behave identically — see
627    /// [`Self::honour_best_acceptable_after_dual_guard`].
628    dual_guard_fired: bool,
629    /// Best (lowest scaled objective) acceptable-quality iterate seen anywhere
630    /// in this solve. Recorded unconditionally — including *before* any
631    /// diversion, which is the point: the guard returns to the driver before
632    /// the recording site on the iteration it fires, so gating the recording on
633    /// `dual_guard_fired` would miss everything up to and including the
634    /// diversion. Only read when `dual_guard_fired`.
635    best_acceptable: Option<VetoSnapshot>,
636    /// `kkt_fidelity_tol` (pounce#173), needed here — not just at termination —
637    /// because the fallback's tiebreak has to predict the post-solve status
638    /// gate. See [`Self::honour_refused_certificate`]. Zero (the default)
639    /// disables the gate, and with it every tiebreak effect it has.
640    pub kkt_fidelity_tol: Number,
641    acceptable_iter_number: Index,
642    /// Shared per-solve diagnostics state. `None` unless the CLI
643    /// requested `--dump <cat>:<spec>`. When set, the outer loop
644    /// advances the state's iter counter and the augmented-system
645    /// solver consults it to gate KKT dumps.
646    diagnostics: Option<Rc<DiagnosticsState>>,
647    /// Optional interactive debugger. Shared (`Rc<RefCell<…>>`) so the
648    /// same debugger instance also drives the restoration inner IPM —
649    /// one debugger sees both levels. Fired at every
650    /// [`crate::debug::Checkpoint`]. See `crate::debug`.
651    debug: Option<Rc<RefCell<dyn crate::debug::DebugHook>>>,
652
653    // ---- Restoration-phase audit counters (pounce#12). ----
654    //
655    // Drained into `SolveStatistics` by `IpoptApplication::optimize_constrained`
656    // after the solve completes. Counts are cumulative across the run.
657    /// Number of `invoke_restoration` entries.
658    pub resto_calls: Index,
659    /// Sum of inner-IPM iter counts across every restoration call.
660    pub resto_inner_iters: Index,
661    /// Number of outer iters that ran in restoration mode (R-line
662    /// equivalents in `print_level=5` output).
663    pub resto_outer_iters: Index,
664    /// Cumulative wall-clock seconds spent inside `perform_restoration`.
665    pub resto_wall_secs: Number,
666
667    // ---- Per-iteration history capture (pounce#8, pounce#71). ----
668    //
669    // The per-iteration trajectory is no longer accumulated on the
670    // algorithm: `iterate()` emits a structured `pounce::iteration`
671    // event each step, and `pounce_observability::IterCollectorLayer`
672    // rebuilds the `IterRecord`s into the active `IterCaptureGuard`
673    // that `IpoptApplication` installs around the solve.
674    /// When `false`, the per-iteration table that `iterate()` writes
675    /// straight to stdout is suppressed. Wired from
676    /// `IpoptApplication`'s `print_level` option: level 0 turns this
677    /// off (matches upstream's "no console output" contract). Default
678    /// `true` so CLI / direct-driver users keep the familiar trace.
679    pub print_iter_output: bool,
680}
681
682impl IpoptAlgorithm {
683    /// Diagnostics from the safeguarded `least_square_init_primal`
684    /// initializer step (gh#605). `None` when the step was not run.
685    pub fn least_square_init_report(&self) -> Option<crate::init::default::LeastSquareInitReport> {
686        self.bundle.init.least_square_report()
687    }
688
689    /// Restoration's release test, evaluated in the outer filter's own
690    /// quantities. Mirrors upstream `IpRestoFilterConvCheck::TestOrigProgress`,
691    /// which sets the original problem's trial point to the restoration
692    /// iterate's `(x, s)` and reads `trial_barrier_obj()` and
693    /// `trial_constraint_violation()` from it: the barrier objective at the
694    /// outer `mu` (damping included) and the 1-norm violation, the same pair
695    /// [`Self`]'s filter entries and reference point were made with.
696    ///
697    /// The outer trial point is put back afterwards. Nothing else reads it
698    /// during restoration, but the line search that follows sets it anew and
699    /// must not find a stale restoration iterate there.
700    fn orig_progress_check(
701        &self,
702        accept: crate::restoration::OrigProgressCallback,
703    ) -> crate::restoration::OrigProgressCheck {
704        let data = Rc::clone(&self.data);
705        let cq = Rc::clone(&self.cq);
706        Box::new(move |x: &dyn Vector, s: &dyn Vector| {
707            let Some(curr) = data.borrow().curr.clone() else {
708                return false;
709            };
710            let mut probe = curr.with_x(Rc::from(x.make_new_copy()));
711            probe.s = Rc::from(s.make_new_copy());
712            let saved = data.borrow_mut().trial.replace(probe);
713            let (barr, theta) = {
714                let cq = cq.borrow();
715                (cq.trial_barrier_obj(), cq.trial_constraint_violation())
716            };
717            data.borrow_mut().trial = saved;
718            barr.is_finite() && accept(barr, theta)
719        })
720    }
721
722    pub fn new(data: IpoptDataHandle, cq: IpoptCqHandle, mut bundle: AlgorithmBundle) -> Self {
723        // The builder may pre-populate `bundle.search_dir` when given a
724        // `LinearBackendFactory`; lift it onto the algorithm so the
725        // iterate body can call into it directly.
726        let search_dir = bundle.search_dir.take();
727        Self {
728            data,
729            cq,
730            bundle,
731            nlp: None,
732            tnlp: None,
733            handover: None,
734            fires_as_restoration: false,
735            live_iterate_fixed_var_duals: true,
736            search_dir,
737            restoration: None,
738            kappa_sigma: 1e10,
739            slack_based_scaling: false,
740            recalc_y: false,
741            recalc_y_feas_tol: 1e-6,
742            max_iter: 3000,
743            start_with_resto: false,
744            alpha_init: 1.0,
745            tiny_step_tol: 10.0 * Number::EPSILON,
746            diverging_iterates_tol: 1e20,
747            divergence_streak: 0,
748            watchdog_defer_streak: 0,
749            divergence_prev_amax: 0.0,
750            divergence_prev_f: Number::INFINITY,
751            divergence_prev_decrease: Number::NAN,
752            recession_streak: 0,
753            recession_prev_amax: 0.0,
754            tiny_step_y_tol: 1e-2,
755            dual_diverging_streak: 15,
756            dual_inf_prev: 0.0,
757            dual_growth_streak: 0,
758            dual_divergence_retry_step_tol: DUAL_DIV_RETRY_STEP_TOL,
759            dual_divergence_retry_du_floor: DUAL_DIV_RETRY_DU_FLOOR,
760            last_step_rel: Number::INFINITY,
761            dual_divergence_signature: false,
762            tiny_step_last_iteration: false,
763            last_resto_entry_x: None,
764            last_resto_entry_s: None,
765            last_resto_recovery_x: None,
766            last_resto_unreleased_x: None,
767            last_resto_unreleased_s: None,
768            last_resto_unreleased_theta_unscaled: 0.0,
769            unreleased_shot_pending: false,
770            unreleased_shot_strikes: 0,
771            unreleased_handback_exit: false,
772            last_resto_recovery_s: None,
773            resto_no_outer_progress_count: 0,
774            resto_decline_deferrals: DEFAULT_RESTO_DECLINE_DEFERRALS,
775            neg_curv_escapes: DEFAULT_NEG_CURV_ESCAPES,
776            neg_curv_escapes_used: 0,
777            last_iter_stats_sink: None,
778            lbfgs_ls_failure_restarts: DEFAULT_LBFGS_LS_FAILURE_RESTARTS,
779            lbfgs_ls_restarts_used: 0,
780            neg_curv_floor: None,
781            neg_curv_deadline_iter: None,
782            resto_decline_progress_ratio: DEFAULT_DECLINE_PROGRESS_RATIO,
783            nlp_err_recent: [Number::NAN; DECLINE_PROGRESS_SAMPLES],
784            nlp_err_recent_len: 0,
785            decline_deferrals_used: 0,
786            decline_floor: None,
787            decline_deadline_iter: None,
788            resto_near_feasible_count: 0,
789            resto_entry_nonfinite_w: false,
790            acceptable_iterate: None,
791            vetoed: None,
792            vetoed_acceptable: None,
793            dual_guard_fired: false,
794            best_acceptable: None,
795            vetoed_seen: false,
796            vetoed_acceptable_seen: false,
797            kkt_fidelity_tol: 0.0,
798            acceptable_iter_number: 0,
799            diagnostics: None,
800            debug: None,
801            resto_calls: 0,
802            resto_inner_iters: 0,
803            resto_outer_iters: 0,
804            resto_wall_secs: 0.0,
805            print_iter_output: true,
806        }
807    }
808
809    /// Stash the current iterate as the "last acceptable" backup —
810    /// port of `IpBacktrackingLineSearch::StoreAcceptablePoint`
811    /// (`IpBacktrackingLineSearch.cpp:1286-1293`).
812    fn store_acceptable_point(&mut self) {
813        let d = self.data.borrow();
814        if let Some(curr) = d.curr.as_ref() {
815            self.acceptable_iterate = Some(curr.clone());
816            self.acceptable_iter_number = d.iter_count;
817        }
818    }
819
820    /// Record this outer iteration's NLP error for the gh #534 progress test.
821    ///
822    /// One push per `iterate()` call, so the samples are consecutive outer
823    /// iterations by construction. Deliberately *not* cleared when restoration
824    /// recovers: a recovery that helped shows up as continued contraction and a
825    /// recovery that hurt shows up as a jump, and the ratio test reads both
826    /// correctly without needing to know which happened.
827    fn note_nlp_err(&mut self, nlp_err: Number) {
828        push_sample(
829            &mut self.nlp_err_recent,
830            &mut self.nlp_err_recent_len,
831            nlp_err,
832        );
833    }
834
835    /// Whether the last [`DECLINE_PROGRESS_SAMPLES`] outer iterations each cut
836    /// the NLP error by at least `resto_decline_progress_ratio` (gh #534).
837    ///
838    /// The question the restoration-decline guard never asked: *is this solve
839    /// still converging?* A full window is required, so the test cannot pass on
840    /// a short history — the early iterations of every solve included.
841    ///
842    /// The test itself lives in the pure [`window_is_contracting`], for the
843    /// reason [`ranks_better_within_band`] does: what it must and must not fire
844    /// on is stated in the issue as two recorded traces, and those are provable
845    /// by deterministic unit test rather than inferable from a solve.
846    fn nlp_err_contracting(&self) -> bool {
847        if self.nlp_err_recent_len < DECLINE_PROGRESS_SAMPLES {
848            return false;
849        }
850        window_is_contracting(&self.nlp_err_recent, self.resto_decline_progress_ratio)
851    }
852
853    /// The live progress window, oldest first, for the gh #534 trace lines.
854    fn nlp_err_window_str(&self) -> String {
855        let live = &self.nlp_err_recent[..self.nlp_err_recent_len];
856        let parts: Vec<String> = live.iter().map(|e| format!("{e:.3e}")).collect();
857        format!("[{}]", parts.join(" -> "))
858    }
859
860    /// Roll the iterate back to the last acceptable snapshot — port of
861    /// `IpBacktrackingLineSearch::RestoreAcceptablePoint`
862    /// (`IpBacktrackingLineSearch.cpp:1295-1310`). Returns `true` if a
863    /// snapshot was available and applied; `false` otherwise (caller
864    /// then surfaces the original failure status).
865    fn restore_acceptable_point(&mut self) -> bool {
866        let Some(prev) = self.acceptable_iterate.clone() else {
867            return false;
868        };
869        let mut d = self.data.borrow_mut();
870        d.set_trial(prev);
871        // `accept_trial_point` promotes `trial → curr`, mirroring the
872        // upstream sequence `set_trial(...); AcceptTrialPoint();`.
873        d.accept_trial_point();
874        true
875    }
876
877    /// Whether a diverging primal iterate is consistent with the feasible
878    /// region actually being *unbounded* (issue #248).
879    ///
880    /// `DivergingIterates` is Ipopt's unboundedness verdict, but a large
881    /// `|x_i|` only proves unboundedness if variable `i` is free to escape
882    /// to infinity in the direction it is heading — i.e. it has no finite
883    /// bound on that side. This lifts a vector of ones from the compressed
884    /// lower/upper bound spaces through the `Px_L` / `Px_U` expansion
885    /// matrices to obtain full-length indicators of which variables carry a
886    /// finite bound, then returns `true` only when some component whose
887    /// magnitude exceeds `diverging_iterates_tol` is heading toward a side
888    /// with no finite bound.
889    ///
890    /// When every large component is pinned by a finite bound — in
891    /// particular when all variables are boxed, so the feasible region is a
892    /// bounded box and unboundedness is structurally impossible — this
893    /// returns `false`, and the caller reports the best iterate via the
894    /// normal convergence / restoration path instead of a spurious
895    /// `Unbounded`.
896    /// #248: consecutive growing, over-threshold iterations required before
897    /// a structurally-free divergence is reported as `DivergingIterates`.
898    /// `jit1`'s transient excursion lasts ~2 growing steps and then
899    /// recedes, so a small persistence requirement clears it without
900    /// materially delaying a genuine ray.
901    const DIVERGENCE_PERSIST_ITERS: u32 = 4;
902    /// #248: an iterate counts as "still growing" toward divergence when it
903    /// grows at least this factor over the previous over-threshold iterate.
904    /// A recession ray in an interior-point method grows geometrically; an
905    /// iterate settling onto a finite optimum above the threshold does not.
906    const DIVERGENCE_GROWTH_FACTOR: Number = 2.0;
907    /// #252: the objective descent must *keep up* — each step's drop must be
908    /// at least this fraction of the previous step's drop for the iterate to
909    /// count toward the divergence streak. A recession ray descends `f` to
910    /// `−∞` with per-step drops that grow (ratio ≥ 1) as `|x|` grows
911    /// geometrically; an excursion converging to a finite optimum decelerates
912    /// (ratio → 0). The slack below 1 tolerates ordinary interior-point noise
913    /// on a genuine ray without admitting a decelerating excursion — jit1's
914    /// node subproblems shrink the drop by 3–15× per step, far past this bar.
915    const DIVERGENCE_DESCENT_KEEPUP: Number = 0.9;
916    /// #248: absolute runaway backstop. An iterate this large is reported
917    /// unbounded regardless of persistence. It sits at or below the default
918    /// `diverging_iterates_tol = 1e20`, so the default behaviour (fire the
919    /// instant `|x|` crosses the threshold) is preserved, while a low
920    /// user threshold no longer fires on the way to a finite optimum.
921    const DIVERGENCE_ABS_RUNAWAY: Number = 1e18;
922    /// gh#1076: consecutive restoration re-entries, each after an unreleased
923    /// hand-back from which the outer accepted only soft-restoration `s`
924    /// steps, before the gh#1042 exit ends the solve. One is not enough:
925    /// `mpcc_qpec_small_biactive` under `issue_884`'s `REPRO` options takes
926    /// one `s` step from its first hand-back, re-enters, and converges after
927    /// the second (Optimal at 97, unscaled dual 1.3e-10); ending it at the
928    /// first strike sends it through a retry (69 + 19). Vanderbei brainpc0
929    /// strikes 45 times in a row, so the budget costs it two cycles.
930    const UNRELEASED_SHOT_STRIKES: u32 = 3;
931    /// Most consecutive iterations the primal divergence guard will defer
932    /// to a watchdog sequence before checking the iterate anyway. Upstream's
933    /// `watchdog_trial_iter_max` default is 3; one spare covers the
934    /// iteration on which the watchdog is armed. See
935    /// [`Self::watchdog_defer_streak`] for why the bound is not simply
936    /// "until `in_watchdog` clears".
937    const WATCHDOG_DEFER_MAX: u32 = 4;
938
939    /// #285: magnitude floor for the checked recession-ray unboundedness path.
940    /// Below this the (slightly more expensive) recession proof is not even
941    /// attempted, so it is inert on every normal, well-scaled solve. Above it,
942    /// unboundedness is only ever concluded through the full checked proof in
943    /// [`Self::curr_is_recession_ray`] — a genuinely *feasible* iterate of this
944    /// magnitude already witnesses an unbounded feasible region, and the proof
945    /// additionally certifies the escape direction. Sits far below the
946    /// `diverging_iterates_tol` (`1e20`) magnitude guard so a linearly-growing
947    /// ray (which never reaches `1e20` within `max_iter`) is still caught.
948    const RECESSION_MIN_NORM: Number = 1e10;
949    /// #285: consecutive growing, proof-passing iterations required before the
950    /// recession-ray path reports `DivergingIterates`. A bounded feasible
951    /// region cannot supply a *growing* sequence of feasible over-floor
952    /// iterates, so persistence is defense-in-depth against a lone numerical
953    /// fluke rather than a soundness requirement.
954    const RECESSION_PERSIST_ITERS: u32 = 4;
955    /// #285: relative feasibility bar for the recession proof. The current
956    /// iterate counts as feasible (hence a witness that the feasible region
957    /// reaches its magnitude) when its unscaled max-norm primal infeasibility
958    /// is at most this fraction of `|x|_∞`. The check is *relative* on purpose:
959    /// evaluating `A_eq x − b` at `|x| ~ 1e17` carries floating-point roundoff
960    /// that scales with `|x|`, while a genuinely infeasible excursion (e.g.
961    /// mid-restoration) has a residual comparable to `|x|` itself.
962    const RECESSION_FEAS_REL: Number = 1e-6;
963    /// #285: relative bar for "the escape direction lies in `null(A_eq)`".
964    /// `‖J_c x‖_∞ ≤ this · |x|_∞` certifies that moving along `d ≈ x` preserves
965    /// the (linearized) equality constraints — `A_eq d ≈ 0`.
966    const RECESSION_DIR_TOL: Number = 1e-6;
967    /// #285: relative descent bar. The objective must strictly decrease along
968    /// the escape direction with a real margin — `∇f·x ≤ −this · ‖∇f‖ ‖x‖` —
969    /// so a variable drifting orthogonally to the objective (`∇f·x ≈ 0`) can
970    /// never be mistaken for a recession ray driving `f → −∞`.
971    const RECESSION_DESC_REL: Number = 1e-6;
972
973    /// Update the divergence-persistence state for the current iterate and
974    /// return whether `DivergingIterates` should be reported now (issues
975    /// #248 / #252). `amax` is `max_i |x_i|`; `structural_free` is the result
976    /// of [`Self::divergence_is_true_unboundedness`] (already gated on
977    /// `amax > diverging_iterates_tol`); `f` is the (minimized, internally
978    /// scaled) objective at the current iterate, supplied only while
979    /// `structural_free` holds.
980    ///
981    /// A large `|x|` is reported as unbounded only when it is heading to an
982    /// unbounded side (`structural_free`) *and* the divergence looks like a
983    /// genuine recession ray: the iterate keeps *growing* while the objective
984    /// keeps *descending toward `−∞` without decelerating* — the per-step drop
985    /// holds up as `|x|` grows geometrically — for
986    /// [`Self::DIVERGENCE_PERSIST_ITERS`] consecutive iterations (or it has
987    /// blown past the absolute runaway backstop). Two failure modes are thereby
988    /// left to the normal convergence machinery instead of being mislabelled
989    /// `UNBOUNDED`:
990    ///
991    /// * #248 — a transient ill-scaling excursion that peaks in `|x|` and
992    ///   recedes never sustains the growth streak.
993    /// * #252 — an excursion that *keeps* growing in `|x|` toward an unbounded
994    ///   box side (a jit1 B&B node subproblem with `ub = +∞`), lowering `f` as
995    ///   it goes, but with a per-step objective drop that *decelerates* toward
996    ///   zero: it is settling onto a finite optimum, not riding a recession
997    ///   ray. The descent must keep up (not merely exist), so this no longer
998    ///   accumulates the streak.
999    fn update_divergence_verdict(
1000        &mut self,
1001        amax: Option<Number>,
1002        structural_free: bool,
1003        f: Option<Number>,
1004    ) -> bool {
1005        let over = matches!(amax, Some(a) if a > self.diverging_iterates_tol) && structural_free;
1006        if !over {
1007            self.divergence_streak = 0;
1008            self.divergence_prev_amax = 0.0;
1009            self.divergence_prev_f = Number::INFINITY;
1010            self.divergence_prev_decrease = Number::NAN;
1011            return false;
1012        }
1013        let a = amax.expect("over implies amax is Some");
1014        // A recession ray in an interior-point method grows the iterate
1015        // geometrically *and* drives the objective down without bound, with a
1016        // per-step drop that keeps up as `|x|` grows. A finite-optimum
1017        // excursion may grow `|x|` and even lower `f` for a few steps, but its
1018        // per-step objective drop decelerates toward zero as it settles onto
1019        // the finite floor. Require all three — growth, descent, and
1020        // non-decelerating descent — before a step counts toward the streak.
1021        let growing = a >= self.divergence_prev_amax * Self::DIVERGENCE_GROWTH_FACTOR;
1022        // `f` is `None` only when `structural_free` is false, already handled
1023        // by the `!over` branch; treat a missing value as non-descending so a
1024        // run can never accumulate without objective evidence.
1025        let fv = f.unwrap_or(Number::INFINITY);
1026        let decrease = self.divergence_prev_f - fv;
1027        let descending = decrease > 0.0;
1028        // Non-decelerating: the drop must be at least a fixed fraction of the
1029        // previous step's drop. Bootstrapped `true` until a first finite
1030        // decrease has been recorded (`divergence_prev_decrease` non-finite),
1031        // so the run's opening steps are admitted on growth + descent alone.
1032        let keeping_up = !self.divergence_prev_decrease.is_finite()
1033            || decrease >= self.divergence_prev_decrease * Self::DIVERGENCE_DESCENT_KEEPUP;
1034        if growing && descending && keeping_up {
1035            self.divergence_streak += 1;
1036        } else {
1037            // Over the threshold on an unbounded side, but the divergence is
1038            // not sustaining a recession ray's growth-and-accelerating-descent
1039            // profile — the hallmark of a scaling excursion toward a finite
1040            // optimum. Drop the streak; a genuine ray re-accumulates it on its
1041            // next qualifying step (or trips the absolute runaway backstop).
1042            self.divergence_streak = 0;
1043        }
1044        self.divergence_prev_amax = a;
1045        self.divergence_prev_f = fv;
1046        // Record the baseline for the next step's keep-up comparison only from
1047        // a finite, real decrease; skip the `+∞` opening step and reset the
1048        // baseline whenever the objective stops descending.
1049        self.divergence_prev_decrease = if decrease.is_finite() && descending {
1050            decrease
1051        } else {
1052            Number::NAN
1053        };
1054        a >= Self::DIVERGENCE_ABS_RUNAWAY
1055            || self.divergence_streak >= Self::DIVERGENCE_PERSIST_ITERS
1056    }
1057
1058    fn divergence_is_true_unboundedness(&self, x: &dyn Vector) -> bool {
1059        self.free_to_escape_over(x, self.diverging_iterates_tol)
1060    }
1061
1062    /// Shared core of the free-variable structural check: returns `true` when
1063    /// some component of `x` with magnitude exceeding `thresh` is heading
1064    /// toward a side (positive → upper, negative → lower) that carries *no*
1065    /// finite bound, so it is free to escape to infinity. Parameterized on the
1066    /// magnitude threshold so both the `diverging_iterates_tol` (`1e20`)
1067    /// divergence guard and the lower `RECESSION_MIN_NORM` recession-ray path
1068    /// (#285) share one implementation.
1069    fn free_to_escape_over(&self, x: &dyn Vector, thresh: Number) -> bool {
1070        use pounce_linalg::DenseVector;
1071
1072        let cq = self.cq.borrow();
1073        let nlp = cq.nlp().borrow();
1074
1075        // Full-length 0/1 indicators of finite lower / upper bounds,
1076        // built by scattering ones through the bound expansion matrices.
1077        let mut ones_l = nlp.x_l().make_new();
1078        ones_l.set(1.0);
1079        let mut has_lb = x.make_new();
1080        nlp.px_l().mult_vector(1.0, &*ones_l, 0.0, &mut *has_lb);
1081
1082        let mut ones_u = nlp.x_u().make_new();
1083        ones_u.set(1.0);
1084        let mut has_ub = x.make_new();
1085        nlp.px_u().mult_vector(1.0, &*ones_u, 0.0, &mut *has_ub);
1086
1087        let downcast = |v: &dyn Vector| -> Option<Vec<Number>> {
1088            v.as_any()
1089                .downcast_ref::<DenseVector>()
1090                .map(|d| d.expanded_values())
1091        };
1092
1093        // POUNCE is dense-only; if a backing is unexpectedly non-dense we
1094        // cannot prove the divergence is spurious, so fall back to the
1095        // original (magnitude-only) verdict to avoid changing behaviour.
1096        let (Some(xv), Some(lb), Some(ub)) = (downcast(x), downcast(&*has_lb), downcast(&*has_ub))
1097        else {
1098            return true;
1099        };
1100
1101        for i in 0..xv.len() {
1102            if xv[i].abs() > thresh {
1103                let free_to_diverge = if xv[i] > 0.0 {
1104                    ub[i] == 0.0
1105                } else {
1106                    lb[i] == 0.0
1107                };
1108                if free_to_diverge {
1109                    return true;
1110                }
1111            }
1112        }
1113        false
1114    }
1115
1116    /// #285: checked recession-ray unboundedness proof at the current iterate.
1117    ///
1118    /// Returns `true` only when the current iterate `x` (with `|x|_∞ = amax`,
1119    /// already known `> RECESSION_MIN_NORM` by the caller) *proves* the
1120    /// problem is unbounded below via a genuine recession ray — the same
1121    /// standard the LP/symmetric path holds itself to, not a magnitude
1122    /// heuristic. All of the following must hold:
1123    ///
1124    /// 1. **Feasible witness.** The iterate's unscaled primal infeasibility is
1125    ///    at most `RECESSION_FEAS_REL · amax`. A genuinely feasible iterate of
1126    ///    norm `≥ 1e10` witnesses that the feasible region reaches that far —
1127    ///    a *bounded* region cannot contain it. (Relative bar: the residual of
1128    ///    `A_eq x − b` carries roundoff that scales with `|x|`.)
1129    /// 2. **Free to escape.** Some over-floor component heads toward a side
1130    ///    with no finite variable bound ([`Self::free_to_escape_over`] at
1131    ///    `RECESSION_MIN_NORM`).
1132    /// 3. **Direction in `null(A_eq)`.** `‖J_c x‖_∞ ≤ RECESSION_DIR_TOL · amax`
1133    ///    — moving along `d ≈ x` preserves the equality constraints.
1134    /// 4. **Inequalities not blocking.** No finitely-bounded inequality row is
1135    ///    driven toward its bound along `d ≈ x`
1136    ///    ([`Self::recession_blocked_by_inequality`]).
1137    /// 5. **Objective descending.** `∇f·x ≤ −RECESSION_DESC_REL · ‖∇f‖ ‖x‖` —
1138    ///    the objective strictly decreases along the escape direction with a
1139    ///    real (non-orthogonal) margin, so `f → −∞` along the ray.
1140    ///
1141    /// On a *bounded* problem at least one of (1)/(2)/(3)/(4)/(5) fails, so
1142    /// this can never manufacture a spurious `DivergingIterates`.
1143    fn curr_is_recession_ray(&self, x: &dyn Vector, amax: Number) -> bool {
1144        // (1) Feasible witness (relative bar).
1145        let primal_inf = self.cq.borrow().curr_unscaled_primal_infeasibility_max();
1146        if !(primal_inf.is_finite() && primal_inf <= Self::RECESSION_FEAS_REL * amax) {
1147            return false;
1148        }
1149        // (2) Some over-floor component free to escape to infinity.
1150        if !self.free_to_escape_over(x, Self::RECESSION_MIN_NORM) {
1151            return false;
1152        }
1153        // (3) Escape direction lies in the equality null space. A non-finite
1154        // (NaN) residual is treated as failing, so the direction is only
1155        // accepted on a genuinely small, finite `‖J_c x‖∞`.
1156        let jc_x_amax = self.cq.borrow().curr_jac_c_times_vec(x).amax();
1157        if !jc_x_amax.is_finite() || jc_x_amax > Self::RECESSION_DIR_TOL * amax {
1158            return false;
1159        }
1160        // (4) No finitely-bounded inequality blocks the direction.
1161        if self.recession_blocked_by_inequality(x, amax) {
1162            return false;
1163        }
1164        // (5) Objective strictly descending along the escape direction.
1165        let (dot, gnorm, xnorm) = {
1166            let cq = self.cq.borrow();
1167            let g = cq.curr_grad_f();
1168            (g.dot(x), g.nrm2(), x.nrm2())
1169        };
1170        if !(dot < 0.0 && dot <= -Self::RECESSION_DESC_REL * gnorm * xnorm) {
1171            return false;
1172        }
1173        true
1174    }
1175
1176    /// #285: does any *finitely-bounded* inequality constraint block motion
1177    /// along the escape direction `d ≈ x`? For each inequality row the
1178    /// constraint value `d(x)` changes at rate `(J_d x)_j` per unit of the
1179    /// direction; if that row has a finite upper bound and the rate is
1180    /// positive (or a finite lower bound and the rate is negative) beyond a
1181    /// relative tolerance, moving out along `d` would eventually violate it,
1182    /// so it is not a feasible recession direction. Bounds are detected via
1183    /// the `Pd_L / Pd_U` expansion matrices exactly as the variable-bound
1184    /// check uses `Px_L / Px_U`.
1185    fn recession_blocked_by_inequality(&self, x: &dyn Vector, amax: Number) -> bool {
1186        use pounce_linalg::DenseVector;
1187
1188        let cq = self.cq.borrow();
1189        // Rate of change of each inequality value along d ≈ x (length m_ineq).
1190        // Compute first so the internal `nlp.borrow_mut()` is released before
1191        // the immutable borrow below.
1192        let jd_x = cq.curr_jac_d_times_vec(x);
1193        let (has_dlb, has_dub) = {
1194            let nlp = cq.nlp().borrow();
1195            let mut ones_dl = nlp.d_l().make_new();
1196            ones_dl.set(1.0);
1197            let mut has_dlb = jd_x.make_new();
1198            nlp.pd_l().mult_vector(1.0, &*ones_dl, 0.0, &mut *has_dlb);
1199
1200            let mut ones_du = nlp.d_u().make_new();
1201            ones_du.set(1.0);
1202            let mut has_dub = jd_x.make_new();
1203            nlp.pd_u().mult_vector(1.0, &*ones_du, 0.0, &mut *has_dub);
1204            // Order matters: bind `(has_dlb, has_dub)` in that exact order so
1205            // the finite-lower / finite-upper indicators are not transposed.
1206            // #314: this pair was returned swapped, inverting the bound
1207            // semantics below — a ray *increasing* a lower-bounded row (moving
1208            // deeper into the feasible set, slack growing) was wrongly treated
1209            // as blocked, so a genuine inequality-slack recession ray was never
1210            // proven unbounded.
1211            (has_dlb, has_dub)
1212        };
1213
1214        let downcast = |v: &dyn Vector| -> Option<Vec<Number>> {
1215            v.as_any()
1216                .downcast_ref::<DenseVector>()
1217                .map(|d| d.expanded_values())
1218        };
1219        // Dense-only fallback: if we cannot inspect the rows, conservatively
1220        // treat the direction as blocked (no spurious unbounded verdict).
1221        let (Some(jd), Some(dlb), Some(dub)) =
1222            (downcast(&*jd_x), downcast(&*has_dlb), downcast(&*has_dub))
1223        else {
1224            return true;
1225        };
1226        let tol = Self::RECESSION_DIR_TOL * amax;
1227        for j in 0..jd.len() {
1228            // Increasing a row that has a finite upper bound, or decreasing a
1229            // row that has a finite lower bound, would leave the feasible set.
1230            if (jd[j] > tol && dub[j] != 0.0) || (jd[j] < -tol && dlb[j] != 0.0) {
1231                return true;
1232            }
1233        }
1234        false
1235    }
1236
1237    /// #285: update the recession-ray persistence state and return whether
1238    /// `DivergingIterates` should be reported now. `amax` is `|x|_∞`;
1239    /// `is_ray` is the result of [`Self::curr_is_recession_ray`]. The verdict
1240    /// fires once the checked proof has held for
1241    /// [`Self::RECESSION_PERSIST_ITERS`] consecutive *growing* iterations — a
1242    /// bounded region cannot supply a growing sequence of feasible over-floor
1243    /// iterates, so this is impossible to satisfy on a bounded problem.
1244    fn update_recession_verdict(&mut self, amax: Number, is_ray: bool) -> bool {
1245        if !is_ray {
1246            self.recession_streak = 0;
1247            self.recession_prev_amax = 0.0;
1248            return false;
1249        }
1250        if amax > self.recession_prev_amax {
1251            self.recession_streak += 1;
1252        } else {
1253            // Proof holds but the iterate is not growing (a stalled or rejected
1254            // step). Restart the run at the current witness rather than firing
1255            // on a plateau; a genuine ray resumes growing next step.
1256            self.recession_streak = 1;
1257        }
1258        self.recession_prev_amax = amax;
1259        self.recession_streak >= Self::RECESSION_PERSIST_ITERS
1260    }
1261
1262    /// Honour a certificate the masked-scale veto refused, when the run that
1263    /// was allowed to continue did not end in one of its own (gh #200).
1264    ///
1265    /// The veto's bargain is "never worse off": it refuses a point that had
1266    /// *already passed the strict test*, betting that continuing reaches a
1267    /// better one. This is the losing side of that bet — so hand back exactly
1268    /// what would have been returned without the veto, point and status both.
1269    ///
1270    /// Two details make that guarantee real rather than approximate:
1271    ///
1272    /// - It runs on **every** non-success exit, applied once where the driver
1273    ///   loop's result is finalized. Wiring individual termination sites was
1274    ///   tried and is not safe: there are sixteen, and the ones easiest to
1275    ///   overlook are the ones most likely to fire here — the veto's extra
1276    ///   iterations are exactly what pushes a run past `max_cpu_time`.
1277    /// - It restores the **refused iterate itself** (`vetoed`), not the last
1278    ///   acceptable snapshot. `store_acceptable_point` overwrites
1279    ///   unconditionally, so after the veto the stored point drifts to whatever
1280    ///   the continued run last touched — which may be worse than the point
1281    ///   that was refused.
1282    ///
1283    /// "Better" is **status-dominant lexicographic**: the reported status first,
1284    /// and the objective only to break a tie *within equal status*. Both halves
1285    /// matter and the order between them is not cosmetic — see the `Success`
1286    /// branch, where reading it as a plain objective comparison costs a status.
1287    fn honour_refused_certificate(&mut self, result: SolverReturn) -> SolverReturn {
1288        if matches!(result, SolverReturn::Success) {
1289            // The continued run produced a certificate of its own — but not
1290            // necessarily a better *outcome*.
1291            //
1292            // This is what makes "never worse" hold even when the bet loses in a
1293            // way that still converges: on a non-convex problem the extra travel
1294            // can reach a different, worse stationary point, and the budget cap
1295            // (`VETO_MAX_EXTRA_ITERS`) can also hand back a late-but-converged
1296            // one. Neither may silently replace a better answer the solver
1297            // already had in hand.
1298            //
1299            // The comparison is NOT objective-only. That was the original bug
1300            // here: both points passed `passes_component_tols`, which looked
1301            // like a licence to treat them as equally valid certificates and
1302            // just take the lower objective. They are not equally valid when
1303            // `kkt_fidelity_tol` is set — `apply_kkt_fidelity_gate` re-grades a
1304            // `Success` on the unscaled KKT error afterwards, on a strictly
1305            // finer criterion than the convergence test. Taking a 3-ulp
1306            // objective win at a point whose unscaled error is 5x worse traded
1307            // `Solve_Succeeded` for `Solved_To_Acceptable_Level`: a status
1308            // regression against baseline, which is the strongest form of the
1309            // guarantee breaking. So rank by the status each point will actually
1310            // be *reported* under, and only then by objective.
1311            let Some((refused, refused_status)) = self.baseline_outcome() else {
1312                return result;
1313            };
1314            self.assert_comparable_scale(&refused);
1315            let (curr_f, curr_kkt) = self.curr_obj_and_unscaled_kkt();
1316            // Rank each candidate by the status it will actually be *reported*
1317            // under, which for a `Success` means after the fidelity gate has had
1318            // its say.
1319            let continued_success = self.survives_fidelity_gate(curr_kkt);
1320            let refused_success = matches!(refused_status, SolverReturn::Success)
1321                && self.survives_fidelity_gate(refused.unscaled_kkt);
1322            let keep_refused = match (continued_success, refused_success) {
1323                // Equal reported status: the objective breaks the tie, which is
1324                // legitimate because both points are feasible to tolerance.
1325                //
1326                // Negated `<=`, not `>`: they differ at NaN, and the difference
1327                // matters. A `Converged` exit at an iterate whose objective is
1328                // NaN but whose residuals are finite and tiny is reachable (the
1329                // convergence test never inspects `f`), and `NaN > x` is false,
1330                // which would keep the NaN point over a finite refused one.
1331                // Phrased as a negated `<=`, an incomparable objective fails to
1332                // justify keeping the continued point and the refused one wins.
1333                (true, true) | (false, false) => !(curr_f <= refused.obj),
1334                // The refused point keeps a status the continued one loses.
1335                (false, true) => true,
1336                (true, false) => false,
1337            };
1338            if !keep_refused {
1339                return result;
1340            }
1341            self.restore_snapshot(&refused);
1342            // The restored point's own status, which is what the baseline
1343            // reported for it. For a strict refusal that is `Success` even when
1344            // it fails the fidelity gate — the gate re-grades the restored point
1345            // downstream, exactly as it would have re-graded the baseline's. For
1346            // an acceptable-level refusal it is `StopAtAcceptablePoint`, since
1347            // claiming `Success` for a point that only ever qualified at the
1348            // acceptable level would over-report.
1349            return refused_status;
1350        }
1351        // The continued run did not certify — but its final point can still be a
1352        // *better* would-be certificate than the one the baseline stopped at, and
1353        // restoring the chronologically-first refusal unconditionally throws it
1354        // away (gh #327). The masking veto keeps refusing at the true optimum too
1355        // (its unscaled error stays above `acceptable_tol` under an extreme
1356        // objective scale), so a run that actually reaches the optimum never gets
1357        // to certify there and instead exits non-`Success` — typically on a tiny
1358        // step once it settles. Rolling straight back to the first refusal then
1359        // hands back the point the baseline stopped at, which can be far worse:
1360        // on `min 1/x` over `[1e-12, 10]` the solve reaches x≈10 (f≈0.1) but was
1361        // rolled back to the first refusal at x≈2.84 (f≈0.35) and reported
1362        // success there.
1363        //
1364        // The extra candidate is admitted *narrowly*, and the gate is
1365        // load-bearing: the continued point may displace the refused snapshot
1366        // only if it itself passes the strict per-component tolerances — i.e. it
1367        // is a would-be strict certificate the veto refused solely because of
1368        // masking. That is precisely what tells the settled true optimum apart
1369        // from a merely lower objective reached on an unbounded ray (e.g.
1370        // `A(x−a)⁴ − K·√(1+y²)`, unbounded below in y): the diverging iterate
1371        // never passes the strict test, so it can never win here, and those runs
1372        // stay bit-for-bit as before. When the gate does open, keep whichever
1373        // point ranks better under the same feasibility-aware key the dual-guard
1374        // fallback uses, and report the baseline's restored status either way —
1375        // never worse than baseline on status, never worse (often better) on the
1376        // point.
1377        let Some((refused, restored_status)) = self.baseline_outcome() else {
1378            return result;
1379        };
1380        self.assert_comparable_scale(&refused);
1381        let curr_nlp_err = self.cq.borrow().curr_nlp_error();
1382        let curr_passes_strict =
1383            self.bundle
1384                .conv_check
1385                .current_passes_strict(curr_nlp_err, &self.data, &self.cq);
1386        let curr_f = self.cq.borrow().curr_f();
1387        let curr_viol = self.cq.borrow().curr_unscaled_primal_infeasibility_max();
1388        // The second admissible candidate: a continued run that ends *at the
1389        // acceptable level itself* (gh #533). The `curr_passes_strict` gate
1390        // exists to tell a settled optimum from a diverging ray, and on this
1391        // exit the exit itself already answers that — `StopAtAcceptablePoint` is
1392        // only reachable at a point that passed the acceptable per-component
1393        // tolerances, either by qualifying here or by being the stashed
1394        // acceptable iterate a rollback restored. A diverging iterate cannot
1395        // produce it.
1396        //
1397        // This matters because the gh #533 progress refusal is frequently paid
1398        // off by a *better acceptable point* rather than by a strict
1399        // certificate: the streak refuses while the solve is still descending,
1400        // the solve descends, and then settles somewhere better but still short
1401        // of `tol`. Without this the refused point is restored and the entire
1402        // continuation is discarded — never worse than baseline, but never
1403        // better either, which for that whole class is pure cost.
1404        //
1405        // Gated on the *restored* status also being `StopAtAcceptablePoint`, so
1406        // a strict refusal's `Success` is never reported at a point that only
1407        // ever qualified at the acceptable level.
1408        let continued_is_acceptable_exit = matches!(result, SolverReturn::StopAtAcceptablePoint)
1409            && matches!(restored_status, SolverReturn::StopAtAcceptablePoint);
1410        // Keep the continued point in place only when it is an admissible
1411        // candidate that also ranks strictly better; otherwise restore the
1412        // refused snapshot exactly as before. `ranks_better` treats a non-finite
1413        // continued objective as worst, so a NaN-objective continuation never
1414        // displaces a finite refused point (the NaN-loses convention the
1415        // `Success` branch relies on).
1416        let keep_continued = (curr_passes_strict || continued_is_acceptable_exit)
1417            && self.ranks_better(curr_f, curr_viol, refused.obj, refused.constr_viol);
1418        if !keep_continued {
1419            self.restore_snapshot(&refused);
1420        }
1421        if self.cq.borrow().curr_f().is_finite() {
1422            restored_status
1423        } else {
1424            result
1425        }
1426    }
1427
1428    /// What the baseline — the same solve with the veto disabled — would have
1429    /// returned, as (point, status), or `None` if nothing was ever refused.
1430    ///
1431    /// The **chronologically first** refusal, not the strictest one. Both arms
1432    /// follow the same trajectory until the first refusal, so that iterate is
1433    /// where the baseline stopped and what it reported. A refusal recorded later
1434    /// sits on the continued trajectory, which the baseline never walked — its
1435    /// point was never on offer, and restoring it would neither reproduce the
1436    /// baseline nor be comparable to it.
1437    ///
1438    /// Both kinds do occur, and in either order: an acceptable-level refusal
1439    /// needs `acceptable_iter` consecutive qualifying iterates, so a strict
1440    /// refusal can precede it, while a run that first drifts through the
1441    /// acceptable band can refuse there and only later pass the strict test.
1442    /// Preferring `Success` unconditionally was wrong for exactly the second
1443    /// case — it compared against a strict point from iteration 50-odd when the
1444    /// baseline had already stopped and reported acceptable at iteration 43.
1445    fn baseline_outcome(&self) -> Option<(VetoSnapshot, SolverReturn)> {
1446        // A refusal that was seen but not captured makes the baseline
1447        // unidentifiable, so decline rather than guess. Without this, a failed
1448        // strict capture alongside a successful acceptable one would present the
1449        // acceptable snapshot as the baseline outcome — but that snapshot sits
1450        // on the continued trajectory, so this would silently reintroduce the
1451        // very misidentification the chronological rule exists to prevent.
1452        // Declining loses the restore; misidentifying reports a wrong point
1453        // under a confident status.
1454        //
1455        // Unreachable today (`data.curr` is always `Some` inside `iterate()`, so
1456        // `snapshot_current` cannot fail), but the latches make the state
1457        // representable, and it must not be handled by accident.
1458        if (self.vetoed_seen && self.vetoed.is_none())
1459            || (self.vetoed_acceptable_seen && self.vetoed_acceptable.is_none())
1460        {
1461            return None;
1462        }
1463        match (&self.vetoed, &self.vetoed_acceptable) {
1464            // Ties go to the strict refusal, and the tie is reachable: both can
1465            // arm in the same call when the acceptable streak crosses on the
1466            // same iterate a strict certificate is refused. Strict is correct
1467            // there because of the baseline's own branch order — the `Converged`
1468            // gate (`opt_error.rs`, in `check_convergence_with_state`) precedes
1469            // `note_acceptable`, so the baseline returned `Converged` at that
1470            // iterate. Reordering those two branches would invert this.
1471            (Some(strict), Some(acc)) => Some(if strict.iter <= acc.iter {
1472                (strict.clone(), SolverReturn::Success)
1473            } else {
1474                (acc.clone(), SolverReturn::StopAtAcceptablePoint)
1475            }),
1476            (Some(strict), None) => Some((strict.clone(), SolverReturn::Success)),
1477            (None, Some(acc)) => Some((acc.clone(), SolverReturn::StopAtAcceptablePoint)),
1478            (None, None) => None,
1479        }
1480    }
1481
1482    /// Capture the current iterate as a veto snapshot, or `None` if there is no
1483    /// current iterate to capture.
1484    ///
1485    /// All-or-nothing by construction — see [`VetoSnapshot`].
1486    fn snapshot_current(&self, iter: Index) -> Option<VetoSnapshot> {
1487        let iterate = self.data.borrow().curr.as_ref().cloned()?;
1488        let cq = self.cq.borrow();
1489        Some(VetoSnapshot {
1490            iterate,
1491            iter,
1492            obj: cq.curr_f(),
1493            mu: self.data.borrow().curr_mu,
1494            unscaled_kkt: cq.curr_unscaled_nlp_error(),
1495            constr_viol: cq.curr_unscaled_primal_infeasibility_max(),
1496            obj_scale: cq.obj_scaling_factor(),
1497        })
1498    }
1499
1500    /// Current objective and max-norm unscaled KKT error, read together so the
1501    /// pair cannot describe different iterates.
1502    fn curr_obj_and_unscaled_kkt(&self) -> (Number, Number) {
1503        let cq = self.cq.borrow();
1504        (cq.curr_f(), cq.curr_unscaled_nlp_error())
1505    }
1506
1507    /// Guard the precondition of every scaled-objective comparison in
1508    /// [`Self::honour_refused_certificate`]: the factor must not have moved
1509    /// between the refusal and now, or the two numbers are not comparable.
1510    fn assert_comparable_scale(&self, snap: &VetoSnapshot) {
1511        debug_assert_eq!(
1512            snap.obj_scale,
1513            self.cq.borrow().obj_scaling_factor(),
1514            "objective scaling factor moved during the solve; the refused and \
1515             continued objectives are scaled differently and cannot be compared \
1516             (gh #200)"
1517        );
1518    }
1519
1520    /// Whether a point with this unscaled KKT error would keep `Solve_Succeeded`
1521    /// through [`IpoptApplication::apply_kkt_fidelity_gate`].
1522    ///
1523    /// Mirrors that gate rather than approximating it: same quantity
1524    /// (`final_unscaled_kkt_error`), same strict comparison, same "non-positive
1525    /// tolerance disables". With the default `kkt_fidelity_tol = 0` this is
1526    /// always `true`, so every caller collapses to the plain objective
1527    /// comparison and the mechanism's behaviour is unchanged.
1528    fn survives_fidelity_gate(&self, unscaled_kkt: Number) -> bool {
1529        // Phrased as the negation of the gate's own `> tol` test rather than as
1530        // `<= tol`, because the two disagree at NaN and the gate is the
1531        // authority: it demotes only on `> tol`, so a NaN error keeps `Success`
1532        // there and must keep it here. Written as `<= tol` this mirror said the
1533        // opposite, which would rank a NaN-error continued point below a refused
1534        // one. Benign in that direction — it restores the baseline point — but a
1535        // mirror that disagrees with the thing it mirrors is a latent trap.
1536        !(self.kkt_fidelity_tol > 0.0) || !(unscaled_kkt > self.kkt_fidelity_tol)
1537    }
1538
1539    /// Record the current iterate as the best acceptable-quality point seen so
1540    /// far in this solve (pounce#250 follow-up).
1541    ///
1542    /// Recording runs on **every** acceptable iterate, not only after the
1543    /// dual-divergence guard has fired. Gating it on the guard was the first
1544    /// attempt and left a hole: the guard fires and returns to the driver
1545    /// *before* this site is reached on that iteration (see the guard block in
1546    /// [`Self::iterate`]), so nothing at or before the diversion was ever
1547    /// captured. A diversion that wrecks the solve immediately — reaching no
1548    /// acceptable point afterwards — therefore had nothing to hand back, which
1549    /// is precisely the case the fallback exists for. `autocorr_bern55-06` hid
1550    /// this, because its better point happens to arrive at iteration 86, well
1551    /// after the guard fires at 23.
1552    ///
1553    /// Recording always is still behaviour-neutral, because the record is only
1554    /// ever *read* under `dual_guard_fired` — see
1555    /// [`Self::honour_best_acceptable_after_dual_guard`]. A solve the guard
1556    /// never touches computes a comparison per acceptable iterate and nothing
1557    /// else.
1558    ///
1559    /// The cost is one `f64` comparison per acceptable iterate; the iterate is
1560    /// cloned only on an actual improvement, so this does not double the
1561    /// per-iteration clone `store_acceptable_point` already pays.
1562    ///
1563    /// "Best" is a feasibility-aware ranking, **not** the lowest objective:
1564    /// candidates are ordered by [`Self::ranks_better`]'s `(feasible_enough,
1565    /// objective)` key, so objective only decides among points already inside a
1566    /// capped feasibility band. Being *bounded* by `acceptable_constr_viol_tol`
1567    /// is not the same as *not trading* feasibility within it — that band is a
1568    /// user option and can be widened to `1e1` or beyond. A pure-objective argmax
1569    /// over it has no lower bound on the feasibility it will spend, and one
1570    /// option-value away it returns a point `pounce verify` rejects under a
1571    /// `Solved_To_Acceptable_Level` status (gh #267). Whether an early
1572    /// low-objective iterate is even a candidate is the user's
1573    /// `acceptable_constr_viol_tol`; the capped feasibility key is what keeps a
1574    /// grossly-infeasible one from winning even when the band admits it.
1575    fn record_best_acceptable(&mut self, curr_f: Number) {
1576        if !curr_f.is_finite() {
1577            return;
1578        }
1579        // Same quantity the acceptable-point gate keys on, so the recorded
1580        // feasibility matches the band the candidate just passed.
1581        let curr_viol = self.cq.borrow().curr_unscaled_primal_infeasibility_max();
1582        // Reject before cloning: only a strictly better candidate — by the
1583        // feasibility-aware key, not objective alone — is worth a snapshot.
1584        if let Some(best) = self.best_acceptable.as_ref() {
1585            let (b_obj, b_viol) = (best.obj, best.constr_viol);
1586            if !self.ranks_better(curr_f, curr_viol, b_obj, b_viol) {
1587                return;
1588            }
1589        }
1590        let iter = self.data.borrow().iter_count;
1591        let Some(snap) = self.snapshot_current(iter) else {
1592            return;
1593        };
1594        // Scaled objectives are only comparable under an unchanged factor; if it
1595        // ever moved, keep the earlier point rather than compare noise.
1596        if let Some(best) = self.best_acceptable.as_ref() {
1597            if snap.obj_scale != best.obj_scale {
1598                return;
1599            }
1600        }
1601        self.best_acceptable = Some(snap);
1602    }
1603
1604    /// Cap on the feasibility band [`Self::ranks_better`] admits, matching the
1605    /// upstream default `acceptable_constr_viol_tol`. The fallback treats a point
1606    /// as "feasible enough to win on objective" only within this band, *however
1607    /// loose the user made `acceptable_constr_viol_tol`*, so widening that option
1608    /// cannot let the fallback trade feasibility for objective (gh #267).
1609    const FEASIBLE_ENOUGH_CAP: Number = 1e-2;
1610
1611    /// Whether candidate `(a_obj, a_viol)` ranks strictly better than
1612    /// `(b_obj, b_viol)` for the best-acceptable fallback (gh #267, gh #280).
1613    ///
1614    /// The key is `(band_clamped_viol, objective)` compared lexicographically,
1615    /// where each violation is clamped *up* to
1616    /// `band = min(acceptable_constr_viol_tol, FEASIBLE_ENOUGH_CAP)` before it is
1617    /// compared. Inside the band every point clamps to `band`, so they tie on
1618    /// feasibility and objective decides — objective still rules *only among
1619    /// points already feasible-enough*. Outside the band the actual violation
1620    /// decides, so the less-infeasible point always wins and a
1621    /// strictly-more-infeasible point can never rank better (gh #280 — the
1622    /// earlier `feasible_enough` partition fell through to objective-only once
1623    /// both points were outside the band). The cap keeps the band no looser than
1624    /// the upstream default: `acceptable_constr_viol_tol` is user-widenable, and
1625    /// admitting a wide band into the *objective-decides* region would let a
1626    /// grossly-infeasible low-objective iterate win. Capping the band bounds that.
1627    ///
1628    /// At default (or tighter) tolerances this is behaviour-neutral: every
1629    /// recorded point already passed the `acceptable_constr_viol_tol` gate, so
1630    /// with that band at or below the cap every candidate clamps to `band` and
1631    /// objective alone decides, exactly as before. The feasibility ordering only
1632    /// bites once the user loosens `acceptable_constr_viol_tol` past its default
1633    /// and two candidates both sit outside the cap.
1634    ///
1635    /// A non-finite objective ranks worst and can never win — feasibility never
1636    /// rescues a `NaN`/`Inf` `f`. This mirrors the `NaN`-loses convention the
1637    /// gh #200 comparisons already rely on, and it keeps a `NaN`-objective
1638    /// returned point losing to a finite recorded one in
1639    /// [`Self::honour_best_acceptable_after_dual_guard`].
1640    ///
1641    /// The ranking itself lives in the pure [`ranks_better_within_band`] so its
1642    /// never-worse-off guarantee can be proven by deterministic unit tests rather
1643    /// than inferred from a host-dependent end-to-end objective comparison (see
1644    /// gh #267, which flagged an earlier CLI test for measuring the wrong,
1645    /// host-varying property). This method only resolves the admitted band.
1646    fn ranks_better(&self, a_obj: Number, a_viol: Number, b_obj: Number, b_viol: Number) -> bool {
1647        let band = self
1648            .bundle
1649            .conv_check
1650            .acceptable_constr_viol_tol_or_default()
1651            .min(Self::FEASIBLE_ENOUGH_CAP);
1652        ranks_better_within_band(a_obj, a_viol, b_obj, b_viol, band)
1653    }
1654
1655    /// Make the dual-divergence guard's diversion non-destructive (pounce#250
1656    /// follow-up).
1657    ///
1658    /// The guard bets that routing to restoration beats grinding on, and nothing
1659    /// made losing that bet safe: it could return a materially worse point than
1660    /// the solve already had, under a status that does not admit it.
1661    ///
1662    /// WHAT THIS DOES AND DOES NOT GUARANTEE. It guarantees the diverted run
1663    /// never returns worse than the best acceptable-quality point **that same
1664    /// run visited**. It does *not* guarantee the diverted run is no worse than
1665    /// not diverting at all — that counterfactual solve never happened, and its
1666    /// points were never on offer to compare against. The distinction is not
1667    /// academic: on the Linux CI host `deb7` returns 97.56 with the guard off and
1668    /// 127.87 with it on at streak 15, and this fallback cannot close that gap,
1669    /// because 127.87 is the best acceptable point the diverted run ever reached.
1670    /// Bounding the diversion's damage is a weaker property than making the
1671    /// diversion harmless, and only the weaker one is available from inside a
1672    /// single solve. It is a large part of why the guard is off by default.
1673    ///
1674    /// The observed case is `autocorr_bern55-06`. The guard fires at iteration
1675    /// 23, the diverted run reaches the true optimum (-2304.0000278, matching
1676    /// Ipopt to 12 significant figures) and holds it from iteration 57 to 86 —
1677    /// but the dual residual sawtooths between 1e-8 and 2e-1 there, so it never
1678    /// strings together the `acceptable_iter` consecutive qualifying iterates
1679    /// that would stop the solve. It then enters restoration a second time,
1680    /// wanders into a worse basin, and terminates `StopAtAcceptablePoint` at
1681    /// -2263.46 — 1.8 % worse, with an overall NLP error of 1.0. The better
1682    /// point was *visited and passed the acceptable test*; it was simply
1683    /// overwritten, because `store_acceptable_point` keeps the latest rather
1684    /// than the best.
1685    ///
1686    /// So: on a non-`Success` exit, if the best acceptable-quality iterate seen
1687    /// anywhere in the solve beats the point being returned, hand that back
1688    /// instead. This is the same "never worse off" bargain the gh #200 veto
1689    /// makes, applied to the other bet in the algorithm.
1690    ///
1691    /// "Beats" is the feasibility-aware ranking in [`Self::ranks_better`], not a
1692    /// bare objective comparison: the recorded point wins only if it is
1693    /// feasible-enough while the returned point is not, or both are in the same
1694    /// feasibility class and it has a lower objective. Ranking by objective alone
1695    /// let a widened `acceptable_constr_viol_tol` band trade feasibility for
1696    /// objective here — restoring a lower-objective point that `pounce verify`
1697    /// rejects, under a success-mapped status (gh #267). The key prevents that:
1698    /// objective can only win among points already inside the capped acceptable
1699    /// feasibility band.
1700    ///
1701    /// Note "anywhere in the solve", not "since the guard fired":
1702    /// [`Self::record_best_acceptable`] runs unconditionally and explains why —
1703    /// points at or before the diversion have to be on offer, or a diversion that
1704    /// wrecks the solve immediately has nothing to hand back. Only this *read* is
1705    /// gated on `dual_guard_fired`.
1706    ///
1707    /// A strict `Success` is never overridden — that point carries a real
1708    /// certificate, and a lower objective at a merely-acceptable point must not
1709    /// displace it.
1710    ///
1711    /// Tuning the guard's firing threshold was tried first and rejected: no
1712    /// setting separates the models it helps from the ones it harms, and the
1713    /// effect turned out to differ by host anyway (see the option help in
1714    /// `upstream_options.rs`). Fixing the consequence is what remained available.
1715    fn honour_best_acceptable_after_dual_guard(&mut self, result: SolverReturn) -> SolverReturn {
1716        if !self.dual_guard_fired || matches!(result, SolverReturn::Success) {
1717            return result;
1718        }
1719        let Some(best) = self.best_acceptable.clone() else {
1720            return result;
1721        };
1722        let (curr_f, _) = self.curr_obj_and_unscaled_kkt();
1723        let curr_viol = self.cq.borrow().curr_unscaled_primal_infeasibility_max();
1724        let curr_scale = self.cq.borrow().obj_scaling_factor();
1725        // Only comparable under the same factor, sign included.
1726        if curr_scale != best.obj_scale {
1727            return result;
1728        }
1729        // Restore only when the recorded point ranks strictly better under the
1730        // feasibility-aware key — more feasible, or equally feasible at a lower
1731        // objective. `ranks_better` also handles the `NaN` case the previous
1732        // bare `!(curr_f <= best.obj)` did: a non-finite returned objective
1733        // ranks worst, so a finite recorded point wins and is restored.
1734        if self.ranks_better(best.obj, best.constr_viol, curr_f, curr_viol) {
1735            tracing::debug!(target: "pounce::algorithm",
1736                "[POUNCE] dual-divergence diversion ended worse than a point already \
1737                 in hand (obj {:.10e} viol {:.3e} -> obj {:.10e} viol {:.3e}, iter {}); \
1738                 restoring it (pounce#250, gh#267).",
1739                curr_f, curr_viol, best.obj, best.constr_viol, best.iter,
1740            );
1741            self.restore_snapshot(&best);
1742            // Swap the *point*, but never let the swap erase why the solve
1743            // stopped. A budget that was exhausted stays reported as exhausted:
1744            // a caller polling for "did I run out of time" must not be told
1745            // "solved to acceptable level" merely because a better point was
1746            // recoverable. Only the outcomes that carry no such fact of their
1747            // own are relabelled to describe what is now being returned.
1748            return match result {
1749                SolverReturn::MaxiterExceeded
1750                | SolverReturn::CpuTimeExceeded
1751                | SolverReturn::WallTimeExceeded
1752                | SolverReturn::UserRequestedStop => result,
1753                _ => SolverReturn::StopAtAcceptablePoint,
1754            };
1755        }
1756        result
1757    }
1758
1759    /// Make a refused snapshot the current iterate again.
1760    fn restore_snapshot(&mut self, snap: &VetoSnapshot) {
1761        let mut d = self.data.borrow_mut();
1762        d.set_trial(snap.iterate.clone());
1763        d.accept_trial_point();
1764        // The restored point's own barrier parameter, not the continued run's —
1765        // see `VetoSnapshot::mu`.
1766        d.curr_mu = snap.mu;
1767    }
1768
1769    /// Decide whether the acceptable-point restoration decline may be deferred
1770    /// this once (gh #534), and arm the bookkeeping that bounds the bet.
1771    ///
1772    /// Four conditions, all required:
1773    ///
1774    /// * the option leaves deferrals available at all
1775    ///   (`resto_decline_deferrals`, `0` = pre-#534 behaviour);
1776    /// * the budget is not already spent;
1777    /// * the NLP error has contracted on every one of the last
1778    ///   [`DECLINE_PROGRESS_SAMPLES`]` - 1` iterations
1779    ///   ([`Self::nlp_err_contracting`]) — the progress test the guard lacked;
1780    /// * the iteration budget has room for a continuation, and the entry point
1781    ///   can actually be captured. Without a floor there is nothing to fall
1782    ///   back to, and a bet with no floor is exactly what must not be placed.
1783    ///
1784    /// The deadline is clamped below `max_iter` so a lost bet can never turn a
1785    /// reportable `StopAtAcceptablePoint` into `Maximum_Iterations_Exceeded`:
1786    /// the continuation is always cut before the iteration budget runs out. A
1787    /// *time* budget is not clamped the same way — elapsed time is an external
1788    /// fact and the deadline cannot predict it — so a solve that expires inside
1789    /// the continuation window still reports the time limit, at the floor
1790    /// iterate rather than at whatever the continuation last touched.
1791    fn may_defer_acceptable_decline(&mut self) -> bool {
1792        if self.decline_deferrals_used >= self.resto_decline_deferrals {
1793            return false;
1794        }
1795        if !self.nlp_err_contracting() {
1796            return false;
1797        }
1798        let iter = self.data.borrow().iter_count;
1799        // No room to continue: the deadline below would fire on the very next
1800        // iteration, so the deferral would buy nothing and cost a restoration.
1801        if iter.saturating_add(1) >= self.max_iter {
1802            return false;
1803        }
1804        if self.decline_floor.is_none() {
1805            let Some(snap) = self.snapshot_current(iter) else {
1806                return false;
1807            };
1808            self.decline_floor = Some(snap);
1809        }
1810        self.decline_deferrals_used += 1;
1811        self.decline_deadline_iter = Some(
1812            iter.saturating_add(DECLINE_CONTINUATION_BUDGET)
1813                .min(self.max_iter.saturating_sub(1)),
1814        );
1815        true
1816    }
1817
1818    /// The deferred continuation ran out of budget without a strict certificate
1819    /// (gh #534). Report the floor — the point the pre-#534 guard would have
1820    /// returned — unless the continuation is standing somewhere at least as
1821    /// good.
1822    fn terminate_at_decline_floor(&mut self) -> IterateOutcome {
1823        let Some(floor) = self.decline_floor.clone() else {
1824            // Unreachable in practice: the deadline is only ever set after a
1825            // floor is captured. Stopping at the current point is still the
1826            // right thing if it somehow is not — the point passed the
1827            // acceptable-level triplet when the deferral was taken.
1828            return IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint);
1829        };
1830        tracing::debug!(target: "pounce::algorithm",
1831            "[POUNCE] deferred restoration decline expired at iter {} without a strict \
1832             certificate; falling back to the floor from iter {} (gh #534).",
1833            self.data.borrow().iter_count, floor.iter,
1834        );
1835        if !self.continuation_outranks(&floor) {
1836            self.restore_snapshot(&floor);
1837        }
1838        IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint)
1839    }
1840
1841    /// Whether the current iterate is a *better* answer than the gh #534 floor.
1842    ///
1843    /// Two gates, in order. The current point must itself pass the
1844    /// acceptable-level triplet — the floor is going to be reported under
1845    /// `Solved_To_Acceptable_Level`, and a continuation that wandered off is not
1846    /// entitled to that status however attractive its objective looks. Only then
1847    /// does [`Self::ranks_better`]'s feasibility-first key decide, and only under
1848    /// an unmoved objective scaling factor, since the two objectives are
1849    /// otherwise not comparable.
1850    fn continuation_outranks(&self, floor: &VetoSnapshot) -> bool {
1851        let (curr_f, _) = self.curr_obj_and_unscaled_kkt();
1852        if !curr_f.is_finite() {
1853            return false;
1854        }
1855        let nlp_err = self.cq.borrow().curr_nlp_error();
1856        if !self
1857            .bundle
1858            .conv_check
1859            .current_is_acceptable_with_state(nlp_err, &self.data, &self.cq)
1860        {
1861            return false;
1862        }
1863        let (curr_viol, curr_scale) = {
1864            let cq = self.cq.borrow();
1865            (
1866                cq.curr_unscaled_primal_infeasibility_max(),
1867                cq.obj_scaling_factor(),
1868            )
1869        };
1870        if curr_scale != floor.obj_scale {
1871            return false;
1872        }
1873        !self.ranks_better(floor.obj, floor.constr_viol, curr_f, curr_viol)
1874    }
1875    /// Try to leave a first-order-stationary point that is not a local minimum
1876    /// (gh #797). Returns `true` when the current iterate has been replaced and
1877    /// the solve should continue instead of terminating.
1878    ///
1879    /// # What this is for
1880    ///
1881    /// The convergence check is a *first-order* test, and on a nonconvex model
1882    /// that is strictly weaker than "local minimum". `nonconvex_qp.nl` is the
1883    /// reported case: `min x₀x₁ s.t. x₀ + x₁ = 2, 0 ≤ x ≤ 4` restricted to its
1884    /// feasible segment is the concave `f(x₀) = x₀(2 - x₀)`, *maximized* at
1885    /// `(1,1)` and minimized at the two endpoints. From the bound-pushed start
1886    /// `(0.01, 0.01)` the first Newton step lands exactly on `(1,1)`, every KKT
1887    /// residual there is zero, and the solve reports `Solve_Succeeded` at
1888    /// `obj = 1` — the constrained maximum.
1889    ///
1890    /// Inertia correction does not save this. It engages (the iteration log
1891    /// shows `lg(rg)` from the second iteration on) and cannot help: `δ_x I` is
1892    /// symmetric, the model and the iterate are symmetric under `x₀ ↔ x₁`, and
1893    /// a symmetric correction applied to a zero gradient gives a zero step
1894    /// however indefinite the reduced Hessian is. The regularization makes the
1895    /// *step* well-posed; nothing in the algorithm asks whether the point it
1896    /// has converged to is a minimum.
1897    ///
1898    /// # What it does
1899    ///
1900    /// [`PdFullSpaceSolver::negative_curvature_direction`] answers that
1901    /// question with the KKT factorization already in hand, and hands back a
1902    /// measured direction `d` with `J_c d_x = 0` and `dᵀ(W + Σ)d < 0`. Since
1903    /// the gradient is (near) zero the barrier objective along `±d` is
1904    /// `φ(α) ≈ φ(0) + ½α²dᵀ(W + Σ)d`, decreasing on *both* sides, so both signs
1905    /// are tried and the better trial wins. The step is capped by the ordinary
1906    /// fraction-to-the-boundary rule and by [`NEG_CURV_MAX_STEP_FACTOR`] times
1907    /// the iterate's own scale, then backtracked until it satisfies that
1908    /// second-order decrease model with an Armijo factor — the same shape as
1909    /// the line search, on the curvature term rather than the gradient term.
1910    /// A trial whose constraint violation exceeds what the convergence check
1911    /// itself calls feasible is refused outright.
1912    ///
1913    /// # Why it cannot make an answer worse
1914    ///
1915    /// The point being left is a *strict certificate* — the solve was about to
1916    /// report `Solve_Succeeded` at it — so it is snapshotted as a floor before
1917    /// the step, exactly as gh #534's deferred restoration decline does with
1918    /// the point its guard would have returned. The continuation gets
1919    /// [`NEG_CURV_CONTINUATION_BUDGET`] outer iterations; past that, and at
1920    /// every other exit of the driver loop, [`Self::honour_neg_curv_floor`]
1921    /// hands the floor back unless the continuation is standing somewhere that
1922    /// both outranks it and carries a certificate of its own. So the escape
1923    /// costs a bounded number of iterations and can only trade the stationary
1924    /// point for a strictly better one.
1925    ///
1926    /// That holds however many escapes are spent, not only at the default of
1927    /// one: a later escape displaces the floor only with a certificate that
1928    /// outranks the one already held (gh #805), so the floor is always at
1929    /// least as good as the point a `neg_curv_escapes = 0` build reports.
1930    fn try_neg_curv_escape(&mut self, iter_count: Index) -> bool {
1931        if self.neg_curv_escapes_used >= self.neg_curv_escapes {
1932            return false;
1933        }
1934        // No room to continue: the deadline below would fire on the very next
1935        // iteration, so the escape would buy nothing and cost a factorization.
1936        if iter_count.saturating_add(1) >= self.max_iter {
1937            return false;
1938        }
1939        if self.nlp.is_none() || self.search_dir.is_none() {
1940            return false;
1941        }
1942        // `data.w` still holds `W(curr_{N-1})` — step 3 of `iterate()` runs
1943        // *after* the convergence check — and curvature at the previous iterate
1944        // is not the question being asked. Re-evaluate it here rather than
1945        // running the Hessian updater a second time at this iterate: that would
1946        // hand the limited-memory updater a zero-length curvature pair to skip
1947        // and count against `limited_memory_max_skipping`, and it would leave
1948        // `data.w` describing a different iterate than it did before, which the
1949        // post-optimal sensitivity hook reads.
1950        //
1951        // With a quasi-Newton `B` there is nothing to re-evaluate and the stale
1952        // one is used. That is not a gap being papered over: BFGS maintains `B`
1953        // positive definite by construction, so under
1954        // `hessian_approximation=limited-memory` the probe's inertia test
1955        // passes at δ_x = 0 and the escape declines — correctly, since the only
1956        // curvature information the solve has says the point is a minimum.
1957        //
1958        // That argument is about BFGS's definiteness, NOT about "not exact",
1959        // and gating on `provides_exact_hessian` conflated the two. A
1960        // finite-difference `W` is not exact but does carry genuine negative
1961        // curvature, so judging the current iterate by the previous one's
1962        // matrix let a stationary maximum be reported as optimal where the
1963        // exact path escapes it (gh#823 review, finding 1, @srikanth-gm).
1964        // `hessian_at_current` asks the question the probe actually has:
1965        // can you give me `W` here? Quasi-Newton updaters still answer `None`
1966        // and still take the stale path, for the reason above.
1967        let w_at_curr = self.bundle.hess.hessian_at_current(&self.data, &self.cq);
1968
1969        let probe = {
1970            let (Some(nlp), Some(sd)) = (self.nlp.as_ref(), self.search_dir.as_mut()) else {
1971                return false;
1972            };
1973            let mut pd = sd.pd_solver_mut();
1974            pd.negative_curvature_direction(&self.data, &self.cq, nlp, w_at_curr)
1975        };
1976        let Some(probe) = probe else {
1977            return false;
1978        };
1979
1980        let Some(floor) = self.snapshot_current(iter_count) else {
1981            // Nothing to fall back to, and a bet with no floor is exactly what
1982            // must not be placed (the gh #534 rule, for the same reason).
1983            return false;
1984        };
1985        let curr = floor.iterate.clone();
1986        let (tau, curr_barr, curr_theta) = {
1987            let d = self.data.borrow();
1988            let cq = self.cq.borrow();
1989            (
1990                d.curr_tau,
1991                cq.curr_barrier_obj(),
1992                cq.curr_constraint_violation(),
1993            )
1994        };
1995        if !curr_barr.is_finite() {
1996            return false;
1997        }
1998        // A trial may raise the violation up to what this solve's own
1999        // convergence check calls feasible, and no further.
2000        let theta_cap = curr_theta.max(self.bundle.conv_check.constr_viol_tol_or_default());
2001        // The direction has unit infinity-norm, so this caps the escape at a
2002        // multiple of the iterate's own scale rather than at an absolute
2003        // distance, which would mean different things on differently scaled
2004        // models.
2005        let step_cap = NEG_CURV_MAX_STEP_FACTOR * (1.0 + curr.x.amax().max(curr.s.amax()));
2006
2007        let mut accepted: Option<(crate::iterates_vector::IteratesVector, Number, Number)> = None;
2008        for sign in [1.0, -1.0] {
2009            let mut dir = probe.delta.deep_copy();
2010            dir.scal(sign);
2011            let dir = dir.freeze();
2012            let alpha_max = self.cq.borrow().aff_step_alpha_primal_max(&dir, tau);
2013            if !(alpha_max > 0.0) {
2014                continue;
2015            }
2016            let mut alpha = alpha_max.min(step_cap);
2017            for _ in 0..NEG_CURV_BACKTRACKS {
2018                if !(alpha > 0.0) || !alpha.is_finite() {
2019                    break;
2020                }
2021                let mut trial = curr.deep_copy();
2022                trial.x.axpy(alpha, &*dir.x);
2023                trial.s.axpy(alpha, &*dir.s);
2024                let trial = trial.freeze();
2025                self.data.borrow_mut().set_trial(trial.clone());
2026                let (barr, theta) = {
2027                    let cq = self.cq.borrow();
2028                    (cq.trial_barrier_obj(), cq.trial_constraint_violation())
2029                };
2030                self.data.borrow_mut().trial = None;
2031                // Second-order sufficient decrease. `probe.curvature` is
2032                // negative, so this asks the trial to realise at least
2033                // `NEG_CURV_ARMIJO` of the decrease the curvature model
2034                // predicts — the guard against a direction that is only
2035                // downhill in the quadratic model and uphill in the function.
2036                let predicted = 0.5 * alpha * alpha * probe.curvature;
2037                if barr.is_finite()
2038                    && theta.is_finite()
2039                    && theta <= theta_cap
2040                    && barr <= curr_barr + NEG_CURV_ARMIJO * predicted
2041                {
2042                    let better = match accepted.as_ref() {
2043                        Some((_, best, _)) => barr < *best,
2044                        None => true,
2045                    };
2046                    if better {
2047                        accepted = Some((trial, barr, alpha));
2048                    }
2049                    break;
2050                }
2051                alpha *= NEG_CURV_BACKTRACK_FACTOR;
2052            }
2053        }
2054
2055        let Some((trial, barr, alpha)) = accepted else {
2056            return false;
2057        };
2058
2059        tracing::debug!(target: "pounce::algorithm",
2060            "[POUNCE] iter {}: certified point has negative reduced curvature \
2061             (dᵀ(W+Σ)d = {:.3e}); escaping along it with α = {:.3e} \
2062             (barrier obj {:.10e} -> {:.10e}) and continuing (gh#797).",
2063            iter_count, probe.curvature, alpha, curr_barr, barr,
2064        );
2065
2066        self.neg_curv_escapes_used += 1;
2067        // gh #805 — the floor is the *best* certificate the escapes have left,
2068        // never simply the most recent one. Replacing it unconditionally is
2069        // what broke the guarantee above at `neg_curv_escapes >= 2`: escape 1
2070        // floors at A, the continuation certifies a different indefinite point
2071        // B, escape 2 overwrites the floor with B, and if that bet is lost the
2072        // run reports B — which nothing has ever compared against A. With
2073        // `f(B) > f(A)` that is worse than `neg_curv_escapes = 0` returns, the
2074        // one outcome the mechanism promises cannot happen. The filter method's
2075        // barrier objective is not monotone across μ updates, so the escape's
2076        // own accounting does not exclude it.
2077        //
2078        // Ranked rather than merely kept (gh #805's suggested fix), because
2079        // keeping A unconditionally has the mirror-image flaw: where B *is* the
2080        // better certificate, a lost second bet would hand back A and make
2081        // `neg_curv_escapes = 2` worse than `= 1`, which returns B. Both points
2082        // are strict certificates — the escape only fires on
2083        // `ConvergenceStatus::Converged` — so the same status-dominant ranking
2084        // [`Self::honour_neg_curv_floor`] uses on the way out decides between
2085        // them, and the floor is monotone in the number of escapes spent.
2086        //
2087        // A provable no-op at the default: the branch is only reachable with a
2088        // floor already held, which takes a second escape, which takes
2089        // `neg_curv_escapes >= 2`.
2090        let replace_floor = match self.neg_curv_floor.as_ref() {
2091            None => true,
2092            Some(held) => self.current_outranks_neg_curv_floor(held, true),
2093        };
2094        if replace_floor {
2095            self.neg_curv_floor = Some(floor);
2096        }
2097        self.neg_curv_deadline_iter = Some(
2098            iter_count
2099                .saturating_add(NEG_CURV_CONTINUATION_BUDGET)
2100                .min(self.max_iter.saturating_sub(1)),
2101        );
2102        {
2103            let mut d = self.data.borrow_mut();
2104            d.set_trial(trial);
2105            d.accept_trial_point();
2106            // Iteration-log marker. `n` is not one of upstream's codes and is
2107            // unused elsewhere in POUNCE; it is what tells a reader of the
2108            // table that the jump between two iterates was an escape and not a
2109            // line-search step.
2110            d.append_info_string("n");
2111        }
2112        // The filter's entries were computed at, and around, a point the
2113        // algorithm has just left discontinuously — the same situation a
2114        // successful restoration leaves behind, and handled the same way.
2115        self.bundle.line_search.reset();
2116        self.bundle.line_search.reset_after_restoration();
2117        true
2118    }
2119
2120    /// Rank the current iterate against a held negative-curvature floor
2121    /// (gh #797, gh #805).
2122    ///
2123    /// Rank by the status each point will actually be *reported* under, and
2124    /// only then by objective — the status-dominant order gh #200 arrived at
2125    /// the hard way. `apply_kkt_fidelity_gate` re-grades a `Success` on the
2126    /// unscaled KKT error after the driver loop returns, so with
2127    /// `kkt_fidelity_tol` set a lower objective at a coarser point is a status
2128    /// regression dressed up as a win.
2129    ///
2130    /// `current_certifies` is whether the current point comes with a
2131    /// certificate of its own: at the exit hook that is the driver's status,
2132    /// and at an escape site it is true by construction, since the escape only
2133    /// fires on `ConvergenceStatus::Converged`.
2134    ///
2135    /// Shared by the two sites that have to answer this question — the exit
2136    /// hook [`Self::honour_neg_curv_floor`], and the point at which a second
2137    /// escape decides which of two certificates to hold (gh #805) — so the two
2138    /// cannot drift into disagreeing about which point is the better answer.
2139    fn current_outranks_neg_curv_floor(
2140        &self,
2141        floor: &VetoSnapshot,
2142        current_certifies: bool,
2143    ) -> bool {
2144        let (_, curr_kkt) = self.curr_obj_and_unscaled_kkt();
2145        let current_success = current_certifies && self.survives_fidelity_gate(curr_kkt);
2146        let floor_success = self.survives_fidelity_gate(floor.unscaled_kkt);
2147        match (current_success, floor_success) {
2148            (true, true) => self.continuation_outranks(floor),
2149            // The current point reports `Solve_Succeeded` where the floor would
2150            // be re-graded down. A better status wins outright.
2151            (true, false) => true,
2152            // No certificate of its own — the escape was a bet placed *from*
2153            // one, so anything short of that loses it.
2154            (false, _) => false,
2155        }
2156    }
2157
2158    /// Make a negative-curvature escape non-destructive (gh #797).
2159    ///
2160    /// The escape is a bet placed *from a strict certificate*, which is what
2161    /// makes its accounting stricter than gh #534's: the floor is a point the
2162    /// solve was about to report `Solve_Succeeded` at, so the continuation has
2163    /// to come back with a certificate of its own at a better point to be
2164    /// preferred. Anything else — a worse point, an acceptable-level stall, a
2165    /// spent iteration budget, a restoration failure — restores the floor and
2166    /// reports it under the status it always had.
2167    ///
2168    /// Restoring reports `Success` even over a budget or user-stop exit, which
2169    /// is the opposite of what [`Self::honour_decline_floor`] and
2170    /// [`Self::honour_best_acceptable_after_dual_guard`] do — and deliberately
2171    /// so. Those two hold an *acceptable-level* point and must not let it erase
2172    /// why the solve stopped. Here a pre-#797 build returns `Solve_Succeeded`
2173    /// at this exact point, and returns it *before* the continuation that spent
2174    /// the budget ever runs: the budget was spent by the bet, not by the
2175    /// caller's problem. Reproducing the baseline outcome — point and status
2176    /// both — is the guarantee, and it is the reading gh #200's hook already
2177    /// takes of a refused certificate.
2178    fn honour_neg_curv_floor(&mut self, result: SolverReturn) -> SolverReturn {
2179        let Some(floor) = self.neg_curv_floor.clone() else {
2180            return result;
2181        };
2182        self.assert_comparable_scale(&floor);
2183        let keep_continuation =
2184            self.current_outranks_neg_curv_floor(&floor, matches!(result, SolverReturn::Success));
2185        if keep_continuation {
2186            tracing::debug!(target: "pounce::algorithm",
2187                "[POUNCE] the negative-curvature escape paid off: the continuation \
2188                 certified a better point than the stationary one it left \
2189                 (obj {:.10e} -> {:.10e}, gh#797).",
2190                floor.obj, self.curr_obj_and_unscaled_kkt().0,
2191            );
2192            return result;
2193        }
2194        tracing::debug!(target: "pounce::algorithm",
2195            "[POUNCE] the negative-curvature escape did not pay off; restoring the \
2196             certified stationary point from iter {} (obj {:.10e} viol {:.3e}) \
2197             and reporting it (gh#797).",
2198            floor.iter, floor.obj, floor.constr_viol,
2199        );
2200        self.restore_snapshot(&floor);
2201        SolverReturn::Success
2202    }
2203
2204    /// The escape's continuation ran out of budget without a certificate of its
2205    /// own (gh #797). Restore the stationary point the escape left and report
2206    /// it — that point is what a pre-#797 build returns, and it is a genuine
2207    /// strict certificate, so `Success` is the honest status for it.
2208    ///
2209    /// Takes the floor rather than cloning it, so
2210    /// [`Self::honour_neg_curv_floor`] is a no-op on the way out.
2211    fn terminate_at_neg_curv_floor(&mut self) -> IterateOutcome {
2212        if let Some(floor) = self.neg_curv_floor.take() {
2213            tracing::debug!(target: "pounce::algorithm",
2214                "[POUNCE] the negative-curvature escape spent its {} iterations \
2215                 without a new certificate; restoring the stationary point from \
2216                 iter {} (obj {:.10e}) and reporting it (gh#797).",
2217                NEG_CURV_CONTINUATION_BUDGET, floor.iter, floor.obj,
2218            );
2219            self.restore_snapshot(&floor);
2220        }
2221        IterateOutcome::Terminate(SolverReturn::Success)
2222    }
2223
2224    /// Make a deferred restoration decline non-destructive (gh #534).
2225    ///
2226    /// The deferral is a bet that a contracting endgame is three iterations from
2227    /// a certificate. This is what makes losing it cost only those iterations:
2228    /// whatever the continued run ends up returning, if it is not at least as
2229    /// good an answer as the floor — the point the pre-#534 guard would have
2230    /// reported — the floor is restored and reported instead.
2231    ///
2232    /// Applied once, in [`Self::optimize`], for the same reason the gh #200 and
2233    /// pounce#250 hooks are: the driver loop has many `return`s and this must
2234    /// see all of them.
2235    ///
2236    /// A strict `Success` is never overridden — that is the bet paying off, and
2237    /// a real certificate outranks any acceptable-level point by construction.
2238    /// The budget statuses keep their own status, as they do in
2239    /// [`Self::honour_best_acceptable_after_dual_guard`]: a caller polling for
2240    /// "did I run out of time" must be told so, even while the point it gets
2241    /// back is swapped for the better one.
2242    fn honour_decline_floor(&mut self, result: SolverReturn) -> SolverReturn {
2243        if matches!(result, SolverReturn::Success) {
2244            if self.decline_floor.is_some() {
2245                tracing::debug!(target: "pounce::algorithm",
2246                    "[POUNCE] the deferred restoration decline paid off: the continuation \
2247                     reached a strict certificate (gh #534).",
2248                );
2249            }
2250            return result;
2251        }
2252        let Some(floor) = self.decline_floor.clone() else {
2253            return result;
2254        };
2255        if self.continuation_outranks(&floor) {
2256            return result;
2257        }
2258        tracing::debug!(target: "pounce::algorithm",
2259            "[POUNCE] the deferred restoration decline did not pay off; restoring the \
2260             floor from iter {} (obj {:.10e} viol {:.3e}) and reporting it (gh #534).",
2261            floor.iter, floor.obj, floor.constr_viol,
2262        );
2263        self.restore_snapshot(&floor);
2264        match result {
2265            SolverReturn::MaxiterExceeded
2266            | SolverReturn::CpuTimeExceeded
2267            | SolverReturn::WallTimeExceeded
2268            | SolverReturn::UserRequestedStop => result,
2269            _ => SolverReturn::StopAtAcceptablePoint,
2270        }
2271    }
2272
2273    /// Terminal fallback for a near-feasible numerical breakdown (a
2274    /// restoration cycle or a failed step computation). If a finite
2275    /// acceptable iterate was recorded earlier in the solve, roll back
2276    /// to it and stop at [`SolverReturn::StopAtAcceptablePoint`] (mapped
2277    /// by the application layer to `Solved_To_Acceptable_Level`) rather
2278    /// than surfacing the hard `fallback` error. This mirrors upstream
2279    /// `IpBacktrackingLineSearch`'s `ACCEPTABLE_POINT_REACHED`
2280    /// precedence: when the line search exhausts but an acceptable point
2281    /// was stored, that point is returned instead of the failure. With
2282    /// no snapshot — or if the restored objective is non-finite — the
2283    /// original `fallback` status is surfaced unchanged, so genuinely
2284    /// failed/infeasible solves keep their honest status. Catches
2285    /// degenerate LPs (kleemin8, nsir2) whose μ-endgame reaches the
2286    /// optimum, then destabilizes on the ill-conditioned vertex and
2287    /// cycles in restoration instead of stopping at the acceptable
2288    /// iterate it already passed through.
2289    fn terminate_acceptable_or(&mut self, fallback: SolverReturn) -> IterateOutcome {
2290        if self.restore_acceptable_point() && self.cq.borrow().curr_f().is_finite() {
2291            IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint)
2292        } else {
2293            IterateOutcome::Terminate(fallback)
2294        }
2295    }
2296
2297    /// The single place this module turns a local-infeasibility conclusion
2298    /// into a returned status (gh #505).
2299    ///
2300    /// Three separate routes reach that verdict — the conv-check's rapid
2301    /// detection, restoration layer 2, and the slow-cycle exits — and the same
2302    /// defect was found in two of them independently: returning the hard
2303    /// verdict without consulting the acceptable-point stash, so a solve that
2304    /// had already passed through an acceptable iterate discarded it. Only the
2305    /// cycle exits got it right, and nothing structural said the other two were
2306    /// wrong.
2307    ///
2308    /// That is the shape of a defect that comes back. The route a solve takes
2309    /// to the verdict is an internal detail — the user sees one status either
2310    /// way — so the *decision* about what that status means must not live at
2311    /// each route. It lives here, and
2312    /// [`no_route_concludes_local_infeasibility_alone`] is a tripwire against
2313    /// a new site rebuilding the outcome inline.
2314    ///
2315    /// The cycle exits are not routed through here because their fallback is
2316    /// chosen between `LocalInfeasibility` and `ErrorInStepComputation` at the
2317    /// call site; they already reach `terminate_acceptable_or`, which is the
2318    /// behaviour this guarantees.
2319    ///
2320    /// Scope: this governs how *this module* returns the verdict. Other layers
2321    /// name `SolverReturn::LocalInfeasibility` for their own reasons — the SQP
2322    /// status map and the ℓ₁ elastic path in `application.rs`, for instance —
2323    /// and are outside both this funnel and its tripwire.
2324    fn terminate_local_infeasibility(&mut self) -> IterateOutcome {
2325        self.terminate_acceptable_or(SolverReturn::LocalInfeasibility)
2326    }
2327
2328    pub fn with_nlp(mut self, nlp: Rc<RefCell<dyn IpoptNlp>>) -> Self {
2329        self.nlp = Some(nlp);
2330        self
2331    }
2332
2333    /// Install a user-facing TNLP handle. Enables per-iteration
2334    /// `TNLP::intermediate_callback` invocation from `optimize()`.
2335    pub fn with_tnlp(mut self, tnlp: Rc<RefCell<dyn TNLP>>) -> Self {
2336        self.tnlp = Some(tnlp);
2337        self
2338    }
2339
2340    /// Build an [`IterStats`] payload from the current `IpoptData` /
2341    /// `IpoptCq` state. Mirrors the field set the upstream Ipopt main
2342    /// loop hands to `IntermediateCallback` after each `AcceptTrialPoint`.
2343    fn build_iter_stats(&self) -> IterStats {
2344        let d = self.data.borrow();
2345        let c = self.cq.borrow();
2346        let dnrm = match d.delta.as_ref() {
2347            Some(delta) => delta.x.amax().max(delta.s.amax()),
2348            None => 0.0,
2349        };
2350        IterStats {
2351            // Regular from the outer loop; restoration from the inner
2352            // sub-IPM, which the outer driver flags at construction
2353            // (gh#645). The outer loop never sets the flag, so every
2354            // fire from here is still `RegularMode` — what changed is
2355            // that restoration now fires at all.
2356            mode: if self.fires_as_restoration {
2357                AlgorithmMode::RestorationPhaseMode
2358            } else {
2359                AlgorithmMode::RegularMode
2360            },
2361            iter: d.iter_count,
2362            obj_value: c.curr_f(),
2363            inf_pr: c.curr_primal_infeasibility_max(),
2364            inf_du: c.curr_dual_infeasibility_max(),
2365            mu: d.curr_mu,
2366            d_norm: dnrm,
2367            regularization_size: d.info_regu_x,
2368            alpha_du: d.info_alpha_dual,
2369            alpha_pr: d.info_alpha_primal,
2370            ls_trials: d.info_ls_count,
2371        }
2372    }
2373
2374    /// Fire `TNLP::intermediate_callback` if a TNLP handle and NLP
2375    /// handle are installed. Wraps the call in an [`IntermediateContext`]
2376    /// guard so downstream inspector entry points (the C API's
2377    /// `GetIpoptCurrent*`) can read live state for the duration. Returns
2378    /// `true` to continue, `false` if the user requested termination.
2379    fn fire_intermediate(&self) -> bool {
2380        let timing = self.data.borrow().timing.clone();
2381        let _guard = timing.fire_intermediate.guard();
2382        let Some(tnlp) = self.tnlp.as_ref() else {
2383            return true;
2384        };
2385        let Some(nlp) = self.nlp.as_ref() else {
2386            return true;
2387        };
2388        // Nothing reads the payload, so building it is the whole cost of the
2389        // fire (gh#965). The sink below is skipped with it, which is safe:
2390        // its only reader re-emits the row into this same callback.
2391        if !tnlp.borrow().wants_intermediate_callback() {
2392            return true;
2393        }
2394        let stats = self.build_iter_stats();
2395        // Record exactly what the callback is about to receive, so a losing
2396        // retry can re-emit the winning attempt's final row (pounce#870).
2397        if let Some(sink) = self.last_iter_stats_sink.as_ref() {
2398            *sink.borrow_mut() = Some(stats);
2399        }
2400        // The live-inspector context is for iterates of the *user's*
2401        // problem only. During restoration the iterate belongs to the
2402        // feasibility subproblem and is not even the same length, so no
2403        // context is installed and `GetIpoptCurrent*` reports no data
2404        // for the duration. See `fires_as_restoration`.
2405        let _guard = (!self.fires_as_restoration).then(|| {
2406            CtxGuard::install(IntermediateContext {
2407                data: Rc::clone(&self.data),
2408                cq: Rc::clone(&self.cq),
2409                nlp: Rc::clone(nlp),
2410            })
2411        });
2412        // The materialised user-space iterate (`with_current_user_iterate`,
2413        // what `GetIpoptCurrentIterate` reads), when the TNLP will read it.
2414        // Built here, before the callback borrows the TNLP, because the
2415        // fixed-variable multiplier recovery evaluates it.
2416        let wants_iterate = !self.fires_as_restoration && tnlp.borrow().wants_current_iterate();
2417        let _iterate_guard = if wants_iterate {
2418            crate::intermediate::ipm_user_iterate(
2419                nlp,
2420                &self.data,
2421                &self.cq,
2422                self.live_iterate_fixed_var_duals,
2423            )
2424            .map(crate::intermediate::UserIterateGuard::install)
2425        } else {
2426            None
2427        };
2428        tnlp.borrow_mut().intermediate_callback(
2429            stats,
2430            &TnlpIpoptData::default(),
2431            &TnlpIpoptCq::default(),
2432        )
2433    }
2434
2435    pub fn with_search_dir(mut self, sd: PdSearchDirCalc) -> Self {
2436        self.search_dir = Some(sd);
2437        self
2438    }
2439
2440    pub fn with_restoration(mut self, resto: Box<dyn RestorationPhase>) -> Self {
2441        self.restoration = Some(resto);
2442        self
2443    }
2444
2445    /// Install the shared diagnostics state. The state is propagated
2446    /// to the augmented-system solver at the top of [`Self::optimize`]
2447    /// so dump sites can consult per-iter gating.
2448    pub fn with_diagnostics(mut self, diag: Rc<DiagnosticsState>) -> Self {
2449        self.diagnostics = Some(diag);
2450        self
2451    }
2452
2453    /// Install an interactive debugger hook. Fired at each checkpoint
2454    /// in [`Self::optimize`]; returning [`crate::debug::DebugAction::Stop`]
2455    /// ends the solve with `SolverReturn::UserRequestedStop`.
2456    pub fn with_debug_hook(mut self, hook: Rc<RefCell<dyn crate::debug::DebugHook>>) -> Self {
2457        self.debug = Some(hook);
2458        self
2459    }
2460
2461    /// Shared handle to the installed debugger, if any — used to forward
2462    /// it into the restoration inner IPM.
2463    pub fn debug_hook(&self) -> Option<Rc<RefCell<dyn crate::debug::DebugHook>>> {
2464        self.debug.as_ref().map(Rc::clone)
2465    }
2466
2467    /// Fire the debugger hook (if installed) at `cp`, building a live
2468    /// [`crate::debug::DebugCtx`] over cheap handle clones. Returns the
2469    /// requested action, defaulting to `Resume` when no hook is set.
2470    fn fire_debug(&mut self, cp: crate::debug::Checkpoint) -> crate::debug::DebugAction {
2471        use crate::debug::{DebugAction, DebugCtx};
2472        // Clone the Rc so the hook borrow is released before we touch
2473        // `self.bundle` to apply any live option changes below.
2474        let Some(hook) = self.debug.as_ref().map(Rc::clone) else {
2475            return DebugAction::Resume;
2476        };
2477        let mut ctx = DebugCtx::new(Rc::clone(&self.data), Rc::clone(&self.cq), cp);
2478        let action = hook.borrow_mut().at_checkpoint(&mut ctx);
2479        // Drain any tolerances the hook asked to hot-swap and write them
2480        // into the live convergence-check policy, so the next iteration's
2481        // termination test uses the new value (no `resolve` needed).
2482        for (name, value) in ctx.take_live_tolerances() {
2483            self.bundle.conv_check.set_tolerance(&name, value);
2484        }
2485        action
2486    }
2487
2488    /// Run the restoration phase, bracketed by the `PreRestoration` /
2489    /// `PostRestoration` debug checkpoints so a debugger can inspect the
2490    /// iterate just before entry and just after exit. With no debugger
2491    /// installed this is exactly `invoke_restoration()`.
2492    fn invoke_restoration_debugged(&mut self) -> IterateOutcome {
2493        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::PreRestoration) {
2494            return o;
2495        }
2496        let outcome = self.invoke_restoration();
2497        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::PostRestoration) {
2498            return o;
2499        }
2500        outcome
2501    }
2502
2503    /// Fire a sub-iteration checkpoint from inside [`Self::iterate`].
2504    /// Returns `Some(Terminate(UserRequestedStop))` if the debugger asked
2505    /// to stop, so the caller can `return` it; `None` to continue.
2506    fn debug_stop(&mut self, cp: crate::debug::Checkpoint) -> Option<IterateOutcome> {
2507        if self.debug.is_none() {
2508            return None;
2509        }
2510        if self.fire_debug(cp) == crate::debug::DebugAction::Stop {
2511            Some(IterateOutcome::Terminate(SolverReturn::UserRequestedStop))
2512        } else {
2513            None
2514        }
2515    }
2516
2517    /// Fire the terminal post-mortem checkpoint (if a debugger is set),
2518    /// carrying the solve outcome so the hook can decide whether to pause
2519    /// at the final iterate. The action is advisory — the loop returns
2520    /// `result` regardless — so the hook just gets a last look.
2521    fn fire_debug_terminal(&mut self, result: SolverReturn) {
2522        use crate::debug::{Checkpoint, DebugCtx};
2523        let Some(hook) = self.debug.as_ref() else {
2524            return;
2525        };
2526        let mut ctx = DebugCtx::new(
2527            Rc::clone(&self.data),
2528            Rc::clone(&self.cq),
2529            Checkpoint::Terminated,
2530        )
2531        .with_status(format!("{result:?}"));
2532        let _ = hook.borrow_mut().at_checkpoint(&mut ctx);
2533    }
2534
2535    /// Cheap mid-iteration time-budget check (pounce#242). Returns the
2536    /// terminal [`SolverReturn`] when the shared [`Deadline`] has been
2537    /// crossed, so the caller can bail *within* an iteration — after the
2538    /// KKT factorization, before the line search — rather than only at the
2539    /// next outer-iteration convergence check. Returns `None` (never
2540    /// terminating) when no deadline is installed, keeping the
2541    /// direct-driver / unit-test paths on their `overall_alg`-based gate.
2542    /// A `None` here is not "no budget" but "check it at the coarse site".
2543    fn deadline_status(&self) -> Option<SolverReturn> {
2544        let d = self.data.borrow();
2545        let kind = d.deadline.as_ref()?.exceeded()?;
2546        Some(match kind {
2547            pounce_common::timing::DeadlineKind::Cpu => SolverReturn::CpuTimeExceeded,
2548            pounce_common::timing::DeadlineKind::Wall => SolverReturn::WallTimeExceeded,
2549        })
2550    }
2551
2552    /// One iteration body — port of `Optimize()`'s inner loop.
2553    /// Returns either `Continue` to keep iterating or a terminal
2554    /// [`SolverReturn`] mirroring upstream's exception → return-code
2555    /// translation table (see `MAIN_LOOP.md` §"Exception mapping").
2556    fn iterate(&mut self) -> IterateOutcome {
2557        // Shared timing accumulator — cheap Rc clone so each phase can
2558        // bump its own counter without re-borrowing `data`.
2559        let timing = self.data.borrow().timing.clone();
2560
2561        // Per-iteration span so every event emitted in this body (the
2562        // structured iteration record, restoration/linear-solve spans)
2563        // is tagged with the iteration index.
2564        let _iter_span =
2565            tracing::info_span!("iteration", iter = self.data.borrow().iter_count).entered();
2566
2567        // 1. Output iteration row. Header every 10 iters; the row itself
2568        //    is built plain by the strategy (so the column widths stay
2569        //    exact and unit-testable) and wrapped in a tiger/rust style
2570        //    at the print site (pounce#71). `anstream::stdout()` strips
2571        //    the escapes automatically when stdout is redirected or
2572        //    `NO_COLOR` is set, so non-TTY output is plain text.
2573        //
2574        //    Print BEFORE `reset_info` so the row reflects the accepted
2575        //    step from the previous iteration (alphas, ls count,
2576        //    alpha_char), matching upstream's `IpIpoptAlgorithm::Optimize`
2577        //    ordering.
2578        timing.output_iteration.start();
2579        self.bundle.iter_output.write_output();
2580        if self.print_iter_output {
2581            use std::io::Write as _;
2582            let (iter_count, alpha_pr, alpha_char) = {
2583                let d = self.data.borrow();
2584                (d.iter_count, d.info_alpha_primal, d.info_alpha_primal_char)
2585            };
2586            let row = self.bundle.iter_output.format_row(&self.data, &self.cq);
2587            // Iteration 0 is the initial point — no step has been taken
2588            // yet, so `alpha_primal` is 0; treat it as a full step
2589            // (neutral black) rather than a stalling alarm (red).
2590            let style_alpha = if iter_count == 0 { 1.0 } else { alpha_pr };
2591            let style = pounce_common::style::iteration_row_style(style_alpha, alpha_char);
2592            let mut out = anstream::stdout();
2593            // Write errors (e.g. a closed pipe / `head` on the output)
2594            // are deliberately ignored: a vanished terminal must not
2595            // panic the solver, unlike the old `println!`.
2596            if iter_count % 10 == 0 {
2597                let _ = write!(out, "{}", crate::output::orig::OrigIterationOutput::HEADER);
2598            }
2599            let _ = writeln!(out, "{}{}{}", style.render(), row, style.render_reset());
2600        }
2601        timing.output_iteration.end();
2602
2603        // Structured per-iteration event (pounce#71) — the single source
2604        // of truth for the per-iteration trajectory. The JSON log sink
2605        // and the solve-report collector
2606        // (`pounce_observability::IterCollectorLayer`) both derive from
2607        // it. The text console layer filters this target out (its human
2608        // form is the colored table above).
2609        //
2610        // Skipped entirely when nothing consumes it (no iter-history
2611        // capture active and JSON logging off) so the default run pays
2612        // no per-iteration field-evaluation / allocation cost.
2613        if pounce_observability::iteration_event_wanted() {
2614            // The objective / `inf_pr` the row printed (gh#979): on the main
2615            // phase the unscaled violation of the user's model rather than
2616            // the internal slack-form residual, and on restoration rows the
2617            // original NLP's values rather than the restoration problem's.
2618            // The internal residual rides alongside as `inf_pr_internal`.
2619            let printed = self
2620                .bundle
2621                .iter_output
2622                .printed_objective_inf_pr(&self.data, &self.cq);
2623            let phase = if self.bundle.iter_output.is_restoration() {
2624                "restoration"
2625            } else {
2626                "main"
2627            };
2628            let d = self.data.borrow();
2629            let c = self.cq.borrow();
2630            let inf_pr_internal = c.curr_primal_infeasibility_max();
2631            let (objective, inf_pr) =
2632                printed.unwrap_or_else(|| (c.unscaled_curr_f(), inf_pr_internal));
2633            let alpha_char = d.info_alpha_primal_char;
2634            let alpha_char_s = alpha_char.to_string();
2635            let d_norm = match &d.delta {
2636                Some(delta) => delta.x.amax().max(delta.s.amax()),
2637                None => 0.0,
2638            };
2639            tracing::info!(
2640                target: pounce_observability::ITER_TARGET,
2641                iter = d.iter_count,
2642                objective = objective,
2643                inf_pr = inf_pr,
2644                inf_pr_internal = inf_pr_internal,
2645                inf_du = c.curr_dual_infeasibility_max(),
2646                mu = d.curr_mu,
2647                d_norm = d_norm,
2648                regularization = d.info_regu_x,
2649                alpha_dual = d.info_alpha_dual,
2650                alpha_primal = d.info_alpha_primal,
2651                ls_trials = d.info_ls_count,
2652                alpha_char = alpha_char_s.as_str(),
2653                resto_kind = pounce_common::style::resto_kind_str(alpha_char),
2654                phase = phase,
2655            );
2656        }
2657
2658        // Reset per-iteration info on data (after printing previous
2659        // iter's accepted-step info; before the next line search).
2660        self.data.borrow_mut().reset_info();
2661
2662        // 2. Convergence check.
2663        timing.check_convergence.start();
2664        let nlp_err = self.cq.borrow().curr_nlp_error();
2665        let iter_count = self.data.borrow().iter_count;
2666        if !nlp_err.is_finite() {
2667            timing.check_convergence.end();
2668            return IterateOutcome::Terminate(SolverReturn::InvalidNumberDetected);
2669        }
2670        // gh #534 progress history. One sample per outer iteration, recorded
2671        // before any of the guards below can divert, so the samples the
2672        // restoration-decline test reads are consecutive by construction.
2673        self.note_nlp_err(nlp_err);
2674        // Divergence guard — port of upstream `IpIpoptAlg.cpp` post-
2675        // AcceptTrialPoint check. When `max_i |x_i|` exceeds the
2676        // registered `diverging_iterates_tol` (default `1e20`), exit
2677        // cleanly with `DivergingIterates` rather than spiralling into
2678        // a degenerate restoration whose inner sub-NLP can't recover
2679        // (MESH: orig `f` already at -3.6e33 by iter 90, restoration
2680        // entered too late to bound `x`).
2681        //
2682        // A large `|x|` alone does not prove unboundedness, though:
2683        // `DivergingIterates` is Ipopt's *unboundedness* signal (it maps
2684        // to the AMPL 300 "unbounded" range), and under severe objective
2685        // ill-scaling the normal-mode IPM can take a large but transient
2686        // excursion on a problem that is bounded below with a finite
2687        // optimum (issue #248: MINLPLib `jit1`). Only conclude divergence
2688        // when the growth is *structurally* consistent with an unbounded
2689        // feasible region — some over-threshold component heading toward a
2690        // side with no finite bound. If every large component is pinned by
2691        // a finite bound (in particular, all variables boxed), the growth
2692        // is a scaling artifact, so let the normal convergence / iteration
2693        // machinery return the best iterate instead of a spurious
2694        // `Unbounded`.
2695        // Evaluate the structural check under an immutable borrow, then
2696        // update the persistence state and take the verdict separately so
2697        // the mutable field updates don't clash with the `data` borrow.
2698        // Two independent unboundedness paths share this block:
2699        //   * the `diverging_iterates_tol` (`1e20`) magnitude guard, gated on
2700        //     the free-variable structural check + geometric-growth streak
2701        //     (issues #248 / #252); and
2702        //   * the #285 recession-ray path — a *checked proof*, active from a
2703        //     far lower magnitude floor, that catches a genuine recession ray
2704        //     in `null(A_eq)` over free variables whose `|x|` grows only
2705        //     linearly and so never reaches `1e20` within `max_iter`.
2706        //
2707        // The whole block is skipped while the line search is inside a
2708        // watchdog trial sequence (gh #818 review). A `'w'` iterate is
2709        // provisional by construction: the acceptor *rejected* it, the
2710        // filter was not augmented, and the line search is holding a
2711        // snapshot it will revert to within `watchdog_trial_iter_max`
2712        // (default 3) iterations. Reporting `DivergingIterates` there
2713        // throws that snapshot away and calls a problem unbounded on a
2714        // point the algorithm had already decided not to keep. This is
2715        // the same false positive `DIVERGENCE_PERSIST_ITERS` was
2716        // introduced for — a transient excursion that peaks and recedes —
2717        // except that a watchdog excursion recedes *by construction*, and
2718        // `DIVERGENCE_ABS_RUNAWAY` bypasses the streak, so the streak
2719        // alone does not cover it. Skipping rather than resetting leaves
2720        // the streak state untouched, so a watchdog gamble in the middle
2721        // of a genuine ray neither accumulates nor erases evidence; a real
2722        // divergence is reported at most three iterations later, from a
2723        // committed iterate. The deferral is capped at
2724        // `WATCHDOG_DEFER_MAX` consecutive iterations so it can never be
2725        // held open by a stale `in_watchdog` — see
2726        // `Self::watchdog_defer_streak` for the path that leaks one.
2727        //
2728        // Measured on the gh #818 quadratic at `n = 8`, cond `1e12`,
2729        // `limited_memory_max_history 6`: the solve reaches iteration 352
2730        // on the *third* watchdog trial of a sequence, at `|x|_inf ~ 5e22`
2731        // with the objective climbing to `+2.0e45` — the opposite of the
2732        // `f -> -inf` that `DivergingIterates` is supposed to mean — one
2733        // iteration before `StopWatchDog` would have restored an iterate
2734        // at `f = 2.26e4`.
2735        let in_watchdog = self.bundle.line_search.in_watchdog()
2736            && self.watchdog_defer_streak < Self::WATCHDOG_DEFER_MAX;
2737        if in_watchdog {
2738            self.watchdog_defer_streak += 1;
2739        } else {
2740            self.watchdog_defer_streak = 0;
2741        }
2742        let (amax, structural_free, is_ray) = {
2743            let data = self.data.borrow();
2744            match data.curr.as_ref() {
2745                Some(curr) if !in_watchdog => {
2746                    let amax = curr.x.amax();
2747                    let structural = amax > self.diverging_iterates_tol
2748                        && self.divergence_is_true_unboundedness(&*curr.x);
2749                    let is_ray = amax > Self::RECESSION_MIN_NORM
2750                        && self.curr_is_recession_ray(&*curr.x, amax);
2751                    (Some(amax), structural, is_ray)
2752                }
2753                _ => (None, false, false),
2754            }
2755        };
2756        // Evaluate the (scaled) objective only while a structural divergence
2757        // is live — the streak's descent gate needs it, and it costs an
2758        // objective evaluation, so skip it on the common non-diverging path.
2759        let curr_f = structural_free.then(|| self.cq.borrow().curr_f());
2760        // Evaluate both streak updates (no short-circuit) so each keeps its
2761        // state current, then fire if either concludes divergence.
2762        // ... but only when the streaks are actually being fed. Inside a
2763        // watchdog sequence `amax` is `None`, and running the updates
2764        // would reset both streaks on a point they never saw.
2765        let (fire_magnitude, fire_recession) = if in_watchdog {
2766            (false, false)
2767        } else {
2768            (
2769                self.update_divergence_verdict(amax, structural_free, curr_f),
2770                self.update_recession_verdict(amax.unwrap_or(0.0), is_ray),
2771            )
2772        };
2773        if fire_magnitude || fire_recession {
2774            if fire_recession && !fire_magnitude {
2775                tracing::debug!(target: "pounce::algorithm",
2776                    "[POUNCE] recession-ray guard fired at iter {} (|x|_inf={:.2e}); \
2777                     reporting DivergingIterates (pounce#285).",
2778                    self.data.borrow().iter_count,
2779                    amax.unwrap_or(f64::NAN),
2780                );
2781            }
2782            timing.check_convergence.end();
2783            return IterateOutcome::Terminate(SolverReturn::DivergingIterates);
2784        }
2785        // Dual-divergence guard (pounce#246). The primal guard above only
2786        // catches `|x|` blowing up; a bad warm start can instead send the
2787        // *dual* infeasibility diverging — `inf_du` 1 -> 1e14, the inertia
2788        // regularization -> 1e14, the barrier parameter frozen, full steps
2789        // still accepted by the filter because primal feasibility inches
2790        // down — while `|x|` stays bounded. `diverging_iterates_tol` never
2791        // trips, restoration is never entered, and the solve grinds in
2792        // ever-more-ill-conditioned KKT factorizations that each take
2793        // seconds (the emfl050 warm-start overshoot: one 3.8 s factorization
2794        // per iteration, forever). Detect a sustained streak of growing dual
2795        // infeasibility in the elevated regime and route to restoration —
2796        // the same recovery the least-square-multiplier init path reaches on
2797        // its own — before the factorizations start choking. Gated on a
2798        // large absolute `inf_du` so a well-behaved solve whose dual
2799        // residual transiently rises (then falls) is never diverted:
2800        // restoration is a heavier hammer than the guard should swing at a
2801        // merely-bumpy-but-converging iterate.
2802        //
2803        // OFF BY DEFAULT (pounce#250 follow-up). The emfl050 overshoot above is
2804        // how this was justified, and it did not reproduce: that measurement was
2805        // caller-side JAX compilation, and the build predating the guard solves
2806        // both emfl050 instances to the same optimum in the same time. What is
2807        // left is an effect on four of 1284 MINLPLib models that is knife-edge
2808        // and non-monotone in `dual_diverging_streak` — a better local optimum on
2809        // deb7/deb9 at exactly 15, and pooling_rt2stp turning Solve_Succeeded
2810        // into Maximum_Iterations_Exceeded at 10 and 15 only. Kept because it
2811        // does help when it helps, but not imposed. Full account in the option
2812        // help (`upstream_options.rs`).
2813        //
2814        // Two things to know before changing this:
2815        //
2816        // * `curr_dual_infeasibility_max` is the RAW ‖∇L‖∞, not divided by the
2817        //   `s_d` optimality scaling the convergence check applies, and this runs
2818        //   *before* `conv_check`. So the thresholds below are not on the same
2819        //   quantity the solver's own tolerances are on, and the claim that they
2820        //   are scale-robust holds only while `nlp_scaling_method != none`. No
2821        //   exploit is known; the margin is thinner than it looks.
2822        // * The `DivergingIterates` fallback at the end is unreachable from every
2823        //   shipped front end — CLI, pounce-py and cinterface all wire a
2824        //   restoration provider, so the guard can only ever route to
2825        //   restoration. Do not assume it is dead code and delete the provider
2826        //   check; do not assume it is live and rely on the status either.
2827        // gh#884 — the dual-divergence-at-a-settled-primal signature.
2828        //
2829        // Four conjuncts, all required **at the same iterate**. That is not
2830        // stylistic: measured on the corpus, `deb7` on the L-BFGS leg reaches
2831        // a settled step of `5.9e-13` at an unscaled dual of `8.6e-7`, and its
2832        // *maximum* unscaled dual over settled iterates is `7.2e6`. A
2833        // formulation that took the minimum step and the maximum dual over a
2834        // window would fire on it; this one does not.
2835        //
2836        // What it is for: at a biactive complementarity pair the product row's
2837        // multiplier is arbitrary rather than determined, so it runs away, `s_d`
2838        // grows with it, and the `s_d`-normalised aggregate the convergence
2839        // check reads stays clean while the honest residual is `7.9e+04`. The
2840        // one quantity that feedback loop cannot fake is the step: with the
2841        // primal settled and the duals diverging the direction collapses. So
2842        // this reads the *raw unscaled* residual, and only at iterates where
2843        // the algorithm has demonstrably stopped moving with the primal solved.
2844        // A multiplier of `1e9` on a `1e-9` gradient cannot satisfy it, because
2845        // nothing here is normalised by a multiplier — which is gh#884's
2846        // criterion 2.
2847        //
2848        // It never changes a verdict. All it does is authorize the application
2849        // layer to spend a second solve; see `run_with_dual_divergence_retry`.
2850        if !self.dual_divergence_signature && self.dual_divergence_retry_step_tol > 0.0 {
2851            let cq = self.cq.borrow();
2852            let has_rows = cq.curr_c().dim() > 0 || cq.curr_d().dim() > 0;
2853            if has_rows && self.last_step_rel <= self.dual_divergence_retry_step_tol {
2854                let inf_pr = cq.curr_primal_infeasibility_max();
2855                let unscaled_du = cq.curr_unscaled_dual_infeasibility_max();
2856                if inf_pr <= DUAL_DIV_RETRY_PRIMAL_TOL
2857                    && unscaled_du >= self.dual_divergence_retry_du_floor
2858                    && unscaled_du.is_finite()
2859                {
2860                    self.dual_divergence_signature = true;
2861                    tracing::debug!(target: "pounce::algorithm",
2862                        "[POUNCE] gh#884 dual-divergence signature at iter {}: \
2863                         step_rel={:.2e} inf_pr={:.2e} unscaled_inf_du={:.2e}; \
2864                         a cold retry is authorized if this solve does not succeed.",
2865                        self.data.borrow().iter_count,
2866                        self.last_step_rel, inf_pr, unscaled_du,
2867                    );
2868                }
2869            }
2870        }
2871
2872        if self.dual_diverging_streak > 0 {
2873            let inf_du = self.cq.borrow().curr_dual_infeasibility_max();
2874            if inf_du.is_finite() && inf_du > self.dual_inf_prev && inf_du > DUAL_DIV_COUNT_FLOOR {
2875                self.dual_growth_streak += 1;
2876            } else {
2877                self.dual_growth_streak = 0;
2878            }
2879            self.dual_inf_prev = inf_du;
2880            if self.dual_growth_streak >= self.dual_diverging_streak && inf_du > DUAL_DIV_FIRE_TOL {
2881                self.dual_growth_streak = 0;
2882                self.dual_inf_prev = 0.0;
2883                // Arm the "never worse off" bookkeeping for the bet about to be
2884                // placed (pounce#250 follow-up).
2885                self.dual_guard_fired = true;
2886                timing.check_convergence.end();
2887                tracing::debug!(target: "pounce::algorithm",
2888                    "[POUNCE] dual-divergence guard fired at iter {} (inf_du={:.2e}); \
2889                     routing to restoration (pounce#246).",
2890                    self.data.borrow().iter_count, inf_du,
2891                );
2892                if self.restoration.is_some() {
2893                    return self.invoke_restoration_debugged();
2894                }
2895                return IterateOutcome::Terminate(SolverReturn::DivergingIterates);
2896            }
2897        }
2898        let conv_status = self
2899            .bundle
2900            .conv_check
2901            .check_convergence_with_state(nlp_err, iter_count, &self.data, &self.cq);
2902        // Snapshot the *first* refused certificate. Baseline would have stopped
2903        // and returned exactly this point, so keeping it — and only it — is what
2904        // makes the "never worse" guarantee exact rather than approximate. A
2905        // later refusal is also a valid certificate but not necessarily a
2906        // better one, so it must not overwrite this.
2907        if !self.vetoed_seen && self.bundle.conv_check.certificate_vetoed() {
2908            // Latch on *seeing* the refusal, not on the snapshot being present:
2909            // the veto flag is sticky, so keying off `vetoed.is_none()` would
2910            // let a failed capture be completed at a later, arbitrary iterate.
2911            // See `IpoptAlgorithm::vetoed_seen`.
2912            self.vetoed_seen = true;
2913            self.vetoed = self.snapshot_current(iter_count);
2914        }
2915        if !self.vetoed_acceptable_seen && self.bundle.conv_check.acceptable_certificate_vetoed() {
2916            self.vetoed_acceptable_seen = true;
2917            self.vetoed_acceptable = self.snapshot_current(iter_count);
2918        }
2919        // gh #695: a successful verdict asserts the convergence test passed;
2920        // reporting one alongside a non-finite objective is self-contradictory,
2921        // and a caller that gates on `status` and then reads `obj_val` silently
2922        // receives `NaN`. The convergence test cannot notice on its own — it
2923        // reads gradients, residuals and complementarity, never the objective
2924        // *value* — so with finite derivatives and a satisfied equality the KKT
2925        // residuals are genuinely small and the solve converges on a point
2926        // whose objective is not a number.
2927        //
2928        // Only the *equality*-constrained shape reached here: the unconstrained
2929        // and bounds-only shapes fail in the step computation and the
2930        // inequality-constrained one already trips an invalid-number guard, so
2931        // this closes the one column of that matrix that was reporting success.
2932        // gh #292 closed the NaN-*gradient* hole and recorded `f`-returns-NaN as
2933        // the safe contrast case, which held for the shapes it exercised and not
2934        // for this one.
2935        //
2936        // `Invalid_Number_Detected` is the status Ipopt's `Eval_f` gives a
2937        // non-finite objective, which POUNCE's own inequality-constrained shape
2938        // already agreed with. The same check already guards the restoration
2939        // near-feasible exit below, for the same reason on a different path
2940        // (CUTE `himmelbj`); this extends it to the ordinary convergence exit
2941        // rather than adding a second rule.
2942        let converged_success = matches!(
2943            conv_status,
2944            ConvergenceStatus::Converged | ConvergenceStatus::ConvergedToAcceptable
2945        );
2946        if converged_success && !self.cq.borrow().curr_f().is_finite() {
2947            timing.check_convergence.end();
2948            return IterateOutcome::Terminate(SolverReturn::InvalidNumberDetected);
2949        }
2950        if conv_status == ConvergenceStatus::Continue
2951            && let Some(hook) = self.handover.as_mut()
2952        {
2953            let (curr, mu) = {
2954                let d = self.data.borrow();
2955                (d.curr.clone(), d.curr_mu)
2956            };
2957            if let Some(next) = curr.and_then(|c| hook(&c, iter_count, nlp_err, mu)) {
2958                timing.check_convergence.end();
2959                let mut d = self.data.borrow_mut();
2960                d.set_curr(next);
2961                // Same frame marker crossover sets: the point sits on the
2962                // declared bounds, not inside the relaxed ones (gh#654).
2963                d.curr_from_crossover = true;
2964                drop(d);
2965                // The handed-over point is a first-order KKT point, which a
2966                // saddle of a nonconvex model also is — and the SQP's step-3
2967                // path certifies it without any curvature test. The interior
2968                // method's own success exit runs the gh #797 escape first;
2969                // this one does too, so the handover cannot report a point
2970                // the interior method would have left (measured: on
2971                // `nonconvex_qp` / `nonconvex_qp_ineq` / `nonconvex_two_escapes`
2972                // it otherwise ended at the stationary point the IPM
2973                // escapes, objective `1` against `≈ 0`).
2974                if self.try_neg_curv_escape(iter_count) {
2975                    // The iterate is the interior method's again.
2976                    self.data.borrow_mut().curr_from_crossover = false;
2977                    return IterateOutcome::Continue;
2978                }
2979                return IterateOutcome::Terminate(SolverReturn::Success);
2980            }
2981        }
2982        match conv_status {
2983            ConvergenceStatus::Continue => {}
2984            ConvergenceStatus::Converged => {
2985                timing.check_convergence.end();
2986                // gh #797: first-order stationarity is not a local minimum on a
2987                // nonconvex model. If the reduced Hessian here is indefinite,
2988                // leave along a direction of negative curvature instead of
2989                // certifying a constrained maximum — bounded in cost, and
2990                // floored at this very point.
2991                if self.try_neg_curv_escape(iter_count) {
2992                    return IterateOutcome::Continue;
2993                }
2994                return IterateOutcome::Terminate(SolverReturn::Success);
2995            }
2996            ConvergenceStatus::ConvergedToAcceptable => {
2997                timing.check_convergence.end();
2998                return IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint);
2999            }
3000            ConvergenceStatus::MaxIterExceeded => {
3001                timing.check_convergence.end();
3002                return IterateOutcome::Terminate(SolverReturn::MaxiterExceeded);
3003            }
3004            ConvergenceStatus::CpuTimeExceeded => {
3005                timing.check_convergence.end();
3006                return IterateOutcome::Terminate(SolverReturn::CpuTimeExceeded);
3007            }
3008            ConvergenceStatus::WallTimeExceeded => {
3009                timing.check_convergence.end();
3010                return IterateOutcome::Terminate(SolverReturn::WallTimeExceeded);
3011            }
3012            ConvergenceStatus::LocallyInfeasible => {
3013                timing.check_convergence.end();
3014                // gh #505: consult the acceptable-point stash, as the
3015                // restoration-cycle exits below already do (`:2686`, `:2716`,
3016                // both via `terminate_acceptable_or`). This arm used to return
3017                // without it, so a solve that had passed through an acceptable
3018                // iterate — stashed, un-vetoed, sitting there as a rollback
3019                // target — discarded it and surfaced the hard verdict instead.
3020                // The stashing code sits *after* this match, so the firing
3021                // iteration returns before it would even consider stashing;
3022                // only iterates from earlier in the solve are on offer, which
3023                // is exactly what a rollback target is.
3024                //
3025                // This is about what to *return* once the verdict has fired,
3026                // not about when it fires. Whether the rapid detector should
3027                // have convicted this point at all is a separate question,
3028                // answered by the violation floor in `OptErrorConvCheck`
3029                // (gh #519).
3030                //
3031                // Inert on genuinely infeasible models: `store_acceptable_point`
3032                // is gated on `current_is_acceptable_with_state`, which requires
3033                // `acceptable_tol` *and* the unscaled violation against
3034                // `acceptable_constr_viol_tol`, and the scale-relative veto
3035                // blocks the stash outright for a row violated relative to its
3036                // own magnitude. Nothing is stashed on such a model, so
3037                // `terminate_acceptable_or` falls through to the verdict
3038                // unchanged. `infeasible_models_are_never_reported_solved`
3039                // (`infeasible_status_tol_invariance.rs`) is the standing guard.
3040                //
3041                // That inertness rests entirely on the stash gate having no
3042                // iteration budget (gh #693). While it carried the certificate
3043                // veto's `VETO_MAX_EXTRA_ITERS`, a solve that took more than 60
3044                // blocked iterations to convict stashed the very point the veto
3045                // exists to reject and rolled back to it here — an infeasible
3046                // model reported `Solved_To_Acceptable_Level`. See
3047                // `issue_693_relative_infeasibility_stash.rs`.
3048                return self.terminate_local_infeasibility();
3049            }
3050            ConvergenceStatus::Failed => {
3051                timing.check_convergence.end();
3052                return IterateOutcome::Terminate(SolverReturn::InternalError);
3053            }
3054        }
3055
3056        // Stash the iterate if it satisfies the per-component
3057        // `acceptable_*_tol` triplet. Mirrors upstream
3058        // `IpBacktrackingLineSearch.cpp:282-289` — checked at the top
3059        // of every line-search call so the most recent acceptable
3060        // iterate is always available as a rollback target if
3061        // restoration later fails. The recorder feeds
3062        // `acceptable_obj_change_tol`'s stability cross-check on
3063        // subsequent iterates.
3064        if self
3065            .bundle
3066            .conv_check
3067            .current_is_acceptable_with_state(nlp_err, &self.data, &self.cq)
3068        {
3069            self.store_acceptable_point();
3070            let curr_f = self.cq.borrow().curr_f();
3071            self.bundle.conv_check.set_curr_acceptable_obj(curr_f);
3072            // pounce#250 follow-up: keep the *best* acceptable iterate, not just
3073            // the latest. `store_acceptable_point` overwrites unconditionally,
3074            // so once the dual-divergence guard diverts a solve the rollback
3075            // target drifts to whatever the diverted run last touched — which
3076            // may be far worse than a point already in hand. Recorded on every
3077            // acceptable iterate (including before any diversion) and read only
3078            // when the guard fired; see `honour_best_acceptable_after_dual_guard`.
3079            self.record_best_acceptable(curr_f);
3080        }
3081        timing.check_convergence.end();
3082
3083        // gh #534: a deferred restoration decline is a bet with a deadline.
3084        // Checked *after* the convergence check, so a strict certificate the
3085        // continuation reached in the meantime wins the bet rather than being
3086        // pre-empted by its own expiry; and after the acceptable stash, so a
3087        // continuation that ended somewhere better has been recorded before the
3088        // floor comparison reads it.
3089        if self.decline_deadline_iter.is_some_and(|d| iter_count > d) {
3090            return self.terminate_at_decline_floor();
3091        }
3092
3093        // gh #797: the negative-curvature escape is the same kind of bet, and
3094        // its deadline is checked in the same place and for the same reason —
3095        // after the convergence check, so a certificate the continuation
3096        // reached wins rather than being pre-empted by its own expiry.
3097        if self.neg_curv_deadline_iter.is_some_and(|d| iter_count > d) {
3098            return self.terminate_at_neg_curv_floor();
3099        }
3100
3101        // 3. Hessian update. Must run BEFORE `update_barrier_parameter`
3102        // so the adaptive-μ oracles (probing, quality-function) drive
3103        // their affine/centering solves against `W(curr_N)`, not the
3104        // stale `W(curr_{N-1})` left in `data.w` by the previous iter's
3105        // tail-end Hessian update. Upstream calls `UpdateHessian()`
3106        // first in every main-loop body (`IpIpoptAlg.cpp:386`); pounce
3107        // previously reordered this to the tail, which made iters 1+
3108        // pick μ from the prior iterate's Hessian on adaptive-mu +
3109        // quality-function — visible on CRESC50 as a catastrophic
3110        // early-iter divergence (theta=5.8e5 by iter 61 vs upstream
3111        // never entering restoration).
3112        timing.update_hessian.start();
3113        let _ = self.bundle.hess.update_hessian(&self.data, &self.cq);
3114        timing.update_hessian.end();
3115
3116        // 4. Barrier parameter. Pass nlp + search_dir through so the
3117        // adaptive μ oracles (probing, quality-function) can drive
3118        // their own affine-step solves; monotone ignores them.
3119        // Snapshot the tiny-step flag (set by the previous iteration's
3120        // tiny-step branch) and the entry mu — if μ can't reduce while
3121        // the flag is on, upstream `IpMonotoneMuUpdate.cpp:158-161`
3122        // throws TINY_STEP_DETECTED → STOP_AT_TINY_STEP, which we
3123        // realise as a clean termination here.
3124        //
3125        // Both updates terminate, by different routes (pounce#512).
3126        // Monotone has one throw site covering its whole update, so the
3127        // μ-unchanged comparison below reconstructs it exactly, gated on
3128        // `terminates_on_tiny_step()`. `IpAdaptiveMuUpdate.cpp` throws at
3129        // two specific sites (`:330-333`, `:377-380`) and merely fixes μ
3130        // and keeps iterating elsewhere, so the comparison would over-fire
3131        // there — on the no-bounds short-circuit, which returns before
3132        // upstream even reads the flag, and on a free-mode oracle that
3133        // re-picks the current μ. The adaptive update therefore raises
3134        // `request_tiny_step_stop` at its own two sites and opts out of
3135        // the comparison. (An earlier comment here claimed the adaptive
3136        // update never self-terminates; it does — `force_no_progress` is
3137        // what happens on the iterations that do *not* throw.)
3138        timing.update_barrier_parameter.start();
3139        let tiny_at_entry = self.data.borrow().tiny_step_flag;
3140        let mu_before = self.data.borrow().curr_mu;
3141        let mu_terminates_on_tiny = self.bundle.mu_update.terminates_on_tiny_step();
3142        let next_mu = self.bundle.mu_update.update_barrier_parameter(
3143            &self.data,
3144            &self.cq,
3145            self.nlp.as_ref(),
3146            self.search_dir.as_mut(),
3147        );
3148        self.data.borrow_mut().curr_mu = next_mu;
3149        timing.update_barrier_parameter.end();
3150
3151        // pounce#510 — line-search reset. Upstream's μ updates own a
3152        // `linesearch_` handle and call `linesearch_->Reset()` (which
3153        // clears the filter via `FilterLSAcceptor::Reset`,
3154        // `IpFilterLSAcceptor.cpp:524-532`) at four fixed points:
3155        // `IpAdaptiveMuUpdate.cpp:339` (fixed-mode decrease), `:386`
3156        // (free→fixed switch), `:431` (**unconditionally** on every
3157        // free-mode iteration, μ moved or not), and
3158        // `IpMonotoneMuUpdate.cpp:165` (after a monotone reduction).
3159        // Pounce's `MuUpdate` trait has no line-search handle, so each
3160        // update raises `request_ls_reset` at exactly those points and
3161        // we honour it here — the same plumbing `request_resto` uses
3162        // below.
3163        //
3164        // This used to be inferred from `next_mu != mu_before`. That
3165        // proxy is right for the monotone update but wrong for the
3166        // adaptive one, which resets every free-mode iteration
3167        // regardless of μ: whenever μ stayed numerically put (the
3168        // free-mode endgame, and any iteration after a restoration that
3169        // returns at the same μ) the filter kept entries computed
3170        // against a barrier parameter and an iterate the algorithm had
3171        // already left. On #505's reproducer that rejected every trial
3172        // step from α=2.4e-6 down to 1e-12 on the filter alone and
3173        // forced a spurious restoration.
3174        //
3175        // Both flags are consumed here, but the tiny-step stop is
3176        // answered first: at each of the two adaptive sites that raise
3177        // it, upstream's `TINY_STEP_DETECTED` throw sits *above* the
3178        // reset it would otherwise reach (`cpp:330-333` before `:339`,
3179        // `:377-380` before `:386`), so a terminating iteration never
3180        // resets the line search.
3181        let (tiny_step_stop_requested, ls_reset) = {
3182            let mut d = self.data.borrow_mut();
3183            let flags = (d.request_tiny_step_stop, d.request_ls_reset);
3184            d.request_tiny_step_stop = false;
3185            d.request_ls_reset = false;
3186            flags
3187        };
3188        if tiny_step_stop_requested
3189            || (tiny_at_entry
3190                && mu_terminates_on_tiny
3191                && (next_mu - mu_before).abs() < Number::EPSILON)
3192        {
3193            return IterateOutcome::Terminate(SolverReturn::StopAtTinyStep);
3194        }
3195        if ls_reset {
3196            self.bundle.line_search.reset();
3197        }
3198
3199        // pounce#58 — iterate-quality guard for the probing oracle.
3200        // The μ-update layer sets `request_resto` when the input
3201        // iterate is too corrupted for the probing rule to produce a
3202        // sane μ (see `mu/adaptive.rs` Probing dispatch). Restoration
3203        // re-initialises the multipliers and gives the outer loop a
3204        // clean iterate to continue from. When no restoration phase
3205        // is configured (embedded callers, tests), emit a one-line
3206        // notice and continue with the current μ — the guard has
3207        // already prevented the destabilising 4-order μ jump.
3208        let request_resto = {
3209            let mut d = self.data.borrow_mut();
3210            let f = d.request_resto;
3211            d.request_resto = false;
3212            // `start_with_resto` — upstream's "switch to the feasibility
3213            // restoration phase in the first iteration". It rides the
3214            // same request flag rather than adding a second path into
3215            // restoration, and it is consumed here so it fires exactly
3216            // once: `iter_count` is 0 only on the first pass, and
3217            // restoration advances it.
3218            f || (self.start_with_resto && d.iter_count == 0)
3219        };
3220        if request_resto {
3221            if self.restoration.is_some() {
3222                return self.invoke_restoration_debugged();
3223            } else {
3224                tracing::warn!(target: "pounce::algorithm",
3225                    "[POUNCE] probing-oracle iterate-quality guard fired \
3226                     at iter {}, but no restoration phase is configured; \
3227                     continuing with μ={:.3e}.",
3228                    self.data.borrow().iter_count,
3229                    next_mu,
3230                );
3231            }
3232        }
3233
3234        // Sub-iteration checkpoint: μ has been updated for this iteration.
3235        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::AfterBarrierUpdate) {
3236            return o;
3237        }
3238
3239        // 4b. `linear_system_scaling=slack-based` — refresh the
3240        //     iterate-dependent part of the augmented-system scaling
3241        //     before anything factorizes it.
3242        //
3243        //     The other scaling methods (Ruiz, MC19) derive their
3244        //     factors from the matrix they are handed and need nothing
3245        //     from here. Slack-based is a function of the iterate, and
3246        //     upstream's method reads `IpCq()` directly; pounce's
3247        //     scaling methods live in `pounce-linsol`, below the
3248        //     algorithm, so the value is computed here and pushed down.
3249        //     Inert unless the option selected it.
3250        self.push_slack_scaling();
3251
3252        // 5. Search direction. Skipped without an NLP + search_dir.
3253        // (Hessian was updated in step 3 above before the barrier-μ
3254        // oracle so that adaptive-μ uses W(curr_N), not stale W.)
3255        if let (Some(nlp), Some(sd)) = (self.nlp.as_ref(), self.search_dir.as_mut()) {
3256            timing.compute_search_direction.start();
3257            // Fields are declared `Empty` and filled by the linear
3258            // solver (matrix size, factor nnz, inertia, ordering — see
3259            // `pounce_feral::record_factor_stats`) and below
3260            // (regularization), so the `linear_solve` span carries the
3261            // KKT-solve characteristics for the JSON sink (pounce#71).
3262            let ls_span = tracing::info_span!(
3263                target: "pounce::linsol",
3264                "linear_solve",
3265                n = tracing::field::Empty,
3266                matrix_nnz = tracing::field::Empty,
3267                factor_nnz = tracing::field::Empty,
3268                inertia_neg = tracing::field::Empty,
3269                fill_ratio = tracing::field::Empty,
3270                ordering = tracing::field::Empty,
3271                regularization = tracing::field::Empty,
3272            );
3273            let ls_enter = ls_span.enter();
3274            let ok = sd.compute_search_direction(&self.data, &self.cq, nlp);
3275            ls_span.record("regularization", self.data.borrow().info_regu_x);
3276            // Within-span marker so the enriched `linear_solve` fields
3277            // (filled by the solver above) surface to the JSON sink at
3278            // debug level; off at the default `info` level.
3279            tracing::debug!(target: "pounce::linsol", "kkt solve complete");
3280            drop(ls_enter);
3281            timing.compute_search_direction.end();
3282            // Fine-grained time-budget gate (pounce#244). The KKT solve now
3283            // checks the shared deadline *between* its major factorization
3284            // steps (inertia correction / iterative refinement) and aborts
3285            // cooperatively when the budget is crossed — bounding the
3286            // overshoot to roughly one factorization instead of the whole
3287            // multi-factorization sweep that #242's post-solve check let run
3288            // to completion. Whether the solve returned a completed step or
3289            // bailed mid-escalation, if the deadline tripped, stop here with
3290            // the time-limit status *before* the `!ok` branch below would
3291            // otherwise route a deadline-aborted solve into restoration.
3292            // `data.curr` is untouched by the step computation, so it still
3293            // holds the last accepted iterate.
3294            if let Some(ret) = self.deadline_status() {
3295                return IterateOutcome::Terminate(ret);
3296            }
3297            if !ok {
3298                // Mirror upstream `IpIpoptAlg.cpp:417-430`: a failed
3299                // step computation puts the algorithm in emergency
3300                // mode, which calls `BacktrackingLineSearch::
3301                // ActivateFallbackMechanism` (cpp:1312-1328). When a
3302                // restoration phase is configured, the next pass of
3303                // `ComputeAcceptableTrialPoint` sees `goto_resto` at
3304                // cpp:299-306 and hands control to restoration. Only
3305                // when neither restoration nor an acceptor-level
3306                // fallback is available does upstream throw
3307                // `STEP_COMPUTATION_FAILED`.
3308                if self.restoration.is_some() {
3309                    // A non-finite Hessian (e.g. `|x|^2·|x|^0.85` evaluated
3310                    // at exactly `x = 0`: `0·∞` in the second derivative)
3311                    // fails the factorization before any inertia question
3312                    // is asked. Restoration is the right fallback — its
3313                    // Hessian drops the objective term and it moves `x`
3314                    // off the point — but the entry says nothing about a
3315                    // restoration cycle, so it must not be a gh#274 strike.
3316                    self.resto_entry_nonfinite_w = self
3317                        .data
3318                        .borrow()
3319                        .w
3320                        .as_ref()
3321                        .is_some_and(|w| !w.has_valid_numbers());
3322                    return self.invoke_restoration_debugged();
3323                }
3324                return IterateOutcome::Terminate(SolverReturn::ErrorInStepComputation);
3325            }
3326            if std::env::var_os("POUNCE_DBG_DELTA").is_some() {
3327                let d = self.data.borrow();
3328                let it = d.iter_count;
3329                if let Some(delta) = d.delta.as_ref() {
3330                    use crate::iterates_vector::IteratesVector;
3331                    use pounce_linalg::{Vector, compound_vector::CompoundVector};
3332                    let dv: &IteratesVector = delta;
3333                    tracing::debug!(target: "pounce::algorithm",
3334                        "[PN_DELTA] iter={} mu={:.6e} dx_amax={:.6e} ds_amax={:.6e} dyc_amax={:.6e} dyd_amax={:.6e} dzL_amax={:.6e} dzU_amax={:.6e} dvL_amax={:.6e} dvU_amax={:.6e}",
3335                        it, d.curr_mu,
3336                        dv.x.amax(), dv.s.amax(), dv.y_c.amax(), dv.y_d.amax(),
3337                        dv.z_l.amax(), dv.z_u.amax(), dv.v_l.amax(), dv.v_u.amax()
3338                    );
3339                    if let Some(cdx) = dv.x.as_any().downcast_ref::<CompoundVector>() {
3340                        tracing::debug!(target: "pounce::algorithm",
3341                            "[PN_DELTA] iter={} dx_blocks_amax: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3342                            it,
3343                            cdx.comp(0).amax(),
3344                            cdx.comp(1).amax(),
3345                            cdx.comp(2).amax(),
3346                            cdx.comp(3).amax(),
3347                            cdx.comp(4).amax(),
3348                        );
3349                        tracing::debug!(target: "pounce::algorithm",
3350                            "[PN_DELTA] iter={} dx_blocks_nrm2: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3351                            it,
3352                            cdx.comp(0).nrm2(),
3353                            cdx.comp(1).nrm2(),
3354                            cdx.comp(2).nrm2(),
3355                            cdx.comp(3).nrm2(),
3356                            cdx.comp(4).nrm2(),
3357                        );
3358                        tracing::debug!(target: "pounce::algorithm",
3359                            "[PN_DELTA] iter={} dx_blocks_asum: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3360                            it,
3361                            cdx.comp(0).asum(),
3362                            cdx.comp(1).asum(),
3363                            cdx.comp(2).asum(),
3364                            cdx.comp(3).asum(),
3365                            cdx.comp(4).asum(),
3366                        );
3367                        // Argmax of orig block via dot with sign — print first few values.
3368                        if let Some(dv_orig) =
3369                            cdx.comp(0)
3370                                .as_any()
3371                                .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
3372                        {
3373                            let v = dv_orig.values();
3374                            let mut imax = 0usize;
3375                            let mut amax = 0.0f64;
3376                            for (i, &x) in v.iter().enumerate() {
3377                                if x.abs() > amax {
3378                                    amax = x.abs();
3379                                    imax = i;
3380                                }
3381                            }
3382                            tracing::debug!(target: "pounce::algorithm",
3383                                "[PN_DELTA] iter={} dx_orig argmax: i={} v={:.17e} (n={})",
3384                                it,
3385                                imax,
3386                                v[imax],
3387                                v.len()
3388                            );
3389                        }
3390                    }
3391                    let p = &d.perturbations;
3392                    tracing::debug!(target: "pounce::algorithm",
3393                        "[PN_DELTA] iter={} pert: dx={:.6e} ds={:.6e} dc={:.6e} dd={:.6e}",
3394                        it, p.delta_x, p.delta_s, p.delta_c, p.delta_d
3395                    );
3396                    drop(d);
3397                    let cq = self.cq.borrow();
3398                    let gf = cq.curr_grad_f();
3399                    let gl = cq.curr_grad_lag_x();
3400                    let cc = cq.curr_c();
3401                    let cd = cq.curr_d_minus_s();
3402                    let sx = cq.curr_sigma_x();
3403                    let ss = cq.curr_sigma_s();
3404                    tracing::debug!(target: "pounce::algorithm",
3405                        "[PN_DELTA] iter={} cq: gradf_amax={:.6e} gradf_nrm2={:.6e} gradlag_amax={:.6e} gradlag_nrm2={:.6e} c_amax={:.6e} c_nrm2={:.6e} d_amax={:.6e} d_nrm2={:.6e} sigx_amax={:.6e} sigx_nrm2={:.6e} sigs_amax={:.6e} sigs_nrm2={:.6e}",
3406                        it,
3407                        gf.amax(), gf.nrm2(),
3408                        gl.amax(), gl.nrm2(),
3409                        cc.amax(), cc.nrm2(),
3410                        cd.amax(), cd.nrm2(),
3411                        sx.amax(), sx.nrm2(),
3412                        ss.amax(), ss.nrm2(),
3413                    );
3414                    if let Some(cgf) = gf.as_any().downcast_ref::<CompoundVector>() {
3415                        tracing::debug!(target: "pounce::algorithm",
3416                            "[PN_DELTA] iter={} gradf_blocks_amax: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3417                            it,
3418                            cgf.comp(0).amax(),
3419                            cgf.comp(1).amax(),
3420                            cgf.comp(2).amax(),
3421                            cgf.comp(3).amax(),
3422                            cgf.comp(4).amax(),
3423                        );
3424                    }
3425                    if let Some(curr) = self.data.borrow().curr.clone() {
3426                        tracing::debug!(target: "pounce::algorithm",
3427                            "[PN_DELTA] iter={} bound_mults: zL_amax={:.6e} zU_amax={:.6e} vL_amax={:.6e} vU_amax={:.6e} s_amax={:.6e} s_nrm2={:.6e} x_amax={:.6e} x_nrm2={:.6e}",
3428                            it,
3429                            curr.z_l.amax(), curr.z_u.amax(),
3430                            curr.v_l.amax(), curr.v_u.amax(),
3431                            curr.s.amax(), curr.s.nrm2(),
3432                            curr.x.amax(), curr.x.nrm2(),
3433                        );
3434                        if let Some(czl) = curr.z_l.as_any().downcast_ref::<CompoundVector>() {
3435                            tracing::debug!(target: "pounce::algorithm",
3436                                "[PN_DELTA] iter={} zL_blocks_amax: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3437                                it,
3438                                czl.comp(0).amax(),
3439                                czl.comp(1).amax(),
3440                                czl.comp(2).amax(),
3441                                czl.comp(3).amax(),
3442                                czl.comp(4).amax(),
3443                            );
3444                        }
3445                        if let Some(czu) = curr.z_u.as_any().downcast_ref::<CompoundVector>() {
3446                            tracing::debug!(target: "pounce::algorithm", "[PN_DELTA] iter={} zU_ncomps={}", it, czu.n_comps());
3447                            for ic in 0..czu.n_comps() {
3448                                tracing::debug!(target: "pounce::algorithm",
3449                                    "[PN_DELTA] iter={} zU_block[{}]_amax={:.6e} dim={}",
3450                                    it,
3451                                    ic,
3452                                    czu.comp(ic).amax(),
3453                                    czu.comp(ic).dim()
3454                                );
3455                            }
3456                        }
3457                    }
3458                    if let Some(csx) = sx.as_any().downcast_ref::<CompoundVector>() {
3459                        tracing::debug!(target: "pounce::algorithm",
3460                            "[PN_DELTA] iter={} sigx_blocks_amax: orig={:.6e} nc={:.6e} pc={:.6e} nd={:.6e} pd={:.6e}",
3461                            it,
3462                            csx.comp(0).amax(),
3463                            csx.comp(1).amax(),
3464                            csx.comp(2).amax(),
3465                            csx.comp(3).amax(),
3466                            csx.comp(4).amax(),
3467                        );
3468                    }
3469                    drop(cq);
3470                    let d = self.data.borrow();
3471                    // Also dump curr.x_orig argmax
3472                    if let Some(curr) = d.curr.as_ref() {
3473                        if let Some(cx) = curr.x.as_any().downcast_ref::<CompoundVector>() {
3474                            if let Some(xo) =
3475                                cx.comp(0)
3476                                    .as_any()
3477                                    .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
3478                            {
3479                                let v = xo.values();
3480                                let mut imax = 0usize;
3481                                let mut amax = 0.0f64;
3482                                for (i, &x) in v.iter().enumerate() {
3483                                    if x.abs() > amax {
3484                                        amax = x.abs();
3485                                        imax = i;
3486                                    }
3487                                }
3488                                tracing::debug!(target: "pounce::algorithm", "[PN_DELTA] iter={} curr_x_orig argmax: i={} v={:.17e} amax={:.17e} nrm2={:.17e}",
3489                                it, imax, v[imax], xo.amax(), xo.nrm2());
3490                            }
3491                        }
3492                    }
3493                }
3494            }
3495        }
3496
3497        // Capture KKT-factorization diagnostics for the debugger before
3498        // the line search runs. Only when a debugger is installed. The
3499        // inertia/status fields are cheap and always captured; the matrix
3500        // triplets and `LDLᵀ` factor are O(nnz) assemblies, so they're
3501        // captured only while the debugger is stepping (`wants_kkt_capture`)
3502        // — a detached/free-running debugger drops them to keep the run
3503        // cheap. `kkt_debug` is overwritten every iteration and never
3504        // cleared at `iter_start`, so a stepping session always has the
3505        // previous iteration's system to look back at via `viz kkt`/`viz L`.
3506        if let Some(hook) = self.debug.as_ref() {
3507            let capture_heavy = hook.borrow().wants_kkt_capture();
3508            let captured_iter = self.data.borrow().iter_count;
3509            let info = self.search_dir.as_ref().map(|sd| {
3510                let pd = sd.pd_solver_mut();
3511                let aug = pd.aug_solver();
3512                let provides = aug.provides_inertia();
3513                crate::ipopt_data::KktDebug {
3514                    iter: captured_iter,
3515                    dim: aug.system_dim(),
3516                    n_neg: if provides {
3517                        aug.number_of_neg_evals()
3518                    } else {
3519                        -1
3520                    },
3521                    provides_inertia: provides,
3522                    status: format!("{:?}", aug.last_solve_status()),
3523                    matrix: if capture_heavy {
3524                        aug.kkt_triplets()
3525                    } else {
3526                        None
3527                    },
3528                    l_factor: if capture_heavy {
3529                        aug.l_factor(true)
3530                    } else {
3531                        None
3532                    },
3533                }
3534            });
3535            self.data.borrow_mut().kkt_debug = info;
3536        }
3537
3538        // Sub-iteration checkpoint: the Newton step `δ` (data.delta) and
3539        // the applied regularization are now available, before the line
3540        // search consumes them.
3541        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::AfterSearchDirection) {
3542            return o;
3543        }
3544
3545        // Fine-grained time-budget gate (pounce#242). The KKT
3546        // factorization (and any inertia-correction / quality-escalation
3547        // refactorizations) is the single most expensive step of a large
3548        // solve, and it has just finished. Check the deadline here so an
3549        // over-budget solve returns its current best iterate *before*
3550        // spending a line search and another whole iteration — bounding
3551        // the overshoot to roughly one search-direction computation
3552        // instead of a full outer iteration. `data.curr` is untouched by
3553        // the step computation (the trial lives in `data.trial`), so it
3554        // still holds the last accepted iterate.
3555        if let Some(ret) = self.deadline_status() {
3556            return IterateOutcome::Terminate(ret);
3557        }
3558
3559        // 6. Acceptable trial point — run the line search if we have a
3560        //    primal/dual step on `data.delta`. Wrap in a guard so all
3561        //    early-return paths (ErrorInStepComputation, InternalError,
3562        //    restoration entry) still stop the timer.
3563        let _ls_guard = timing.compute_acceptable_trial_point.guard();
3564        let have_delta = self.data.borrow().delta.is_some();
3565        if have_delta {
3566            let delta = match self.data.borrow().delta.as_ref().cloned() {
3567                Some(d) => d,
3568                None => {
3569                    return IterateOutcome::Terminate(SolverReturn::ErrorInStepComputation);
3570                }
3571            };
3572            // Cap alpha by the primal fraction-to-the-boundary so the
3573            // first trial cannot push slacks past their bounds, and by
3574            // the dual FTB so bound multipliers stay positive. Mirrors
3575            // upstream `IpBacktrackingLineSearch::FindAcceptableTrialPoint`'s
3576            // calls to `IpCq.primal_frac_to_the_bound` /
3577            // `IpCq.dual_frac_to_the_bound` with τ = `curr_tau`.
3578            let tau = self.data.borrow().curr_tau;
3579            let alpha_p_max = self.cq.borrow().aff_step_alpha_primal_max(&delta, tau);
3580            let alpha_d_max = self.cq.borrow().aff_step_alpha_dual_max(&delta, tau);
3581
3582            // Tiny-step gate — port of `IpBacktrackingLineSearch.cpp:363`
3583            // and the handling block at lines 382-435. When the search
3584            // direction is so small that any nonzero α would just
3585            // bounce inside floating-point noise, take the FTB step
3586            // unchecked and skip the line search; that's the only way
3587            // to hit `STOP_AT_TINY_STEP` cleanly when the iterate is
3588            // already at a converged point but `nlp_error > tol` due to
3589            // scaling or unbounded duals.
3590            // gh#884 — record the direction's scale-relative magnitude for
3591            // the dual-divergence-retry signature. Done here, where `delta`
3592            // is already in hand, rather than recomputed at the gate.
3593            self.last_step_rel = self.scale_relative_step_max(&delta);
3594
3595            if self.detect_tiny_step(&delta) {
3596                let alpha_p = alpha_p_max;
3597                let alpha_d = alpha_d_max;
3598                let curr = match self.data.borrow().curr.clone() {
3599                    Some(c) => c,
3600                    None => return IterateOutcome::Terminate(SolverReturn::InternalError),
3601                };
3602                let trial_iv = scaled_step_unchecked(&curr, &delta, alpha_p, alpha_d);
3603                {
3604                    let mut d = self.data.borrow_mut();
3605                    d.set_trial(trial_iv);
3606                    d.info_alpha_primal = alpha_p;
3607                    d.info_alpha_dual = alpha_d;
3608                    d.info_ls_count = 0;
3609                    if self.tiny_step_last_iteration {
3610                        d.info_alpha_primal_char = 'T';
3611                        d.tiny_step_flag = true;
3612                    } else {
3613                        d.info_alpha_primal_char = 't';
3614                    }
3615                }
3616                let dy_amax = delta.y_c.amax().max(delta.y_d.amax());
3617                self.tiny_step_last_iteration = dy_amax < self.tiny_step_y_tol;
3618            } else {
3619                self.tiny_step_last_iteration = false;
3620                let alpha_init = self.alpha_init.min(alpha_p_max);
3621                let alpha_dual = self.alpha_init.min(alpha_d_max);
3622                let outcome = self.bundle.line_search.find_acceptable_trial_point(
3623                    &self.data,
3624                    &self.cq,
3625                    &delta,
3626                    alpha_init,
3627                    alpha_dual,
3628                    self.nlp.as_ref(),
3629                    self.search_dir.as_mut(),
3630                );
3631                match outcome {
3632                    Outcome::Accepted => {
3633                        // A normal LS-accepted step breaks any in-flight
3634                        // restoration cycle — clear the cycle detector
3635                        // so the next resto entry starts fresh.
3636                        self.last_resto_entry_x = None;
3637                        self.last_resto_entry_s = None;
3638                        self.last_resto_recovery_x = None;
3639                        self.last_resto_recovery_s = None;
3640                        self.resto_no_outer_progress_count = 0;
3641                        // Intentionally *not* clearing
3642                        // `resto_near_feasible_count` here: DECONVBNE's
3643                        // cycle interleaves R-recoveries with 2-3
3644                        // LS-accepted 'f'/'h' steps (which return
3645                        // `Outcome::Accepted` but accomplish no real
3646                        // outer progress — alpha drops to 1e-6 and
3647                        // inf_du remains pinned at 1.9e7), so resetting
3648                        // on every accept would zero the counter every
3649                        // cycle and never fire. The counter persists
3650                        // for the duration of the run and trips after
3651                        // 3 cumulative near-feasible entries; legitimate
3652                        // solves enter resto at most once at near-
3653                        // feasibility (POLAK6, HAIFAM) and stay under
3654                        // the limit.
3655                    }
3656                    Outcome::TinyStep | Outcome::Failed => {
3657                        // Debugger stop: the line search rejected the step
3658                        // (tiny-step floor or all backtracks failed), before
3659                        // we fall into restoration. Lets a "why did the line
3660                        // search give up?" inspection happen at the failing
3661                        // point distinctly from the restoration entry.
3662                        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::StepRejected) {
3663                            return o;
3664                        }
3665                        // Upstream `IpBacktrackingLineSearch.cpp` raises
3666                        // `LINE_SEARCH_FAILED` when α drops below
3667                        // `alpha_min` or all retries reject, which in
3668                        // turn triggers `ActivateLineSearch` →
3669                        // restoration.
3670                        return self.invoke_restoration_debugged();
3671                    }
3672                    Outcome::Deadline => {
3673                        // The time budget was crossed inside the line
3674                        // search (pounce#242). No trial was promoted, so
3675                        // `data.curr` still holds the best iterate; stop
3676                        // with the matching time-limit status. Re-derive
3677                        // wall vs CPU from the deadline (it can only still
3678                        // be exceeded — time is monotonic).
3679                        return IterateOutcome::Terminate(
3680                            self.deadline_status()
3681                                .unwrap_or(SolverReturn::WallTimeExceeded),
3682                        );
3683                    }
3684                }
3685            }
3686        }
3687
3688        // End the line-search/trial timer here so the bookkeeping in
3689        // steps 7-8 below is attributed to `accept_trial_point` (which
3690        // mirrors upstream's split: filter update and FTB reset are
3691        // accept-side, not line-search-side).
3692        _ls_guard.stop();
3693
3694        // 7. Accept trial point (promotes `trial` to `curr` if set).
3695        //    The acceptor's filter has already been augmented (when
3696        //    appropriate) inside `find_acceptable_trial_point` via
3697        //    `update_for_next_iteration`, mirroring upstream's call
3698        //    chain in `IpBacktrackingLineSearch.cpp:839`.
3699        let _accept_guard = timing.accept_trial_point.guard();
3700
3701        // 7a. Safe-slack bound adjustment. Before promoting `trial`, move
3702        //     any `x_L/x_U/d_L/d_U` whose trial slack fell below
3703        //     `eps*min(1,mu)` so the slack becomes representable (port of
3704        //     the bound-adjustment block in
3705        //     `IpoptAlgorithm::AcceptTrialPoint`, `IpIpoptAlg.cpp:664-706`).
3706        self.adjust_variable_bounds_for_small_slacks();
3707
3708        // An unreleased hand-back's shot is taken by the first step the
3709        // original globalization accepts (gh#1076); a soft-restoration `s`
3710        // step is accepted on the primal-dual error instead, because the
3711        // filter rejected it.
3712        if self.data.borrow().info_alpha_primal_char != 's' {
3713            self.unreleased_shot_pending = false;
3714            self.unreleased_shot_strikes = 0;
3715        }
3716        self.data.borrow_mut().accept_trial_point();
3717
3718        // 8. Bound multiplier kappa_sigma reset.
3719        self.correct_bound_multiplier();
3720
3721        // 8b. `recalc_y` — re-estimate the equality/inequality
3722        //     multipliers by least squares once the iterate is feasible
3723        //     enough (`IpIpoptAlg.cpp:AcceptTrialPoint`). Off unless the
3724        //     user asks; see `application.rs` for why we do not turn it
3725        //     on for L-BFGS the way upstream's option text says it does.
3726        //
3727        //     Ordering: this runs after the kappa_sigma reset. The two
3728        //     are not obviously independent — the least-square RHS is
3729        //     `−∇f + Pₗz_L − Pᵤz_U` (`IpLeastSquareMults.cpp:54`), so it
3730        //     reads the bound multipliers step 8 just corrected — but
3731        //     running the sweep with the two swapped produces a
3732        //     byte-identical corpus, so the coupling does not bite in
3733        //     practice. Kept here on the argument that `y` should be
3734        //     estimated against the multipliers the iteration actually
3735        //     ends with.
3736        self.maybe_recalc_y();
3737
3738        // 8c. Square-problem multipliers. `IpIpoptAlg.cpp:409` runs this
3739        //     between `AcceptTrialPoint` and the next `CheckConvergence`,
3740        //     on every iteration, for square problems only. pounce's
3741        //     `iterate()` boundary falls between those two — the outer
3742        //     loop bumps `iter_count` and the next `iterate()` opens with
3743        //     the convergence check — so this is the same slot, and the
3744        //     `+ 1` inside is that pending bump (upstream increments
3745        //     before the call, at `IpIpoptAlg.cpp:407`).
3746        if self.is_square_problem() {
3747            self.compute_feasibility_multipliers();
3748        }
3749
3750        // Sub-iteration checkpoint: the trial point was accepted; α and
3751        // the new iterate are in place (before the loop's iter bookkeeping
3752        // and the next `IterStart`).
3753        drop(_accept_guard);
3754        if let Some(o) = self.debug_stop(crate::debug::Checkpoint::AfterStep) {
3755            return o;
3756        }
3757
3758        IterateOutcome::Continue
3759    }
3760
3761    /// `max(max_i |δx_i|/(1+|x_i|), max_i |δs_i|/(1+|s_i|))` — the same
3762    /// scale-relative measure [`Self::detect_tiny_step`] thresholds, kept
3763    /// as a magnitude.
3764    ///
3765    /// Scale-relative rather than a bare `‖d‖` on purpose: a bare norm is
3766    /// a length in the model's units, so on a badly scaled model it says
3767    /// more about the units than about whether the iterate has stopped
3768    /// moving. gh#884's signature needs the latter.
3769    fn scale_relative_step_max(&self, delta: &crate::iterates_vector::IteratesVector) -> Number {
3770        let curr = match self.data.borrow().curr.clone() {
3771            Some(c) => c,
3772            None => return Number::INFINITY,
3773        };
3774
3775        let mut tmp = curr.x.make_new_copy();
3776        tmp.element_wise_abs();
3777        tmp.add_scalar(1.0);
3778        let mut tmp2 = delta.x.make_new_copy();
3779        tmp2.element_wise_divide(&*tmp);
3780        let mut worst = tmp2.amax();
3781
3782        if curr.s.dim() > 0 {
3783            let mut tmp = curr.s.make_new_copy();
3784            tmp.element_wise_abs();
3785            tmp.add_scalar(1.0);
3786            let mut tmp2 = delta.s.make_new_copy();
3787            tmp2.element_wise_divide(&*tmp);
3788            worst = worst.max(tmp2.amax());
3789        }
3790        worst
3791    }
3792
3793    /// Whether this solve ever saw gh#884's dual-divergence-at-a-settled-primal
3794    /// signature. Sticky; see [`Self::dual_divergence_signature`].
3795    pub fn dual_divergence_signature(&self) -> bool {
3796        self.dual_divergence_signature
3797    }
3798
3799    /// Whether this solve ended on the gh#1042 exit: the outer re-entered
3800    /// restoration from an unreleased converged-to-feasible hand-back
3801    /// without leaving it. Read by the second-opinion ladder, which opens
3802    /// its `mu_strategy=adaptive` rung on that `Restoration_Failed` and on
3803    /// no other (see `SecondOpinionTrigger::UnreleasedHandback`).
3804    pub fn unreleased_handback_exit(&self) -> bool {
3805        self.unreleased_handback_exit
3806    }
3807
3808    /// gh#990 item 13: whether a strict termination certificate was refused
3809    /// because the objective scaling masked it (sticky for the solve).
3810    pub fn obj_scale_certificate_refused(&self) -> bool {
3811        self.vetoed_seen
3812    }
3813
3814    /// Same, for an acceptable-level certificate.
3815    pub fn obj_scale_acceptable_refused(&self) -> bool {
3816        self.vetoed_acceptable_seen
3817    }
3818
3819    /// Port of `IpBacktrackingLineSearch::DetectTinyStep`
3820    /// (`IpBacktrackingLineSearch.cpp:1219-1278`). Returns true iff
3821    /// `max_i |δx_i|/(1+|x_i|) ≤ tiny_step_tol`,
3822    /// `max_i |δs_i|/(1+|s_i|) ≤ tiny_step_tol`, AND
3823    /// `curr_constraint_violation ≤ 1e-4`. Disabled when
3824    /// `tiny_step_tol == 0`.
3825    fn detect_tiny_step(&self, delta: &crate::iterates_vector::IteratesVector) -> bool {
3826        if self.tiny_step_tol == 0.0 {
3827            return false;
3828        }
3829        let curr = match self.data.borrow().curr.clone() {
3830            Some(c) => c,
3831            None => return false,
3832        };
3833
3834        // |x_i|+1
3835        let mut tmp = curr.x.make_new_copy();
3836        tmp.element_wise_abs();
3837        tmp.add_scalar(1.0);
3838        // |δx_i|/(|x_i|+1) ; checked via Amax of (δx ./ (|x|+1)).
3839        let mut tmp2 = delta.x.make_new_copy();
3840        tmp2.element_wise_divide(&*tmp);
3841        if tmp2.amax() > self.tiny_step_tol {
3842            return false;
3843        }
3844
3845        if curr.s.dim() > 0 {
3846            let mut tmp = curr.s.make_new_copy();
3847            tmp.element_wise_abs();
3848            tmp.add_scalar(1.0);
3849            let mut tmp2 = delta.s.make_new_copy();
3850            tmp2.element_wise_divide(&*tmp);
3851            if tmp2.amax() > self.tiny_step_tol {
3852                return false;
3853            }
3854        }
3855
3856        let cviol = self.cq.borrow().curr_constraint_violation();
3857        if cviol > 1e-4 {
3858            return false;
3859        }
3860        true
3861    }
3862
3863    /// Re-anchor the quasi-Newton model instead of handing off to
3864    /// restoration, when the line search has failed at a point
3865    /// restoration cannot improve (gh#818). Returns `true` if the model
3866    /// was re-anchored, in which case the caller retries this iterate.
3867    ///
3868    /// **The two failures the line search cannot tell apart.** When no
3869    /// trial step is acceptable, either the *point* is bad — infeasible,
3870    /// and restoration is exactly the right tool — or the *direction* is,
3871    /// because `W` is a quasi-Newton model carrying curvature the iterate
3872    /// has left behind. Upstream has one answer for both, because
3873    /// restoration is the only fallback it has. At an already-feasible
3874    /// point that answer is a no-op: the restoration NLP minimizes the
3875    /// constraint violation, and there is none to minimize, so it wanders
3876    /// at `theta ~ 1e-13` and reports `Restoration_Failed`.
3877    ///
3878    /// Measured on the `deb7` fixture under `limited-memory`: the solve
3879    /// stalls with `inf_pr ~ 1e-12` and `inf_du ~ 1e5`, enters
3880    /// restoration at a point feasible to 8e-13, and spends 340 of its
3881    /// 1242 iterations there before failing. On the unconstrained
3882    /// gh#818 quadratic under `alpha_red_factor 0.8` it is starker
3883    /// still — `theta` is identically zero, so restoration cannot move
3884    /// at all, and the solve dies at **iteration 1** with
3885    /// `Error_In_Step_Computation` and the objective still at its
3886    /// starting value.
3887    ///
3888    /// So this is a rung, not a refusal: it fires only where restoration
3889    /// has nothing to reduce, it is bounded, and every path that reached
3890    /// restoration before still reaches it once the rung is spent.
3891    ///
3892    /// **Deliberately *after* the acceptable-point decline.** The call
3893    /// site is inside [`Self::invoke_restoration`], immediately behind
3894    /// that decline, and not at the `Outcome::Failed` arm in
3895    /// [`Self::iterate`] where the hand-off is decided — `eigena2` and
3896    /// `csfi2` reach the hand-off at feasible points that already pass
3897    /// the acceptable tolerances, and those must go on being reported
3898    /// rather than re-anchored and continued. Being inside
3899    /// `invoke_restoration` means the `PreRestoration` debug checkpoint
3900    /// fires ahead of a rung that then does not enter restoration; that
3901    /// is the price of the ordering and is the checkpoint's documented
3902    /// meaning ("just before entry"), not a promise that entry follows.
3903    ///
3904    /// **And deliberately not a feasibility gate on restoration itself.**
3905    /// That was tried and rejected before (see the `constr_viol_tol`
3906    /// paragraph in [`Self::invoke_restoration`]): feasible entries are
3907    /// ordinary, and nothing observable at the doorway separates a
3908    /// restoration that recovers from one that does not. This rung does
3909    /// not decide that question — it spends one cheap retry on the
3910    /// hypothesis that the model, not the point, is at fault, and hands
3911    /// over unchanged if the retry fails too.
3912    ///
3913    /// The bound is structural as well as counted. `reanchor` returns
3914    /// `false` once the history is down to its newest pair, so a second
3915    /// failure at the same iterate finds nothing to give up and falls
3916    /// through; refilling the history takes accepted steps, so the
3917    /// counter only advances once per genuine stall.
3918    /// `limited_memory_ls_failure_restarts` caps the total.
3919    fn try_reanchor_before_restoration(&mut self) -> bool {
3920        if self.lbfgs_ls_failure_restarts == 0
3921            || self.lbfgs_ls_restarts_used >= self.lbfgs_ls_failure_restarts
3922        {
3923            return false;
3924        }
3925        // Restoration's objective is the constraint violation. Only
3926        // stand in front of it where that objective is already at its
3927        // floor, so the rung can never pre-empt a restoration that had
3928        // real work to do. `constr_viol_tol` is the same tolerance the
3929        // convergence check calls feasible.
3930        let theta = self.cq.borrow().curr_constraint_violation();
3931        if !(theta <= self.bundle.conv_check.constr_viol_tol_or_default()) {
3932            return false;
3933        }
3934        if !self.bundle.hess.reanchor() {
3935            return false;
3936        }
3937        self.lbfgs_ls_restarts_used += 1;
3938        // 'Wa' alongside the updater's own 'Wr' (the
3939        // `limited_memory_max_skipping` reset), so the two re-anchorings
3940        // are distinguishable in the iteration table rather than both
3941        // reading as "the Hessian did something".
3942        self.data.borrow_mut().append_info_string("Wa");
3943        tracing::debug!(target: "pounce::algorithm",
3944            "[POUNCE] line search failed at a feasible point (theta {:.3e}); re-anchoring \
3945             the limited-memory Hessian on its newest curvature pair and retrying instead \
3946             of entering restoration, which has nothing to reduce here (gh#818). \
3947             Restart {} of {}.",
3948            theta, self.lbfgs_ls_restarts_used, self.lbfgs_ls_failure_restarts,
3949        );
3950        true
3951    }
3952
3953    /// Drive the restoration phase after a line-search failure.
3954    /// Returns `IterateOutcome::Continue` if the restoration driver
3955    /// recovered (the algorithm carries on from the recovered iterate);
3956    /// otherwise terminates with [`SolverReturn::RestorationFailure`].
3957    /// Mirrors upstream's
3958    /// `IpBacktrackingLineSearch::ActivateLineSearch` → `PerformRestoration`
3959    /// chain.
3960    fn invoke_restoration(&mut self) -> IterateOutcome {
3961        // Consumed on every entry, whichever exit below is taken, so a
3962        // flag set by one entry can never exempt a later one.
3963        let entry_nonfinite_w = std::mem::take(&mut self.resto_entry_nonfinite_w);
3964        // Snapshot the outer reference iterate's `(theta, barr)` and
3965        // build the orig-progress callback the inner IPM will consult
3966        // at every iteration (mirrors upstream
3967        // `IpRestoFilterConvCheck::SetOrigLSAcceptor` plus
3968        // `IpFilterLSAcceptor::Reset`'s `reference_*_` snapshot).
3969        let reference_theta = self.cq.borrow().curr_constraint_violation();
3970        let reference_barr = self.cq.borrow().curr_barrier_obj();
3971
3972        if std::env::var("POUNCE_DBG_RESTO").is_ok() {
3973            let iter = self.data.borrow().iter_count;
3974            tracing::debug!(target: "pounce::algorithm",
3975                "RESTO_ENTRY iter={} theta={:.6e} barr={:.6e} near_feas_ct={}",
3976                iter, reference_theta, reference_barr, self.resto_near_feasible_count,
3977            );
3978        }
3979
3980        // Port gap: upstream refuses to enter restoration from an acceptable
3981        // point, and this was missing. `IpBacktrackingLineSearch.cpp:557-570`,
3982        // in the `if (!accept)` arm that hands off to restoration:
3983        //
3984        //     if( CurrentIsAcceptable() )
3985        //     {
3986        //        THROW_EXCEPTION(ACCEPTABLE_POINT_REACHED,
3987        //                        "Restoration phase called at acceptable point.");
3988        //     }
3989        //
3990        // The rationale is the obvious one: restoration reduces the constraint
3991        // violation, so from a point that already passes the acceptable-level
3992        // tolerances it has nothing to reduce, and entering can only risk a
3993        // reportable solution.
3994        //
3995        // What the gap cost, measured on mittelmann `qcqp1000-1nc` (n=1000):
3996        // the line search fails at iteration 187 on a point carrying the
3997        // published optimum (`-2.6628866e+07`, matching ipopt-ma57 to 9
3998        // significant figures) with overall NLP error `6.0e-8` — two orders
3999        // inside `acceptable_tol`. Restoration walked it to `theta 5e-3` and
4000        // ground out 2780 further iterations without recovering, so a solved
4001        // problem reported a failure.
4002        //
4003        // The predicate is upstream's, unmodified: acceptability alone. A
4004        // strict `constr_viol_tol` gate was tried on top and is both a
4005        // deviation and useless — at their restoration entries `qcqp1000-1nc`
4006        // sits at `theta = 6.0e-8`, `csfi2` at `1.5e-7`, `eigena2` at
4007        // `2.1e-10`, all strictly feasible, one by six orders. Nothing
4008        // observable at the doorway separates a restoration that recovers from
4009        // one that does not, which is why upstream does not try to.
4010        //
4011        // Placed ahead of the cycle detectors below rather than beside
4012        // upstream's `PrepareRestoPhaseStart()`: those detectors are a
4013        // pounce-side addition, and an acceptable point should be reported
4014        // regardless of cycle state. Filter augmentation is skipped on this
4015        // path, which is immaterial — the run stops here.
4016        //
4017        // `current_is_acceptable_with_state` is the full triplet, never
4018        // `theta` alone: gh #274, a perfectly feasible point can be
4019        // arbitrarily far from stationary (`min -exp(x) s.t. x >= 0` reaches
4020        // here with `inf_pr = 1.7e-10` and `inf_du = 8.8e+47`), and the
4021        // triplet carries `acceptable_dual_inf_tol` to reject it. The
4022        // finiteness check mirrors the one below (CUTE `himmelbj` reaches a
4023        // near-feasible point where `f` evaluates to NaN) and matches
4024        // upstream's own `curr_f` precondition for acceptability.
4025        let (entry_f_finite, entry_nlp_err) = {
4026            let cq = self.cq.borrow();
4027            (cq.curr_f().is_finite(), cq.curr_nlp_error())
4028        };
4029        //
4030        // What the guard still did not ask is whether the solve was *converging*
4031        // (gh #534). It reads the entry point and nothing about the trajectory
4032        // that reached it, so it stops a contracting endgame and a dead stall
4033        // with equal confidence. On `eigena2` it fires while the dual
4034        // infeasibility is quartering every iteration on unit steps
4035        // (`1.19e-5 → 2.96e-6 → 7.38e-7 → 1.84e-7`), three iterations short of a
4036        // strict certificate that costs nothing but those three iterations.
4037        // [`Self::may_defer_acceptable_decline`] adds that missing question,
4038        // and only that: when the answer is no — `eigenb2`'s tail rises, and
4039        // `csfi2`'s last two iterations are flat to three digits — the guard
4040        // fires exactly as before.
4041        if entry_f_finite
4042            && self.bundle.conv_check.current_is_acceptable_with_state(
4043                entry_nlp_err,
4044                &self.data,
4045                &self.cq,
4046            )
4047        {
4048            if self.may_defer_acceptable_decline() {
4049                tracing::debug!(target: "pounce::algorithm",
4050                    "[POUNCE] deferring the restoration decline at theta {:.3e}: the entry \
4051                     point passes the acceptable-level tolerances (nlp_err {:.3e}) but the \
4052                     NLP error has contracted every iteration over the last {} \
4053                     ({:.3e} -> {:.3e}); continuing for up to {} iterations, with that point \
4054                     held as the floor (gh #534).",
4055                    reference_theta, entry_nlp_err, DECLINE_PROGRESS_SAMPLES - 1,
4056                    self.nlp_err_recent[0], entry_nlp_err, DECLINE_CONTINUATION_BUDGET,
4057                );
4058            } else {
4059                // The window is on the line because "why did the guard not
4060                // defer?" is the first question anyone reading this trace has
4061                // (gh #534), and reconstructing it from the iteration table
4062                // means recomputing the scaled aggregate by hand.
4063                tracing::debug!(target: "pounce::algorithm",
4064                    "[POUNCE] declining restoration at theta {:.3e}: the entry point already \
4065                     passes the acceptable-level tolerances (nlp_err {:.3e}); reporting it \
4066                     rather than risking it in restoration. Recent NLP errors {} \
4067                     (contracting: {}).",
4068                    reference_theta, entry_nlp_err,
4069                    self.nlp_err_window_str(), self.nlp_err_contracting(),
4070                );
4071                return IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint);
4072            }
4073        }
4074
4075        // gh#818 — one rung before the hand-off proper: re-anchor the
4076        // quasi-Newton model and retry this iterate. Placed *here*, and
4077        // not at the `Outcome::Failed` arm in `iterate`, because it has
4078        // to run behind the acceptable-point decline above: `eigena2`
4079        // and `csfi2` arrive at feasible points that already pass the
4080        // acceptable tolerances, and those must go on being reported
4081        // rather than re-anchored and continued. The gh#534 deferral
4082        // path falls through to here, which is the right order too —
4083        // the deferral has already captured its floor, so a rung taken
4084        // under a live deferral is protected by it.
4085        if self.try_reanchor_before_restoration() {
4086            return IterateOutcome::Continue;
4087        }
4088
4089        // No-progress restoration cycle detector. Two layered checks
4090        // surface as `ErrorInStepComputation` instead of cycling to
4091        // `max_iter` exhaustion (mirrors the *intent* of upstream
4092        // `IpBacktrackingLineSearch.cpp:580-600`'s almost-feasible
4093        // resto guard):
4094        //
4095        // 1. *Static cycle*: entry-to-entry — when the curr `(x, s)`
4096        //    at this entry is essentially identical to the snapshot
4097        //    from the previous entry, the inner resto-IPM is
4098        //    returning recovered iterates indistinguishable from
4099        //    entry, AND the outer didn't move either. Fires
4100        //    immediately. Catches QCNEW, EQC, MESH, POLAK6, S365,
4101        //    S365MOD, SIPOW2M, PFIT4.
4102        //
4103        // 2. *Slow-progress cycle*: recovery-to-entry — when curr at
4104        //    this entry is essentially identical to the *recovery*
4105        //    iterate from the previous resto, the outer made no
4106        //    progress between resto invocations even though resto's
4107        //    inner moved substantively. Counted, fires after 5
4108        //    consecutive entries. Catches ACOPR14, ACOPR30, TRO3X3
4109        //    while letting MAKELA3, HAIFAM, HALDMADS, ROBOT,
4110        //    TENBARS2 — which need 2-3 productive resto entries
4111        //    before LS accepts — pass through.
4112        //
4113        // A productive single-restoration sequence (BT8, HIMMELBJ,
4114        // LINSPANH, LSNNODOC, ODFITS, OET3) clears both snapshots via
4115        // `Outcome::Accepted` between entries and is unaffected.
4116        let curr = self
4117            .data
4118            .borrow()
4119            .curr
4120            .as_ref()
4121            .expect("curr set before invoke_restoration")
4122            .clone();
4123        // Helper: when the cycle detector fires and the orig cv is a
4124        // violation the *user* calls a violation (e.g. PFIT1's 2.73e-2),
4125        // the outer is stuck at a feasibility-stationary point and the
4126        // honest exit is `LocalInfeasibility`. Below that threshold the
4127        // iterate is primal-feasible by the user's own declaration, so there
4128        // is no infeasibility to certify — the failure is numerical, not
4129        // algorithmic, and `ErrorInStepComputation` is retained.
4130        //
4131        // The threshold is `constr_viol_tol`, and *only* `constr_viol_tol`
4132        // (gh #508). The question this ternary asks — "is this violation
4133        // real?" — is a question about the constraint violation, so it has to
4134        // be asked with the option that declares what a violated constraint
4135        // is. The previous form, `max(100·tol, 1e-4)`, was built from `tol`, a
4136        // tolerance on the **KKT error**: different quantity, different units,
4137        // and it never consulted `constr_viol_tol` at all. Two consequences,
4138        // both measured on `min (x-5)² s.t. x²+δ = 0` (infeasible for every
4139        // δ>0, reported violation exactly δ):
4140        //
4141        //   * sweeping `constr_viol_tol` over four orders moved the boundary
4142        //     not at all — at `constr_viol_tol = 1e-3` a violation of `1e-4`,
4143        //     comfortably inside the user's declared feasibility tolerance,
4144        //     still exited 500;
4145        //   * sweeping `tol` moved it a great deal, and in the wrong
4146        //     direction: at `tol = 1e-4` the `1e-2` threshold swallowed every
4147        //     δ from `3e-4` to `1e-2` — a model infeasible by a full percent
4148        //     answered "your solver broke". Loosening `tol` is the standard
4149        //     user reaction to a struggling solve, so the failure widened
4150        //     exactly when the user tried to help.
4151        //
4152        // No `infeas_viol_kappa` margin on top, unlike the rapid-infeasibility
4153        // pre-filter in `conv_check`. That detector fires *during* the solve
4154        // off a streak heuristic and needs the margin to avoid convicting an
4155        // iterate that is still converging; here restoration has already
4156        // demonstrably cycled, so the certainty comes from the cycle evidence
4157        // rather than from extra violation headroom. Widening to
4158        // `kappa·constr_viol_tol` would move the default threshold from `1e-4`
4159        // to `1e-2` and hand back 500 on the whole band in between.
4160        //
4161        // The comparison is `>=`, not `>`. A violation landing exactly on the
4162        // threshold is a violation at the user's declared tolerance, and the
4163        // reproducer above hits the boundary to the digit (`δ = 1e-4` at the
4164        // default `constr_viol_tol`), where `>` returned 500 for a model
4165        // infeasible by precisely the amount the user said was too much.
4166        //
4167        // The violation is measured **unscaled**. `reference_theta` is the
4168        // row-scaled residual, but the floor below is an absolute, user-facing
4169        // magnitude, so comparing the two mixes unit systems — and on a problem
4170        // whose rows are scaled down the scaled residual can never clear it.
4171        // `infeasible_equalities.nl` is the worked example: a square 2x2 system
4172        // with a true violation of 2.0 that NLP scaling reports as 6.67e-7, so
4173        // this test read `6.67e-7 > 1e-4` = false and a blatantly infeasible
4174        // model exited `Error_In_Step_Computation` (AMPL 500, Pyomo
4175        // `internalSolverError`). Square problems have no restoration-side
4176        // locally-infeasible gate — `strict` carves them out so the outer gets
4177        // another shot — so this cycle exit *is* their safety net, and it was
4178        // disabled by the unit mismatch. Same user-visible family as gh #372.
4179        //
4180        // Note this also moves from a 1-norm (`curr_constraint_violation`) to a
4181        // max-norm. Max-norm <= 1-norm, so the test is marginally stricter
4182        // about declaring infeasibility on an unscaled problem — the safe
4183        // direction for a verdict this consequential.
4184        //
4185        // `theta > 0` in front of the `>=` is not redundant: the options layer
4186        // registers `constr_viol_tol` with a *strict* lower bound of zero, but
4187        // a library embedder setting `ConvCheckOptions` directly is not bound
4188        // by that, and `0 >= 0` would turn an exactly-feasible iterate into an
4189        // infeasibility certificate. A zero violation never proves anything.
4190        let cycle_viol_tol = self.bundle.conv_check.constr_viol_tol_or_default();
4191        let reference_theta_unscaled = self.cq.borrow().curr_unscaled_primal_infeasibility_max();
4192        let cycle_exit =
4193            if reference_theta_unscaled > 0.0 && reference_theta_unscaled >= cycle_viol_tol {
4194                SolverReturn::LocalInfeasibility
4195            } else {
4196                SolverReturn::ErrorInStepComputation
4197            };
4198        let static_cycle = if let (Some(prev_x), Some(prev_s)) = (
4199            self.last_resto_entry_x.as_ref(),
4200            self.last_resto_entry_s.as_ref(),
4201        ) {
4202            let dx_rel = relative_distance(&*curr.x, &**prev_x);
4203            let ds_rel = relative_distance(&*curr.s, &**prev_s);
4204            if std::env::var_os("POUNCE_DBG_RESTO_CYCLE").is_some() {
4205                tracing::debug!(target: "pounce::algorithm",
4206                    "[PN_RESTO_CYCLE] entry-vs-entry dx_rel={:.6e} ds_rel={:.6e}",
4207                    dx_rel, ds_rel
4208                );
4209            }
4210            dx_rel <= 1e-10 && ds_rel <= 1e-10
4211        } else {
4212            false
4213        };
4214        if static_cycle {
4215            // Prefer the last acceptable point over the cycle error —
4216            // the borrows above are released, so the `&mut self` helper
4217            // is free to roll back.
4218            return self.terminate_acceptable_or(cycle_exit);
4219        }
4220        let recovery_cycle = if let (Some(prev_x), Some(prev_s)) = (
4221            self.last_resto_recovery_x.as_ref(),
4222            self.last_resto_recovery_s.as_ref(),
4223        ) {
4224            let dx_rel = relative_distance(&*curr.x, &**prev_x);
4225            let ds_rel = relative_distance(&*curr.s, &**prev_s);
4226            if std::env::var_os("POUNCE_DBG_RESTO_CYCLE").is_some() {
4227                tracing::debug!(target: "pounce::algorithm",
4228                    "[PN_RESTO_CYCLE] entry-vs-recovery dx_rel={:.6e} ds_rel={:.6e} count={}",
4229                    dx_rel, ds_rel, self.resto_no_outer_progress_count
4230                );
4231            }
4232            dx_rel <= 1e-10 && ds_rel <= 1e-10
4233        } else {
4234            false
4235        };
4236        // A handed-back converged-to-feasible point the outer could not
4237        // leave (gh#1042). Restoration ended a previous call on upstream's
4238        // `RESTORATION_CONVERGED_TO_FEASIBLE_POINT` condition: layer 2's
4239        // `ConvergedToFeasiblePoint` verdict (`IpRestoConvCheck.cpp:227-234`)
4240        // or an inner stop at its acceptable level with the original NLP
4241        // feasible to `1e2·tol` (`IpRestoMinC_1Nrm.cpp:278-287`). Either
4242        // way the point was feasible but never released by layer 1 — the
4243        // outer filter rejected it, or it did not cut the violation by
4244        // `kappa_resto`. Upstream fails restoration right there; pounce
4245        // hands the point back to give the outer phase one shot from it,
4246        // which paid on the `dallas*` family (every hand-back there is
4247        // followed by accepted steps, soft-restoration ones included).
4248        // Since the `.nl` reader merges `|x|^2·|x|^0.85` (gh#1042 R3),
4249        // `dallasl` and `dallasm` never enter restoration on either leg
4250        // and `dallass` hands back once, on L-BFGS only; the hand-backs
4251        // above survive in `tests/data/dallass_kink_unmerged.nl`.
4252        //
4253        // The shot was not taken when the outer asks for restoration again
4254        // from that very point. That is either no accepted step at all, or
4255        // steps a watchdog rolled back — so this compares positions, not
4256        // `Outcome::Accepted`. A soft-restoration step moves the iterate and
4257        // so counts as taking the shot (`dallasl`: `s s S`, then converges).
4258        //
4259        // One strike is the whole budget, and that is what separates this
4260        // from the 10-strike counter below. That counter's recoveries were
4261        // *released* — layer 1 judged them acceptable to the outer filter —
4262        // so a few immediate re-entries can still be the outer working its
4263        // way out (OET7). These were not; restoration has certified it cannot
4264        // do better than this point and the outer has shown it cannot leave
4265        // it. This is the upstream verdict, one restoration late.
4266        //
4267        // An entry forced by a non-finite Hessian is exempt, as it is from
4268        // the gh#274 strike below: the factorization rejected `W` before the
4269        // outer could try a step, so it says nothing about being stuck.
4270        //
4271        // The status is upstream's: `IpIpoptAlg.cpp:480-493` maps this
4272        // exception to `RESTORATION_FAILURE` on a non-square problem, and it
4273        // goes through the acceptable-point rollback the sibling exits use.
4274        // One refinement, and it is the gh#508 rule rather than a new one:
4275        // "feasible" in layer 2 means `θ ≤ 1e2·tol`, a KKT tolerance, and
4276        // under a loose `tol` that admits a point the *user's*
4277        // `constr_viol_tol` calls violated. Measured: `issue_508`'s
4278        // `min (x−5)² s.t. x²+δ = 0` at `tol=1e-3`, `δ = 1e-4` reaches this
4279        // exit at a violation of exactly `1e-4`, and the honest verdict there
4280        // is `Infeasible_Problem_Detected`, not AMPL 500. So the same
4281        // unscaled-vs-`constr_viol_tol` test `cycle_exit` uses picks the
4282        // infeasible arm; below it, the point is feasible by the user's own
4283        // declaration and the failure is restoration's. A point the user calls
4284        // feasible is never certified infeasible here. A square problem never
4285        // gets here — its feasible point leaves restoration as
4286        // `FeasiblePointFound`.
4287        //
4288        // The exit also sets `unreleased_handback_exit`, which the
4289        // second-opinion ladder reads: this `Restoration_Failed`, and no other,
4290        // opens `mu_strategy=adaptive` ahead of the displaced start
4291        // (`SecondOpinionTrigger::UnreleasedHandback`). Before the status was
4292        // upstream's, this exit reported `Error_In_Step_Computation`, whose one
4293        // rung is adaptive, and that rung is what recovered brainpc0/1/2.
4294        //
4295        // Measured on Vanderbei brainpc1 (FERAL 0.21): the first such
4296        // re-entry is outer iteration 378, after 13 restoration calls;
4297        // without this exit the solve ran 39 more, to 1073. brainpc0: 956
4298        // after 31 calls, against 2117 after 121.
4299        //
4300        // **The shot not taken, away from the point (gh#1076).** Comparing
4301        // positions catches an outer that cannot move. It misses one that
4302        // moves only on soft-restoration `s` steps — accepted on the
4303        // primal-dual error *because* the original filter rejects them —
4304        // and drifts back into restoration from somewhere else. That is the
4305        // same verdict: no step the outer's own globalization accepts was
4306        // ever taken from the hand-back. It became the common case once the
4307        // release test read the filter's real quantities (#1075): Vanderbei
4308        // brainpc0 then hands back a point at f ≈ 8e5 against a filter
4309        // holding f ≈ 0.38, takes `s s s` back to f ≈ 0.378, re-enters, and
4310        // repeats 45 times with the hand-back drifting (8.3e5 → 1.06e6), so
4311        // no position test fires, until a restoration sub-solve's layer-2
4312        // verdict misreads one of those feasible points as infeasible at
4313        // iteration 1678. Upstream fails restoration at the first of them
4314        // ("converged to a feasible point that is unacceptable to the
4315        // filter", 236 iterations on 3.14.19). An `S` step — soft
4316        // restoration that *also* satisfies the original criterion — or any
4317        // ordinary `f`/`h`/`w` step takes the shot (`dallasl`: `s s S`).
4318        //
4319        // The verdict is judged on the handed-back point, not the re-entry
4320        // point: the outer drifted away from a point restoration certified
4321        // feasible, so the re-entry's violation says nothing about the
4322        // model's feasibility. On the same-point arm the two coincide.
4323        let shot_not_taken = std::mem::take(&mut self.unreleased_shot_pending);
4324        let unreleased_same_point = if let (Some(px), Some(ps)) = (
4325            self.last_resto_unreleased_x.as_ref(),
4326            self.last_resto_unreleased_s.as_ref(),
4327        ) {
4328            relative_distance(&*curr.x, &**px) <= 1e-10
4329                && relative_distance(&*curr.s, &**ps) <= 1e-10
4330        } else {
4331            false
4332        };
4333        // Counted, not one-shot: see [`Self::UNRELEASED_SHOT_STRIKES`]. A
4334        // non-finite-W entry neither counts nor clears the run.
4335        if shot_not_taken && !entry_nonfinite_w {
4336            self.unreleased_shot_strikes += 1;
4337        }
4338        let shot_not_taken =
4339            shot_not_taken && self.unreleased_shot_strikes >= Self::UNRELEASED_SHOT_STRIKES;
4340        let unreleased_repeat = unreleased_same_point || shot_not_taken;
4341        if unreleased_repeat && entry_nonfinite_w {
4342            tracing::debug!(target: "pounce::algorithm",
4343                "[POUNCE] re-entered restoration from an unreleased hand-back, but on a \
4344                 non-finite Hessian; exempt from the gh#1042 exit.",
4345            );
4346        }
4347        if unreleased_repeat && !entry_nonfinite_w {
4348            let handback_theta = self.last_resto_unreleased_theta_unscaled;
4349            let verdict = if handback_theta > 0.0 && handback_theta >= cycle_viol_tol {
4350                SolverReturn::LocalInfeasibility
4351            } else {
4352                SolverReturn::RestorationFailure
4353            };
4354            if unreleased_same_point {
4355                tracing::debug!(target: "pounce::algorithm",
4356                    "[POUNCE] restoration handed back a converged-to-feasible point it never \
4357                     released, and the outer re-entered restoration from it without leaving it \
4358                     (accepted steps in between: {}); ending the solve with {:?} (gh#1042).",
4359                    !recovery_cycle, verdict,
4360                );
4361            } else {
4362                tracing::debug!(target: "pounce::algorithm",
4363                    "[POUNCE] restoration handed back a converged-to-feasible point it never \
4364                     released, and the outer re-entered restoration without the original \
4365                     globalization accepting a step from it (soft-restoration steps only); \
4366                     ending the solve with {:?} (gh#1076).",
4367                    verdict,
4368                );
4369            }
4370            self.unreleased_handback_exit = true;
4371            return self.terminate_acceptable_or(verdict);
4372        }
4373        if recovery_cycle {
4374            self.resto_no_outer_progress_count =
4375                self.resto_no_outer_progress_count.saturating_add(1);
4376            // 10-strike limit: tuned to give OET7-style traces room
4377            // to break through (inner inf_pr still decreasing across
4378            // strikes) while still bounding DECONVBNE-style cycles
4379            // (which need a guard but tolerate a wider window —
4380            // ~3 outer steps per cycle, so 10 strikes ≈ 30 outer
4381            // iters, well below the 2987-iter pathological run).
4382            if self.resto_no_outer_progress_count >= 10 {
4383                // Prefer the last acceptable point over the cycle error;
4384                // borrows are released, so the `&mut self` helper is free.
4385                return self.terminate_acceptable_or(cycle_exit);
4386            }
4387        } else {
4388            self.resto_no_outer_progress_count = 0;
4389        }
4390        // Near-feasible resto re-entry detector — matches the *intent*
4391        // of upstream `IpBacktrackingLineSearch.cpp:580-600`'s almost-
4392        // feasible-resto guard with a looser cv threshold. When the
4393        // outer enters restoration with the constraint violation
4394        // already at or below `tol`, the resto sub-IPM will produce a
4395        // recovered iterate that's at most marginally more feasible,
4396        // and any post-recovery σ-blowup from the next outer KKT solve
4397        // will re-trigger resto on the next iteration. Counting these
4398        // entries surfaces the cycle as `StopAtAcceptablePoint` —
4399        // primal feasibility is already met, only the dual residual
4400        // remains. Catches DECONVBNE: pounce ran 2987 iters before
4401        // this guard (cycle of ~30-inner-resto + 3 outer per cycle);
4402        // upstream solves in 505 iters via a different x trajectory.
4403        // Single-entry productive restos (BT8, HIMMELBJ, ODFITS) and
4404        // sub-tol-but-recoverable starts pass through under the 3-
4405        // strike limit.
4406        let outer_tol = self.bundle.conv_check.tol_or_default();
4407        if reference_theta <= outer_tol {
4408            if !entry_nonfinite_w {
4409                self.resto_near_feasible_count = self.resto_near_feasible_count.saturating_add(1);
4410            }
4411            if self.resto_near_feasible_count >= 3 {
4412                // Constraint feasibility is met, but a near-feasible iterate is
4413                // only "acceptable" if its objective is finite. CUTE `himmelbj`
4414                // reaches a point with cv ≈ 2e-9 where f evaluates to NaN; that
4415                // must surface as Invalid_Number_Detected rather than be
4416                // reported as Solved_To_Acceptable_Level with a `nan` objective.
4417                if !self.cq.borrow().curr_f().is_finite() {
4418                    return IterateOutcome::Terminate(SolverReturn::InvalidNumberDetected);
4419                }
4420                // Constraint feasibility alone does not make a point
4421                // acceptable. `reference_theta` measures only the *primal*
4422                // residual, so a perfectly feasible iterate can still be
4423                // arbitrarily far from stationary — which is exactly what an
4424                // unbounded objective looks like from here: the constraints
4425                // stay satisfied while the iterates run off toward -inf.
4426                //
4427                // `min -exp(x) s.t. x >= 0` re-enters restoration with
4428                // `inf_pr = 1.7e-10` and `inf_du = 8.8e+47`; before gh #274
4429                // the finiteness check was the only gate, `-8.8e47` is
4430                // finite, and the solve was reported as
4431                // `Solved_To_Acceptable_Level` — which Pyomo maps into the
4432                // *solved* family, loading the diverging iterate as an
4433                // optimal solution.
4434                //
4435                // So require the point to pass the full acceptable-level
4436                // triplet (which includes `acceptable_dual_inf_tol`) before
4437                // claiming acceptability. When it does not, surface
4438                // `cycle_exit` — the same honest status the other two
4439                // restoration-cycle exits in this function use.
4440                let nlp_err = self.cq.borrow().curr_nlp_error();
4441                if !self
4442                    .bundle
4443                    .conv_check
4444                    .current_is_acceptable_with_state(nlp_err, &self.data, &self.cq)
4445                {
4446                    tracing::debug!(target: "pounce::algorithm",
4447                        "[POUNCE] near-feasible restoration re-entry at theta {:.3e} \
4448                         but the point fails the acceptable-level tolerances \
4449                         (nlp_err {:.3e}); reporting {:?} rather than \
4450                         Solved_To_Acceptable_Level (gh#274).",
4451                        reference_theta, nlp_err, cycle_exit,
4452                    );
4453                    return IterateOutcome::Terminate(cycle_exit);
4454                }
4455                return IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint);
4456            }
4457        } else {
4458            self.resto_near_feasible_count = 0;
4459        }
4460        self.last_resto_entry_x = Some(curr.x.make_new_copy());
4461        self.last_resto_entry_s = Some(curr.s.make_new_copy());
4462
4463        // Augment the outer's filter with the resto-entry envelope —
4464        // mirrors upstream `IpBacktrackingLineSearch.cpp:566`:
4465        // `acceptor_->PrepareRestoPhaseStart()`. Adds
4466        // `((1-γ_θ)·θ_entry, φ_entry - γ_φ·θ_entry)` to the filter so
4467        // that after restoration recovers, the outer's Newton step is
4468        // forced by the filter to make real progress vs the entry
4469        // point. Without this, the outer accepts null-progress 'h'
4470        // steps and re-enters restoration on the next iteration (root
4471        // cause of DECONVBNE's 323 R-accepts vs ipopt's 21).
4472        self.bundle
4473            .line_search
4474            .acceptor_mut()
4475            .prepare_resto_phase_start(reference_theta, reference_barr);
4476
4477        let orig_progress_cb = self
4478            .bundle
4479            .line_search
4480            .acceptor()
4481            .make_orig_progress_check(reference_theta, reference_barr, 5.0)
4482            .map(|accept| self.orig_progress_check(accept));
4483
4484        let (Some(nlp), Some(sd), Some(resto)) = (
4485            self.nlp.as_ref(),
4486            self.search_dir.as_mut(),
4487            self.restoration.as_mut(),
4488        ) else {
4489            return IterateOutcome::Terminate(SolverReturn::RestorationFailure);
4490        };
4491        resto.set_orig_progress_check(orig_progress_cb);
4492        // Forward the shared debugger so it can step the inner solve.
4493        resto.set_debug_hook(self.debug.as_ref().map(Rc::clone));
4494        // Forward the user's TNLP so the callback fires from the inner
4495        // solve too (gh#645). `None` when the caller installed no
4496        // callback, which keeps the whole path inert for them.
4497        resto.set_intermediate_tnlp(self.tnlp.as_ref().map(Rc::clone));
4498        let mut pd_guard = sd.pd_solver_mut();
4499        let aug = pd_guard.aug_solver_mut();
4500        // Audit counters (pounce#12). Increment call count + outer-iter
4501        // count (one outer iter is consumed per restoration call) and
4502        // wall-time around the inner call. Inner iter count is read
4503        // after via the trait accessor.
4504        //
4505        // `outer_iter_at_entry` is captured *before* the call because the
4506        // inner IPM's counter is seeded from it (`inner.iter_count =
4507        // outer_iter + 1`, upstream `IpRestoMinC_1Nrm.cpp:181`). The
4508        // accessor hands back that seeded, absolute number; the sub-solve's
4509        // own length is the difference. Adding the raw accessor value was
4510        // gh #819's second defect — `restoration_inner_iters` was a sum of
4511        // absolute positions, a quantity with no meaning — and it is the
4512        // same misreading gh#664 records for the stall gate.
4513        let outer_iter_at_entry = self.data.borrow().iter_count;
4514        self.resto_calls = self.resto_calls.saturating_add(1);
4515        self.resto_outer_iters = self.resto_outer_iters.saturating_add(1);
4516        let resto_t0 = std::time::Instant::now();
4517        let outcome = resto.perform_restoration(&self.data, &self.cq, nlp, aug);
4518        drop(pd_guard);
4519        self.resto_wall_secs += resto_t0.elapsed().as_secs_f64();
4520        let inner_final_iter = resto.last_inner_iter_count();
4521        let recovery_unreleased = resto.last_recovery_unreleased();
4522        self.resto_inner_iters = self
4523            .resto_inner_iters
4524            .saturating_add((inner_final_iter - outer_iter_at_entry).max(0));
4525        // gh #819. Roll the reported iteration count forward over the
4526        // restoration rows on the paths that *terminate* the solve.
4527        //
4528        // `RestorationOutcome::Recovered` already does this for itself, in
4529        // `min_c_1nrm.rs`'s step 2g (`Set_iter_count(resto_iter_count - 1)`,
4530        // one short because the outer loop is about to increment). Every
4531        // other outcome returns `Terminate` from the match below without
4532        // passing through that block, so the whole sub-solve used to vanish
4533        // from the summary: on gh #815's flowsheet the log ends at row
4534        // `3000r`, above a summary that said `Number of Iterations....: 3`.
4535        //
4536        // Ipopt reports the index of the last row it printed, `r` rows
4537        // included, on every exit path. Measured on the gh #815 model and
4538        // three variants of it: last row `2418r` / reported 2418, `412r` /
4539        // 412, `1547r` / 1547, `1348r` / 1348 — exits `Restoration Failed`,
4540        // local infeasibility and `Maximum Number of Iterations Exceeded`
4541        // respectively. Assigning the absolute inner count reproduces that
4542        // rule exactly.
4543        //
4544        // Safe against trajectory: every non-`Recovered` arm below returns
4545        // `IterateOutcome::Terminate`, and `optimize_inner`'s loop breaks on
4546        // `Terminate` without consulting the counter again. Nothing reads
4547        // `iter_count` between here and the summary.
4548        if !matches!(outcome, RestorationOutcome::Recovered)
4549            && inner_final_iter > outer_iter_at_entry
4550        {
4551            self.data.borrow_mut().iter_count = inner_final_iter;
4552        }
4553        // pounce#244: the restoration inner IPM shares the outer solve's
4554        // `Deadline` (both its convergence check and — post-#244 — its KKT
4555        // solves consult it), so a budget crossing inside restoration
4556        // terminates the inner solve with a time-limit status. Surface that
4557        // as the time limit directly instead of letting the `Failed` arm map
4558        // it onto `RestorationFailure` / `StopAtAcceptablePoint`. `data.curr`
4559        // is the last accepted outer iterate — restoration stages its
4560        // recovered point onto `trial`, not `curr`, and we return before
4561        // promoting it — so this hands back a valid iterate.
4562        if let Some(ret) = self.deadline_status() {
4563            return IterateOutcome::Terminate(ret);
4564        }
4565        match outcome {
4566            RestorationOutcome::Recovered => {
4567                // Mirror upstream `IpBacktrackingLineSearch.cpp:624-631`:
4568                // a successful restoration clears the line search's
4569                // cross-iteration globalization counters. Upstream runs
4570                // restoration inside `FindAcceptableTrialPoint` so those
4571                // assignments are inline; pounce runs it here, so the
4572                // reset has to be driven from here. Without it
4573                // `watchdog_shortened_iter` survives a restoration
4574                // episode and runs of shortened steps on either side of
4575                // one accumulate as if consecutive, arming the watchdog
4576                // where upstream would not. See
4577                // `BacktrackingLineSearch::reset_after_restoration`.
4578                self.bundle.line_search.reset_after_restoration();
4579                // An unreleased hand-back from a restoration that a
4580                // non-finite Hessian forced at a point already feasible to
4581                // `tol` restarts the filter (gh#1076). Pounce enters
4582                // restoration there only to move off the kink; upstream
4583                // stops (MA57: `Invalid_Number_Detected`), and would not hand
4584                // a point that feasible to restoration in any case
4585                // (`IpBacktrackingLineSearch.cpp:580`). Restoration has no
4586                // violation to reduce, so its iterates can only *raise* the
4587                // barrier objective against the entry, and the outer filter
4588                // holds that entry's envelope at `θ ≈ 0` — which dominates
4589                // every feasible point with a higher φ. The release test is
4590                // unsatisfiable by construction, and so is every outer step
4591                // from the point handed back in its place: the one shot the
4592                // hand-back exists to give cannot be taken. Under the old
4593                // release quantities (max-norm θ against the filter's 1-norm,
4594                // plain f against the barrier objective) such points were
4595                // released by accident and the question never arose. The
4596                // reset is upstream's own `FilterLSAcceptor::Reset`, the one
4597                // a μ decrease performs. Measured on `dallass_kink_unmerged`:
4598                // Optimal at 61 with no ladder (65 on main), where the
4599                // corrected test alone ended the base solve
4600                // `Error_In_Step_Computation` at 116.
4601                //
4602                // It is scoped to the non-finite-W entry on purpose. Applied
4603                // to every feasible entry it also rescues `ssebnln` (Optimal
4604                // at 125 instead of the gh#1042 exit at 117 + 41), but it
4605                // costs `issue_884`'s reproducer its answer: under `REPRO`
4606                // options `mpcc_qpec_small_biactive` then converges with an
4607                // unscaled dual infeasibility of 3.4e-4 instead of 1.3e-10.
4608                if recovery_unreleased && entry_nonfinite_w && reference_theta <= outer_tol {
4609                    tracing::debug!(target: "pounce::algorithm",
4610                        "[POUNCE] unreleased hand-back from a restoration entered at a \
4611                         feasible point (theta {:.3e} <= tol); restarting the filter (gh#1076).",
4612                        reference_theta,
4613                    );
4614                    self.bundle.line_search.reset();
4615                }
4616                // The driver has staged the recovered point on
4617                // `data.trial`; apply the safe-slack bound adjustment
4618                // (as the main accept path does), then promote it and
4619                // continue iterating.
4620                self.adjust_variable_bounds_for_small_slacks();
4621                self.data.borrow_mut().accept_trial_point();
4622                // Snapshot the recovery iterate for the slow-cycle
4623                // detector at the top of the next `invoke_restoration`.
4624                // Compared against next-entry curr, dx_rel ≈ ‖α·d‖ —
4625                // measures purely the outer step. See header comment
4626                // on the cycle detector above.
4627                let recovered = self
4628                    .data
4629                    .borrow()
4630                    .curr
4631                    .as_ref()
4632                    .expect("accept_trial_point sets curr")
4633                    .clone();
4634                self.last_resto_recovery_x = Some(recovered.x.make_new_copy());
4635                self.last_resto_recovery_s = Some(recovered.s.make_new_copy());
4636                self.unreleased_shot_pending = recovery_unreleased;
4637                if !recovery_unreleased {
4638                    self.unreleased_shot_strikes = 0;
4639                }
4640                if recovery_unreleased {
4641                    self.last_resto_unreleased_x = Some(recovered.x.make_new_copy());
4642                    self.last_resto_unreleased_s = Some(recovered.s.make_new_copy());
4643                    self.last_resto_unreleased_theta_unscaled =
4644                        self.cq.borrow().curr_unscaled_primal_infeasibility_max();
4645                } else {
4646                    self.last_resto_unreleased_x = None;
4647                    self.last_resto_unreleased_s = None;
4648                }
4649                if recovery_unreleased {
4650                    tracing::debug!(target: "pounce::algorithm",
4651                        "[POUNCE] restoration converged to a feasible point it did not \
4652                         release; resuming the outer phase from it (gh#1042)."
4653                    );
4654                }
4655                // Mirror upstream `IpoptAlgorithm::AcceptTrialPoint`
4656                // (`IpIpoptAlg.cpp:917-963`): kappa_sigma clamp on the
4657                // four bound-multiplier vectors. Upstream applies this
4658                // unconditionally inside AcceptTrialPoint, so the
4659                // post-restoration path inherits it; pounce factored
4660                // the clamp out of the data swap so we must call it
4661                // explicitly here. Without it the all-1 multiplier
4662                // reset (`bound_mult_reset_threshold`) leaves z*s far
4663                // from mu at the recovered iterate, blowing up the
4664                // next KKT solve's σ = z/s diagonal.
4665                self.correct_bound_multiplier();
4666                IterateOutcome::Continue
4667            }
4668            RestorationOutcome::Failed => {
4669                // Mirrors upstream `IpBacktrackingLineSearch.cpp:611-623`:
4670                // when `PerformRestoration` returns false, attempt to
4671                // roll back to the most recent acceptable iterate before
4672                // surfacing failure. If a snapshot is available we exit
4673                // cleanly with `StopAtAcceptablePoint` (mapped by the
4674                // application layer to `Solved_To_Acceptable_Level`),
4675                // matching the upstream `ACCEPTABLE_POINT_REACHED`
4676                // throw. Without a snapshot we surface
4677                // `RestorationFailure` — unless the restoration left the
4678                // iterate diverging (`|x|_∞ > diverging_iterates_tol`), in
4679                // which case we surface `DivergingIterates` to mirror the
4680                // outcome upstream produces on pathological problems like
4681                // MESH (where ipopt reports `Diverging_Iterates` and
4682                // pounce previously reported `Restoration_Failed` with an
4683                // obj of −3.6e+33). As in the running guard above, a large
4684                // `|x|` is only reported as unbounded when it is
4685                // structurally consistent with an unbounded feasible region
4686                // and the divergence is genuine — either it has persisted
4687                // (the running guard's growth-and-descent streak, which only
4688                // accumulates on a real recession ray; issues #248 / #252) or
4689                // blown past the absolute runaway backstop; otherwise the
4690                // failure is a plain `RestorationFailure`, never a spurious
4691                // `Unbounded`.
4692                //
4693                // gh#1000: a restoration that failed because the inner
4694                // counter — seeded from the outer one, so absolute — ran
4695                // into `max_iter` did not fail; it ran out of budget.
4696                // Upstream throws `RESTORATION_MAXITER_EXCEEDED`
4697                // (`IpRestoMinC_1Nrm.cpp`) and `IpIpoptAlg` reports
4698                // `MAXITER_EXCEEDED`, past the line search's
4699                // acceptable-point fallback. Reporting it as
4700                // `Restoration_Failed` told the caller the model defeated
4701                // the algorithm when it was the cap that stopped it.
4702                if inner_final_iter >= self.max_iter {
4703                    IterateOutcome::Terminate(SolverReturn::MaxiterExceeded)
4704                } else if self.restore_acceptable_point() {
4705                    IterateOutcome::Terminate(SolverReturn::StopAtAcceptablePoint)
4706                } else {
4707                    let diverging = {
4708                        let data = self.data.borrow();
4709                        match data.curr.as_ref() {
4710                            Some(curr) => {
4711                                let amax = curr.x.amax();
4712                                amax > self.diverging_iterates_tol
4713                                    && self.divergence_is_true_unboundedness(&*curr.x)
4714                                    && (amax >= Self::DIVERGENCE_ABS_RUNAWAY
4715                                        || self.divergence_streak >= Self::DIVERGENCE_PERSIST_ITERS)
4716                            }
4717                            None => false,
4718                        }
4719                    };
4720                    if diverging {
4721                        IterateOutcome::Terminate(SolverReturn::DivergingIterates)
4722                    } else {
4723                        IterateOutcome::Terminate(SolverReturn::RestorationFailure)
4724                    }
4725                }
4726            }
4727            RestorationOutcome::UserRequestedStop => {
4728                // gh#645. Same discipline as the pounce#244 deadline
4729                // exit a few lines up, and for the same reason: the
4730                // recovered point is staged on `data.trial` and we
4731                // return without promoting it, so `data.curr` is still
4732                // the last iterate accepted for the *original* NLP.
4733                // That matters more than the status code to the caller
4734                // this exists for — a controller that aborts on a
4735                // deadline still has to apply something, and the
4736                // subproblem's iterate is not a point it should apply.
4737                IterateOutcome::Terminate(SolverReturn::UserRequestedStop)
4738            }
4739            RestorationOutcome::FeasiblePointFound => {
4740                // Port of `IpIpoptAlg.cpp:542` — the catch of
4741                // `FEASIBILITY_PROBLEM_SOLVED`, thrown by
4742                // `IpRestoMinC_1Nrm.cpp:269` when restoration reaches a
4743                // point feasible for a *square* original NLP. Upstream
4744                // recomputes the multipliers before returning
4745                // `FEASIBLE_POINT_FOUND`; without that step the reported
4746                // dual infeasibility is `∇f` at a point whose status says
4747                // the constraints are satisfied. On the gh#508 probe that
4748                // is the difference between Ipopt's `1.78e-15` and a bare
4749                // `10.0`.
4750                //
4751                // The driver has already promoted the recovered point to
4752                // `data.curr`, so the multipliers are computed at the
4753                // point that will be reported.
4754                if self.is_square_problem() {
4755                    self.compute_feasibility_multipliers_postprocess();
4756                }
4757                IterateOutcome::Terminate(SolverReturn::FeasiblePointFound)
4758            }
4759            RestorationOutcome::LocallyInfeasible => {
4760                // Mirrors upstream's catch of `LOCALLY_INFEASIBLE` thrown
4761                // from `IpRestoConvCheck.cpp:240` — the resto sub-IPM
4762                // settled at a stationary point of `||c(x)||_1` whose
4763                // residual is still well above `tol`. Without this
4764                // detection the outer would re-enter restoration on the
4765                // unchanged iterate forever.
4766                //
4767                // gh #505: consult the acceptable-point stash, for the same
4768                // reason the conv-check arm above does and the cycle exits
4769                // already did. This is the *third* site that produced
4770                // `LocalInfeasibility`, and the only one not gated on
4771                // `infeas_max_streak` — which matters, because on the reported
4772                // instance raising that knob to 15 did not move the run by a
4773                // single iteration, so the verdict there is not the outer
4774                // detector's. Whichever route reaches it, a solve that passed
4775                // through an acceptable iterate must not discard it.
4776                //
4777                // Inert on genuinely infeasible models by the same argument as
4778                // the other two: nothing is stashed unless the whole acceptable
4779                // triplet passed, so `terminate_acceptable_or` falls through to
4780                // the verdict unchanged.
4781                self.terminate_local_infeasibility()
4782            }
4783        }
4784    }
4785
4786    /// Safe-slack bound adjustment, applied to the staged `trial`
4787    /// iterate before it is promoted to `curr`. When one or more trial
4788    /// slacks fell below `eps*min(1,mu)`, [`IpoptCalculatedQuantities::
4789    /// adjusted_trial_bounds`] returns the moved `x_L/x_U/d_L/d_U`; we
4790    /// install them on the NLP so the slack becomes representable. Port
4791    /// of the bound-adjustment block in `IpoptAlgorithm::AcceptTrialPoint`
4792    /// (`IpIpoptAlg.cpp:664-706`).
4793    fn adjust_variable_bounds_for_small_slacks(&mut self) {
4794        // Compute the moved bounds (releases the CQ/NLP borrows on return).
4795        let adjusted = {
4796            let trial_set = self.data.borrow().trial.is_some();
4797            if !trial_set {
4798                return;
4799            }
4800            self.cq.borrow().adjusted_trial_bounds()
4801        };
4802        let Some(bounds) = adjusted else {
4803            return;
4804        };
4805        tracing::debug!(
4806            target: "pounce::algorithm",
4807            "slack_move: {} slack(s) too small, adjusting variable bound(s) at iter {}",
4808            bounds.adjusted,
4809            self.data.borrow().iter_count,
4810        );
4811        let nlp = Rc::clone(self.cq.borrow().nlp());
4812        nlp.borrow_mut().adjust_variable_bounds(
4813            &*bounds.x_l,
4814            &*bounds.x_u,
4815            &*bounds.d_l,
4816            &*bounds.d_u,
4817        );
4818    }
4819
4820    /// Refresh the `s`-block factors for
4821    /// `linear_system_scaling=slack-based`.
4822    ///
4823    /// A no-op for every other scaling choice: the flag is set only when
4824    /// the builder installed a `SlackBasedTSymScalingMethod`, and the
4825    /// method itself ignores the push if it never receives one.
4826    ///
4827    /// Silently skips when the quantity cannot be formed — no NLP, no
4828    /// current iterate, no inequality rows, or a primal vector shape the
4829    /// CQ does not recognise. The scaling method then keeps behaving as
4830    /// identity, which is what `linear_system_scaling=none` would have
4831    /// done, so a missing push costs conditioning and never correctness.
4832    fn push_slack_scaling(&mut self) {
4833        if !self.slack_based_scaling {
4834            return;
4835        }
4836        if self.nlp.is_none() {
4837            return;
4838        }
4839        let nx = match self.data.borrow().curr.as_ref() {
4840            Some(c) => c.x.dim(),
4841            None => return,
4842        };
4843        let Some(s_scale) = self.cq.borrow().curr_slack_based_s_scaling() else {
4844            return;
4845        };
4846        if s_scale.is_empty() {
4847            return;
4848        }
4849        if let Some(sd) = self.search_dir.as_mut() {
4850            sd.pd_solver_mut()
4851                .aug_solver_mut()
4852                .set_slack_scaling(nx, &s_scale);
4853        }
4854    }
4855
4856    /// `recalc_y` — replace `y_c`/`y_d` with least-square estimates once
4857    /// the iterate is feasible enough. Port of the `recalc_y_` block in
4858    /// `IpIpoptAlg.cpp:AcceptTrialPoint`.
4859    ///
4860    /// Silently does nothing — leaving the Newton-step multipliers in
4861    /// place — when disabled, when the violation is still above
4862    /// `recalc_y_feas_tol`, when there is nothing to estimate, or when
4863    /// the augmented-system solve fails. A failed estimate is not an
4864    /// error: the multipliers we already have are valid, just less
4865    /// accurate, so falling back to them costs accuracy and never
4866    /// correctness. Same reasoning as the initializer's `y0` fallback in
4867    /// `init/default.rs`.
4868    fn maybe_recalc_y(&mut self) {
4869        if !self.recalc_y {
4870            return;
4871        }
4872        let Some(nlp) = self.nlp.as_ref().map(Rc::clone) else {
4873            return;
4874        };
4875        // Feasibility gate. Upstream compares against the same
4876        // `curr_constraint_violation` the convergence check uses.
4877        if self.cq.borrow().curr_constraint_violation() >= self.recalc_y_feas_tol {
4878            return;
4879        }
4880        let (n_yc, n_yd) = {
4881            let d = self.data.borrow();
4882            match d.curr.as_ref() {
4883                Some(c) => (c.y_c.dim(), c.y_d.dim()),
4884                None => return,
4885            }
4886        };
4887        if n_yc + n_yd == 0 {
4888            return;
4889        }
4890        // The augmented-system solver is owned by the search-direction
4891        // calculator, as it is for the initializer's least-square call.
4892        let Some(sd) = self.search_dir.as_mut() else {
4893            return;
4894        };
4895        let mut new_y_c = pounce_linalg::dense_vector::DenseVectorSpace::new(n_yc).make_new_dense();
4896        let mut new_y_d = pounce_linalg::dense_vector::DenseVectorSpace::new(n_yd).make_new_dense();
4897        let mut pd_guard = sd.pd_solver_mut();
4898        // This was the first call site to drop review item M3's 1e-8
4899        // perturbation (#688), on the argument that `recalc_y` overwrites
4900        // `y` every iteration — so a bias in the estimator is a *fixed
4901        // point* rather than a transient, nothing downstream corrects it,
4902        // and it lands directly in `inf_du`, the quantity the run is
4903        // judged on. gh#693 extended the same treatment to the other
4904        // three sites, so `calculate_y_eq` no longer takes a flag: every
4905        // caller now gets δ=0 with the perturbed solve as a retry.
4906        let ok = self.bundle.eq_mult.calculate_y_eq(
4907            &self.data,
4908            &self.cq,
4909            &nlp,
4910            pd_guard.aug_solver_mut(),
4911            &mut new_y_c,
4912            &mut new_y_d,
4913        );
4914        drop(pd_guard);
4915        if !ok {
4916            tracing::debug!(
4917                target: "pounce::algorithm",
4918                "recalc_y: least-square solve failed at iter {}, keeping Newton multipliers",
4919                self.data.borrow().iter_count,
4920            );
4921            return;
4922        }
4923        // Mark the iteration, exactly as upstream does
4924        // (`IpData().Append_info_string("y ")` in
4925        // `IpIpoptAlg.cpp:AcceptTrialPoint`). Without it the iteration
4926        // log gives no way to tell which iterations re-estimated `y`
4927        // and which carried the Newton multipliers — and when a solve
4928        // stalls with an oscillating `inf_du`, whether the oscillation
4929        // tracks the re-estimation is the first thing worth knowing.
4930        self.data.borrow_mut().append_info_string("y ");
4931
4932        // Share x/s/z/v; swap only the equality/inequality multipliers.
4933        let curr = match self.data.borrow().curr.clone() {
4934            Some(c) => c,
4935            None => return,
4936        };
4937        let new_iv = crate::iterates_vector::IteratesVector::new(
4938            curr.x.clone(),
4939            curr.s.clone(),
4940            Rc::new(new_y_c),
4941            Rc::new(new_y_d),
4942            curr.z_l.clone(),
4943            curr.z_u.clone(),
4944            curr.v_l.clone(),
4945            curr.v_u.clone(),
4946        );
4947        self.data.borrow_mut().set_curr(new_iv);
4948    }
4949
4950    /// Port of `IpoptCalculatedQuantities::IsSquareProblem`
4951    /// (`IpIpoptCalculatedQuantities.cpp:3732`): as many equality
4952    /// constraints as variables, so the NLP has zero degrees of freedom.
4953    /// There is nothing to optimise — only a system to solve — and the
4954    /// objective is decorative.
4955    ///
4956    /// The consequence that matters is algebraic. `J_c` is square, so the
4957    /// least-square multiplier system `J_cᵀ y = −∇f (+ bound terms)` is
4958    /// exactly solvable and the dual residual can always be driven to
4959    /// zero, however large `y` has to be. On a non-square problem it
4960    /// generally cannot, which is why this is the right gate and not a
4961    /// heuristic.
4962    fn is_square_problem(&self) -> bool {
4963        match self.data.borrow().curr.as_ref() {
4964            Some(c) => c.x.dim() == c.y_c.dim(),
4965            None => false,
4966        }
4967    }
4968
4969    /// Zero the four bound multipliers and replace `y_c`/`y_d` with the
4970    /// least-square multipliers of the resulting feasibility problem —
4971    /// the shared body of `ComputeFeasibilityMultipliers`
4972    /// (`IpIpoptAlg.cpp:893-922`) and
4973    /// `ComputeFeasibilityMultipliersPostprocess` (`cpp:964-984`), which
4974    /// upstream writes out twice.
4975    ///
4976    /// Returns the iterate that was in place beforehand, so a caller that
4977    /// must be able to undo the swap can. `None` means nothing was
4978    /// installed — no iterate, no multipliers, or the least-square solve
4979    /// failed — in which case the original iterate is left untouched.
4980    fn install_feasibility_multipliers(
4981        &mut self,
4982    ) -> Option<crate::iterates_vector::IteratesVector> {
4983        let nlp = self.nlp.as_ref().map(Rc::clone)?;
4984        let curr_backup = self.data.borrow().curr.clone()?;
4985        let (n_yc, n_yd) = (curr_backup.y_c.dim(), curr_backup.y_d.dim());
4986        if n_yc + n_yd == 0 {
4987            return None;
4988        }
4989
4990        // Zero the bound multipliers and install that iterate *before* the
4991        // solve, so the least-square RHS is the feasibility problem's
4992        // (`cpp:893-910`): the calculator reads `curr`, so the zeroing has
4993        // to be visible to it, not applied to the result afterwards.
4994        let zeroed = |v: &Rc<dyn Vector>| -> Rc<dyn Vector> {
4995            let mut t = v.make_new();
4996            t.set(0.0);
4997            Rc::from(t)
4998        };
4999        let z_l = zeroed(&curr_backup.z_l);
5000        let z_u = zeroed(&curr_backup.z_u);
5001        let v_l = zeroed(&curr_backup.v_l);
5002        let v_u = zeroed(&curr_backup.v_u);
5003        self.data
5004            .borrow_mut()
5005            .set_curr(crate::iterates_vector::IteratesVector::new(
5006                curr_backup.x.clone(),
5007                curr_backup.s.clone(),
5008                curr_backup.y_c.clone(),
5009                curr_backup.y_d.clone(),
5010                z_l.clone(),
5011                z_u.clone(),
5012                v_l.clone(),
5013                v_u.clone(),
5014            ));
5015
5016        let mut new_y_c = pounce_linalg::dense_vector::DenseVectorSpace::new(n_yc).make_new_dense();
5017        let mut new_y_d = pounce_linalg::dense_vector::DenseVectorSpace::new(n_yd).make_new_dense();
5018        let ok = match self.search_dir.as_mut() {
5019            None => false,
5020            Some(sd) => {
5021                let mut pd_guard = sd.pd_solver_mut();
5022                let ok = self.bundle.eq_mult.calculate_y_eq(
5023                    &self.data,
5024                    &self.cq,
5025                    &nlp,
5026                    pd_guard.aug_solver_mut(),
5027                    &mut new_y_c,
5028                    &mut new_y_d,
5029                );
5030                drop(pd_guard);
5031                ok
5032            }
5033        };
5034        if !ok {
5035            // `cpp:986` logs a warning and keeps whatever `y` was there.
5036            tracing::debug!(
5037                target: "pounce::algorithm",
5038                "square problem: least-square multiplier solve failed, keeping Newton multipliers",
5039            );
5040            self.data.borrow_mut().set_curr(curr_backup);
5041            return None;
5042        }
5043
5044        self.data
5045            .borrow_mut()
5046            .set_curr(crate::iterates_vector::IteratesVector::new(
5047                curr_backup.x.clone(),
5048                curr_backup.s.clone(),
5049                Rc::new(new_y_c),
5050                Rc::new(new_y_d),
5051                z_l,
5052                z_u,
5053                v_l,
5054                v_u,
5055            ));
5056        Some(curr_backup)
5057    }
5058
5059    /// Port of `IpoptAlgorithm::ComputeFeasibilityMultipliersPostprocess`
5060    /// (`IpIpoptAlg.cpp:949`). Same swap as
5061    /// [`Self::compute_feasibility_multipliers`], but unconditional: the
5062    /// run is over and the point has already been judged, so there is no
5063    /// convergence check to gate on and nothing to restore. Called on the
5064    /// two square-problem exits that report a feasible point
5065    /// (`cpp:484`, `cpp:542`), whose whole claim is that the constraints
5066    /// are satisfied — reporting `∇f` as the dual residual of such a point
5067    /// would contradict the status printed next to it.
5068    fn compute_feasibility_multipliers_postprocess(&mut self) {
5069        debug_assert!(self.is_square_problem());
5070        let _ = self.install_feasibility_multipliers();
5071    }
5072
5073    /// Port of `IpoptAlgorithm::ComputeFeasibilityMultipliers`
5074    /// (`IpIpoptAlg.cpp:857`). On a square problem, once the iterate is
5075    /// primal-feasible to `constr_viol_tol`, re-estimate `y_c`/`y_d` as
5076    /// the multipliers of the *feasibility* problem: zero the four bound
5077    /// multipliers and take the least-square `y` against that iterate. If
5078    /// the convergence check then accepts, keep them; otherwise restore
5079    /// the iterate untouched.
5080    ///
5081    /// Why it exists (gh#508). A square problem is a system of equations.
5082    /// If the solver has found a point satisfying them to the tolerance
5083    /// the user declared, that point *is* the answer, and the leftover
5084    /// objective gradient is not evidence of anything. Without this,
5085    /// `inf_du` carries `∇f` — on the gh#508 probe `|2(x−5)| = 10` at a
5086    /// point whose violation is `1e-4` inside a `constr_viol_tol` of
5087    /// `1e-3` — the convergence check refuses, and the rapid-infeasibility
5088    /// detector convicts a point Ipopt calls feasible.
5089    ///
5090    /// Note the double convergence check, which is upstream's too: one to
5091    /// decide whether to bother (`cpp:880`), one to decide whether to keep
5092    /// the result (`cpp:924`). Both go through
5093    /// [`ConvergenceCheck::probe_convergence`], not the real check —
5094    /// upstream can afford `CheckConvergence` here because the only state
5095    /// it carries is `acceptable_counter_`, whereas pounce's also carries
5096    /// the gh#505 rapid-infeasibility streak, the gh#200 veto budget and
5097    /// the gh#533 progress window. Advancing those three times per
5098    /// iteration instead of once is not a faithful port of anything: on
5099    /// the gh#508 probe it moved the infeasibility conviction from
5100    /// iteration 86 to 33.
5101    fn compute_feasibility_multipliers(&mut self) {
5102        debug_assert!(self.is_square_problem());
5103
5104        // Not primal feasible yet → no multipliers to compute (cpp:864).
5105        // Upstream measures this on the *unscaled* violation in the max
5106        // norm, against `constr_viol_tol`.
5107        let constr_viol_tol = self.bundle.conv_check.constr_viol_tol_or_default();
5108        if self.cq.borrow().curr_unscaled_primal_infeasibility_max() > constr_viol_tol {
5109            return;
5110        }
5111
5112        // No calculator → upstream logs and leaves `y` alone (cpp:872).
5113        if self.nlp.is_none() {
5114            return;
5115        }
5116
5117        // `iter_count + 1`: see the call site. Upstream has already
5118        // incremented when it reaches here.
5119        let iter_count = self.data.borrow().iter_count + 1;
5120        let nlp_err = self.cq.borrow().curr_nlp_error();
5121        if !nlp_err.is_finite() {
5122            return;
5123        }
5124
5125        // Already converged, or out of iterations/time → do not touch the
5126        // multipliers (cpp:884). `Continue` is the case worth acting on:
5127        // it usually means dual feasibility is what is still missing.
5128        if self
5129            .bundle
5130            .conv_check
5131            .probe_convergence(nlp_err, iter_count, &self.data, &self.cq)
5132            != ConvergenceStatus::Continue
5133        {
5134            return;
5135        }
5136
5137        let Some(curr_backup) = self.install_feasibility_multipliers() else {
5138            return;
5139        };
5140
5141        // Keep them only if they actually buy a verdict (cpp:924).
5142        let nlp_err = self.cq.borrow().curr_nlp_error();
5143        if nlp_err.is_finite()
5144            && matches!(
5145                self.bundle
5146                    .conv_check
5147                    .probe_convergence(nlp_err, iter_count, &self.data, &self.cq,),
5148                ConvergenceStatus::Converged | ConvergenceStatus::ConvergedToAcceptable
5149            )
5150        {
5151            // Upstream marks nothing here; `"y "` is `recalc_y`'s. Use a
5152            // distinct tag so the iteration log says which mechanism
5153            // moved the multipliers.
5154            self.data.borrow_mut().append_info_string("f ");
5155            return;
5156        }
5157
5158        tracing::debug!(
5159            target: "pounce::algorithm",
5160            "square problem: feasibility multipliers at iter {} did not converge the check, restoring",
5161            iter_count,
5162        );
5163        self.data.borrow_mut().set_curr(curr_backup);
5164    }
5165
5166    /// Port of `IpIpoptAlg::correct_bound_multiplier`
5167    /// (`IpIpoptAlg.cpp:1055-1134`). Clamp each bound multiplier
5168    /// component into `[mu/(kappa_sigma * s_i), kappa_sigma * mu / s_i]`
5169    /// for all four bound-multiplier vectors.
5170    fn correct_bound_multiplier(&mut self) {
5171        if self.kappa_sigma < 1.0 {
5172            return;
5173        }
5174        let mu = self.data.borrow().curr_mu;
5175        let curr = match self.data.borrow().curr.clone() {
5176            Some(c) => c,
5177            None => return,
5178        };
5179
5180        let cq = self.cq.borrow();
5181
5182        let z_l_new = clamp_against_slack(&*curr.z_l, &*cq.curr_slack_x_l(), mu, self.kappa_sigma);
5183        let z_u_new = clamp_against_slack(&*curr.z_u, &*cq.curr_slack_x_u(), mu, self.kappa_sigma);
5184        let v_l_new = clamp_against_slack(&*curr.v_l, &*cq.curr_slack_s_l(), mu, self.kappa_sigma);
5185        let v_u_new = clamp_against_slack(&*curr.v_u, &*cq.curr_slack_s_u(), mu, self.kappa_sigma);
5186        drop(cq);
5187
5188        let new_iv = crate::iterates_vector::IteratesVector::new(
5189            curr.x.clone(),
5190            curr.s.clone(),
5191            curr.y_c.clone(),
5192            curr.y_d.clone(),
5193            z_l_new,
5194            z_u_new,
5195            v_l_new,
5196            v_u_new,
5197        );
5198        self.data.borrow_mut().set_curr(new_iv);
5199    }
5200
5201    /// Outer entry point — port of `IpoptAlgorithm::Optimize()`. Calls
5202    /// the iterate-initializer once, then loops `iterate()` until a
5203    /// terminal status. The exception → SolverReturn mapping
5204    /// (TINY_STEP_DETECTED → STEP_BECOMES_TINY,
5205    /// RESTORATION_FAILED → RESTORATION_FAILURE, etc.) lands in
5206    /// Phase 9 alongside the restoration phase.
5207    /// Run the solve and finalize its result.
5208    ///
5209    /// A thin wrapper on purpose. The gh #200 fallback must see **every** exit
5210    /// of the driver loop, and wiring it into individual termination sites was
5211    /// tried and failed — there are sixteen, and the ones easiest to overlook
5212    /// are the ones most likely to matter. Keeping the loop in a separate
5213    /// function means every `return` inside it, present or future, flows through
5214    /// [`Self::honour_refused_certificate`] by construction rather than by the
5215    /// author remembering to.
5216    ///
5217    /// This got more important once the fallback started changing the status in
5218    /// *both* directions: it can now hand back `StopAtAcceptablePoint` for a
5219    /// `Success` it was given. Anything reading `result` before the hook is
5220    /// reading a status that is not the one reported.
5221    pub fn optimize(&mut self) -> SolverReturn {
5222        let result = self.optimize_inner();
5223
5224        // gh #200: a refused certificate outranks any non-success verdict the
5225        // continued run reached, and an earlier refusal can outrank the
5226        // continued run's own certificate. Applied here, once.
5227        let result = self.honour_refused_certificate(result);
5228
5229        // pounce#250 follow-up: the dual-divergence guard's diversion to
5230        // restoration is a bet, and a lost bet must not return a worse point
5231        // than the solve already had in hand. Applied here, once, for the same
5232        // reason the #200 hook is — every `return` in the loop flows through
5233        // this point by construction.
5234        let result = self.honour_best_acceptable_after_dual_guard(result);
5235
5236        // gh #534: deferring the acceptable-point restoration decline is also a
5237        // bet, and this is the net under it — a continuation that did not beat
5238        // the point the guard would have returned hands that point back. Last of
5239        // the three, so it compares against whatever the hooks above settled on.
5240        let result = self.honour_decline_floor(result);
5241
5242        // gh #797: leaving a certified stationary point along a direction of
5243        // negative curvature is a bet placed *from* a certificate, so it is
5244        // settled last — whatever the hooks above arrived at, the escape either
5245        // beat the point it left with a certificate of its own or that point is
5246        // handed back.
5247        let result = self.honour_neg_curv_floor(result);
5248
5249        // Terminal post-mortem checkpoint. Skipped when the user already
5250        // asked to stop (they were just at a prompt); otherwise the
5251        // debugger gets a last look at the final/failing iterate.
5252        if !matches!(result, SolverReturn::UserRequestedStop) {
5253            self.fire_debug_terminal(result);
5254        }
5255        result
5256    }
5257
5258    fn optimize_inner(&mut self) -> SolverReturn {
5259        // Top-level span for the whole solve; every iteration / linear
5260        // solve / restoration event nests under it (pounce#71).
5261        let _solve_span = tracing::info_span!("solve").entered();
5262
5263        // Shared timing accumulator — every phase below records into it.
5264        let timing = self.data.borrow().timing.clone();
5265
5266        // Install the shared accumulator on the augmented-system solver
5267        // so its factor / back-solve calls are attributed to
5268        // `linear_system_factorization` / `linear_system_back_solve`.
5269        // Same pattern for the diagnostics state when present, so KKT
5270        // dump sites can consult per-iter gating.
5271        if let Some(sd) = self.search_dir.as_mut() {
5272            sd.pd_solver_mut()
5273                .aug_solver_mut()
5274                .set_timing_stats(std::rc::Rc::clone(&timing));
5275            if let Some(diag) = self.diagnostics.as_ref() {
5276                sd.pd_solver_mut()
5277                    .aug_solver_mut()
5278                    .set_diagnostics(Rc::clone(diag));
5279            }
5280        }
5281
5282        // 0a. Strategy initialization — port of upstream's
5283        //     `IpoptAlgorithm::InitializeImpl` calls. The mu update needs
5284        //     `data.curr_mu`/`curr_tau` seeded before the iterate
5285        //     initializer runs (`CalculateSafeSlack` reads them).
5286        self.bundle.mu_update.initialize(&self.data);
5287
5288        // 0b. Iterate initializer. Requires NLP; without one the caller
5289        //    must have populated `data.curr` themselves.
5290        if let Some(nlp) = self.nlp.as_ref() {
5291            // The initializer needs an aug-system solver for the
5292            // least-square multiplier branch; until that's wired we
5293            // route through whatever the search-direction calculator
5294            // owns when present. For the stub flow we skip the LSM
5295            // path by giving the initializer a dummy solver only if
5296            // the search_dir is present (otherwise the init function
5297            // is responsible for not consulting it).
5298            if let Some(sd) = self.search_dir.as_mut() {
5299                timing.initialize_iterates.start();
5300                let mut pd_guard = sd.pd_solver_mut();
5301                let aug_solver = pd_guard.aug_solver_mut();
5302                let ok = self
5303                    .bundle
5304                    .init
5305                    .set_initial_iterates(&self.data, &self.cq, nlp, aug_solver);
5306                drop(pd_guard);
5307                timing.initialize_iterates.end();
5308                if !ok {
5309                    return SolverReturn::InvalidProblemDefinition;
5310                }
5311            }
5312        }
5313
5314        // 0c. Seed `IpoptData::w` with the initial-iterate Hessian.
5315        //     Redundant with the iter-body `update_hessian` call (which
5316        //     now runs BEFORE `update_barrier_parameter`) but kept to
5317        //     cover any code path that consults `data.w` between
5318        //     `set_initial_iterates` and the first `iterate()` call
5319        //     (e.g. the iter-0 trace dump below).
5320        if self.data.borrow().curr.is_some() {
5321            timing.update_hessian.start();
5322            let _ = self.bundle.hess.update_hessian(&self.data, &self.cq);
5323            timing.update_hessian.end();
5324        }
5325
5326        // Track-A iterate-trace dumper. Activated by
5327        // `IPOPT_ITER_DUMP_PATH`; otherwise no-op. See `iter_dump.rs`.
5328        let mut dumper = IterDumper::from_env();
5329        // Iter 0 record — captures the initialised iterate before any
5330        // step. Mirrors upstream's "after InitializeIterates(), before
5331        // the loop" emission point.
5332        if let Some(d) = dumper.as_mut() {
5333            d.write_record(&self.data, &self.cq);
5334        }
5335
5336        // Advance the diagnostics iter counter so the first `iterate()`
5337        // body reports as iter 0 (matches `data.iter_count`). Subsequent
5338        // bumps live at the bottom of the loop alongside the iter_count
5339        // bookkeeping.
5340        if let Some(diag) = self.diagnostics.as_ref() {
5341            diag.bump_iter();
5342            // Iter-0 iterate row (issue #68). Same hook point as
5343            // the binary IterDumper above; emits only when
5344            // `--dump iterates:*` is configured.
5345            emit_iterate_record(diag.as_ref(), &self.data, &self.cq);
5346        }
5347
5348        // Iter 0 intermediate callback — upstream fires once after
5349        // `InitializeIterates` before the loop body starts so users
5350        // observe the initial point.
5351        if !self.fire_intermediate() {
5352            return SolverReturn::UserRequestedStop;
5353        }
5354        if self.fire_debug(crate::debug::Checkpoint::IterStart) == crate::debug::DebugAction::Stop {
5355            return SolverReturn::UserRequestedStop;
5356        }
5357
5358        // pounce#246: bound the initialization / restoration-entry window.
5359        // Everything above — `mu_update.initialize`, `set_initial_iterates`
5360        // (which for a bad warm start can grind in its least-square /
5361        // feasibility setup), and the initial `update_hessian` — runs
5362        // *before* the first `iterate()`, whose convergence check and
5363        // post-`compute_search_direction` gate are the earliest deadline
5364        // checks (#242/#244/#245). A solve handed a poor warm start could
5365        // therefore spend the whole budget here and only consult the
5366        // deadline once it reached the first outer-iteration /
5367        // KKT-factorization boundary. Consult it now, before the loop, so a
5368        // bad-start init stall returns promptly with the time-limit status
5369        // (best-so-far being the initialised iterate) instead of running to
5370        // a multiple of the budget. This also bounds the *restoration
5371        // entry*: the nested restoration IPM shares this `Deadline` and runs
5372        // the same `optimize_inner`, so a budget already crossed by the time
5373        // the inner solve starts up terminates it here rather than after its
5374        // own first iterate.
5375        if let Some(ret) = self.deadline_status() {
5376            return ret;
5377        }
5378
5379        let result = loop {
5380            match self.iterate() {
5381                IterateOutcome::Terminate(ret) => break ret,
5382                IterateOutcome::Continue => {
5383                    // Source the local counter from `data.iter_count`
5384                    // each pass so a pre-seeded counter (e.g. the inner
5385                    // restoration IPM at `outer.iter + 1`, matching
5386                    // upstream `IpRestoMinC_1Nrm.cpp:181`) and any
5387                    // restoration step that set
5388                    // `data.iter_count = inner.iter_count - 1`
5389                    // (mirroring `IpRestoMinC_1Nrm.cpp:Set_iter_count`)
5390                    // are honored — without this the local counter
5391                    // would advance from its pre-restoration value,
5392                    // ignoring the inner-IPM iterations.
5393                    let mut iter_count: Index = self.data.borrow().iter_count;
5394                    iter_count += 1;
5395                    // Do NOT short-circuit to `MaxiterExceeded` here: bump the
5396                    // counter and loop, letting the next `iterate()` run its
5397                    // convergence check (`OptimalityErrorConvergenceCheck`,
5398                    // which tests the component tolerances *before* its own
5399                    // `iter_count >= max_iter` gate at
5400                    // `conv_check/opt_error.rs`). Breaking before that call
5401                    // skipped the convergence test on the iterate produced by
5402                    // the final permitted step, so a solve converging on
5403                    // exactly the `max_iter`-th iterate reported
5404                    // `Maximum_Iterations_Exceeded` where upstream Ipopt —
5405                    // which runs `CheckConvergence` at the top of its loop,
5406                    // convergence-first — reports success. The check is
5407                    // guaranteed to terminate the loop: once `iter_count`
5408                    // reaches `max_iter`, `check_convergence_with_state`
5409                    // returns either `Converged`/`ConvergedToAcceptable` or
5410                    // `MaxIterExceeded`, never `Continue` (L1).
5411                    self.data.borrow_mut().iter_count = iter_count;
5412                    // Floor evidence for restoration's gh#661 divergence
5413                    // guard: how long this solve has sat at a violation
5414                    // it could not get below. Sampled here, once per
5415                    // accepted iterate, from the same quantity the
5416                    // `inf_pr` column reports — so it is free, and it
5417                    // sees the whole outer trajectory rather than the
5418                    // handful of iterations a restoration sub-solve runs.
5419                    // The nested restoration IPM reaches this line too,
5420                    // but writes its own `IpoptData`, so the two
5421                    // trajectories never mix.
5422                    let inf_pr_now = self.cq.borrow().curr_primal_infeasibility_max();
5423                    self.data.borrow_mut().inf_pr_floor.observe(inf_pr_now);
5424                    // Keep the diagnostics counter in lock-step with
5425                    // `data.iter_count` so KKT-dump gating reflects the
5426                    // about-to-execute iteration.
5427                    if let Some(diag) = self.diagnostics.as_ref() {
5428                        diag.bump_iter();
5429                        // Per-iter iterate row (issue #68). Mirrors
5430                        // the binary IterDumper hook below.
5431                        emit_iterate_record(diag.as_ref(), &self.data, &self.cq);
5432                    }
5433                    // Per-iteration record — emitted after the
5434                    // iter_count bump so the recorded `iter` field
5435                    // matches `IpData().iter_count()` at the moment of
5436                    // emission, identical to upstream's writer.
5437                    if let Some(d) = dumper.as_mut() {
5438                        d.write_record(&self.data, &self.cq);
5439                    }
5440                    // Per-iteration intermediate callback — fired with
5441                    // an `IntermediateContext` guard so downstream
5442                    // inspector entry points (the C API
5443                    // `GetIpoptCurrent*` family) see live state for the
5444                    // duration of the user callback.
5445                    if !self.fire_intermediate() {
5446                        break SolverReturn::UserRequestedStop;
5447                    }
5448                    if self.fire_debug(crate::debug::Checkpoint::IterStart)
5449                        == crate::debug::DebugAction::Stop
5450                    {
5451                        break SolverReturn::UserRequestedStop;
5452                    }
5453                }
5454            }
5455        };
5456
5457        result
5458    }
5459}
5460
5461/// A termination certificate the masked-scale veto refused (gh #200), with
5462/// everything the fallback needs to undo the refusal verbatim.
5463///
5464/// One struct rather than a field per component. The fallback is only correct if
5465/// these all describe *the same iterate*, and parallel `Option`s make
5466/// "objective recorded, iterate missing" representable — which was reachable:
5467/// the iterate is cloned out of `data.curr` and can come back `None`, while the
5468/// objective and barrier parameter were written unconditionally. Capture is now
5469/// all-or-nothing, so the disagreement cannot be constructed.
5470#[derive(Clone)]
5471struct VetoSnapshot {
5472    /// The refused iterate itself.
5473    iterate: crate::iterates_vector::IteratesVector,
5474    /// Iteration at which the refusal happened.
5475    ///
5476    /// Needed to identify which refusal is the *baseline-equivalent* one. The
5477    /// baseline stops at the first iterate where it would terminate, so when
5478    /// both a strict and an acceptable-level refusal are on record it is the
5479    /// chronologically earlier one that says what the baseline returned — not
5480    /// the stricter one. The later refusal sits on the continued trajectory,
5481    /// which the baseline never walked, so comparing against it compares
5482    /// against a point that was never on offer.
5483    iter: Index,
5484    /// Scaled objective there, so the refused point can be compared against
5485    /// whatever the continued run reached without re-evaluating it.
5486    obj: Number,
5487    /// Barrier parameter there.
5488    ///
5489    /// `curr_mu` lives on `IpoptData` rather than in the `IteratesVector`, so
5490    /// restoring the iterate does not rewind it, and `stats.final_mu` is read
5491    /// after the restore — leaving the continued run's barrier parameter
5492    /// reported next to the refused run's `x`. That pair feeds a warm-started
5493    /// corrector's `mu_init` and reaches callers as `info["mu"]`, so it must
5494    /// describe the point actually returned. (Not currently observable: `mu` has
5495    /// bottomed out at its floor in every fallback case reachable so far, making
5496    /// the two values coincide. Kept correct rather than left to depend on that.)
5497    mu: Number,
5498    /// Max-norm unscaled KKT error there, so the tiebreak can see what
5499    /// `apply_kkt_fidelity_gate` will see. Recorded at refusal time because the
5500    /// gate runs post-solve, long after this iterate is gone.
5501    unscaled_kkt: Number,
5502    /// Unscaled max-norm constraint violation there — the same quantity the
5503    /// `acceptable_constr_viol_tol` gate is defined against
5504    /// (`curr_unscaled_primal_infeasibility_max`, cf. gh #261). The
5505    /// best-acceptable fallback ranks candidates by `(feasible_enough,
5506    /// objective)` rather than objective alone, so a point outside a capped
5507    /// feasibility band can never displace one inside it on objective grounds;
5508    /// without this field the ranking has no feasibility term and, under a
5509    /// user-widened `acceptable_constr_viol_tol`, will trade feasibility for
5510    /// objective and hand back a verifiably infeasible point under a success
5511    /// status (gh #267). Unused by the gh #200 masked-scale paths, which key on
5512    /// objective only.
5513    constr_viol: Number,
5514    /// Objective scaling factor in force when `obj` was recorded.
5515    ///
5516    /// `obj` is a *scaled* objective, so comparing it against the continued
5517    /// run's is only meaningful under the same factor, sign included. Held so
5518    /// that assumption is asserted rather than trusted: periodic or adaptive
5519    /// rescaling is a natural thing to add for exactly the ill-scaled problems
5520    /// this mechanism targets, and it would silently turn the comparison into
5521    /// noise.
5522    obj_scale: Number,
5523}
5524
5525/// Internal result of one [`IpoptAlgorithm::iterate`] call. Mirrors the
5526/// upstream try/catch around `IpoptAlg::Optimize` — anything that's not
5527/// `Continue` carries the [`SolverReturn`] that the outer loop will
5528/// surface to `IpoptApplication`.
5529enum IterateOutcome {
5530    Continue,
5531    Terminate(SolverReturn),
5532}
5533
5534/// Feasibility-aware ranking core for the best-acceptable fallback (gh #267).
5535///
5536/// `true` iff candidate `(a_obj, a_viol)` ranks **strictly** better than
5537/// `(b_obj, b_viol)` under the `(band_clamped_viol, objective)` key, where each
5538/// violation is clamped up to `band` before it is compared. Lexicographic: the
5539/// point with the smaller clamped violation wins outright; only when the clamped
5540/// violations tie does the lower objective decide. A non-finite objective ranks
5541/// worst (never wins, always loses to a finite one); a non-finite violation is
5542/// treated as infinitely infeasible.
5543///
5544/// The clamp is what makes this a **total order** rather than a two-class
5545/// partition, and it is the whole gh #280 fix. Clamping the violation *up* to
5546/// `band` collapses every point inside the feasibility band to the single value
5547/// `band`, so within the band those points tie on feasibility and objective
5548/// decides — the intended, gh #267-preserving behaviour. Outside the band the
5549/// clamp is the identity, so the *actual* violation decides and the
5550/// less-infeasible point always wins. The earlier `(feasible_enough, objective)`
5551/// key was a two-class partition: once **both** points sat outside the band it
5552/// fell through to a bare `a_obj < b_obj`, reading neither violation — the exact
5553/// pre-#267 objective-only rule, which lets a strictly-more-infeasible point win
5554/// on objective (gh #280). Under the clamped key a strictly-more-infeasible
5555/// point can never rank better, at any band.
5556///
5557/// Pure and total, so the fallback's "never worse off" guarantee is a theorem
5558/// this function's unit tests prove by cases — host-independent by construction,
5559/// unlike an end-to-end objective comparison across two live nonconvex solves
5560/// (the trap gh #267 caught). [`IpoptAlgorithm::ranks_better`] supplies `band`
5561/// as `min(acceptable_constr_viol_tol, FEASIBLE_ENOUGH_CAP)`; both the record
5562/// and the read side route through here, so they cannot disagree.
5563/// Append `value` to a fixed-capacity oldest-first window, dropping the oldest
5564/// sample once the window is full (gh #534).
5565fn push_sample(buf: &mut [Number; DECLINE_PROGRESS_SAMPLES], len: &mut usize, value: Number) {
5566    if *len < DECLINE_PROGRESS_SAMPLES {
5567        buf[*len] = value;
5568        *len += 1;
5569    } else {
5570        buf.rotate_left(1);
5571        buf[DECLINE_PROGRESS_SAMPLES - 1] = value;
5572    }
5573}
5574
5575/// Whether every consecutive pair in `samples` (oldest first) contracted by at
5576/// least `ratio` — the gh #534 progress test, as a pure function.
5577///
5578/// A sample that is not finite, or a predecessor that is not strictly positive,
5579/// fails the window: neither is evidence of progress, and a zero predecessor
5580/// makes the ratio meaningless. A `ratio` of `1` admits any non-increasing
5581/// window, and a large one admits every finite window — which is how
5582/// `resto_decline_progress_ratio` doubles as the "drop the progress
5583/// requirement" switch.
5584///
5585/// Pure and total for the same reason [`ranks_better_within_band`] is: the two
5586/// traces the issue records — `eigena2` quartering and `eigenb2` rising — decide
5587/// what this must do, and a unit test can hold it to them exactly.
5588fn window_is_contracting(samples: &[Number], ratio: Number) -> bool {
5589    samples.windows(2).all(|w| {
5590        let (prev, next) = (w[0], w[1]);
5591        prev.is_finite() && prev > 0.0 && next.is_finite() && next <= ratio * prev
5592    })
5593}
5594
5595fn ranks_better_within_band(
5596    a_obj: Number,
5597    a_viol: Number,
5598    b_obj: Number,
5599    b_viol: Number,
5600    band: Number,
5601) -> bool {
5602    if !a_obj.is_finite() {
5603        return false;
5604    }
5605    if !b_obj.is_finite() {
5606        return true;
5607    }
5608    // Clamp each violation up to `band`: everything inside the feasibility band
5609    // maps to the single value `band` (so objective decides there), while outside
5610    // it the actual violation is kept (so the less-infeasible point strictly
5611    // wins). A non-finite violation is infinitely infeasible. This is a total
5612    // order — a strictly-more-infeasible point can never rank better (gh #280).
5613    let clamped = |v: Number| {
5614        if v.is_finite() {
5615            v.max(band)
5616        } else {
5617            Number::INFINITY
5618        }
5619    };
5620    let (a_key, b_key) = (clamped(a_viol), clamped(b_viol));
5621    if a_key != b_key {
5622        // The less-infeasible point wins outright, whatever the objectives.
5623        return a_key < b_key;
5624    }
5625    // Same clamped feasibility (both inside the band, or an exact tie outside it):
5626    // lower objective wins (the original within-band behaviour).
5627    a_obj < b_obj
5628}
5629
5630/// `||a - b||_2 / (1 + ||b||_2)`. Used by the restoration cycle
5631/// detector in [`IpoptAlgorithm::invoke_restoration`] to test whether
5632/// the outer iterate has moved between two consecutive restoration
5633/// entries.
5634fn relative_distance(a: &dyn Vector, b: &dyn Vector) -> Number {
5635    if a.dim() == 0 {
5636        return 0.0;
5637    }
5638    let mut diff = a.make_new_copy();
5639    diff.axpy(-1.0, b);
5640    diff.nrm2() / (1.0 + b.nrm2())
5641}
5642
5643/// `out = curr + α_p · δ` for the primal/equality blocks and
5644/// `out = curr + α_d · δ` for the bound multipliers, returned as a
5645/// fresh frozen `IteratesVector`. Mirrors `scaled_step` in the line
5646/// search; duplicated here for the tiny-step branch which bypasses
5647/// the line-search driver.
5648fn scaled_step_unchecked(
5649    curr: &crate::iterates_vector::IteratesVector,
5650    delta: &crate::iterates_vector::IteratesVector,
5651    alpha_primal: Number,
5652    alpha_dual: Number,
5653) -> crate::iterates_vector::IteratesVector {
5654    let mut out = curr.make_new_zeroed();
5655    out.add_one_vector(1.0, curr, 0.0);
5656    out.x.axpy(alpha_primal, &*delta.x);
5657    out.s.axpy(alpha_primal, &*delta.s);
5658    out.y_c.axpy(alpha_primal, &*delta.y_c);
5659    out.y_d.axpy(alpha_primal, &*delta.y_d);
5660    out.z_l.axpy(alpha_dual, &*delta.z_l);
5661    out.z_u.axpy(alpha_dual, &*delta.z_u);
5662    out.v_l.axpy(alpha_dual, &*delta.v_l);
5663    out.v_u.axpy(alpha_dual, &*delta.v_u);
5664    out.freeze()
5665}
5666
5667/// Allocate a fresh `Rc<dyn Vector>` with `kappa_sigma_clamp`
5668/// applied component-wise against the supplied `slack`. Inputs are
5669/// borrowed; the original `z` is never mutated. Ports the per-vector
5670/// piece of `IpIpoptAlg.cpp:1080-1133`.
5671fn clamp_against_slack(
5672    z: &dyn Vector,
5673    slack: &dyn Vector,
5674    mu: Number,
5675    kappa_sigma: Number,
5676) -> Rc<dyn Vector> {
5677    debug_assert_eq!(z.dim(), slack.dim());
5678    let n = z.dim() as usize;
5679    // Flatten both z and slack into contiguous slices so the
5680    // elementwise clamp doesn't care whether the inputs are
5681    // [`DenseVector`] (regular IPM path) or [`CompoundVector`]
5682    // (resto IPM path). The result is reconstructed into a
5683    // same-shape Vector via `Vector::make_new` + a flat-write
5684    // helper so the caller sees a vector with the same blocking as
5685    // its input.
5686    let mut buf = vec![0.0_f64; n];
5687    flat_read_into(z, &mut buf);
5688    let s_vals = flat_read_owned(slack);
5689    let _ = kappa_sigma_clamp(&mut buf, &s_vals, mu, kappa_sigma);
5690    let mut out: Box<dyn Vector> = z.make_new();
5691    flat_write_into(&mut *out, &buf);
5692    Rc::from(out)
5693}
5694
5695pub(crate) fn flat_read_into(v: &dyn Vector, dst: &mut [Number]) {
5696    if let Some(dv) = v
5697        .as_any()
5698        .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
5699    {
5700        let vs = dv.expanded_values();
5701        dst.copy_from_slice(&vs);
5702        return;
5703    }
5704    if let Some(cv) = v.as_any().downcast_ref::<pounce_linalg::CompoundVector>() {
5705        let mut off = 0usize;
5706        for k in 0..cv.n_comps() {
5707            let blk = cv.comp(k);
5708            let dim = blk.dim() as usize;
5709            let dblk = blk
5710                .as_any()
5711                .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
5712                .expect("clamp_against_slack: CompoundVector blocks must be DenseVectors");
5713            let vs = dblk.expanded_values();
5714            dst[off..off + dim].copy_from_slice(&vs);
5715            off += dim;
5716        }
5717        return;
5718    }
5719    panic!("clamp_against_slack: unsupported Vector kind");
5720}
5721
5722pub(crate) fn flat_read_owned(v: &dyn Vector) -> Vec<Number> {
5723    let mut out = vec![0.0; v.dim() as usize];
5724    flat_read_into(v, &mut out);
5725    out
5726}
5727
5728pub(crate) fn flat_write_into(v: &mut dyn Vector, src: &[Number]) {
5729    if let Some(dv) = v
5730        .as_any_mut()
5731        .downcast_mut::<pounce_linalg::dense_vector::DenseVector>()
5732    {
5733        dv.set_values(src);
5734        return;
5735    }
5736    if let Some(cv) = v
5737        .as_any_mut()
5738        .downcast_mut::<pounce_linalg::CompoundVector>()
5739    {
5740        let mut off = 0usize;
5741        for k in 0..cv.n_comps() {
5742            let blk = cv.comp_mut(k);
5743            let dim = blk.dim() as usize;
5744            let dblk = blk
5745                .as_any_mut()
5746                .downcast_mut::<pounce_linalg::dense_vector::DenseVector>()
5747                .expect("clamp_against_slack: CompoundVector blocks must be DenseVectors");
5748            dblk.set_values(&src[off..off + dim]);
5749            off += dim;
5750        }
5751        return;
5752    }
5753    panic!("clamp_against_slack: unsupported Vector kind");
5754}
5755
5756/// Per-element kappa-sigma clamp — the elementwise arithmetic at the
5757/// heart of `IpIpoptAlg.cpp:correct_bound_multiplier` (lines
5758/// 1090-1133). For each index `i`:
5759///
5760/// ```text
5761///   slack_i  = max(slack_i, tiny_double)   // avoid /0
5762///   z_lo_i   = mu / (kappa_sigma * slack_i)
5763///   z_hi_i   = kappa_sigma * mu / slack_i
5764///   z_i      ← clamp(z_i, z_lo_i, z_hi_i)
5765/// ```
5766///
5767/// Returns the maximum elementwise correction magnitude (matching
5768/// upstream's `Max(max_correction_up, max_correction_low)`).
5769///
5770/// `kappa_sigma < 1` short-circuits to the identity per upstream's
5771/// guard at line 1065.
5772pub fn kappa_sigma_clamp(
5773    z: &mut [Number],
5774    slack: &[Number],
5775    mu: Number,
5776    kappa_sigma: Number,
5777) -> Number {
5778    debug_assert_eq!(z.len(), slack.len());
5779    if kappa_sigma < 1.0 {
5780        return 0.0;
5781    }
5782    let mut max_correction = 0.0_f64;
5783    for (zi, &si) in z.iter_mut().zip(slack.iter()) {
5784        let s_safe = si.max(Number::MIN_POSITIVE);
5785        let lo = mu / (kappa_sigma * s_safe);
5786        let hi = kappa_sigma * mu / s_safe;
5787        let clamped = zi.clamp(lo, hi);
5788        let delta = (clamped - *zi).abs();
5789        if delta > max_correction {
5790            max_correction = delta;
5791        }
5792        *zi = clamped;
5793    }
5794    max_correction
5795}
5796
5797#[cfg(test)]
5798mod tests {
5799    use super::*;
5800
5801    #[test]
5802    fn kappa_sigma_below_one_is_identity() {
5803        let mut z = vec![1.0, 2.0, 3.0];
5804        let slack = [1.0, 1.0, 1.0];
5805        let m = kappa_sigma_clamp(&mut z, &slack, 1.0, 0.5);
5806        assert_eq!(m, 0.0);
5807        assert_eq!(z, [1.0, 2.0, 3.0]);
5808    }
5809
5810    #[test]
5811    fn within_band_is_unchanged() {
5812        // mu=1, kappa=10, slack=1 → band [0.1, 10]. z=1 → unchanged.
5813        let mut z = vec![1.0];
5814        let slack = [1.0];
5815        let m = kappa_sigma_clamp(&mut z, &slack, 1.0, 10.0);
5816        assert_eq!(m, 0.0);
5817        assert_eq!(z, [1.0]);
5818    }
5819
5820    #[test]
5821    fn above_upper_clamped_down() {
5822        // mu=1, kappa=10, slack=1 → upper = 10. z=100 → 10.
5823        let mut z = vec![100.0];
5824        let slack = [1.0];
5825        let m = kappa_sigma_clamp(&mut z, &slack, 1.0, 10.0);
5826        assert!((m - 90.0).abs() < 1e-13);
5827        assert_eq!(z, [10.0]);
5828    }
5829
5830    #[test]
5831    fn below_lower_clamped_up() {
5832        // mu=1, kappa=10, slack=1 → lower = 0.1. z=0.001 → 0.1.
5833        let mut z = vec![0.001];
5834        let slack = [1.0];
5835        let m = kappa_sigma_clamp(&mut z, &slack, 1.0, 10.0);
5836        assert!((m - 0.099).abs() < 1e-13);
5837        assert!((z[0] - 0.1).abs() < 1e-15);
5838    }
5839
5840    #[test]
5841    fn returns_max_over_components() {
5842        let mut z = vec![100.0, 0.001];
5843        let slack = [1.0, 1.0];
5844        let m = kappa_sigma_clamp(&mut z, &slack, 1.0, 10.0);
5845        assert!((m - 90.0).abs() < 1e-13);
5846        assert_eq!(z[0], 10.0);
5847        assert!((z[1] - 0.1).abs() < 1e-15);
5848    }
5849
5850    #[test]
5851    fn slack_clamped_to_min_positive_avoids_division_by_zero() {
5852        let mut z = vec![1e100];
5853        let slack = [0.0];
5854        let _ = kappa_sigma_clamp(&mut z, &slack, 1.0, 10.0);
5855        assert!(z[0].is_finite() || z[0] == 1e100);
5856    }
5857
5858    /// The restoration slot is exercised structurally:
5859    /// `IpoptAlgorithm::with_restoration` accepts a
5860    /// `Box<dyn RestorationPhase>` and the trait's default
5861    /// `perform_restoration` returns `Failed`. End-to-end coverage
5862    /// (iterate() → line-search-Failed → restoration → recovered)
5863    /// lands in the Phase 9 integration suite alongside the nested
5864    /// IPM driver.
5865    struct _DummyResto;
5866    impl RestorationPhase for _DummyResto {}
5867
5868    // --------------------------------------------------------------
5869    // Best-acceptable fallback ranking (gh #267).
5870    //
5871    // These prove the "never worse off" guarantee host-independently, by
5872    // cases, on the pure ranking core — the property the earlier end-to-end
5873    // `hair_trigger_*` objective comparison could only *approximate* on one
5874    // host's basin luck (gh #267's secondary finding). `band` here stands in
5875    // for the resolved `min(acceptable_constr_viol_tol, FEASIBLE_ENOUGH_CAP)`.
5876    // --------------------------------------------------------------
5877
5878    #[test]
5879    fn ranks_better_is_a_strict_order_within_a_feasibility_class() {
5880        let band = 1e-2;
5881        // Both feasible: lower objective wins, strictly.
5882        assert!(ranks_better_within_band(-2.0, 1e-4, -1.0, 1e-4, band));
5883        assert!(!ranks_better_within_band(-1.0, 1e-4, -2.0, 1e-4, band));
5884        // Ties are not "strictly better" in either direction — so an equal
5885        // returned point is never displaced, matching the read side's
5886        // keep-current-on-tie contract.
5887        assert!(!ranks_better_within_band(-1.0, 1e-4, -1.0, 5e-3, band));
5888        assert!(!ranks_better_within_band(-1.0, 5e-3, -1.0, 1e-4, band));
5889        // Both infeasible: the less-infeasible point wins. Here it also has the
5890        // lower objective, so this held under the old objective-only fall-through
5891        // too — `ranks_better_puts_feasibility_first_among_two_infeasibles` is the
5892        // case that separates the two rules (gh #280).
5893        assert!(ranks_better_within_band(-2.0, 5.0, -1.0, 9.0, band));
5894    }
5895
5896    #[test]
5897    fn ranks_better_puts_feasibility_first_among_two_infeasibles() {
5898        // The gh #280 hole: once BOTH points sit outside the (capped) band the
5899        // old `(feasible_enough, objective)` partition read a_ok == b_ok == false
5900        // and fell through to `a_obj < b_obj` — objective alone, the exact
5901        // pre-#267 rule — so a strictly-MORE-infeasible point could win by having
5902        // a better objective. This is the deb7 swap the fallback made: incumbent
5903        // at viol 5.292e-1, recorded point at viol 9.951e-1 with a 36%-better
5904        // objective. The less-infeasible point must win regardless of objective.
5905        let band = 1e-2;
5906        // Less-infeasible incumbent, WORSE objective — must still win.
5907        assert!(ranks_better_within_band(
5908            89.0, 5.292e-1, 56.9, 9.951e-1, band
5909        ));
5910        // The more-infeasible, better-objective point must NOT win — the swap
5911        // gh #280 forbids.
5912        assert!(!ranks_better_within_band(
5913            56.9, 9.951e-1, 89.0, 5.292e-1, band
5914        ));
5915        // A strictly-more-infeasible point never replaces the incumbent even with
5916        // an arbitrarily better objective.
5917        assert!(!ranks_better_within_band(-1e12, 9.0, 0.0, 5.0, band));
5918        assert!(ranks_better_within_band(0.0, 5.0, -1e12, 9.0, band));
5919    }
5920
5921    #[test]
5922    fn ranks_better_puts_feasibility_first_regardless_of_objective() {
5923        let band = 1e-2;
5924        // The gh #267 case in miniature: a feasible point outranks an
5925        // arbitrarily-lower-objective infeasible one, and vice-versa.
5926        assert!(ranks_better_within_band(0.0, 1e-4, -1e9, 9.94, band));
5927        assert!(!ranks_better_within_band(-1e9, 9.94, 0.0, 1e-4, band));
5928        // Exactly at the band is still feasible_enough; just past it is not.
5929        assert!(ranks_better_within_band(
5930            1.0,
5931            band,
5932            -1.0,
5933            band * 1.000_001,
5934            band
5935        ));
5936    }
5937
5938    #[test]
5939    fn ranks_better_never_lets_a_widened_band_matter_past_the_cap() {
5940        // The band the method feeds is capped at FEASIBLE_ENOUGH_CAP, so a
5941        // point beyond the cap is never feasible_enough however loose the
5942        // user's `acceptable_constr_viol_tol`. Model that by passing the capped
5943        // band: the near-optimal-but-mildly-infeasible endpoint (viol 1.13e-4,
5944        // within the cap) must beat the grossly-infeasible lower-objective
5945        // point (viol 9.94, past it) — the exact swap the fix forbids.
5946        let band = IpoptAlgorithm::FEASIBLE_ENOUGH_CAP;
5947        assert!(ranks_better_within_band(
5948            -2303.99, 1.13e-4, -2307.32, 9.94, band
5949        ));
5950        assert!(!ranks_better_within_band(
5951            -2307.32, 9.94, -2303.99, 1.13e-4, band
5952        ));
5953    }
5954
5955    #[test]
5956    fn ranks_better_ranks_a_nonfinite_objective_worst() {
5957        let band = 1e-2;
5958        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
5959            // A non-finite objective never ranks better than a finite one...
5960            assert!(!ranks_better_within_band(bad, 0.0, 0.0, 9.9, band));
5961            // ...and always loses to one, even on worse feasibility — so a
5962            // finite recorded point is restored over a NaN-objective return,
5963            // preserving the pre-fix `!(curr <= best)` NaN behaviour.
5964            assert!(ranks_better_within_band(0.0, 9.9, bad, 0.0, band));
5965        }
5966    }
5967
5968    #[test]
5969    fn ranks_better_treats_a_nonfinite_violation_as_infeasible() {
5970        let band = 1e-2;
5971        // A NaN violation is never feasible_enough, so a genuinely feasible
5972        // point outranks it regardless of objective.
5973        assert!(ranks_better_within_band(0.0, 0.0, -100.0, f64::NAN, band));
5974        assert!(!ranks_better_within_band(-100.0, f64::NAN, 0.0, 0.0, band));
5975    }
5976
5977    /// gh #534, the case the guard was stopping: `eigena2`'s dual infeasibility
5978    /// quarters on unit steps for four straight iterations, three short of a
5979    /// strict certificate. Quoted from the issue's own iteration table.
5980    #[test]
5981    fn eigena2_endgame_reads_as_contracting() {
5982        let eigena2 = [1.19e-05, 2.96e-06, 7.38e-07, 1.84e-07];
5983        assert!(window_is_contracting(
5984            &eigena2,
5985            DEFAULT_DECLINE_PROGRESS_RATIO
5986        ));
5987    }
5988
5989    /// gh #534, the case the guard was right about: `eigenb2`'s tail *rises*
5990    /// on heavily backtracked steps. The issue calls it a plausible genuine
5991    /// stall, so the progress test must refuse it and leave the guard alone.
5992    #[test]
5993    fn eigenb2_stall_does_not_read_as_contracting() {
5994        let eigenb2 = [1.88e-07, 2.69e-07, 2.89e-07, 2.93e-07];
5995        assert!(!window_is_contracting(
5996            &eigenb2,
5997            DEFAULT_DECLINE_PROGRESS_RATIO
5998        ));
5999    }
6000
6001    /// gh #534: `csfi2`'s window, measured on this build at the guard. Three
6002    /// healthy contractions and then a flat step — the solve has stopped
6003    /// moving, so the deferral must not fire however good the earlier ratios
6004    /// look. This is the shape every live guard firing reachable from the
6005    /// in-repo corpus has, which is why the whole window is tested and not
6006    /// just its first ratios.
6007    #[test]
6008    fn csfi2_flat_final_step_does_not_read_as_contracting() {
6009        let csfi2 = [3.267e0, 1.845e-6, 8.468e-8, 8.524e-8];
6010        assert!(!window_is_contracting(
6011            &csfi2,
6012            DEFAULT_DECLINE_PROGRESS_RATIO
6013        ));
6014        // ... and it is the *last* step that decides: drop it and the same
6015        // trace passes, which is exactly the distinction the test exists for.
6016        assert!(window_is_contracting(
6017            &csfi2[..3],
6018            DEFAULT_DECLINE_PROGRESS_RATIO
6019        ));
6020    }
6021
6022    /// gh #534: a large ratio drops the progress requirement, so the decline is
6023    /// deferred on any window. That is the "bypass the guard and see how far the
6024    /// solve gets" switch the issue asks for. A ratio of exactly `1` is the
6025    /// weaker "no backsliding" reading and still refuses `csfi2`, whose last
6026    /// step rises.
6027    #[test]
6028    fn a_large_ratio_accepts_a_stalled_window() {
6029        let csfi2 = [3.267e0, 1.845e-6, 8.468e-8, 8.524e-8];
6030        assert!(!window_is_contracting(&csfi2, 1.0));
6031        assert!(window_is_contracting(&[1e-8, 1e-8, 1e-8, 1e-8], 1.0));
6032        assert!(window_is_contracting(&csfi2, 1e20));
6033        // Still not a licence to read garbage as progress.
6034        assert!(!window_is_contracting(
6035            &[1.0, Number::NAN, 1e-9, 1e-12],
6036            1e20
6037        ));
6038    }
6039
6040    /// gh #534 edge cases: the ratio must never be evaluated against a
6041    /// non-positive or non-finite predecessor.
6042    #[test]
6043    fn degenerate_windows_never_read_as_contracting() {
6044        let r = DEFAULT_DECLINE_PROGRESS_RATIO;
6045        // A zero predecessor makes the ratio meaningless (0 <= 0.5*0 would
6046        // otherwise read as "contracting" forever).
6047        assert!(!window_is_contracting(&[0.0, 0.0, 0.0, 0.0], r));
6048        assert!(!window_is_contracting(&[1e-9, 0.0, 0.0, 0.0], r));
6049        assert!(!window_is_contracting(
6050            &[Number::INFINITY, 1e-3, 1e-6, 1e-9],
6051            r
6052        ));
6053        assert!(!window_is_contracting(&[1e-3, 1e-6, 1e-9, Number::NAN], r));
6054        // A genuine run down to exactly zero is progress, not a degenerate
6055        // window — the predecessor is positive at every step.
6056        assert!(window_is_contracting(&[1e-3, 1e-6, 1e-9, 0.0], r));
6057    }
6058
6059    /// gh #534: the window slides one sample per outer iteration and holds the
6060    /// most recent [`DECLINE_PROGRESS_SAMPLES`]. A short history is never a full
6061    /// window, which is what stops the first restoration entry of a solve from
6062    /// being deferred on no evidence at all — `nlp_err_contracting` requires
6063    /// `len == DECLINE_PROGRESS_SAMPLES` before it consults the samples.
6064    #[test]
6065    fn progress_window_slides_oldest_out() {
6066        let mut buf = [Number::NAN; DECLINE_PROGRESS_SAMPLES];
6067        let mut len = 0usize;
6068        for e in [1e-1, 1e-2, 1e-3] {
6069            push_sample(&mut buf, &mut len, e);
6070        }
6071        assert_eq!(len, 3);
6072        push_sample(&mut buf, &mut len, 1e-4);
6073        assert_eq!(len, DECLINE_PROGRESS_SAMPLES);
6074        assert_eq!(buf, [1e-1, 1e-2, 1e-3, 1e-4]);
6075        assert!(window_is_contracting(&buf, DEFAULT_DECLINE_PROGRESS_RATIO));
6076        // One flat iteration slides the oldest sample out and withdraws the
6077        // verdict.
6078        push_sample(&mut buf, &mut len, 1e-4);
6079        assert_eq!(len, DECLINE_PROGRESS_SAMPLES);
6080        assert_eq!(buf, [1e-2, 1e-3, 1e-4, 1e-4]);
6081        assert!(!window_is_contracting(&buf, DEFAULT_DECLINE_PROGRESS_RATIO));
6082    }
6083
6084    /// gh #505: no route may conclude `LocalInfeasibility` on its own.
6085    ///
6086    /// Three routes reach that verdict, and two of them independently shipped
6087    /// the same defect — building the terminate outcome directly, so the
6088    /// acceptable-point stash was never consulted and a good point the solve
6089    /// already had in hand was discarded. They were found one at a time,
6090    /// because nothing tied them together.
6091    ///
6092    /// The route a solve takes is an internal detail; the user sees one status
6093    /// either way. So what that status means is decided in one place — every
6094    /// route goes through [`IpoptAlgorithm::terminate_local_infeasibility`],
6095    /// or, for the cycle exits whose fallback is chosen between two statuses
6096    /// at the call site, through `terminate_acceptable_or`. Both consult the
6097    /// stash.
6098    ///
6099    /// **This is a tripwire, not a proof.** It is a substring scan of this
6100    /// file's source for the bare `IterateOutcome::Terminate(SolverReturn::
6101    /// LocalInfeasibility)` construction. A rustfmt line break through that
6102    /// expression, a `let` binding for the status, or a construction in
6103    /// another module all evade it — `application.rs` names the same variant
6104    /// on the SQP and ℓ₁ elastic paths and is deliberately out of scope. What
6105    /// it does buy is that the *obvious* way to add a fourth bare exit here
6106    /// fails loudly and points at the helper, which is the mistake that was
6107    /// actually made twice.
6108    ///
6109    /// The needle is assembled at runtime so this test's own source cannot
6110    /// satisfy the pattern it is checking for; an earlier version counted its
6111    /// own lines and failed against clean code.
6112    #[test]
6113    fn no_route_concludes_local_infeasibility_alone() {
6114        let needle = format!(
6115            "IterateOutcome::Terminate(SolverReturn::{})",
6116            "LocalInfeasibility"
6117        );
6118        let offenders: Vec<usize> = include_str!("ipopt_alg.rs")
6119            .lines()
6120            .enumerate()
6121            .filter(|(_, l)| {
6122                let t = l.trim_start();
6123                !t.starts_with("//") && !t.starts_with("///")
6124            })
6125            .filter(|(_, l)| l.contains(&needle))
6126            .map(|(i, _)| i + 1)
6127            .collect();
6128        assert!(
6129            offenders.is_empty(),
6130            "line(s) {offenders:?} build the local-infeasibility verdict directly. \
6131             Call `terminate_local_infeasibility()` instead — it consults the \
6132             acceptable-point stash first, so a solve that already passed through an \
6133             acceptable iterate returns that point rather than a hard failure. Two \
6134             routes shipped this bug before the helper existed (gh #505)."
6135        );
6136    }
6137}