optimization_job_api/legacy/
result.rs1use crate::{Result, legacy::JobSpec, storage};
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5use std::{collections::BTreeSet, path::Path};
6#[derive(Clone, Debug, Serialize, Deserialize)]
7#[serde(deny_unknown_fields)]
8pub struct RetryRecord {
11 pub retry_id: usize,
13 pub run_seed: u64,
15 pub spec_digest: String,
17 pub initialization: String,
19 pub x: Vec<f64>,
21 pub y: Option<f64>,
23 pub actual_evaluations: u64,
25 pub elapsed_seconds: f64,
27 pub valid: bool,
29 pub feasible: bool,
31}
32pub fn replay(dir: &Path, spec: &JobSpec) -> Result<Vec<RetryRecord>> {
37 let path = dir.join("retries.jsonl");
38 if !path.exists() {
39 return Ok(vec![]);
40 }
41 let records: Vec<RetryRecord> = storage::read_checked(&path, 1)?;
42 let digest = spec.digest()?;
43 let mut ids = BTreeSet::new();
44 for r in &records {
45 if !ids.insert(r.retry_id)
46 || r.retry_id >= spec.budget.retries
47 || r.spec_digest != digest
48 || r.x.len() != spec.problem.config.dimension
49 || r.x.iter().any(|x| !x.is_finite())
50 || r.x
51 .iter()
52 .zip(
53 spec.problem
54 .bounds
55 .lower
56 .iter()
57 .zip(&spec.problem.bounds.upper),
58 )
59 .any(|(x, (l, u))| x < l || x > u)
60 || !r.elapsed_seconds.is_finite()
61 || r.elapsed_seconds < 0.0
62 || r.y.is_some_and(|y| !y.is_finite())
63 || r.valid != r.y.is_some()
64 || (r.feasible && !r.valid)
65 || r.actual_evaluations == 0
66 || r.actual_evaluations > spec.maximum_evaluations()? / (spec.budget.retries as u64)
67 {
68 return Err("invalid or duplicate retry journal record".into());
69 }
70 }
71 Ok(records)
72}
73pub fn manifest(
76 dir: &Path,
77 spec: &JobSpec,
78 status: &str,
79 complete: bool,
80 elapsed: f64,
81 worker_digest: &str,
82) -> Result<Value> {
83 let records = replay(dir, spec)?;
84 let known = records.iter().try_fold(0u64, |sum, r| {
85 sum.checked_add(r.actual_evaluations)
86 .ok_or("evaluation sum overflow")
87 })?;
88 let best = records
89 .iter()
90 .filter(|r| r.feasible)
91 .min_by(|a, b| a.y.unwrap().total_cmp(&b.y.unwrap()));
92 let artifacts = if dir.join("retries.jsonl").exists() {
95 json!({"retries":"retries.jsonl"})
96 } else {
97 json!({})
98 };
99 Ok(
100 json!({"schema_version":1,"tutorial":"fcmaes-native-worker","formulation":"single_objective",
101 "command":"fcmaes-native-worker execute JOB_DIRECTORY", "status":status,
102 "seed":spec.execution.seed,"workers":spec.execution.workers,
103 "requested_evaluations":spec.requested()?,"actual_evaluations":if complete {Some(known)}else{None},
104 "elapsed_seconds":elapsed,"objectives":[{"column":"objective","label":spec.problem.id,"unit":if spec.problem.id=="gtop.cassini1" {"km/s"}else{"dimensionless"}}],
105 "descriptors":[],"feasible_results":records.iter().filter(|r|r.feasible).count(),
106 "best":best.map(|r|json!({"x":r.x,"y":r.y,"retry_id":r.retry_id})),
107 "artifacts":artifacts,
108 "runner":{"profile":"fcmaes.runner/0.1","spec_digest":spec.digest()?,"worker_digest":worker_digest,
109 "problem":spec.problem,"optimizer":spec.optimizer,"budget":spec.budget,"execution":spec.execution,
110 "termination_reason":status,"accounting_complete":complete,"known_evaluations_lower_bound":known,
111 "completed_retries":records.len(),"constraints":"none; finite objective required","data":"built-in",
112 "initialization":"uniform bounds; solver seed=retry_run_seed(root_seed,global_retry_id); runid=0"}
113 }),
114 )
115}
116pub fn compare(runs: &[Value]) -> Result<Value> {
118 if runs.len() < 2 {
119 return Err("comparison needs at least two manifests".into());
120 }
121 for r in runs {
122 if r["schema_version"] != 1
123 || (!r["runner"]["profile"].is_null() && !r["objectives"].is_array())
124 || !r["tutorial"].is_string()
125 || !r["formulation"].is_string()
126 {
127 return Err("not a run.json v1 manifest".into());
128 }
129 }
130 let first = &runs[0];
131 let mut warnings = Vec::<String>::new();
132 for r in &runs[1..] {
133 for key in ["tutorial", "formulation", "objectives"] {
134 if r[key] != first[key] {
135 return Err(format!("incompatible {key}").into());
136 }
137 }
138 if r["runner"]["profile"].is_null() || first["runner"]["profile"].is_null() {
139 warnings.push("Legacy manifest: compatibility of data, transformations and constraints requires domain review; descriptive comparison only".into());
140 } else {
141 for key in ["problem", "data", "constraints"] {
142 if r["runner"][key] != first["runner"][key] {
143 return Err(format!("incompatible runner.{key}").into());
144 }
145 }
146 if r["runner"]["worker_digest"] != first["runner"]["worker_digest"] {
147 warnings.push("Different worker binaries; review code provenance".into());
148 }
149 }
150 if r["seed"] != first["seed"] {
151 warnings.push("Seeds differ; arms are unpaired".into());
152 }
153 if r["workers"] != first["workers"] {
154 warnings.push("Worker allocations differ".into());
155 }
156 let mode = &r["runner"]["budget"]["evaluation_limit_mode"];
157 if !mode.is_null() && *mode != first["runner"]["budget"]["evaluation_limit_mode"] {
158 warnings.push(
159 "Evaluation limit modes differ (hard vs soft); compare actual, not requested, work"
160 .into(),
161 );
162 }
163 }
164 if first["formulation"] != "single_objective" {
165 warnings.push("No automatic Pareto or hypervolume comparison; common scaling/reference definitions required".into());
166 }
167 for r in runs {
168 if r["actual_evaluations"].is_null() {
169 warnings.push(
170 "At least one arm has incomplete accounting (forced stop); its actual work is only a lower bound"
171 .into(),
172 );
173 }
174 }
175 warnings.sort();
176 warnings.dedup();
177 let budget = |r: &Value| r["runner"]["budget"]["wall_time_seconds"].clone();
178 let summary: Vec<Value> = runs
179 .iter()
180 .enumerate()
181 .map(|(arm, r)| {
182 json!({"arm":arm,"optimizer":r["runner"]["optimizer"]["kind"],
183 "evaluation_limit_mode":r["runner"]["budget"]["evaluation_limit_mode"],
184 "status":r["status"],"seed":r["seed"],"workers":r["workers"],
185 "requested_evaluations":r["requested_evaluations"],"actual_evaluations":r["actual_evaluations"],
186 "known_evaluations_lower_bound":r["runner"]["known_evaluations_lower_bound"],
187 "completed_retries":r["runner"]["completed_retries"],"feasible_results":r["feasible_results"],
188 "best_y":r["best"]["y"],"elapsed_seconds":r["elapsed_seconds"]})
189 })
190 .collect();
191 Ok(
192 json!({"summary":summary,"arms":runs,"equal_requested_work":runs.iter().all(|r|r["requested_evaluations"]==first["requested_evaluations"]),
193 "equal_actual_work":!first["actual_evaluations"].is_null() && runs.iter().all(|r|r["actual_evaluations"]==first["actual_evaluations"]),
194 "equal_wall_time_budget":!budget(first).is_null() && runs.iter().all(|r|budget(r)==budget(first)),
195 "warnings":warnings,"interpretation":"Descriptive arms; no statistical winner inferred. Incomplete and zero-feasible arms retained."}),
196 )
197}