1use 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
12pub const SCHEMA: &str = "optimization.result/0.2";
14pub const SCHEMAS: [&str; 2] = ["optimization.result/0.1", SCHEMA];
17
18pub 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];
34const POINT_CLAIMS: [&str; 6] = [
36 "feasible",
37 "best_found",
38 "numerical_optimum",
39 "first_order",
40 "certified_optimum",
41 "elite_archive",
42];
43const OBJECTIVE_CLAIMS: [&str; 5] = [
46 "best_found",
47 "numerical_optimum",
48 "first_order",
49 "certified_optimum",
50 "elite_archive",
51];
52const NO_FEASIBLE_POINT: [&str; 2] = ["infeasible", "locally_infeasible"];
57const PROBLEM_CLAIMS: [&str; 3] = ["infeasible", "unbounded", "infeasible_or_unbounded"];
60pub const BOUND_TOLERANCE: f64 = 1e-6;
66pub const LEVELS: [&str; 3] = ["claimed", "rechecked", "certified"];
68pub const CHECKS: [&str; 7] = [
70 "objective",
71 "bounds",
72 "constraints",
73 "integrality",
74 "kkt",
75 "non_dominance",
76 "niche",
77];
78pub const VERDICTS: [&str; 5] = [
81 "infeasible_point",
82 "objective_mismatch",
83 "false_optimality",
84 "false_infeasibility",
85 "invalid_certificate",
86];
87
88#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
91#[serde(deny_unknown_fields)]
92pub struct Outcome {
93 pub termination: String,
96 pub claim: String,
99 pub feasible: Option<bool>,
102 pub objective: Option<f64>,
105 pub x: Option<Vec<f64>>,
107 pub details: Value,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub evidence: Option<Evidence>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub objective_bounds: Option<ObjectiveBounds>,
118 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
121 pub imprecise: bool,
122}
123#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
125#[serde(deny_unknown_fields)]
126pub struct Evidence {
127 pub level: String,
131 #[serde(default)]
133 pub checks: Vec<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub refuted: Option<Refutation>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub certificate: Option<Certificate>,
141}
142#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
144#[serde(deny_unknown_fields)]
145pub struct Refutation {
146 pub claim: String,
148 pub verdict: String,
150 pub message: String,
152}
153#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
155#[serde(deny_unknown_fields)]
156pub struct Certificate {
157 pub format: String,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub artifact: Option<String>,
162 pub sha256: String,
164 pub checker: String,
166 pub verdict: String,
168}
169#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
171#[serde(deny_unknown_fields)]
172pub struct ObjectiveBounds {
173 pub sense: String,
176 pub primal: Option<f64>,
178 pub dual: Option<f64>,
180}
181
182pub 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 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 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 pub fn rechecked(checks: &[&str]) -> Self {
217 Self {
218 level: "rechecked".into(),
219 ..Self::claimed(checks)
220 }
221 }
222 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 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 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 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 || (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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
377#[serde(deny_unknown_fields)]
378pub struct Record {
379 pub task_id: usize,
381 pub spec_digest: String,
383 pub elapsed_seconds: f64,
385 pub work: BTreeMap<String, u64>,
388 pub outcome: Outcome,
390}
391pub 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}
427pub 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}
438pub 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 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}
474pub 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}
498pub 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}
519pub 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}
541pub 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 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}
593pub 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}