interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / research / atemporal / at1 / evaluator / src / result.rs

585 lines · 21073 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! AT1_RESULT_V1 strict parser and canonical writer (section 1 line order,
17//! section 2 number tokens, section 6 identities).
18
19use crate::case::{validate_lines, BoundKind, Case};
20use crate::model::Status;
21use crate::rat::{parse_int, parse_scaled, scaled_text, Scaled, Tok, Q};
22use crate::sha256::tagged_hex;
23use crate::text::{is_digest, is_hex40, is_path, is_repo, is_text200, is_utc, join_lf, lines_checked, FAILURE_CODES, RUN_ERROR_CODES};
24use crate::big::Int;
25
26pub const VERDICT_DOMAIN: &str = "omega.at1.verdict.v1";
27pub const EVIDENCE_DOMAIN: &str = "omega.at1.evidence.v1";
28pub const CHECK_NAMES: [&str; 12] = [
29 "bound_kind_sufficient",
30 "values_finite",
31 "physical_state_nontrivial",
32 "constraint_residual",
33 "povm_normalization",
34 "clock_probability_sum",
35 "probability_range",
36 "pauli_pair_sum",
37 "conditional_defined",
38 "target_agreement",
39 "oracle_cross_check",
40 "label_status_agreement",
41];
42pub const AXES: [&str; 3] = ["X", "Y", "Z"];
43pub const SIGNS: [&str; 2] = ["PLUS", "MINUS"];
44
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub enum Kind {
47 Value(u64),
48 Nonfinite,
49 Undefined,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct RVal {
54 pub kind: Kind,
55 pub bound: Scaled,
56}
57impl RVal {
58 pub fn undefined() -> RVal {
59 RVal { kind: Kind::Undefined, bound: zero_scaled() }
60 }
61 pub fn of(x: f64, bound: &Scaled) -> RVal {
62 if !x.is_finite() {
63 return RVal { kind: Kind::Nonfinite, bound: bound.clone() };
64 }
65 let bits = if x == 0.0 { 0 } else { x.to_bits() };
66 RVal { kind: Kind::Value(bits), bound: bound.clone() }
67 }
68 pub fn q(&self) -> Option<Q> {
69 match self.kind {
70 Kind::Value(b) => Some(Q::from_f64_bits(b)),
71 _ => None,
72 }
73 }
74 pub fn bq(&self) -> Q {
75 Q::from_scaled(&self.bound)
76 }
77 pub fn text(&self) -> String {
78 let v = match self.kind {
79 Kind::Value(b) => format!("f64:{:016x}", b),
80 Kind::Nonfinite => "nonfinite".into(),
81 Kind::Undefined => "undefined".into(),
82 };
83 format!("{} {}", v, scaled_text(&self.bound))
84 }
85}
86pub fn zero_scaled() -> Scaled {
87 Scaled { n: Int::zero(), k: 0 }
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub enum Ck {
92 Pass,
93 Fail,
94 Indet,
95 NotEval,
96}
97impl Ck {
98 pub fn text(self) -> &'static str {
99 match self {
100 Ck::Pass => "PASS",
101 Ck::Fail => "FAIL",
102 Ck::Indet => "INDETERMINATE",
103 Ck::NotEval => "NOT_EVALUATED",
104 }
105 }
106 fn parse(s: &str) -> Option<Ck> {
107 match s {
108 "PASS" => Some(Ck::Pass),
109 "FAIL" => Some(Ck::Fail),
110 "INDETERMINATE" => Some(Ck::Indet),
111 "NOT_EVALUATED" => Some(Ck::NotEval),
112 _ => None,
113 }
114 }
115}
116
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct Verdict {
119 pub checks: [Ck; 12],
120 pub outcome: String,
121 pub failure_codes: Vec<String>,
122 pub error_code: String,
123 pub expectation: String,
124}
125impl Verdict {
126 pub fn lines(&self) -> Vec<String> {
127 let mut v = vec!["begin verdict".to_string()];
128 for i in 0..12 {
129 v.push(format!("check {} {}", CHECK_NAMES[i], self.checks[i].text()));
130 }
131 v.push(format!("outcome {}", self.outcome));
132 v.push(format!("failure_codes {}", if self.failure_codes.is_empty() { "none".to_string() } else { self.failure_codes.join(",") }));
133 v.push(format!("error_code {}", self.error_code));
134 v.push(format!("expectation_met {}", self.expectation));
135 v.push("end verdict".into());
136 v
137 }
138}
139
140#[derive(Clone, Debug)]
141pub struct Prov {
142 pub source_repo: String,
143 pub source_commit: String,
144 pub source_tree_clean: String,
145 pub contract_commit: String,
146 pub engine_sha256: String,
147 pub oracle_repo: String,
148 pub oracle_commit: String,
149 pub oracle_sha256: String,
150 pub build_cc: String,
151 pub build_flags: String,
152 pub host: String,
153 pub run_started: String,
154 pub run_finished: String,
155 pub artifacts: Vec<(String, String)>,
156}
157
158pub type Six = [[RVal; 2]; 3];
159
160#[derive(Clone, Debug)]
161pub struct ResultFile {
162 pub case: Case,
163 pub case_file_sha256: String,
164 pub arithmetic: String,
165 pub bound_kind: BoundKind,
166 pub kernel_dim: i64,
167 pub constraint: RVal,
168 pub povm: RVal,
169 pub label: Vec<Status>,
170 pub clock: Vec<RVal>,
171 pub pauli: Vec<Six>,
172 pub ref_label: Vec<Status>,
173 pub ref_clock: Vec<RVal>,
174 pub ref_ideal: Vec<Six>,
175 pub ref_inter: Vec<Six>,
176 pub verdict: Verdict,
177 pub verdict_id: String,
178 pub prov: Prov,
179 pub evidence_digest: String,
180}
181
182fn six_lines(key: &str, k: usize, s: &Six, out: &mut Vec<String>) {
183 for a in 0..3 {
184 for g in 0..2 {
185 out.push(format!("{} {} {} {} {}", key, k, AXES[a], SIGNS[g], s[a][g].text()));
186 }
187 }
188}
189
190impl ResultFile {
191 pub fn values_lines(&self) -> Vec<String> {
192 let m = self.case.m;
193 let mut v = vec!["begin values".to_string(), format!("physical_state_kernel_dim {}", self.kernel_dim)];
194 v.push(format!("constraint_residual {}", self.constraint.text()));
195 v.push(format!("povm_residual {}", self.povm.text()));
196 for k in 0..m {
197 v.push(format!("label {} {} {}", k, self.case.labels[k], self.label[k].text()));
198 }
199 for k in 0..m {
200 v.push(format!("clock_probability {} {}", k, self.clock[k].text()));
201 }
202 for k in 0..m {
203 six_lines("pauli", k, &self.pauli[k], &mut v);
204 }
205 for k in 0..m {
206 v.push(format!("reference_label {} {} {}", k, self.case.labels[k], self.ref_label[k].text()));
207 }
208 for k in 0..m {
209 v.push(format!("reference_clock_probability {} {}", k, self.ref_clock[k].text()));
210 }
211 for k in 0..m {
212 six_lines("reference_ideal", k, &self.ref_ideal[k], &mut v);
213 }
214 for k in 0..m {
215 six_lines("reference_interacting", k, &self.ref_inter[k], &mut v);
216 }
217 v.push("end values".into());
218 v
219 }
220 pub fn compute_verdict_id(&self) -> String {
221 let mut b = format!("case_id {}\nacceptance_id {}\n", self.case.case_id, self.case.acceptance_id).into_bytes();
222 b.extend(join_lf(&self.verdict.lines()));
223 tagged_hex(VERDICT_DOMAIN, &b)
224 }
225 /// Every line above evidence_digest.
226 pub fn pre_evidence_lines(&self) -> Vec<String> {
227 let mut v = vec![
228 "OMEGA-AT1-RESULT v1".to_string(),
229 "domain omega.at1.result.v1".into(),
230 "contract AT1_RESULT_V1".into(),
231 "case_contract AT1_CASE_V1".into(),
232 ];
233 v.extend(self.case.body_lines[..self.case.body_lines.len() - 2].iter().cloned());
234 v.push(format!("case_id {}", self.case.case_id));
235 v.push(format!("acceptance_id {}", self.case.acceptance_id));
236 v.push(format!("case_file_sha256 {}", self.case_file_sha256));
237 v.push("begin numerics".into());
238 v.push(format!("arithmetic {}", self.arithmetic));
239 v.push(format!("bound_kind {}", self.bound_kind.text()));
240 v.push("threads 1".into());
241 v.push("end numerics".into());
242 v.extend(self.values_lines());
243 v.extend(self.verdict.lines());
244 v.push(format!("verdict_id {}", self.verdict_id));
245 let p = &self.prov;
246 v.push("begin provenance".into());
247 v.push(format!("source_repo {}", p.source_repo));
248 v.push(format!("source_commit {}", p.source_commit));
249 v.push(format!("source_tree_clean {}", p.source_tree_clean));
250 v.push(format!("contract_commit {}", p.contract_commit));
251 v.push(format!("engine_sha256 {}", p.engine_sha256));
252 v.push(format!("oracle_repo {}", p.oracle_repo));
253 v.push(format!("oracle_commit {}", p.oracle_commit));
254 v.push(format!("oracle_sha256 {}", p.oracle_sha256));
255 v.push(format!("build_cc {}", p.build_cc));
256 v.push(format!("build_flags {}", p.build_flags));
257 v.push(format!("host {}", p.host));
258 v.push(format!("run_started_utc {}", p.run_started));
259 v.push(format!("run_finished_utc {}", p.run_finished));
260 for (a, d) in &p.artifacts {
261 v.push(format!("artifact {} {}", a, d));
262 }
263 v.push("end provenance".into());
264 v
265 }
266 pub fn compute_evidence(&self) -> String {
267 tagged_hex(EVIDENCE_DOMAIN, &join_lf(&self.pre_evidence_lines()))
268 }
269 /// Recomputes verdict_id and evidence_digest (writer role).
270 pub fn seal(&mut self) {
271 self.verdict_id = self.compute_verdict_id();
272 self.evidence_digest = self.compute_evidence();
273 }
274 pub fn lines(&self) -> Vec<String> {
275 let mut v = self.pre_evidence_lines();
276 v.push(format!("evidence_digest {}", self.evidence_digest));
277 v.push("end".into());
278 v
279 }
280 pub fn bytes(&self) -> Vec<u8> {
281 join_lf(&self.lines())
282 }
283}
284
285struct Rd<'a> {
286 l: &'a [String],
287 i: usize,
288}
289type Pr<T> = Result<T, String>;
290impl<'a> Rd<'a> {
291 fn line(&mut self) -> Pr<&'a str> {
292 let s = self.l.get(self.i).ok_or_else(|| format!("line {}: unexpected end of file", self.i + 1))?;
293 self.i += 1;
294 Ok(s)
295 }
296 fn exact(&mut self, t: &str) -> Pr<()> {
297 let s = self.line()?;
298 if s != t {
299 return Err(format!("line {}: expected `{}`", self.i, t));
300 }
301 Ok(())
302 }
303 fn toks(&mut self, key: &str, n: usize) -> Pr<Vec<&'a str>> {
304 let s = self.line()?;
305 let t: Vec<&str> = s.split(' ').collect();
306 if t[0] != key || t.len() != n + 1 {
307 return Err(format!("line {}: expected `{}` with {} token(s)", self.i, key, n));
308 }
309 Ok(t[1..].to_vec())
310 }
311 /// `<key> <text>` where text may contain spaces.
312 fn text(&mut self, key: &str) -> Pr<&'a str> {
313 let s = self.line()?;
314 let pre = format!("{} ", key);
315 match s.strip_prefix(&pre) {
316 Some(t) => Ok(t),
317 None => Err(format!("line {}: expected `{}`", self.i, key)),
318 }
319 }
320 fn err<T>(&self, m: &str) -> Pr<T> {
321 Err(format!("line {}: {}", self.i, m))
322 }
323}
324
325fn parse_val(rd: &Rd, v: &str, b: &str) -> Pr<RVal> {
326 let kind = if v == "nonfinite" {
327 Kind::Nonfinite
328 } else if v == "undefined" {
329 Kind::Undefined
330 } else if let Some(h) = v.strip_prefix("f64:") {
331 if h.len() != 16 || !h.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) {
332 return rd.err("f64 token must be 16 lowercase hex digits");
333 }
334 let bits = u64::from_str_radix(h, 16).map_err(|_| "bad hex".to_string())?;
335 if (bits >> 52) & 0x7ff == 0x7ff {
336 return rd.err("non-finite bit pattern written as f64");
337 }
338 if bits == 0x8000_0000_0000_0000 {
339 return rd.err("-0.0 must be written as f64:0000000000000000");
340 }
341 Kind::Value(bits)
342 } else {
343 return rd.err("value token is not f64:, nonfinite or undefined");
344 };
345 match parse_scaled(b) {
346 Some((s, Tok::Ok)) => {
347 if kind == Kind::Undefined && !s.n.is_zero() {
348 return rd.err("undefined must carry bound 0@0");
349 }
350 Ok(RVal { kind, bound: s })
351 }
352 _ => rd.err("bound is not a canonical scaled decimal"),
353 }
354}
355
356fn parse_status(rd: &Rd, s: &str) -> Pr<Status> {
357 match Status::parse(s) {
358 Some(x) => Ok(x),
359 None => rd.err("label status outside its set"),
360 }
361}
362
363fn parse_six(rd: &mut Rd, key: &str, k: usize) -> Pr<Six> {
364 let mut out: Vec<RVal> = Vec::new();
365 for a in 0..3 {
366 for g in 0..2 {
367 let t = rd.toks(key, 5)?;
368 if t[0] != k.to_string() || t[1] != AXES[a] || t[2] != SIGNS[g] {
369 return rd.err(&format!("{} line out of order (want {} {} {})", key, k, AXES[a], SIGNS[g]));
370 }
371 out.push(parse_val(rd, t[3], t[4])?);
372 }
373 }
374 Ok([[out[0].clone(), out[1].clone()], [out[2].clone(), out[3].clone()], [out[4].clone(), out[5].clone()]])
375}
376
377/// Strict parse. Err carries a line-numbered reason (the evaluator reports E4-PARSE).
378pub fn parse(bytes: &[u8]) -> Pr<ResultFile> {
379 let lines = lines_checked(bytes)?;
380 let mut rd = Rd { l: &lines, i: 0 };
381 rd.exact("OMEGA-AT1-RESULT v1")?;
382 rd.exact("domain omega.at1.result.v1")?;
383 rd.exact("contract AT1_RESULT_V1")?;
384 rd.exact("case_contract AT1_CASE_V1")?;
385 let (case, end) = match validate_lines(&lines, 4, None) {
386 Ok(x) => x,
387 Err((code, m)) => return Err(format!("embedded case refused {}: {}", code.code(), m)),
388 };
389 rd.i = end;
390 let sha = rd.toks("case_file_sha256", 1)?[0];
391 if !is_digest(sha) {
392 return rd.err("case_file_sha256 is not a digest");
393 }
394 rd.exact("begin numerics")?;
395 let arith = rd.toks("arithmetic", 1)?[0];
396 if !["BINARY64", "BINARY64_INTERVAL", "BINARY64_COMPENSATED", "NONE"].contains(&arith) {
397 return rd.err("arithmetic outside its set");
398 }
399 let bk = match BoundKind::parse(rd.toks("bound_kind", 1)?[0]) {
400 Some(b) => b,
401 None => return rd.err("bound_kind outside its set"),
402 };
403 rd.exact("threads 1")?;
404 rd.exact("end numerics")?;
405 rd.exact("begin values")?;
406 let kd = rd.toks("physical_state_kernel_dim", 1)?[0];
407 let kernel_dim = match parse_int(kd) {
408 Some((v, Tok::Ok)) if !v.is_neg() && v.bits() < 31 => v.low_u64() as i64,
409 _ => return rd.err("physical_state_kernel_dim is not a canonical non-negative integer"),
410 };
411 let t = rd.toks("constraint_residual", 2)?;
412 let constraint = parse_val(&rd, t[0], t[1])?;
413 let t = rd.toks("povm_residual", 2)?;
414 let povm = parse_val(&rd, t[0], t[1])?;
415 let m = case.m;
416 let mut label = Vec::new();
417 for k in 0..m {
418 let t = rd.toks("label", 3)?;
419 if t[0] != k.to_string() || t[1] != case.labels[k] {
420 return rd.err("label line index or label text differs from the case");
421 }
422 label.push(parse_status(&rd, t[2])?);
423 }
424 let mut clock = Vec::new();
425 for k in 0..m {
426 let t = rd.toks("clock_probability", 3)?;
427 if t[0] != k.to_string() {
428 return rd.err("clock_probability out of order");
429 }
430 clock.push(parse_val(&rd, t[1], t[2])?);
431 }
432 let mut pauli = Vec::new();
433 for k in 0..m {
434 pauli.push(parse_six(&mut rd, "pauli", k)?);
435 }
436 let mut ref_label = Vec::new();
437 for k in 0..m {
438 let t = rd.toks("reference_label", 3)?;
439 if t[0] != k.to_string() || t[1] != case.labels[k] {
440 return rd.err("reference_label line index or label text differs from the case");
441 }
442 ref_label.push(parse_status(&rd, t[2])?);
443 }
444 let mut ref_clock = Vec::new();
445 for k in 0..m {
446 let t = rd.toks("reference_clock_probability", 3)?;
447 if t[0] != k.to_string() {
448 return rd.err("reference_clock_probability out of order");
449 }
450 ref_clock.push(parse_val(&rd, t[1], t[2])?);
451 }
452 let mut ref_ideal = Vec::new();
453 for k in 0..m {
454 ref_ideal.push(parse_six(&mut rd, "reference_ideal", k)?);
455 }
456 let mut ref_inter = Vec::new();
457 for k in 0..m {
458 ref_inter.push(parse_six(&mut rd, "reference_interacting", k)?);
459 }
460 rd.exact("end values")?;
461 rd.exact("begin verdict")?;
462 let mut checks = [Ck::NotEval; 12];
463 for i in 0..12 {
464 let t = rd.toks("check", 2)?;
465 if t[0] != CHECK_NAMES[i] {
466 return rd.err(&format!("check {} expected in position {}", CHECK_NAMES[i], i + 1));
467 }
468 checks[i] = match Ck::parse(t[1]) {
469 Some(c) => c,
470 None => return rd.err("check status outside its set"),
471 };
472 }
473 let outcome = rd.toks("outcome", 1)?[0].to_string();
474 if !["PASS", "FAIL", "ERROR", "NOT_RUN"].contains(&outcome.as_str()) {
475 return rd.err("outcome outside its set");
476 }
477 let fc = rd.toks("failure_codes", 1)?[0];
478 let failure_codes: Vec<String> = if fc == "none" { Vec::new() } else { fc.split(',').map(|s| s.to_string()).collect() };
479 for c in &failure_codes {
480 if !FAILURE_CODES.contains(&c.as_str()) {
481 return rd.err("failure code outside the closed set");
482 }
483 }
484 for i in 1..failure_codes.len() {
485 if failure_codes[i - 1].as_bytes() >= failure_codes[i].as_bytes() {
486 return rd.err("failure_codes not sorted bytewise or not unique");
487 }
488 }
489 let ec = rd.toks("error_code", 1)?[0].to_string();
490 if ec != "none" && !RUN_ERROR_CODES.contains(&ec.as_str()) {
491 return rd.err("error_code outside the closed set");
492 }
493 let em = rd.toks("expectation_met", 1)?[0].to_string();
494 if !["YES", "NO", "NOT_APPLICABLE"].contains(&em.as_str()) {
495 return rd.err("expectation_met outside its set");
496 }
497 rd.exact("end verdict")?;
498 let vid = rd.toks("verdict_id", 1)?[0];
499 if !is_digest(vid) {
500 return rd.err("verdict_id is not a digest");
501 }
502 let placeholder_ok = outcome == "ERROR" || outcome == "NOT_RUN";
503 rd.exact("begin provenance")?;
504 let field = |rd: &mut Rd, key: &str, check: &dyn Fn(&str) -> bool, may_none: bool| -> Pr<String> {
505 let t = rd.text(key)?;
506 if (may_none && placeholder_ok && t == "none") || check(t) {
507 Ok(t.to_string())
508 } else {
509 rd.err(&format!("{} grammar", key))
510 }
511 };
512 let source_repo = field(&mut rd, "source_repo", &|s| is_repo(s), false)?;
513 let source_commit = field(&mut rd, "source_commit", &|s| is_hex40(s), false)?;
514 let source_tree_clean = field(&mut rd, "source_tree_clean", &|s| s == "YES" || s == "NO", false)?;
515 let contract_commit = field(&mut rd, "contract_commit", &|s| is_hex40(s), false)?;
516 let engine_sha256 = field(&mut rd, "engine_sha256", &|s| is_digest(s), true)?;
517 let oracle_repo = field(&mut rd, "oracle_repo", &|s| is_repo(s), true)?;
518 let oracle_commit = field(&mut rd, "oracle_commit", &|s| is_hex40(s), true)?;
519 let oracle_sha256 = field(&mut rd, "oracle_sha256", &|s| is_digest(s), true)?;
520 let build_cc = field(&mut rd, "build_cc", &|s| is_text200(s), true)?;
521 let build_flags = field(&mut rd, "build_flags", &|s| is_text200(s), true)?;
522 let host = field(&mut rd, "host", &|s| is_text200(s), true)?;
523 let run_started = field(&mut rd, "run_started_utc", &|s| is_utc(s), true)?;
524 let run_finished = field(&mut rd, "run_finished_utc", &|s| is_utc(s), true)?;
525 let mut artifacts: Vec<(String, String)> = Vec::new();
526 loop {
527 let s = rd.line()?;
528 if s == "end provenance" {
529 break;
530 }
531 let t: Vec<&str> = s.split(' ').collect();
532 if t.len() != 3 || t[0] != "artifact" || !is_path(t[1]) || !is_digest(t[2]) {
533 return rd.err("expected `artifact <path> <digest>` or `end provenance`");
534 }
535 if let Some((prev, _)) = artifacts.last() {
536 if prev.as_bytes() >= t[1].as_bytes() {
537 return rd.err("artifact paths not unique and strictly increasing");
538 }
539 }
540 artifacts.push((t[1].to_string(), t[2].to_string()));
541 }
542 let ed = rd.toks("evidence_digest", 1)?[0];
543 if !is_digest(ed) {
544 return rd.err("evidence_digest is not a digest");
545 }
546 rd.exact("end")?;
547 if rd.i != lines.len() {
548 return rd.err("content after `end`");
549 }
550 Ok(ResultFile {
551 case,
552 case_file_sha256: sha.to_string(),
553 arithmetic: arith.to_string(),
554 bound_kind: bk,
555 kernel_dim,
556 constraint,
557 povm,
558 label,
559 clock,
560 pauli,
561 ref_label,
562 ref_clock,
563 ref_ideal,
564 ref_inter,
565 verdict: Verdict { checks, outcome, failure_codes, error_code: ec, expectation: em },
566 verdict_id: vid.to_string(),
567 prov: Prov {
568 source_repo,
569 source_commit,
570 source_tree_clean,
571 contract_commit,
572 engine_sha256,
573 oracle_repo,
574 oracle_commit,
575 oracle_sha256,
576 build_cc,
577 build_flags,
578 host,
579 run_started,
580 run_finished,
581 artifacts,
582 },
583 evidence_digest: ed.to_string(),
584 })
585}