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 / verify.rs

431 lines · 20467 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//! Verification of one AT1_RESULT_V1 file: structure, identities, binding to
17//! the case, provenance, token discipline, exact re-derivation of the verdict,
18//! and comparison of every engine and oracle value with the shadow model.
19//! Status: FAIL if any FAIL finding, else INCONCLUSIVE if any INCONCLUSIVE
20//! finding, else PASS. PASS means contract conformance and agreement with the
21//! shadow within the case tolerances; it says nothing about physics.
22
23use crate::case::{case_bytes_from_body, validate_bytes, BoundKind};
24use crate::judge::{label_from, rederive};
25use crate::model::{shadow, Mods, Shadow, Status, Val};
26use crate::rat::Q;
27use crate::result::{parse, Ck, Kind, RVal, ResultFile, Six, CHECK_NAMES, EVIDENCE_DOMAIN};
28use crate::sha256::{sha256_hex, tagged_hex};
29use crate::text::{join_lf, lines_checked};
30use std::cmp::Ordering;
31
32/// aien-architecture commits whose three contract files were verified by digest
33/// (AT1_CASE_V1 e62018d8.., AT1_RESULT_V1 3e6efd7e.., AT0_RESULT_V2 bd0f9eb8..).
34pub const CONTRACT_COMMITS: [&str; 3] = [
35 "cbe4c8ed88d28bb96d5209327ecd30aa9cddaf7a",
36 "81047f52850f4bd14c2fc5772ec2ac833ac694b9",
37 "ea91d7c06507c8e43fdcef2b685f29d88a9e7d81",
38];
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Sev {
42 Fail,
43 Inconclusive,
44}
45
46#[derive(Clone, Debug)]
47pub struct Finding {
48 pub code: String,
49 pub detail: String,
50 pub sev: Sev,
51}
52
53#[derive(Clone, Debug, Default)]
54pub struct Report {
55 pub findings: Vec<Finding>,
56 pub derived_outcome: String,
57 pub derived_codes: Vec<String>,
58 pub derived_expectation: String,
59 pub any_indeterminate: bool,
60}
61
62impl Report {
63 fn add(&mut self, sev: Sev, code: &str, detail: String) {
64 // keep the report readable: at most 4 findings per code
65 let n = self.findings.iter().filter(|f| f.code == code).count();
66 if n < 4 {
67 self.findings.push(Finding { code: code.into(), detail, sev });
68 } else if n == 4 {
69 self.findings.push(Finding { code: code.into(), detail: "(further findings with this code suppressed)".into(), sev });
70 }
71 }
72 pub fn fail(&mut self, code: &str, detail: String) {
73 self.add(Sev::Fail, code, detail);
74 }
75 pub fn inconclusive(&mut self, code: &str, detail: String) {
76 self.add(Sev::Inconclusive, code, detail);
77 }
78 pub fn status(&self) -> &'static str {
79 if self.findings.iter().any(|f| f.sev == Sev::Fail) {
80 "FAIL"
81 } else if !self.findings.is_empty() {
82 "INCONCLUSIVE"
83 } else {
84 "PASS"
85 }
86 }
87 pub fn codes(&self) -> Vec<String> {
88 let mut v: Vec<String> = self.findings.iter().map(|f| f.code.clone()).collect();
89 v.sort();
90 v.dedup();
91 v
92 }
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Role {
97 /// a spliced candidate result (engine values + oracle references)
98 Candidate,
99 /// a record written by the oracle itself (G3)
100 Oracle,
101}
102
103fn is_placeholder(r: &ResultFile) -> bool {
104 r.verdict.outcome == "ERROR" || r.verdict.outcome == "NOT_RUN"
105}
106
107/// The file's own claim of a trivial kernel.
108pub fn claims_trivial(r: &ResultFile) -> bool {
109 r.kernel_dim == 0 || r.constraint.kind == Kind::Undefined
110}
111
112/// Tri-state agreement of a written value with the shadow: Some(true) when the
113/// value is beyond its tolerance for certain, Some(false) when it is only beyond
114/// its own bound, None when it agrees within its own bound.
115/// Reference lines (oracle families) are calibration data: the value itself must lie
116/// within tolerance of the exact value, whatever bound the file writes beside it, so a
117/// wrong reference cannot hide behind a wide bound (review finding 1).
118fn compare_strict(v: &RVal, s: &Val, tol: &Q) -> Option<bool> {
119 let x = v.q()?;
120 let d = x.sub(&s.q).abs();
121 if d.sub(&s.bound()).cmp(tol) == Ordering::Greater {
122 Some(true)
123 } else if d.cmp(&v.bq().add(&s.bound())) == Ordering::Greater {
124 Some(false)
125 } else {
126 None
127 }
128}
129
130fn compare(v: &RVal, s: &Val, tol: &Q) -> Option<bool> {
131 let x = v.q()?;
132 let d = x.sub(&s.q).abs();
133 let b = v.bq().add(&s.bound());
134 if d.sub(&b).cmp(tol) == Ordering::Greater {
135 Some(true)
136 } else if d.cmp(&b) == Ordering::Greater {
137 Some(false)
138 } else {
139 None
140 }
141}
142
143struct Cmp<'a> {
144 rep: &'a mut Report,
145 bk: BoundKind,
146 strict: bool,
147}
148impl<'a> Cmp<'a> {
149 fn one(&mut self, code: &str, what: String, v: &RVal, s: &Val, tol: &Q) {
150 match if self.strict { compare_strict(v, s, tol) } else { compare(v, s, tol) } {
151 Some(true) => self.rep.fail(code, format!("{} = {:.12e}, shadow {:.12e} (beyond tolerance)", what, v.q().unwrap().to_f64(), s.q.to_f64())),
152 Some(false) => self.bound_claim(&what, v, s),
153 None => {}
154 }
155 }
156 fn bound_claim(&mut self, what: &str, v: &RVal, s: &Val) {
157 let msg = format!("{} = {:.17e} differs from shadow {:.17e} by more than its own bound {}", what, v.q().unwrap().to_f64(), s.q.to_f64(), crate::rat::scaled_text(&v.bound));
158 match self.bk {
159 BoundKind::Rigorous => self.rep.fail("E4-BOUND-CLAIM-FALSE", msg),
160 BoundKind::Estimated => self.rep.inconclusive("E4-BOUND-ESTIMATE-LOW", msg),
161 BoundKind::None => {}
162 }
163 }
164 fn six(&mut self, code: &str, what: &str, k: usize, v: &Six, s: &[[Val; 2]; 3], tol: &Q) {
165 let ax = ["X", "Y", "Z"];
166 let sg = ["PLUS", "MINUS"];
167 for a in 0..3 {
168 for g in 0..2 {
169 self.one(code, format!("{} {} {} {}", what, k, ax[a], sg[g]), &v[a][g], &s[a][g], tol);
170 }
171 }
172 }
173}
174
175fn six_all(s: &Six, f: impl Fn(&RVal) -> bool) -> bool {
176 s.iter().all(|a| a.iter().all(|v| f(v)))
177}
178
179/// Verifies one result file. `case_bytes`, when given, must be the case file the
180/// result claims to come from. `sh_override` lets a caller reuse a shadow.
181pub fn verify(bytes: &[u8], case_bytes: Option<&[u8]>, role: Role) -> Report {
182 let mut rep = Report::default();
183 let r = match parse(bytes) {
184 Ok(r) => r,
185 Err(m) => {
186 rep.fail("E4-PARSE", m);
187 return rep;
188 }
189 };
190 let c = &r.case;
191 // ---- identities ----
192 let vid = r.compute_verdict_id();
193 if vid != r.verdict_id {
194 rep.fail("E4-VERDICT-ID", format!("verdict_id does not recompute (expected {})", vid));
195 }
196 let lines = lines_checked(bytes).unwrap_or_default();
197 let ed = tagged_hex(EVIDENCE_DOMAIN, &join_lf(&lines[..lines.len().saturating_sub(2)]));
198 if ed != r.evidence_digest {
199 rep.fail("E4-EVIDENCE-DIGEST", format!("evidence_digest does not recompute (expected {})", ed));
200 }
201 // ---- binding: the case file is fully determined by the copied lines ----
202 let rebuilt = case_bytes_from_body(&c.body_lines);
203 let rsha = sha256_hex(&rebuilt);
204 if rsha != r.case_file_sha256 {
205 rep.fail("E4-CASE-SHA", format!("case_file_sha256 {} is not the digest {} of the copied case", r.case_file_sha256, rsha));
206 }
207 if let Some(cb) = case_bytes {
208 match validate_bytes(cb) {
209 Err((code, m)) => rep.fail("E4-CASE-BINDING", format!("supplied case file is refused: {} ({})", code.code(), m)),
210 Ok(_) => {
211 if cb != rebuilt.as_slice() {
212 rep.fail("E4-CASE-BINDING", "the copied case_name, blocks or identities differ from the supplied case file".into());
213 }
214 }
215 }
216 }
217 // ---- provenance ----
218 let p = &r.prov;
219 if !CONTRACT_COMMITS.contains(&p.contract_commit.as_str()) {
220 rep.inconclusive("E4-PROV-CONTRACT-UNKNOWN", format!("contract_commit {} is not in the verified allowlist (src/verify.rs)", p.contract_commit));
221 }
222 if p.source_tree_clean != "YES" {
223 rep.inconclusive("E4-PROV-DIRTY-TREE", "source_tree_clean NO: not citable for a gate (AT0_RESULT_V2 section 7)".into());
224 }
225 let oracle_marked = p.build_cc.starts_with("oracle ") && p.engine_sha256 == p.oracle_sha256;
226 match role {
227 Role::Candidate => {
228 if p.build_cc.starts_with("oracle ") {
229 rep.fail("E4-PROV-ORACLE-RECORD", "an oracle-written record is never a candidate result (AT1_RESULT_V1 section 1)".into());
230 } else if p.engine_sha256 == p.oracle_sha256 && p.engine_sha256 != "none" {
231 rep.fail("E4-PROV-ORACLE-IS-ENGINE", "engine_sha256 equals oracle_sha256: the references did not come from a separate executable".into());
232 }
233 }
234 Role::Oracle => {
235 if !oracle_marked {
236 rep.fail("E4-PROV-ORACLE-RECORD", "oracle record must have build_cc beginning `oracle ` and engine_sha256 equal to oracle_sha256".into());
237 }
238 }
239 }
240 if is_placeholder(&r) {
241 let mut bad = r.kernel_dim != 0 || !r.verdict.failure_codes.is_empty() || r.verdict.expectation != "NOT_APPLICABLE";
242 bad |= r.verdict.checks.iter().any(|c| *c != Ck::NotEval);
243 bad |= crate::judge::all_values(&r).iter().any(|v| v.kind != Kind::Undefined);
244 bad |= r.label.iter().chain(r.ref_label.iter()).any(|s| *s != Status::Undefined);
245 bad |= (r.verdict.outcome == "ERROR") == (r.verdict.error_code == "none");
246 if bad {
247 rep.fail("E4-PLACEHOLDER-SHAPE", "ERROR/NOT_RUN result violates the shape of AT0_RESULT_V2 section 5".into());
248 }
249 rep.fail("E4-RUN-NOT-COMPLETED", format!("outcome {} error_code {}", r.verdict.outcome, r.verdict.error_code));
250 return rep;
251 }
252 for (k, v) in [("engine_sha256", &p.engine_sha256), ("oracle_repo", &p.oracle_repo), ("oracle_commit", &p.oracle_commit), ("oracle_sha256", &p.oracle_sha256), ("build_cc", &p.build_cc), ("build_flags", &p.build_flags), ("host", &p.host), ("run_started_utc", &p.run_started), ("run_finished_utc", &p.run_finished)] {
253 if v.as_str() == "none" {
254 rep.fail("E4-PROV-NONE", format!("completed run carries `{} none`", k));
255 }
256 }
257 if p.run_finished < p.run_started {
258 rep.fail("E4-PROV-TIME-ORDER", format!("run_finished_utc {} precedes run_started_utc {}", p.run_finished, p.run_started));
259 }
260 if r.verdict.error_code != "none" {
261 rep.fail("E4-UNDEFINED-DISCIPLINE", format!("completed run carries error_code {}", r.verdict.error_code));
262 }
263 // ---- shadow (always computable: AT-1 spectra are rational by rule 4) ----
264 let sh: Shadow = shadow(c, &Mods::default(), false);
265 let nontrivial = !sh.trivial;
266 let tolz = Q::from_scaled(&c.tol_zero);
267 // ---- token discipline (section 1) ----
268 if nontrivial {
269 let mut u = vec![];
270 if r.constraint.kind == Kind::Undefined {
271 u.push("constraint_residual".to_string());
272 }
273 if r.povm.kind == Kind::Undefined {
274 u.push("povm_residual".into());
275 }
276 for k in 0..c.m {
277 if r.clock[k].kind == Kind::Undefined {
278 u.push(format!("clock_probability {}", k));
279 }
280 if r.ref_clock[k].kind == Kind::Undefined {
281 u.push(format!("reference_clock_probability {}", k));
282 }
283 if !six_all(&r.ref_ideal[k], |v| v.kind != Kind::Undefined) {
284 u.push(format!("reference_ideal {}", k));
285 }
286 let pd = r.label[k] == Status::Defined;
287 if pd != six_all(&r.pauli[k], |v| v.kind != Kind::Undefined) || (!pd && !six_all(&r.pauli[k], |v| v.kind == Kind::Undefined)) {
288 u.push(format!("pauli {} (undefined exactly when label is not DEFINED)", k));
289 }
290 let rd = r.ref_label[k] == Status::Defined;
291 if rd != six_all(&r.ref_inter[k], |v| v.kind != Kind::Undefined) || (!rd && !six_all(&r.ref_inter[k], |v| v.kind == Kind::Undefined)) {
292 u.push(format!("reference_interacting {} (undefined exactly when reference_label is not DEFINED)", k));
293 }
294 }
295 if !u.is_empty() {
296 rep.fail("E4-UNDEFINED-DISCIPLINE", format!("undefined-token rule of AT1_RESULT_V1 section 1 broken on: {}", u.join("; ")));
297 }
298 } else {
299 let mut bad = r.constraint.kind != Kind::Undefined || r.povm.kind == Kind::Undefined;
300 let mut obad = false;
301 for k in 0..c.m {
302 bad |= r.label[k] != Status::Undefined || r.clock[k].kind != Kind::Undefined;
303 bad |= !six_all(&r.pauli[k], |v| v.kind == Kind::Undefined);
304 obad |= r.ref_label[k] != Status::Undefined || r.ref_clock[k].kind != Kind::Undefined;
305 obad |= !six_all(&r.ref_inter[k], |v| v.kind == Kind::Undefined) || !six_all(&r.ref_ideal[k], |v| v.kind != Kind::Undefined);
306 }
307 if bad {
308 rep.fail("E4-TRIVIAL-SHAPE", "trivial kernel: labels UNDEFINED, clock_probability, pauli and constraint_residual undefined 0@0, povm_residual a value (AT1_RESULT_V1 section 1)".into());
309 }
310 if obad {
311 rep.fail("E4-ORACLE-TRIVIAL", "trivial kernel: reference_label UNDEFINED, reference_clock_probability and reference_interacting undefined 0@0, reference_ideal values (AT1_RESULT_V1 section 1)".into());
312 }
313 }
314 // ---- label rule: each status follows from its own clock value and bound ----
315 for k in 0..c.m {
316 if label_from(&r.clock[k], &tolz) != r.label[k] {
317 rep.fail("E4-LABEL-RULE", format!("label {} is {} but its clock_probability gives {}", k, r.label[k].text(), label_from(&r.clock[k], &tolz).text()));
318 }
319 if label_from(&r.ref_clock[k], &tolz) != r.ref_label[k] {
320 rep.fail("E4-LABEL-RULE", format!("reference_label {} is {} but its reference_clock_probability gives {}", k, r.ref_label[k].text(), label_from(&r.ref_clock[k], &tolz).text()));
321 }
322 }
323 if r.bound_kind == BoundKind::None {
324 let mut nz = !r.constraint.bound.n.is_zero() || !r.povm.bound.n.is_zero();
325 for k in 0..c.m {
326 nz |= !r.clock[k].bound.n.is_zero() || !six_all(&r.pauli[k], |v| v.bound.n.is_zero());
327 // Agent 0 ruling 4 (omega#371 comment 6093827495): bound_kind describes the engine's own
328 // lines; the spliced reference_* families keep the oracle's bounds, so the NONE rule of
329 // AT1_RESULT_V1 section 2 is judged on engine lines only.
330 }
331 if nz {
332 rep.fail("E4-BOUND-NONE-NONZERO", "bound_kind NONE but an engine line carries a nonzero bound (AT1_RESULT_V1 section 2: every bound 0@0; reference lines keep the oracle's bounds: ruling 4, omega#371)".into());
333 }
334 }
335 // ---- exact re-derivation of the verdict ----
336 let d = rederive(&r, nontrivial);
337 for i in 0..12 {
338 if d.checks[i] != r.verdict.checks[i] {
339 rep.fail("E4-CHECK-MISMATCH", format!("check {} reported {}, re-derived {}", CHECK_NAMES[i], r.verdict.checks[i].text(), d.checks[i].text()));
340 }
341 }
342 if d.outcome != r.verdict.outcome {
343 rep.fail("E4-OUTCOME-MISMATCH", format!("outcome reported {}, re-derived {}", r.verdict.outcome, d.outcome));
344 }
345 if d.failure_codes != r.verdict.failure_codes {
346 rep.fail("E4-CODES-MISMATCH", format!("failure_codes reported {:?}, re-derived {:?}", r.verdict.failure_codes, d.failure_codes));
347 }
348 if d.expectation != r.verdict.expectation {
349 rep.fail("E4-EXPECTATION-MISMATCH", format!("expectation_met reported {}, re-derived {}", r.verdict.expectation, d.expectation));
350 }
351 rep.any_indeterminate = d.checks.iter().any(|c| *c == Ck::Indet) || r.label.iter().any(|s| *s == Status::Indeterminate);
352 if role == Role::Candidate && d.expectation != "YES" {
353 let exp = if c.expected_codes.is_empty() { "none".to_string() } else { c.expected_codes.join(",") };
354 let got = if d.failure_codes.is_empty() { "none".to_string() } else { d.failure_codes.join(",") };
355 let msg = format!("re-derived outcome {} codes {} vs expected {} codes {}", d.outcome, got, if c.expected_pass { "PASS" } else { "FAIL" }, exp);
356 let only_precision = d.failure_codes.iter().filter(|x| !c.expected_codes.contains(x)).all(|x| x == "PRECISION_INSUFFICIENT")
357 && c.expected_codes.iter().all(|x| d.failure_codes.contains(x));
358 if only_precision && rep.any_indeterminate {
359 rep.inconclusive("E4-EXPECTATION-INDETERMINATE", msg);
360 } else {
361 rep.fail("E4-EXPECTATION-NOT-MET", msg);
362 }
363 }
364 rep.derived_outcome = d.outcome.clone();
365 rep.derived_codes = d.failure_codes.clone();
366 rep.derived_expectation = d.expectation.clone();
367 // ---- shadow agreement ----
368 let tol_prob = Q::from_scaled(&c.tol_prob);
369 let tol_schro = Q::from_scaled(&c.tol_schro);
370 let tol_povm = Q::from_scaled(&c.tol_povm);
371 let mut cm = Cmp { rep: &mut rep, bk: r.bound_kind, strict: false };
372 {
373 if r.kernel_dim as usize != sh.kernel_dim {
374 cm.rep.fail("E4-SHADOW-KERNEL-DIM", format!("physical_state_kernel_dim {}, exact value {}", r.kernel_dim, sh.kernel_dim));
375 }
376 if claims_trivial(&r) != sh.trivial {
377 cm.rep.fail("E4-SHADOW-TRIVIAL", format!("the file {} a trivial kernel; the exact decision is {}", if claims_trivial(&r) { "claims" } else { "denies" }, if sh.trivial { "trivial" } else { "nontrivial" }));
378 }
379 if nontrivial {
380 if let Some(x) = r.constraint.q() {
381 // the exact residual of a vector built from exact kernel pairs is 0
382 if x.abs().cmp(&r.constraint.bq()) == Ordering::Greater {
383 let z = Val::exact(Q::zero());
384 cm.bound_claim("constraint_residual", &r.constraint, &z);
385 }
386 }
387 }
388 cm.one("E4-SHADOW-POVM", "povm_residual".into(), &r.povm, &sh.povm_residual, &tol_povm);
389 if nontrivial {
390 for k in 0..c.m {
391 cm.one("E4-SHADOW-CLOCK", format!("clock_probability {}", k), &r.clock[k], &sh.p[k], &tol_prob);
392 let (es, ss) = (r.label[k], sh.status[k]);
393 if es != Status::Indeterminate && ss != Status::Indeterminate && es != ss {
394 cm.rep.fail("E4-SHADOW-LABEL", format!("label {} is {}, exact status {}", k, es.text(), ss.text()));
395 }
396 if let Some(sp) = &sh.pauli[k] {
397 if es == Status::Defined {
398 cm.six("E4-SHADOW-PAULI", "pauli", k, &r.pauli[k], sp, &tol_schro);
399 }
400 }
401 // oracle families (gate G3 when the role is Oracle; always reported)
402 cm.strict = true;
403 cm.one("E4-ORACLE-CLOCK", format!("reference_clock_probability {}", k), &r.ref_clock[k], &sh.p[k], &tol_prob);
404 let rs = r.ref_label[k];
405 if rs != Status::Indeterminate && ss != Status::Indeterminate && rs != ss {
406 cm.rep.fail("E4-ORACLE-LABEL", format!("reference_label {} is {}, exact status {}", k, rs.text(), ss.text()));
407 }
408 if let Some(sp) = &sh.pauli[k] {
409 if rs == Status::Defined {
410 cm.six("E4-ORACLE-INTERACTING", "reference_interacting", k, &r.ref_inter[k], sp, &tol_schro);
411 }
412 }
413 cm.strict = false;
414 }
415 }
416 for k in 0..c.m {
417 cm.strict = true;
418 cm.six("E4-ORACLE-IDEAL", "reference_ideal", k, &r.ref_ideal[k], &sh.ideal[k], &tol_schro);
419 }
420 }
421 rep
422}
423
424/// Per-case candidate status for the table: PASS, FAIL or INDETERMINATE.
425pub fn case_status(rep: &Report) -> &'static str {
426 match rep.status() {
427 "PASS" => "PASS",
428 "FAIL" => "FAIL",
429 _ => "INDETERMINATE",
430 }
431}