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