Skip to main content

optimization_job_api/
result.rs

1//! The result contract `optimization.result/0.2`: outcomes with claims and
2//! evidence, the result journal, and the manifests the runner builds from it
3//! (the guide's section [Results and durable recovery](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#results-and-durable-recovery)).
4use crate::{JobSpec, Request, Result, artifact, legacy, safe_name, storage};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7use std::{
8    collections::{BTreeMap, BTreeSet},
9    path::Path,
10};
11
12/// Result manifests written by this build.
13pub const SCHEMA: &str = "optimization.result/0.2";
14/// Result manifests `compare` reads. A 0.1 manifest is a valid 0.2 manifest
15/// without evidence, objective bounds or the claims added in 0.2.
16pub const SCHEMAS: [&str; 2] = ["optimization.result/0.1", SCHEMA];
17
18/// Every claim. A claim states what the worker asserts about the task's
19/// answer; `evidence` states how much of that was verified.
20pub const CLAIMS: [&str; 12] = [
21    "none",
22    "feasible",
23    "best_found",
24    "numerical_optimum",
25    "first_order",
26    "certified_optimum",
27    "non_dominated_set",
28    "elite_archive",
29    "infeasible",
30    "unbounded",
31    "infeasible_or_unbounded",
32    "locally_infeasible",
33];
34/// Claims about one returned point, which must be feasible.
35const POINT_CLAIMS: [&str; 6] = [
36    "feasible",
37    "best_found",
38    "numerical_optimum",
39    "first_order",
40    "certified_optimum",
41    "elite_archive",
42];
43/// Point claims that also need the point's (scalar) objective. A feasible
44/// point of a multi-objective or constraint-only model has none.
45const OBJECTIVE_CLAIMS: [&str; 5] = [
46    "best_found",
47    "numerical_optimum",
48    "first_order",
49    "certified_optimum",
50    "elite_archive",
51];
52/// Claims that rule out a feasible returned point: the problem has none
53/// (`infeasible`), or the point is a local minimizer of the infeasibility
54/// (`locally_infeasible`). `infeasible_or_unbounded` allows one: with a
55/// feasible point, the problem is unbounded if the claim holds.
56const NO_FEASIBLE_POINT: [&str; 2] = ["infeasible", "locally_infeasible"];
57/// Claims about the whole problem that no recomputation of returned points
58/// can confirm: their evidence is `claimed` or `certified`, never `rechecked`.
59const PROBLEM_CLAIMS: [&str; 3] = ["infeasible", "unbounded", "infeasible_or_unbounded"];
60/// Relative tolerance of the objective-bound rules of [`Outcome::check`]:
61/// two objective values `a` and `b` agree, and a dual bound may lie beyond
62/// the primal bound, by at most `BOUND_TOLERANCE * max(1, |a|, |b|)`. Workers
63/// with tighter tolerances decide more strictly on their own and keep a
64/// rejected value in `details`.
65pub const BOUND_TOLERANCE: f64 = 1e-6;
66/// Evidence levels, weakest first.
67pub const LEVELS: [&str; 3] = ["claimed", "rechecked", "certified"];
68/// Properties a worker recomputes independently of the solver.
69pub const CHECKS: [&str; 7] = [
70    "objective",
71    "bounds",
72    "constraints",
73    "integrality",
74    "kkt",
75    "non_dominance",
76    "niche",
77];
78/// Why an independent check refuted the solver's claim; the solver
79/// competitions' wrong-answer categories.
80pub const VERDICTS: [&str; 5] = [
81    "infeasible_point",
82    "objective_mismatch",
83    "false_optimality",
84    "false_infeasibility",
85    "invalid_certificate",
86];
87
88/// What a worker reports for one task: why it stopped, what it claims and how
89/// the claim is supported. [`Outcome::check`] enforces the contract's rules.
90#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
91#[serde(deny_unknown_fields)]
92pub struct Outcome {
93    /// Why the task stopped, in the solver's words (`evaluation_limit`,
94    /// `optimal`, `converged`, `cancelled`, ...). Never a claim.
95    pub termination: String,
96    /// One of [`CLAIMS`]. A non_dominated_set describes a set of points in
97    /// `details` and has no single `x` or `objective`.
98    pub claim: String,
99    /// Whether the returned point satisfies the model's constraints within
100    /// their tolerances; `None` if that is unknown.
101    pub feasible: Option<bool>,
102    /// The objective of `x`; `None` without a point or with several
103    /// objectives.
104    pub objective: Option<f64>,
105    /// The returned point, finite and nonempty; `None` if there is none.
106    pub x: Option<Vec<f64>>,
107    /// Solver-specific details such as gaps, residuals, a front or elites
108    /// (the guide's section [Details](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#details)).
109    pub details: Value,
110    /// How the claim is supported. Workers of protocol 0.2 always report it;
111    /// a record without it predates 0.2 and is only `claimed`.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub evidence: Option<Evidence>,
114    /// Best objective of a feasible point (primal) and a proven bound on the
115    /// optimum (dual), in the model's own sense.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub objective_bounds: Option<ObjectiveBounds>,
118    /// The engine reported success only at relaxed accuracy. Qualifies the
119    /// claim; never set together with `none`.
120    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
121    pub imprecise: bool,
122}
123/// How much of a claim was verified, and how.
124#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
125#[serde(deny_unknown_fields)]
126pub struct Evidence {
127    /// One of [`LEVELS`]: `claimed` (the solver's report alone), `rechecked`
128    /// (returned points recomputed from the registered model, as `checks`
129    /// list) or `certified` (a proof verified by an independent checker).
130    pub level: String,
131    /// Properties recomputed independently of the solver, from [`CHECKS`].
132    #[serde(default)]
133    pub checks: Vec<String>,
134    /// The solver's claim that an independent check rejected. `claim` then
135    /// states only what survived the check.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub refuted: Option<Refutation>,
138    /// The proof that an independent checker judged, if there is one.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub certificate: Option<Certificate>,
141}
142/// A claim of the solver that an independent check rejected.
143#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
144#[serde(deny_unknown_fields)]
145pub struct Refutation {
146    /// The rejected claim.
147    pub claim: String,
148    /// One of [`VERDICTS`].
149    pub verdict: String,
150    /// What the check found.
151    pub message: String,
152}
153/// A proof of a claim and the verdict of the checker that judged it.
154#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
155#[serde(deny_unknown_fields)]
156pub struct Certificate {
157    /// Proof format, for example `vipr`, `lrat`, `veripb` or `farkas`.
158    pub format: String,
159    /// File name of the proof in the attempt directory, if it was kept.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub artifact: Option<String>,
162    /// SHA-256 of the proof bytes.
163    pub sha256: String,
164    /// Name and version of the checker that judged it.
165    pub checker: String,
166    /// `verified` or `rejected`.
167    pub verdict: String,
168}
169/// The objective of the best feasible point and a proven bound on the optimum.
170#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
171#[serde(deny_unknown_fields)]
172pub struct ObjectiveBounds {
173    /// `minimize` or `maximize`: the dual bound is a lower bound when
174    /// minimizing and an upper bound when maximizing.
175    pub sense: String,
176    /// Objective of the best feasible point, if one was found.
177    pub primal: Option<f64>,
178    /// Proven bound on the optimal objective, if the solver proved one.
179    pub dual: Option<f64>,
180}
181
182/// Whether objective values `a` and `b` agree within [`BOUND_TOLERANCE`].
183pub fn objectives_agree(a: f64, b: f64) -> bool {
184    (a - b).abs() <= BOUND_TOLERANCE * 1f64.max(a.abs()).max(b.abs())
185}
186
187impl ObjectiveBounds {
188    /// Whether the bounds are in order: when both exist, the dual bound lies
189    /// below the primal one when minimizing and above it when maximizing,
190    /// within [`BOUND_TOLERANCE`]. A dual bound beyond the objective of a
191    /// feasible point contradicts it: one of the two is wrong.
192    pub fn ordered(&self) -> bool {
193        let (Some(primal), Some(dual)) = (self.primal, self.dual) else {
194            return true;
195        };
196        let slack = BOUND_TOLERANCE * 1f64.max(primal.abs()).max(dual.abs());
197        match self.sense.as_str() {
198            "minimize" => dual <= primal + slack,
199            "maximize" => dual >= primal - slack,
200            _ => false,
201        }
202    }
203}
204
205impl Evidence {
206    /// The solver's report alone; `checks` may list recomputations of
207    /// returned points that the claim does not depend on.
208    pub fn claimed(checks: &[&str]) -> Self {
209        Self {
210            level: "claimed".into(),
211            checks: checks.iter().map(|c| c.to_string()).collect(),
212            ..Self::default()
213        }
214    }
215    /// Returned points recomputed independently: `checks` names what.
216    pub fn rechecked(checks: &[&str]) -> Self {
217        Self {
218            level: "rechecked".into(),
219            ..Self::claimed(checks)
220        }
221    }
222    /// Records that the checks rejected the solver's `claim`.
223    pub fn refuting(mut self, claim: &str, verdict: &str, message: impl Into<String>) -> Self {
224        self.refuted = Some(Refutation {
225            claim: claim.into(),
226            verdict: verdict.into(),
227            message: message.into(),
228        });
229        self
230    }
231}
232
233fn lowercase_sha256(s: &str) -> bool {
234    s.len() == 64
235        && s.bytes()
236            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
237}
238
239impl Outcome {
240    /// Checks the rules of the result contract (the guide's section
241    /// [Termination, claim and evidence](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#termination-claim-and-evidence)).
242    /// The runner applies them to every journal record.
243    pub fn check(&self) -> std::result::Result<(), String> {
244        let claim = self.claim.as_str();
245        if self.termination.is_empty() {
246            return Err("empty termination".into());
247        }
248        if !CLAIMS.contains(&claim) {
249            return Err(format!("unknown claim {claim:?}"));
250        }
251        if self.objective.is_some_and(|v| !v.is_finite())
252            || self
253                .x
254                .as_ref()
255                .is_some_and(|v| v.is_empty() || v.iter().any(|x| !x.is_finite()))
256        {
257            return Err("objective and x must be finite and x nonempty".into());
258        }
259        if self.objective.is_some() && self.x.is_none() {
260            return Err("an objective needs its point x".into());
261        }
262        let set = claim == "non_dominated_set";
263        if self.feasible == Some(true) && self.x.is_none() && !set {
264            return Err("a feasible outcome needs its point x".into());
265        }
266        if POINT_CLAIMS.contains(&claim) && (self.feasible != Some(true) || self.x.is_none()) {
267            return Err(format!("{claim} needs a feasible point x"));
268        }
269        if OBJECTIVE_CLAIMS.contains(&claim) && self.objective.is_none() {
270            return Err(format!("{claim} needs an objective"));
271        }
272        // A set claim lives in details: no single point or objective.
273        if set && (self.feasible != Some(true) || self.x.is_some()) {
274            return Err("non_dominated_set needs feasible true and no single point".into());
275        }
276        if NO_FEASIBLE_POINT.contains(&claim) && self.feasible == Some(true) {
277            return Err(format!("{claim} contradicts a feasible point"));
278        }
279        if self.imprecise && claim == "none" {
280            return Err("imprecise qualifies a claim; none has nothing to qualify".into());
281        }
282        if let Some(b) = &self.objective_bounds
283            && (!matches!(b.sense.as_str(), "minimize" | "maximize")
284                || b.primal.is_some_and(|v| !v.is_finite())
285                || b.dual.is_some_and(|v| !v.is_finite()))
286        {
287            return Err("objective_bounds need a sense and finite (or null) bounds".into());
288        }
289        if let Some(b) = &self.objective_bounds {
290            // The primal bound is the objective of the returned feasible
291            // point, not of an incumbent the outcome does not show.
292            if let Some(primal) = b.primal
293                && (self.feasible != Some(true)
294                    || self.objective.is_none_or(|v| !objectives_agree(v, primal)))
295            {
296                return Err(format!(
297                    "objective_bounds.primal {primal} must be the objective of the returned feasible point"
298                ));
299            }
300            if !b.ordered() {
301                return Err(format!(
302                    "the dual bound {} contradicts the primal bound {} of a {} problem",
303                    b.dual.unwrap_or_default(),
304                    b.primal.unwrap_or_default(),
305                    b.sense
306                ));
307            }
308        }
309        let level = self
310            .evidence
311            .as_ref()
312            .map_or("claimed", |e| e.level.as_str());
313        if claim == "certified_optimum" && level != "certified" {
314            return Err("certified_optimum needs certified evidence".into());
315        }
316        if PROBLEM_CLAIMS.contains(&claim) && level == "rechecked" {
317            return Err(format!(
318                "{claim} concerns the whole problem; it cannot be rechecked"
319            ));
320        }
321        let Some(e) = &self.evidence else {
322            return Ok(());
323        };
324        let mut seen = BTreeSet::new();
325        if !LEVELS.contains(&level)
326            || e.checks
327                .iter()
328                .any(|c| !CHECKS.contains(&c.as_str()) || !seen.insert(c))
329        {
330            return Err("unknown evidence level, or unknown or repeated check".into());
331        }
332        if level == "rechecked" && e.checks.is_empty() {
333            return Err("rechecked evidence must name its checks".into());
334        }
335        if let Some(c) = &e.certificate
336            && (!safe_name(&c.format)
337                || !safe_name(&c.checker)
338                || !lowercase_sha256(&c.sha256)
339                || c.artifact.as_deref().is_some_and(|a| !safe_name(a))
340                || !matches!(c.verdict.as_str(), "verified" | "rejected"))
341        {
342            return Err("certificate needs format, checker, lowercase SHA-256 and verdict verified or rejected".into());
343        }
344        let verified = e
345            .certificate
346            .as_ref()
347            .is_some_and(|c| c.verdict == "verified");
348        if level == "certified" && !verified {
349            return Err("certified evidence needs a verified certificate".into());
350        }
351        if let Some(r) = &e.refuted {
352            let rejected = e
353                .certificate
354                .as_ref()
355                .is_some_and(|c| c.verdict == "rejected");
356            if !CLAIMS.contains(&r.claim.as_str())
357                || r.claim == "none"
358                || r.claim == claim
359                || !VERDICTS.contains(&r.verdict.as_str())
360                // A rejected certificate may accompany another refutation;
361                // invalid_certificate needs one.
362                || (r.verdict == "invalid_certificate" && !rejected)
363                || (r.verdict != "invalid_certificate" && level != "rechecked")
364            {
365                return Err(
366                    "a refutation names another claim, a known verdict and the check that failed"
367                        .into(),
368                );
369            }
370        }
371        Ok(())
372    }
373}
374
375/// One committed task in the result journal `results.jsonl`.
376#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
377#[serde(deny_unknown_fields)]
378pub struct Record {
379    /// The task's index, below the resolved `task_count`.
380    pub task_id: usize,
381    /// The [`JobSpec::digest`] of the task's job.
382    pub spec_digest: String,
383    /// The time the task took.
384    pub elapsed_seconds: f64,
385    /// Named work counters, such as evaluations or iterations. Counters of
386    /// different profiles measure different work.
387    pub work: BTreeMap<String, u64>,
388    /// The task's outcome.
389    pub outcome: Outcome,
390}
391/// The result journal of the attempt in `dir`, ordered by `task_id`; empty
392/// without a journal. Each record must have a task ID below `task_count` and
393/// not seen before, the job's digest, a finite nonnegative time, safe counter
394/// names and an outcome that passes [`Outcome::check`]. An incomplete final
395/// line is ignored; any other invalid record is an error.
396pub fn replay(dir: &Path, spec: &JobSpec) -> Result<Vec<Record>> {
397    let path = dir.join("results.jsonl");
398    if !path.exists() {
399        return Ok(vec![]);
400    }
401    let mut records: Vec<Record> =
402        storage::read_checked(&path, 1).map_err(|e| format!("{}: {e}", path.display()))?;
403    let digest = spec.digest()?;
404    let mut ids = BTreeSet::new();
405    for r in &records {
406        let invalid = |why: String| {
407            format!(
408                "{}: invalid, mismatched or duplicate result record (task {}): {why}",
409                path.display(),
410                r.task_id
411            )
412        };
413        if r.task_id >= spec.task_count.ok_or("unresolved task_count")?
414            || !ids.insert(r.task_id)
415            || r.spec_digest != digest
416            || !r.elapsed_seconds.is_finite()
417            || r.elapsed_seconds < 0.0
418            || r.work.keys().any(|k| !safe_name(k))
419        {
420            return Err(invalid("task, digest, elapsed time or work counters".into()).into());
421        }
422        r.outcome.check().map_err(invalid)?;
423    }
424    records.sort_by_key(|r| r.task_id);
425    Ok(records)
426}
427/// The work counters of `records`, summed per name; an overflow is an error.
428pub fn counts(records: &[Record]) -> Result<BTreeMap<String, u64>> {
429    let mut counts = BTreeMap::<String, u64>::new();
430    for r in records {
431        for (k, v) in &r.work {
432            let n = counts.entry(k.clone()).or_default();
433            *n = n.checked_add(*v).ok_or("work count overflow")?;
434        }
435    }
436    Ok(counts)
437}
438/// The result manifest `run.json` of the attempt in `dir`, built from its
439/// journal and its artifacts. With `complete` false, the work is not fully
440/// accounted for: `work` is null and only `known_work_lower_bound` is given.
441pub fn manifest(
442    dir: &Path,
443    spec: &Request,
444    status: &str,
445    complete: bool,
446    elapsed: f64,
447    worker_digest: &str,
448) -> Result<Value> {
449    let s = match spec {
450        Request::Legacy(s) => {
451            return legacy::result::manifest(dir, s, status, complete, elapsed, worker_digest);
452        }
453        Request::Job(s) => s,
454    };
455    let records = replay(dir, s)?;
456    let known = counts(&records)?;
457    // Declared artifacts are indexed with their digests; a problem with them
458    // is reported, never a reason to distrust the results.
459    let (artifacts, index, errors) = artifact::sealed(dir);
460    let mut run = json!({
461        "schema_version":SCHEMA, "status":status,
462        "worker":s.worker,"payload_schema":s.payload_schema,"elapsed_seconds":elapsed,
463        "completed_tasks":records.len(),"requested_tasks":s.task_count,
464        "work":if complete { Some(&known) } else { None },"known_work_lower_bound":known,
465        "results":records,
466        "artifacts":artifacts,
467        "runner":{"profile":"optimization.runner/0.1","spec_digest":s.digest()?,"worker_digest":worker_digest,"accounting_complete":complete,"resources":s.resources,"recovery":"journal_only_no_resume","artifact_index":index}
468    });
469    if !errors.is_empty() {
470        run["runner"]["artifact_errors"] = json!(errors);
471    }
472    Ok(run)
473}
474/// The manifest of an attempt whose journal cannot be replayed (a corrupt or
475/// invalid record before its final line). No record is trusted, so there are
476/// no results and no work totals; `runner.journal_error` says why.
477pub fn unreadable_manifest(
478    spec: &Request,
479    elapsed: f64,
480    worker_digest: &str,
481    error: &str,
482) -> Value {
483    match spec {
484        Request::Legacy(_) => json!({
485            "schema_version":1,"status":"failed","actual_evaluations":null,
486            "elapsed_seconds":elapsed,
487            "runner":{"worker_digest":worker_digest,"accounting_complete":false,"journal_error":error}
488        }),
489        Request::Job(s) => json!({
490            "schema_version":SCHEMA, "status":"failed",
491            "worker":s.worker,"payload_schema":s.payload_schema,"elapsed_seconds":elapsed,
492            "completed_tasks":null,"requested_tasks":s.task_count,
493            "work":null,"known_work_lower_bound":null,"results":[],"artifacts":{},
494            "runner":{"profile":"optimization.runner/0.1","spec_digest":s.digest().ok(),"worker_digest":worker_digest,"accounting_complete":false,"resources":s.resources,"recovery":"journal_only_no_resume","journal_error":error}
495        }),
496    }
497}
498/// The progress of a running attempt: its completed tasks, its known work and
499/// its artifact index.
500pub fn progress(dir: &Path, s: &Request) -> Result<Value> {
501    match s {
502        Request::Legacy(s) => {
503            let r = legacy::result::replay(dir, s)?;
504            Ok(
505                json!({"completed_retries":r.len(),"known_evaluations_lower_bound":r.iter().map(|r|r.actual_evaluations).sum::<u64>()}),
506            )
507        }
508        Request::Job(s) => {
509            let r = replay(dir, s)?;
510            let (index, errors) = artifact::progress(dir);
511            let mut v = json!({"completed_tasks":r.len(),"requested_tasks":s.task_count,"known_work_lower_bound":counts(&r)?,"artifact_index":index});
512            if !errors.is_empty() {
513                v["artifact_errors"] = json!(errors);
514            }
515            Ok(v)
516        }
517    }
518}
519/// Replays the journal of the attempt in `dir`, then ends a torn final line:
520/// a valid record gets its newline, anything else is removed. An invalid
521/// earlier record is an error, and the journal stays unchanged.
522pub fn repair(dir: &Path, s: &Request) -> Result<()> {
523    match s {
524        Request::Legacy(s) => {
525            legacy::result::replay(dir, s)?;
526            let p = dir.join("retries.jsonl");
527            if p.exists() {
528                storage::repair_tail::<legacy::result::RetryRecord>(&p, 1)?;
529            }
530        }
531        Request::Job(s) => {
532            replay(dir, s)?;
533            let p = dir.join("results.jsonl");
534            if p.exists() {
535                storage::repair_tail::<Record>(&p, 1)?;
536            }
537        }
538    }
539    Ok(())
540}
541/// The status and elapsed time from the worker's own `run.json` in `dir`, if
542/// it can be trusted: it belongs to this job, its accounting is complete, its
543/// status is terminal, and its results and work equal the journal's.
544/// Otherwise `None`. A `completed` manifest without all tasks, or an invalid
545/// elapsed time, is an error.
546pub fn worker_outcome(dir: &Path, s: &Request) -> Result<Option<(String, f64)>> {
547    if !dir.join("run.json").exists() {
548        return Ok(None);
549    }
550    let r: Value = serde_json::from_slice(&std::fs::read(dir.join("run.json"))?)?;
551    let status = r["status"].as_str().unwrap_or_default();
552    if r["runner"]["spec_digest"] != s.digest()?
553        || r["runner"]["accounting_complete"] != true
554        || !matches!(status, "completed" | "cancelled" | "timed_out")
555    {
556        return Ok(None);
557    }
558    let (done, total, valid) = match s {
559        Request::Legacy(s) => {
560            let rr = legacy::result::replay(dir, s)?;
561            (
562                rr.len(),
563                s.budget.retries,
564                r["actual_evaluations"].as_u64()
565                    == Some(rr.iter().map(|r| r.actual_evaluations).sum()),
566            )
567        }
568        Request::Job(s) => {
569            let rr = replay(dir, s)?;
570            (
571                rr.len(),
572                s.task_count.ok_or("unresolved task count")?,
573                // Compared as records, not as JSON text: an absent optional
574                // field and an explicit null mean the same.
575                r["work"] == serde_json::to_value(counts(&rr)?)?
576                    && serde_json::from_value::<Vec<Record>>(r["results"].clone())
577                        .is_ok_and(|reported| reported == rr),
578            )
579        }
580    };
581    if !valid {
582        return Ok(None);
583    }
584    if status == "completed" && done != total {
585        return Err("worker completed without all tasks".into());
586    }
587    let elapsed = r["elapsed_seconds"]
588        .as_f64()
589        .filter(|v| v.is_finite() && *v >= 0.0)
590        .ok_or("invalid worker elapsed time")?;
591    Ok(Some((status.into(), elapsed)))
592}
593/// Sets result manifests side by side. All must use a schema of [`SCHEMAS`],
594/// the same payload schema and the same `spec_digest`; manifests of the legacy
595/// format go to [`legacy::result::compare`]. The answer lists the arms and
596/// warnings and names no winner.
597pub fn compare(runs: &[Value]) -> Result<Value> {
598    let common = |r: &Value| {
599        r["schema_version"]
600            .as_str()
601            .is_some_and(|v| SCHEMAS.contains(&v))
602    };
603    if !runs.iter().any(common) {
604        return legacy::result::compare(runs);
605    }
606    if runs.iter().any(|r| {
607        !common(r)
608            || r["payload_schema"] != runs[0]["payload_schema"]
609            || r["runner"]["spec_digest"] != runs[0]["runner"]["spec_digest"]
610    }) {
611        return Err("comparison requires the same resolved job content and profile; LP and SQP claims are not interchangeable".into());
612    }
613    let mut warnings = vec![json!(
614        "No automatic winner; inspect mathematical outcomes, worker hashes and complete accounting."
615    )];
616    if runs
617        .iter()
618        .any(|r| r["schema_version"] != runs[0]["schema_version"])
619    {
620        warnings.push(json!(
621            "Arms use different result schemas: 0.1 records carry no evidence and report infeasibility as claim none."
622        ));
623    }
624    Ok(json!({"arms":runs,"warnings":warnings}))
625}