Skip to main content

pounce_solve_report/
lib.rs

1//! Machine-readable JSON solve report (pounce#8).
2//!
3//! Bundles the same payload AMPL's `.sol` carries (status, primal,
4//! dual, suffixes) with FAIR-aligned provenance metadata (solver
5//! identity, input descriptor, timestamp) and per-iteration history
6//! when requested. Schema is versioned via the top-level `schema`
7//! field so future extensions don't silently change semantics.
8//!
9//! FAIR reference: Wilkinson et al. (2016). *The FAIR Guiding
10//! Principles for scientific data management and stewardship.*
11//! Scientific Data, 3, 160018. DOI:
12//! [10.1038/sdata.2016.18](https://doi.org/10.1038/sdata.2016.18).
13//! Verified via Crossref on 2026-05-14.
14//!
15//! # Schema versioning
16//!
17//! The current schema tag is `pounce.solve-report/v1`. Breaking
18//! changes bump the major version (v2 etc.). Adding fields without
19//! removing or renaming existing ones is non-breaking — JSON
20//! consumers should tolerate unknown fields.
21//!
22//! # Detail levels
23//!
24//! [`ReportDetail::Summary`] (default) emits the FAIR metadata,
25//! problem dimensions, final solution, and aggregate statistics
26//! — equivalent to a `.sol` plus provenance. [`ReportDetail::Full`]
27//! additionally emits the per-iteration history (when captured by
28//! [`pounce_algorithm::application::IpoptApplication::enable_iter_history`])
29//! and any `solution.suffixes`. Choose `Summary` for production logs
30//! and `Full` for debug captures.
31
32use std::path::{Path, PathBuf};
33use std::time::{SystemTime, UNIX_EPOCH};
34
35use pounce_common::types::{Index, Number};
36use pounce_linsol::summary::LinearSolverSummary;
37use pounce_nlp::return_codes::ApplicationReturnStatus;
38use pounce_nlp::solve_statistics::{IterRecord, SolveStatistics};
39use serde::{Deserialize, Serialize};
40
41/// Ipopt-style console printers (banner, problem statistics, end-of-run
42/// summary). The single source of truth for the text log: the algorithm's
43/// output layer emits these gated on `print_level`, and the CLI reuses the
44/// banner. Moved out of `pounce-cli` so `pounce-algorithm` can emit them
45/// natively (#206).
46pub mod console;
47
48/// Verbosity knob for the JSON report. Maps onto the `--json-detail`
49/// CLI flag.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ReportDetail {
52    /// FAIR metadata, problem, solution scalars + arrays, aggregate
53    /// stats. Per-iteration history and suffix blocks omitted.
54    Summary,
55    /// Everything in `Summary` plus per-iteration history and any
56    /// suffix outputs (`sens_sol_state_1`, reduced-Hessian blocks).
57    Full,
58}
59
60impl ReportDetail {
61    pub fn parse(s: &str) -> Result<Self, String> {
62        match s.to_ascii_lowercase().as_str() {
63            "summary" => Ok(ReportDetail::Summary),
64            "full" => Ok(ReportDetail::Full),
65            other => Err(format!(
66                "unknown --json-detail '{other}' (expected: summary | full)"
67            )),
68        }
69    }
70}
71
72/// Top-level report struct. Fields are ordered so the JSON has the
73/// most identifying / metadata fields first when pretty-printed.
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct SolveReport {
76    /// Schema identifier. Always
77    /// `"pounce.solve-report/v1"` for this version of the writer.
78    pub schema: String,
79    /// FAIR provenance metadata.
80    pub fair_metadata: FairMetadata,
81    /// Problem dimensions and shape.
82    pub problem: ProblemInfo,
83    /// Final solution payload (status, primal, dual, suffixes).
84    pub solution: SolutionInfo,
85    /// Aggregate statistics (eval counts, KKT residuals, timing).
86    pub statistics: StatisticsInfo,
87    /// Per-iteration history. Empty when the report is at
88    /// [`ReportDetail::Summary`] or iter history was never enabled.
89    #[serde(skip_serializing_if = "Vec::is_empty", default)]
90    pub iterations: Vec<IterRecord>,
91    /// Aggregate linear-solver post-mortem. Populated when the
92    /// workspace-default FERAL backend ran (it self-instruments via
93    /// `feral::Solver::last_factor_stats()`); `None` for HSL MA57 and
94    /// for custom backends plugged through
95    /// [`pounce_algorithm::application::IpoptApplication::set_linear_backend_factory`].
96    /// Additive — older `pounce.solve-report/v1` JSON without this
97    /// field deserializes unchanged.
98    #[serde(skip_serializing_if = "Option::is_none", default)]
99    pub linear_solver: Option<LinearSolverSummaryInfo>,
100    /// What the second-opinion ladder did, when it ran at all. `None` when the
101    /// verdict opened no ladder — which is every ordinary solve.
102    ///
103    /// Additive; older `pounce.solve-report/v1` JSON without this field
104    /// deserializes unchanged.
105    #[serde(skip_serializing_if = "Option::is_none", default)]
106    pub second_opinion: Option<SecondOpinionInfo>,
107}
108
109/// The second-opinion ladder's record: which rungs ran, which (if any) was
110/// promoted, and **what the base solve did before any of it** (gh #850).
111///
112/// # Why the base solve's numbers are the point
113///
114/// On a promotion the reported `status` and `statistics.iteration_count` both
115/// become the promoted rung's, and nothing else in the report says the base
116/// solver failed. That makes a *lost* solve indistinguishable from a faster
117/// one, and it is worse than a gap in the evidence: it produces positive
118/// evidence for the wrong conclusion.
119///
120/// The case that exposed it is `square_flowsheet_resto`, where `v0.10.0`'s
121/// base solver converged in 116 iterations and HEAD's does not converge at all
122/// — `RestorationFailed` at 131 — with the answer coming from a ladder rung
123/// (`start_point_perturbation=1e-2`) added in the same release, which promotes
124/// at 54. `scripts/sweep-fixtures.sh` read that as `116 -> 54`, **a 2× win**.
125///
126/// The cost is understated on top of that: `statistics.iteration_count` is the
127/// promoted rung's alone, so the fixture's true cost is `131 + 54`, 3.4× what
128/// the report says. [`Self::total_iteration_count`] is the honest number.
129///
130/// This is the same shape of invisibility the sweep's engine column was added
131/// to close, and CLAUDE.md's rule applies verbatim: a line whose only moving
132/// field is "solved directly" → "promoted from a rung" is a trajectory change,
133/// and is as reportable as a moved iteration count.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct SecondOpinionInfo {
136    /// Rung labels actually run, in order.
137    pub tried: Vec<String>,
138    /// The rung whose re-solve was promoted, or `None` when the original
139    /// verdict survived every rung and shipped unchanged.
140    #[serde(skip_serializing_if = "Option::is_none", default)]
141    pub promoted_by: Option<String>,
142    /// The verdict the ladder was opened on, before any rung ran.
143    pub base_status: String,
144    /// Iterations the base solve spent. Not included in
145    /// `statistics.iteration_count` when a rung was promoted.
146    pub base_iteration_count: usize,
147    /// Iterations each rung in `tried` spent, in the same order.
148    pub rung_iteration_counts: Vec<usize>,
149    /// Base plus every rung: what the solve actually cost.
150    pub total_iteration_count: usize,
151}
152
153/// Serializable mirror of [`pounce_linsol::summary::LinearSolverSummary`].
154/// Lives in the CLI crate (rather than `pounce-linsol`) so the linsol
155/// trait crate stays serde-free. Field shape is identical; serde
156/// defaults keep it forward-compatible with future additions.
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct LinearSolverSummaryInfo {
159    pub solver_name: String,
160    pub n_factors: u64,
161    pub n_pattern_reuse: u64,
162    pub n_pattern_changes: u64,
163    #[serde(skip_serializing_if = "Option::is_none", default)]
164    pub max_fill_ratio: Option<f64>,
165    #[serde(skip_serializing_if = "Option::is_none", default)]
166    pub min_abs_pivot: Option<f64>,
167    #[serde(skip_serializing_if = "Option::is_none", default)]
168    pub max_abs_pivot: Option<f64>,
169    /// `(positive, negative, zero)` inertia of the final factorisation.
170    #[serde(skip_serializing_if = "Option::is_none", default)]
171    pub last_inertia: Option<(usize, usize, usize)>,
172    #[serde(skip_serializing_if = "Option::is_none", default)]
173    pub last_nnz_a: Option<usize>,
174    #[serde(skip_serializing_if = "Option::is_none", default)]
175    pub last_nnz_l: Option<usize>,
176}
177
178impl From<LinearSolverSummary> for LinearSolverSummaryInfo {
179    fn from(s: LinearSolverSummary) -> Self {
180        Self {
181            solver_name: s.solver_name,
182            n_factors: s.n_factors,
183            n_pattern_reuse: s.n_pattern_reuse,
184            n_pattern_changes: s.n_pattern_changes,
185            max_fill_ratio: s.max_fill_ratio,
186            min_abs_pivot: s.min_abs_pivot,
187            max_abs_pivot: s.max_abs_pivot,
188            last_inertia: s.last_inertia,
189            last_nnz_a: s.last_nnz_a,
190            last_nnz_l: s.last_nnz_l,
191        }
192    }
193}
194
195/// FAIR-aligned provenance block. The four FAIR principles
196/// (Wilkinson et al., 2016) map onto fields here as:
197/// * **F**indable: `result_id` (unique per solve), `created_at_iso`.
198/// * **A**ccessible: this JSON file is the artifact — no protocol
199///   gating, plain text on disk.
200/// * **I**nteroperable: schema versioned, types are JSON primitives,
201///   units documented in field doc comments.
202/// * **R**eusable: `solver`, `license`, `input` describe what was
203///   solved with what code, enough to reproduce.
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct FairMetadata {
206    /// Unique per-solve identifier. Composed as
207    /// `<unix_nanos>-<process_id>` so it is monotonically ordered
208    /// within a process and globally unique across processes.
209    pub result_id: String,
210    /// Solve start time as ISO-8601 UTC (`YYYY-MM-DDTHH:MM:SS.sssZ`).
211    pub created_at_iso: String,
212    /// Same instant in Unix nanoseconds (since 1970-01-01 UTC).
213    /// Provided alongside the ISO string for callers that prefer
214    /// integer arithmetic over date parsing.
215    pub created_at_unix_nanos: i128,
216    /// Wallclock seconds the solve took. Mirrors
217    /// [`SolveStatistics::total_wallclock_time_secs`].
218    pub elapsed_seconds: Number,
219    /// Solver identity — name + version + (best-effort) git commit.
220    pub solver: SolverIdentity,
221    /// SPDX license string. Always `"EPL-2.0"` for this crate.
222    pub license: String,
223    /// Input descriptor. `kind` is `nl-file`, `builtin`, or
224    /// `tnlp-direct` (for library callers).
225    pub input: InputDescriptor,
226    /// Solve-affecting environment variables present in the process
227    /// environment at report time (`POUNCE_FERAL_*` numerics knobs and
228    /// the legacy `FERAL_PIVTOL` / `FERAL_PARALLEL`). These alter the
229    /// factorization or parallelism and can otherwise silently differ a
230    /// run between two machines — e.g. one with `POUNCE_FERAL_PIVTOL`
231    /// exported in a shell profile — with nothing in the report saying
232    /// so (pounce#235). Recorded for reproducibility (the FAIR **R**
233    /// principle). Presence here means the variable was set, not
234    /// necessarily that it took effect: an explicit `OptionsList` setting
235    /// (e.g. a `feral_pivtol` in an options file) takes precedence over
236    /// the env fallback. Empty (and omitted from the JSON) when none are
237    /// set. Additive — older `pounce.solve-report/v1` JSON without this
238    /// field deserializes unchanged.
239    #[serde(skip_serializing_if = "Vec::is_empty", default)]
240    pub environment: Vec<EnvOverride>,
241}
242
243/// One solve-affecting environment variable and its value, as captured
244/// into [`FairMetadata::environment`].
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct EnvOverride {
247    /// Variable name, e.g. `POUNCE_FERAL_PIVTOL`.
248    pub name: String,
249    /// Its value verbatim, as read from the environment.
250    pub value: String,
251}
252
253/// Environment variables that change pounce's numerics or parallelism —
254/// the ones worth recording for reproducibility. Deliberately excludes the
255/// `POUNCE_DBG_*` debug gates (they only add diagnostic output, never
256/// altering the result) and compile-time / logging vars. Kept in a fixed
257/// order so [`capture_solve_env_overrides`] is deterministic.
258const SOLVE_AFFECTING_ENV_VARS: &[&str] = &[
259    "POUNCE_FERAL_ORDERING",
260    "POUNCE_FERAL_SCALING",
261    "POUNCE_FERAL_PIVTOL",
262    "POUNCE_FERAL_REFINE",
263    "POUNCE_FERAL_CASCADE_BREAK",
264    "POUNCE_FERAL_FMA",
265    "POUNCE_FERAL_SINGULAR_PIVOT_FLOOR",
266    "POUNCE_FERAL_MIN_PAR_FLOPS",
267    // Legacy aliases without the `POUNCE_` prefix (still honored by the
268    // FERAL backend): the deprecated pivot-threshold spelling and the
269    // process-wide internal-parallelism switch.
270    "FERAL_PIVTOL",
271    "FERAL_PARALLEL",
272];
273
274/// Snapshot the solve-affecting environment variables ([`SOLVE_AFFECTING_ENV_VARS`])
275/// that are currently set, for [`FairMetadata::environment`]. Reads the
276/// process environment, so call it in the solving process. Returns them in
277/// the fixed list order; absent variables are simply skipped.
278pub fn capture_solve_env_overrides() -> Vec<EnvOverride> {
279    SOLVE_AFFECTING_ENV_VARS
280        .iter()
281        .filter_map(|&name| {
282            std::env::var(name).ok().map(|value| EnvOverride {
283                name: name.to_string(),
284                value,
285            })
286        })
287        .collect()
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct SolverIdentity {
292    pub name: String,
293    pub version: String,
294    /// Git commit hash, captured at build time from the
295    /// `POUNCE_GIT_COMMIT` environment variable. `None` if the build
296    /// environment didn't set it — set via
297    /// `POUNCE_GIT_COMMIT=$(git rev-parse HEAD) cargo build`.
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub git_commit: Option<String>,
300    /// Build target triple (e.g. `x86_64-apple-darwin`). Captured at
301    /// build time from `TARGET` (Cargo standard env var).
302    pub target_triple: String,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize)]
306#[serde(tag = "kind", rename_all = "kebab-case")]
307pub enum InputDescriptor {
308    NlFile {
309        path: PathBuf,
310        #[serde(skip_serializing_if = "Option::is_none")]
311        size_bytes: Option<u64>,
312    },
313    /// A Conic Benchmark Format (`.cbf`) instance — e.g. a CBLIB problem
314    /// solved through the convex conic driver.
315    CbfFile {
316        path: PathBuf,
317        #[serde(skip_serializing_if = "Option::is_none")]
318        size_bytes: Option<u64>,
319    },
320    Builtin {
321        name: String,
322    },
323    TnlpDirect,
324}
325
326#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct ProblemInfo {
328    pub n_variables: Index,
329    pub n_constraints: Index,
330    pub n_objectives: Index,
331    pub minimize: bool,
332    /// Number of non-zeros declared by the TNLP for the constraint
333    /// Jacobian. `None` if not exposed by the input path.
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub nnz_jac_g: Option<Index>,
336    /// Number of non-zeros declared for the Lagrangian Hessian.
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub nnz_h_lag: Option<Index>,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
342pub struct SolutionInfo {
343    /// Which engine produced this verdict: `"cvx-qp"`, `"cvx-qcqp"`,
344    /// `"qp-active-set"`, `"sqp-active-set"` or `"nlp"`.
345    ///
346    /// `"qp-active-set"` and `"sqp-active-set"` are different engines and
347    /// not synonyms: the first is `pounce_convex::active_set` reached by
348    /// `solver_selection=qp-active-set` on an LP or convex QP, the second is
349    /// `pounce_algorithm::sqp`'s outer loop reached by
350    /// `algorithm=active-set-sqp` on a general NLP. Both solve their
351    /// subproblems with `pounce-qp`, which is why the names are close; they
352    /// wrap it in different algorithms, which is why they are not the same
353    /// string.
354    ///
355    /// The `Selected solver:` banner names the engine *routing* chose, which
356    /// is not always the one that answered: a convex solve that declines its
357    /// own result hands the model to the NLP arm (gh #535), and the banner
358    /// has already been printed by then. `scripts/sweep-fixtures.sh` scraped
359    /// that banner because the report carried nothing better, so a reroute
360    /// left no trace in the sweep diff — the precise blind spot CLAUDE.md
361    /// names when it says a routing regression "used to leave no trace".
362    ///
363    /// Empty when a path does not set it, which a consumer should read as
364    /// "unknown" rather than as any particular arm.
365    #[serde(default, skip_serializing_if = "String::is_empty")]
366    pub engine: String,
367    /// `SolveSucceeded`, `MaximumIterationsExceeded`, etc. The string
368    /// form is the Rust enum variant name verbatim.
369    pub status: ApplicationReturnStatus,
370    /// The same verdict in upstream Ipopt's C enumerator spelling —
371    /// `Solve_Succeeded`, `Infeasible_Problem_Detected` — from
372    /// `IpReturnCodes_inc.h`.
373    ///
374    /// [`Self::status`] carries the Rust variant name, which is *not* the
375    /// name any Ipopt-facing consumer already keys off: CUTEst status
376    /// tables, `benchmarks/scripts/run_nl_bench.sh`, the reference JSONs
377    /// under `benchmarks/*/ipopt_ma57.json` and the CLI's own `Status:`
378    /// line all spell it with separators. A consumer comparing
379    /// `solution.status == "Solve_Succeeded"` against the report matched
380    /// nothing and silently classified every solve as a failure (gh #767).
381    /// This field is that spelling, so the comparison can be literal.
382    ///
383    /// Derived from [`Self::status`] by [`ReportBuilder::finish`] — never
384    /// set by a caller, so the two cannot disagree. Empty when read back
385    /// from a pre-#767 report.
386    #[serde(default)]
387    pub status_upstream: String,
388    /// AMPL-style solve-result code (Gay 2005, §5 p. 23 table).
389    pub solve_result_num: i32,
390    /// Final unscaled objective value (mirrors
391    /// `SolveStatistics::final_objective`). `NaN` if unknown.
392    pub objective: Number,
393    /// Final primal vector, length `problem.n_variables`. Empty if
394    /// not captured.
395    #[serde(skip_serializing_if = "Vec::is_empty", default)]
396    pub x: Vec<Number>,
397    /// Final dual (constraint multiplier) vector, length
398    /// `problem.n_constraints`.
399    #[serde(skip_serializing_if = "Vec::is_empty", default)]
400    pub lambda: Vec<Number>,
401    /// Optional sIPOPT-style suffix blocks (`sens_sol_state_1` etc.).
402    /// Stored as a flat map keyed by suffix name → list of
403    /// `(index, value)` pairs, matching the AMPL `.sol` shape.
404    /// Empty when no sensitivity / reduced-Hessian step ran.
405    #[serde(skip_serializing_if = "Vec::is_empty", default)]
406    pub suffixes: Vec<SolutionSuffix>,
407}
408
409#[derive(Debug, Clone, Serialize, Deserialize)]
410pub struct SolutionSuffix {
411    pub name: String,
412    /// `"var" | "con" | "obj" | "problem"` per AMPL convention.
413    pub target: String,
414    /// `"int"` or `"real"`.
415    pub kind: String,
416    /// Dense values (length = target dimension); zero-filled for
417    /// slots the writer didn't populate. Real-typed values are stored
418    /// here; int-typed in `int_values`.
419    #[serde(skip_serializing_if = "Vec::is_empty", default)]
420    pub values: Vec<Number>,
421    #[serde(skip_serializing_if = "Vec::is_empty", default)]
422    pub int_values: Vec<Index>,
423}
424
425/// NaN, for a residual slot that was never filled in.
426fn uncomputed() -> Number {
427    Number::NAN
428}
429
430/// Accept `null` for a residual the solve never computed.
431///
432/// `SolveStatistics` defaults its residual fields to NaN rather than `0.0`, so
433/// that "the convergence check never ran" is distinguishable from "converged
434/// exactly". `serde_json` renders a non-finite float as `null`, so a report
435/// written for a solve that was refused during setup carries `null` in these
436/// slots. Without this the report round-trip fails — pounce would write
437/// reports its own `--cite` / studio / verify paths could not read back.
438fn null_as_nan<'de, D>(de: D) -> Result<Number, D::Error>
439where
440    D: serde::Deserializer<'de>,
441{
442    Ok(Option::<Number>::deserialize(de)?.unwrap_or_else(uncomputed))
443}
444
445/// Subset of `SolveStatistics` projected for the report. Mirrors the
446/// fields the existing console summary prints.
447#[derive(Debug, Clone, Serialize, Deserialize)]
448pub struct StatisticsInfo {
449    pub iteration_count: Index,
450    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
451    pub final_objective: Number,
452    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
453    pub final_scaled_objective: Number,
454    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
455    pub final_dual_inf: Number,
456    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
457    pub final_constr_viol: Number,
458    /// Primal violation against the model **as declared**, before the convex
459    /// arm's `bound_relax_factor` widening (`qp_extract::BoundRelax`, gh
460    /// #744/#745).
461    ///
462    /// `final_constr_viol` measures the model the solver was HANDED, whose
463    /// inequality rows and variable box are widened by `min(factor,cap)·|b|`.
464    /// That is the model its convergence test is about and every acceptance
465    /// gate reads — and it is not how far the returned point sits outside the
466    /// model the caller wrote. On netlib `afiro` the point is `4.99e-06`
467    /// outside a declared row `b = 500` (exactly `1e-8·500`) while
468    /// `final_constr_viol` reads `8.68e-13`; `25fv47` reports `2.19e-11`
469    /// against `1.97e-05`.
470    ///
471    /// `NaN` when the solve applied no widening (the two coincide by
472    /// construction) or on a path that does not compute it — every NLP-arm
473    /// solve today. Additive to `pounce.solve-report/v1`: readers predating
474    /// it are unaffected.
475    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
476    pub final_declared_constr_viol: Number,
477    /// How far the returned point sits outside the **declared** variable box —
478    /// the box the caller wrote, before the `bound_relax_factor` widening.
479    /// Ipopt's `Variable bound violation`, and the box half of
480    /// `final_declared_constr_viol` reported on its own: maxed together, a box
481    /// violation and a row violation cannot be told apart.
482    ///
483    /// Variable bounds carry no scaling, so there is one number rather than a
484    /// scaled/unscaled pair. `NaN` on a path that does not compute it.
485    /// Additive to `pounce.solve-report/v1`: readers predating it are
486    /// unaffected.
487    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
488    pub final_declared_box_viol: Number,
489    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
490    pub final_compl: Number,
491    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
492    pub final_kkt_error: Number,
493    /// The aggregate the strict convergence gate tested (gh #528): as
494    /// `final_kkt_error`, but counting each constraint row's residual only
495    /// where it exceeds what that row can represent in floating point. Equal
496    /// to `final_kkt_error` unless a row is at its own resolution limit.
497    #[serde(default = "uncomputed", deserialize_with = "null_as_nan")]
498    pub final_kkt_error_above_noise: Number,
499    pub num_obj_evals: Index,
500    pub num_constr_evals: Index,
501    pub num_obj_grad_evals: Index,
502    pub num_constr_jac_evals: Index,
503    pub num_hess_evals: Index,
504    pub total_wallclock_time_secs: Number,
505    pub restoration_calls: Index,
506    pub restoration_inner_iters: Index,
507    pub restoration_outer_iters: Index,
508    pub restoration_wall_secs: Number,
509    /// Successful linear-solver quality escalations over the whole solve,
510    /// restoration sub-solves included (gh#857). `0` on paths that never
511    /// escalate. `serde(default)` so a report written before this field
512    /// existed still deserializes — it reads as "no escalations", which
513    /// is wrong-but-harmless for an old file and correct for every new
514    /// one.
515    #[serde(default)]
516    pub quality_escalations: Index,
517    /// The solve saw the gh#884 biactive dual-divergence signature: at one
518    /// and the same iterate a converged primal, a scale-relative step at
519    /// zero, and an *unscaled* dual infeasibility far above `dual_inf_tol`.
520    /// Reported whether or not a retry ran or promoted, because the
521    /// distinction it draws — the multipliers ran away on a settled
522    /// iterate, as against the iterate itself never settling — is not
523    /// visible in any other field. `serde(default)` for the same reason as
524    /// `quality_escalations`.
525    #[serde(default)]
526    pub dual_divergence_signature: bool,
527    /// A gh#884 dual-divergence retry ran *and* its answer was returned.
528    /// `false` both when no retry ran and when one ran and lost — in the
529    /// latter case every other field here describes the base attempt.
530    #[serde(default)]
531    pub dual_divergence_retry_promoted: bool,
532}
533
534/// Builder collecting the inputs for a [`SolveReport`]. The CLI
535/// drivers populate one of these as they walk through the solve and
536/// `finish()` it at the end.
537pub struct ReportBuilder {
538    detail: ReportDetail,
539    started_at: SystemTime,
540    started_unix_nanos: i128,
541    pub input: InputDescriptor,
542    pub problem: ProblemInfo,
543    pub solution: SolutionInfo,
544    pub stats: StatisticsInfo,
545    pub iterations: Vec<IterRecord>,
546    pub linear_solver: Option<LinearSolverSummaryInfo>,
547    pub second_opinion: Option<SecondOpinionInfo>,
548}
549
550impl ReportBuilder {
551    pub fn new(detail: ReportDetail, input: InputDescriptor) -> Self {
552        let now = SystemTime::now();
553        let nanos = now
554            .duration_since(UNIX_EPOCH)
555            .map(|d| d.as_nanos() as i128)
556            .unwrap_or(0);
557        Self {
558            detail,
559            started_at: now,
560            started_unix_nanos: nanos,
561            input,
562            problem: ProblemInfo {
563                n_variables: 0,
564                n_constraints: 0,
565                n_objectives: 0,
566                minimize: true,
567                nnz_jac_g: None,
568                nnz_h_lag: None,
569            },
570            solution: SolutionInfo {
571                engine: String::new(),
572                status: ApplicationReturnStatus::InternalError,
573                // Overwritten from `status` by `finish`; see the field docs.
574                status_upstream: String::new(),
575                solve_result_num: 500,
576                // 0.0 (not NaN) so JSON round-trips. Callers that
577                // need "unknown objective" semantics check
578                // `statistics.iteration_count > 0` first.
579                objective: 0.0,
580                x: Vec::new(),
581                lambda: Vec::new(),
582                suffixes: Vec::new(),
583            },
584            stats: empty_stats(),
585            iterations: Vec::new(),
586            linear_solver: None,
587            second_opinion: None,
588        }
589    }
590
591    /// Record what the second-opinion ladder did. Called only when it ran; a
592    /// verdict that opens no ladder leaves this `None` and the field out of
593    /// the JSON entirely (gh #850).
594    pub fn set_second_opinion(&mut self, info: SecondOpinionInfo) {
595        self.second_opinion = Some(info);
596    }
597
598    /// Attach a linear-solver post-mortem. Called once per solve after
599    /// `optimize_tnlp` returns and before [`Self::finish`].
600    pub fn set_linear_solver_summary(&mut self, summary: LinearSolverSummary) {
601        self.linear_solver = Some(summary.into());
602    }
603
604    /// Pull `iteration_count`, `final_*`, and counters into the
605    /// `stats` slot; copy `iterations` only if detail = Full.
606    pub fn ingest_stats(&mut self, src: &SolveStatistics) {
607        self.stats = StatisticsInfo {
608            iteration_count: src.iteration_count,
609            final_objective: src.final_objective,
610            final_scaled_objective: src.final_scaled_objective,
611            final_dual_inf: src.final_dual_inf,
612            final_constr_viol: src.final_constr_viol,
613            final_declared_constr_viol: src.final_declared_constr_viol,
614            final_declared_box_viol: src.final_declared_box_viol,
615            final_compl: src.final_compl,
616            final_kkt_error: src.final_kkt_error,
617            final_kkt_error_above_noise: src.final_kkt_error_above_noise,
618            num_obj_evals: src.num_obj_evals,
619            num_constr_evals: src.num_constr_evals,
620            num_obj_grad_evals: src.num_obj_grad_evals,
621            num_constr_jac_evals: src.num_constr_jac_evals,
622            num_hess_evals: src.num_hess_evals,
623            total_wallclock_time_secs: src.total_wallclock_time_secs,
624            restoration_calls: src.restoration_calls,
625            restoration_inner_iters: src.restoration_inner_iters,
626            restoration_outer_iters: src.restoration_outer_iters,
627            restoration_wall_secs: src.restoration_wall_secs,
628            quality_escalations: src.quality_escalations,
629            dual_divergence_signature: src.dual_divergence_signature,
630            dual_divergence_retry_promoted: src.dual_divergence_retry_promoted,
631        };
632        if matches!(self.detail, ReportDetail::Full) {
633            self.iterations = src.iterations.clone();
634        }
635    }
636
637    pub fn finish(self) -> SolveReport {
638        let elapsed = self
639            .started_at
640            .elapsed()
641            .map(|d| d.as_secs_f64())
642            .unwrap_or(0.0);
643        // Derived here rather than at each call site: every producer of a
644        // report (CLI, C interface, Python bindings, the CBF driver) sets
645        // `solution.status` and none of them can forget the upstream
646        // spelling, nor set one that disagrees with the other (gh #767).
647        let mut solution = self.solution;
648        solution.status_upstream = solution.status.upstream_name().to_string();
649        let result_id = format!("{}-{}", self.started_unix_nanos, std::process::id());
650        let created_at_iso = unix_nanos_to_iso(self.started_unix_nanos);
651
652        SolveReport {
653            schema: "pounce.solve-report/v1".to_string(),
654            fair_metadata: FairMetadata {
655                result_id,
656                created_at_iso,
657                created_at_unix_nanos: self.started_unix_nanos,
658                elapsed_seconds: elapsed,
659                solver: SolverIdentity {
660                    name: "pounce".to_string(),
661                    version: env!("CARGO_PKG_VERSION").to_string(),
662                    git_commit: option_env!("POUNCE_GIT_COMMIT").map(String::from),
663                    target_triple: TARGET_TRIPLE.to_string(),
664                },
665                license: "EPL-2.0".to_string(),
666                input: self.input,
667                environment: capture_solve_env_overrides(),
668            },
669            problem: self.problem,
670            solution,
671            statistics: self.stats,
672            iterations: self.iterations,
673            linear_solver: self.linear_solver,
674            second_opinion: self.second_opinion,
675        }
676    }
677}
678
679/// The build target triple (e.g. `aarch64-apple-darwin`).
680///
681/// Cargo only exposes `TARGET` to *build scripts*, not to crate source, so
682/// `option_env!("TARGET")` here is always `None`. Our `build.rs` re-exports
683/// the build script's `TARGET` as `POUNCE_TARGET_TRIPLE`, which we read
684/// instead. Falls back to "unknown" if the build script did not run (e.g.
685/// some non-Cargo tooling).
686const TARGET_TRIPLE: &str = match option_env!("POUNCE_TARGET_TRIPLE") {
687    Some(t) => t,
688    None => "unknown",
689};
690
691fn empty_stats() -> StatisticsInfo {
692    // All scalar fields start at 0.0 (not NaN) so the report
693    // round-trips through `serde_json` — JSON has no NaN literal, and
694    // serde_json's default is to write `null` for NaN, which then
695    // fails to deserialize back into `Number`. Callers reading these
696    // pre-solve treat `iteration_count == 0` as "no solve yet".
697    StatisticsInfo {
698        iteration_count: 0,
699        final_objective: 0.0,
700        final_scaled_objective: 0.0,
701        final_dual_inf: 0.0,
702        final_constr_viol: 0.0,
703        // not "uncomputed": this is the pre-solve placeholder, and 0.0 is
704        // what every residual beside it carries here.
705        final_declared_constr_viol: 0.0,
706        final_declared_box_viol: 0.0,
707        final_compl: 0.0,
708        final_kkt_error: 0.0,
709        final_kkt_error_above_noise: 0.0,
710        num_obj_evals: 0,
711        num_constr_evals: 0,
712        num_obj_grad_evals: 0,
713        num_constr_jac_evals: 0,
714        num_hess_evals: 0,
715        total_wallclock_time_secs: 0.0,
716        restoration_calls: 0,
717        restoration_inner_iters: 0,
718        restoration_outer_iters: 0,
719        restoration_wall_secs: 0.0,
720        quality_escalations: 0,
721        dual_divergence_signature: false,
722        dual_divergence_retry_promoted: false,
723    }
724}
725
726/// AMPL-style `solve_result_num` per Gay 2005 (Hooking Your Solver to
727/// AMPL §5, p. 23 table): 0 = solved, 100s = warning, 200s =
728/// infeasible, 300s = unbounded, 400s = limit reached, 500s = failure.
729/// Shared by the CLI and cinterface report writers so both encode the
730/// same int codes into `SolutionInfo::solve_result_num`.
731///
732/// `DivergingIterates` is Ipopt's unboundedness signal (the iterates run
733/// off to infinity), so it maps to the 300 "unbounded" range — matching
734/// upstream Ipopt's ASL driver and the CLI's own convex path, which
735/// reports `QpStatus::DualInfeasible` (unbounded) as 300 (`main.rs`). It
736/// is *not* a limit (400) condition.
737///
738/// `SolvedToAcceptableLevel` is `1`, not the 100 band, matching Ipopt's
739/// ASL driver exactly (`Ipopt/src/Apps/AmplSolver/AmplTNLP.cpp`:
740/// `STOP_AT_ACCEPTABLE_POINT` → `solve_result_num = 1`, message
741/// "Solved To Acceptable Level."). The band is what consumers key on, and
742/// the two bands are not interchangeable here: Pyomo's legacy `.sol`
743/// reader turns `0..=99` into `status=ok` but `100..=199` into
744/// `status=warning` with the same `termination_condition=optimal`, so the
745/// 100 band made Pyomo log a "Loading a SolverResults object with a
746/// warning status" warning on an accepted solve that Ipopt loads clean —
747/// breaking solver-swappable clients whose accepted-solve contract
748/// includes `status == ok` (gh #591). The reduced-accuracy convergence
749/// stays visible in the status name and the `.sol` message line; it just
750/// no longer reads as a warning.
751///
752/// `FeasiblePointFound` is `2`, Ipopt's own code, and therefore in the
753/// `0..=99` solved band. It used to be `100`, justified by the claim that
754/// the two statuses do not mean the same thing — that Ipopt returns
755/// `FEASIBLE_POINT_FOUND` only for a square problem, where a feasible
756/// point *is* the solution, while POUNCE used it more loosely for any
757/// usable feasible point that missed the convergence criteria.
758///
759/// That claim was false about POUNCE's own code. The status has exactly
760/// one production site: `min_c_1nrm.rs` returns
761/// `RestorationOutcome::FeasiblePointFound`, reached only through the
762/// gate at `resto_inner_solver.rs`, which is `is_square_problem && ...`.
763/// `is_square_problem()` (`ipopt_alg.rs`) is `c.x.dim() == c.y_c.dim()`,
764/// a port of `IpoptCalculatedQuantities::IsSquareProblem` — the same
765/// condition Ipopt uses. So POUNCE emits this status *only* for square
766/// problems, carrying Ipopt's meaning precisely, and on a square problem
767/// there is no further convergence criterion to miss: the objective is
768/// constant, so a feasible point is the solution.
769///
770/// The band is what consumers key on, and `100` was not a softer way of
771/// saying the same thing — it inverted the answer. Pyomo's v2 reader
772/// (`pyomo/contrib/solver/solvers/asl_sol_reader.py`) maps `100..=199` to
773/// `TerminationCondition.error`, so a correct square-problem solve
774/// reached the caller as a *solver error*; the legacy reader
775/// (`pyomo/opt/plugins/sol.py`) maps it to `optimal` + `status=warning`,
776/// the same gh #591 warning `SolvedToAcceptableLevel` was moved out of the
777/// band to escape. Ipopt on the identical solve loads clean in both. This
778/// is what gh #815 surfaced: an IDAES square flowsheet that POUNCE solves
779/// to a constraint violation of 2.2e-06 was reported as a failure.
780///
781/// This crate is not the only place that had to agree. `python/pounce/gams/link.py`
782/// already mapped the status to `(MODELSTAT_FEASIBLE, SOLVESTAT_NORMAL)`
783/// and listed it as a success, and
784/// `crates/pounce-algorithm/tests/issue_390_nonlinear_equality_scale.rs`
785/// already called it "a success-band answer — AMPL `objno` code 2, which
786/// every band table reads as SOLVED". The two Pyomo tables
787/// (`pyomo_pounce.v2._V2_STATUS`, `pyomo_pounce.sens._STATUS_RESULT`) were
788/// the dissenters and moved with this change.
789///
790/// Being in the solved band is *not* a claim that any feasible point is
791/// acceptable. `issue_390_nonlinear_equality_scale.rs` is the guard that a
792/// model with no solution is never reported feasible at any row scale; the
793/// relative-violation threshold at `resto_inner_solver.rs` is what keeps
794/// that true. This mapping decides how a verdict is reported, not when it
795/// is reached.
796pub fn status_to_solve_result_num(status: ApplicationReturnStatus) -> i32 {
797    use ApplicationReturnStatus::*;
798    match status {
799        SolveSucceeded => 0,
800        SolvedToAcceptableLevel => 1,
801        FeasiblePointFound => 2,
802        InfeasibleProblemDetected => 200,
803        DivergingIterates => 300,
804        SearchDirectionBecomesTooSmall => 400,
805        MaximumIterationsExceeded => 400,
806        MaximumCpuTimeExceeded => 400,
807        MaximumWallTimeExceeded => 400,
808        UserRequestedStop => 502,
809        RestorationFailed => 500,
810        ErrorInStepComputation => 500,
811        InvalidNumberDetected => 500,
812        InternalError => 500,
813        UnrecoverableException => 500,
814        NonIpoptExceptionThrown => 500,
815        InsufficientMemory => 503,
816        InvalidProblemDefinition => 504,
817        InvalidOption => 504,
818        NotEnoughDegreesOfFreedom => 504,
819    }
820}
821
822/// Write a [`SolveReport`] to `path` as pretty-printed JSON. Returns
823/// bytes written on success.
824pub fn write_report_file(path: &Path, report: &SolveReport) -> std::io::Result<usize> {
825    let s = serde_json::to_string_pretty(report)
826        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
827    std::fs::write(path, &s)?;
828    Ok(s.len())
829}
830
831/// Convert Unix nanoseconds since the epoch to an ISO-8601 UTC
832/// timestamp `YYYY-MM-DDTHH:MM:SS.sssZ`. Pure stdlib; no chrono /
833/// time dependency. The conversion is based on the proleptic
834/// Gregorian calendar formula from Howard Hinnant's "date" reference
835/// (https://howardhinnant.github.io/date_algorithms.html), `days_from_civil`
836/// in reverse — verified against `date -u -r <secs>` for several
837/// epochs on 2026-05-14.
838fn unix_nanos_to_iso(nanos: i128) -> String {
839    let total_secs = nanos.div_euclid(1_000_000_000) as i64;
840    let frac_nanos = nanos.rem_euclid(1_000_000_000) as i64;
841    let millis = frac_nanos / 1_000_000;
842
843    let days = total_secs.div_euclid(86_400);
844    let secs_of_day = total_secs.rem_euclid(86_400);
845    let hh = (secs_of_day / 3600) as i32;
846    let mm = ((secs_of_day % 3600) / 60) as i32;
847    let ss = (secs_of_day % 60) as i32;
848
849    // Howard Hinnant's `civil_from_days` algorithm:
850    //   z = days + 719468
851    //   era = (z >= 0 ? z : z - 146096) / 146097
852    //   doe = z - era*146097
853    //   yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365
854    //   y = yoe + era*400
855    //   doy = doe - (365*yoe + yoe/4 - yoe/100)
856    //   mp = (5*doy + 2) / 153
857    //   d = doy - (153*mp + 2)/5 + 1
858    //   m = mp < 10 ? mp + 3 : mp - 9
859    //   y += (m <= 2)
860    let z: i64 = days + 719468;
861    let era = if z >= 0 { z } else { z - 146096 } / 146097;
862    let doe = (z - era * 146097) as i64; // [0, 146096]
863    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
864    let mut y = yoe + era * 400;
865    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
866    let mp = (5 * doy + 2) / 153; // [0, 11]
867    let d = (doy - (153 * mp + 2) / 5 + 1) as i32;
868    let m = if mp < 10 { mp + 3 } else { mp - 9 } as i32;
869    if m <= 2 {
870        y += 1;
871    }
872
873    format!(
874        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
875        y, m, d, hh, mm, ss, millis
876    )
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    #[test]
884    fn iso_formatter_matches_known_epochs() {
885        // Epoch.
886        assert_eq!(unix_nanos_to_iso(0), "1970-01-01T00:00:00.000Z");
887        // 2000-01-01T00:00:00Z = 946684800 seconds.
888        assert_eq!(
889            unix_nanos_to_iso(946_684_800_000_000_000),
890            "2000-01-01T00:00:00.000Z",
891        );
892        // 2024-02-29T12:34:56.789Z (leap-year sanity check).
893        // Seconds: (2024 - 1970) * 365.25 days * 86400 ≈ 1709209296 — let's compute exactly.
894        // Days from 1970-01-01 to 2024-02-29: 19782.
895        // 19782 * 86400 = 1709164800. Plus 12*3600 + 34*60 + 56 = 45296.
896        // Total = 1709210096.
897        let s = unix_nanos_to_iso(1_709_210_096_789_000_000);
898        assert_eq!(s, "2024-02-29T12:34:56.789Z", "got: {s}");
899    }
900
901    #[test]
902    fn target_triple_resolves_to_real_triple_not_unknown() {
903        // Fail-first: before the build.rs re-export this constant read
904        // `option_env!("TARGET")`, which is `None` at crate-source compile
905        // time (Cargo only exposes TARGET to build scripts), so it was always
906        // "unknown". The build.rs now re-exports TARGET as
907        // POUNCE_TARGET_TRIPLE, which resolves it to the real build triple.
908        assert_ne!(
909            TARGET_TRIPLE, "unknown",
910            "build.rs should re-export the build target triple"
911        );
912        // A real triple has the `arch-vendor-os[-abi]` shape (>= 2 dashes).
913        assert!(
914            TARGET_TRIPLE.matches('-').count() >= 2,
915            "unexpected target triple: {TARGET_TRIPLE:?}"
916        );
917
918        // And it must propagate into the finished report.
919        let b = ReportBuilder::new(
920            ReportDetail::Summary,
921            InputDescriptor::NlFile {
922                path: PathBuf::from("/tmp/foo.nl"),
923                size_bytes: None,
924            },
925        );
926        let report = b.finish();
927        assert_eq!(report.fair_metadata.solver.target_triple, TARGET_TRIPLE);
928        assert_ne!(report.fair_metadata.solver.target_triple, "unknown");
929    }
930
931    #[test]
932    fn report_serializes_round_trip() {
933        let mut b = ReportBuilder::new(
934            ReportDetail::Summary,
935            InputDescriptor::NlFile {
936                path: PathBuf::from("/tmp/foo.nl"),
937                size_bytes: Some(123),
938            },
939        );
940        b.problem.n_variables = 5;
941        b.problem.n_constraints = 4;
942        b.solution.status = ApplicationReturnStatus::SolveSucceeded;
943        b.solution.solve_result_num = 0;
944        b.solution.objective = 0.55;
945        b.solution.x = vec![0.63, 0.39, 0.02, 5.0, 1.0];
946        b.solution.lambda = vec![-0.16, -0.29, -0.16, 0.18];
947        b.stats.iteration_count = 9;
948
949        let report = b.finish();
950        let json = serde_json::to_string_pretty(&report).expect("serialize");
951        let back: SolveReport = serde_json::from_str(&json).expect("deserialize");
952        assert_eq!(back.schema, "pounce.solve-report/v1");
953        assert_eq!(back.problem.n_variables, 5);
954        assert_eq!(back.solution.x.len(), 5);
955        assert!(matches!(
956            back.solution.status,
957            ApplicationReturnStatus::SolveSucceeded,
958        ));
959    }
960
961    /// gh #767: the report is the FAIR-aligned machine surface, and a
962    /// consumer keyed on Ipopt's own enumerator spelling — which is what
963    /// CUTEst tables, the reference JSONs and the CLI's `Status:` line all
964    /// use — must be able to compare a field literally. `status` carries
965    /// the Rust variant name (`SolveSucceeded`); `status_upstream` carries
966    /// `Solve_Succeeded`. A consumer that compared the former against the
967    /// latter's spelling matched nothing and read every solve as a failure.
968    #[test]
969    fn report_carries_the_upstream_status_spelling_beside_the_rust_one() {
970        let mut b = ReportBuilder::new(
971            ReportDetail::Summary,
972            InputDescriptor::Builtin {
973                name: "rosenbrock".into(),
974            },
975        );
976        b.solution.status = ApplicationReturnStatus::SolveSucceeded;
977        let json = serde_json::to_value(b.finish()).expect("serialize");
978        assert_eq!(json["solution"]["status"], "SolveSucceeded");
979        assert_eq!(json["solution"]["status_upstream"], "Solve_Succeeded");
980    }
981
982    /// The derived field tracks whatever `status` was last set to — it is
983    /// computed in `finish`, so a caller cannot leave it stale or set the
984    /// two to different verdicts.
985    #[test]
986    fn upstream_status_spelling_is_derived_not_stored() {
987        for status in [
988            ApplicationReturnStatus::MaximumIterationsExceeded,
989            ApplicationReturnStatus::InfeasibleProblemDetected,
990            ApplicationReturnStatus::SolvedToAcceptableLevel,
991        ] {
992            let mut b = ReportBuilder::new(
993                ReportDetail::Summary,
994                InputDescriptor::Builtin { name: "x".into() },
995            );
996            // Deliberately wrong; `finish` must overwrite it.
997            b.solution.status_upstream = "Solve_Succeeded".to_string();
998            b.solution.status = status;
999            let report = b.finish();
1000            assert_eq!(report.solution.status_upstream, status.upstream_name());
1001        }
1002    }
1003
1004    #[test]
1005    fn summary_detail_omits_iterations_block() {
1006        let mut b = ReportBuilder::new(
1007            ReportDetail::Summary,
1008            InputDescriptor::Builtin {
1009                name: "rosenbrock".into(),
1010            },
1011        );
1012        let mut stats = SolveStatistics::default();
1013        stats.iterations.push(IterRecord {
1014            iter: 0,
1015            objective: 1.0,
1016            ..IterRecord::default()
1017        });
1018        b.ingest_stats(&stats);
1019        let r = b.finish();
1020        assert!(
1021            r.iterations.is_empty(),
1022            "Summary detail should drop iter history; got {} rows",
1023            r.iterations.len()
1024        );
1025        // And the JSON should not include the key at all (skip-empty).
1026        let json = serde_json::to_string(&r).unwrap();
1027        assert!(!json.contains("\"iterations\":"), "json: {json}");
1028    }
1029
1030    #[test]
1031    fn full_detail_includes_iteration_rows() {
1032        let mut b = ReportBuilder::new(ReportDetail::Full, InputDescriptor::TnlpDirect);
1033        let mut stats = SolveStatistics::default();
1034        stats.iterations.push(IterRecord {
1035            iter: 0,
1036            objective: 1.0,
1037            inf_pr: 0.5,
1038            ..IterRecord::default()
1039        });
1040        stats.iterations.push(IterRecord {
1041            iter: 1,
1042            objective: 0.5,
1043            inf_pr: 0.1,
1044            ..IterRecord::default()
1045        });
1046        b.ingest_stats(&stats);
1047        let r = b.finish();
1048        assert_eq!(r.iterations.len(), 2);
1049        assert_eq!(r.iterations[0].iter, 0);
1050        assert_eq!(r.iterations[1].iter, 1);
1051    }
1052
1053    #[test]
1054    fn detail_parser_accepts_known_values() {
1055        assert_eq!(
1056            ReportDetail::parse("summary").unwrap(),
1057            ReportDetail::Summary
1058        );
1059        assert_eq!(ReportDetail::parse("Full").unwrap(), ReportDetail::Full);
1060        assert!(ReportDetail::parse("verbose").is_err());
1061    }
1062
1063    #[test]
1064    fn diverging_iterates_maps_to_unbounded_range() {
1065        use ApplicationReturnStatus::*;
1066        // M12 regression: DivergingIterates is Ipopt's unboundedness
1067        // signal and must land in the AMPL 300 "unbounded" range, not
1068        // the 400 "limit" range — matching upstream Ipopt's ASL driver
1069        // and the CLI convex path (QpStatus::DualInfeasible → 300).
1070        assert_eq!(status_to_solve_result_num(DivergingIterates), 300);
1071
1072        // Lock the surrounding range convention so the fix can't silently
1073        // drift back: solved / infeasible / limit / failure buckets.
1074        assert_eq!(status_to_solve_result_num(SolveSucceeded), 0);
1075        assert_eq!(status_to_solve_result_num(InfeasibleProblemDetected), 200);
1076        assert_eq!(
1077            status_to_solve_result_num(MaximumIterationsExceeded),
1078            400,
1079            "iteration limit stays in the 400 range",
1080        );
1081        assert_eq!(
1082            status_to_solve_result_num(SearchDirectionBecomesTooSmall),
1083            400,
1084        );
1085        assert_eq!(status_to_solve_result_num(RestorationFailed), 500);
1086    }
1087
1088    /// gh #591: an accepted (reduced-accuracy) solve must land in AMPL's
1089    /// `0..=99` *solved* band with Ipopt's own code, `1`. In the 100 band
1090    /// Pyomo's legacy `.sol` reader loads the result as
1091    /// `status=warning, termination_condition=optimal` and logs a warning,
1092    /// while the identical Ipopt solve loads as `status=ok` — so a
1093    /// solver-swappable client that treats `status == ok` as part of its
1094    /// accepted-solve contract had to special-case POUNCE.
1095    #[test]
1096    fn solved_to_acceptable_level_is_in_the_solved_band_like_ipopt() {
1097        use ApplicationReturnStatus::*;
1098        let code = status_to_solve_result_num(SolvedToAcceptableLevel);
1099        assert_eq!(
1100            code, 1,
1101            "Ipopt's ASL driver emits 1 for STOP_AT_ACCEPTABLE_POINT",
1102        );
1103        assert!(
1104            (0..=99).contains(&code),
1105            "must be in the solved band Pyomo maps to status=ok, got {code}",
1106        );
1107        // Still distinguishable from a full-accuracy solve: the two codes
1108        // differ, and the status name carries the distinction verbatim into
1109        // the `.sol` message line.
1110        assert_ne!(code, status_to_solve_result_num(SolveSucceeded));
1111
1112        // `FeasiblePointFound` is also in the solved band, for its own
1113        // reason — see `a_square_problem_feasible_point_is_in_the_solved_band`.
1114        assert_ne!(code, status_to_solve_result_num(FeasiblePointFound));
1115    }
1116
1117    /// POUNCE emits `FeasiblePointFound` only for square problems — the
1118    /// status has one production site (`min_c_1nrm.rs`) behind one gate
1119    /// (`resto_inner_solver.rs`), and that gate is `is_square_problem &&
1120    /// ...`. That is exactly Ipopt's meaning, and on a square problem a
1121    /// feasible point *is* the solution, so the code is Ipopt's own `2`.
1122    ///
1123    /// The band, not the number, is what breaks: at `100` Pyomo's v2 ASL
1124    /// reader returns `TerminationCondition.error` for a correct solve
1125    /// (gh #815 — an IDAES flowsheet solved to a 2.2e-06 constraint
1126    /// violation and reported as a solver error), and the legacy reader
1127    /// returns `status=warning`, the same gh #591 complaint that moved
1128    /// `SolvedToAcceptableLevel` out of the band.
1129    #[test]
1130    fn a_square_problem_feasible_point_is_in_the_solved_band() {
1131        use ApplicationReturnStatus::*;
1132        let code = status_to_solve_result_num(FeasiblePointFound);
1133        assert_eq!(
1134            code, 2,
1135            "Ipopt's ASL driver emits 2 for FEASIBLE_POINT_FOUND"
1136        );
1137        assert!(
1138            (0..=99).contains(&code),
1139            "must be in the solved band both Pyomo readers accept, got {code}",
1140        );
1141        // Still its own verdict: distinguishable from both other members of
1142        // the band, with the distinction carried verbatim in the status name
1143        // and the `.sol` message line.
1144        assert_ne!(code, status_to_solve_result_num(SolveSucceeded));
1145        assert_ne!(code, status_to_solve_result_num(SolvedToAcceptableLevel));
1146    }
1147
1148    #[test]
1149    fn result_id_is_unique_and_time_ordered() {
1150        let a = ReportBuilder::new(ReportDetail::Summary, InputDescriptor::TnlpDirect).finish();
1151        std::thread::sleep(std::time::Duration::from_millis(2));
1152        let b = ReportBuilder::new(ReportDetail::Summary, InputDescriptor::TnlpDirect).finish();
1153        assert_ne!(a.fair_metadata.result_id, b.fair_metadata.result_id);
1154        assert!(
1155            b.fair_metadata.created_at_unix_nanos > a.fair_metadata.created_at_unix_nanos,
1156            "second result_id should sort after first"
1157        );
1158    }
1159}