Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-proof/src/formal.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-proof / src / formal.rs` 562 lines ยท 20976 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 //! Formal oracle bindings: tie a formal proof job to the exact evidence it ran on. 17 //! 18 //! A formal job (a theorem prover or model checker run) is one more 19 //! qualification procedure. Its result becomes an ordinary `EvidenceReceiptV1` 20 //! of kind [`KIND`]. No new receipt fields and no new canonical encoding exist: 21 //! each bound item is a stable assertion ID, the four input digests sit in 22 //! `input_artifacts`, the oracle toolchain sits in `toolchain`, and the output 23 //! digest and dependencies use the native fields. Names are tool neutral 24 //! (`oracle_toolchain`, `proof_source_digest`) so a later oracle can replace 25 //! the bootstrap one without a format change (ADR 0027 point 5). 26 //! 27 //! A PASS here is one evidence input bound to one source and model revision. 28 //! It is not authority (ADR 0027 point 6); `authority` stays empty. 29 //! 30 //! Invalidation rests on [`crate::fingerprint`]: a job whose inputs include 31 //! the invariant manifest, the formal model and proof sources, and the covered 32 //! implementation file gets a new job key when any of them changes, so an old 33 //! stamp is never replayed for new evidence. 34 35 use std::path::{Path, PathBuf}; 36 37 use crate::evidence::{Assertion, Receipt, Verdict}; 38 use crate::fingerprint::inputs_digest; 39 use crate::import::{build_receipt, ImportRequest}; 40 41 /// Receipt kind for formal oracle bindings. 42 pub const KIND: &str = "formal-oracle-binding"; 43 44 pub const A_INVARIANT_ID: &str = "oracle_binding.invariant_id"; 45 pub const A_INVARIANT_VERSION: &str = "oracle_binding.invariant_version"; 46 pub const A_MODEL_DIGEST: &str = "oracle_binding.model_digest"; 47 pub const A_ORACLE_TOOLCHAIN: &str = "oracle_binding.oracle_toolchain"; 48 pub const A_PROOF_SOURCE_DIGEST: &str = "oracle_binding.proof_source_digest"; 49 pub const A_COVERED_IMPL_DIGEST: &str = "oracle_binding.covered_impl_digest"; 50 pub const A_MANIFEST_DIGEST: &str = "oracle_binding.manifest_digest"; 51 /// Prefix of one assertion per theorem checked: `oracle_binding.theorem:`. 52 pub const A_THEOREM_PREFIX: &str = "oracle_binding.theorem:"; 53 54 const SOURCE: &str = "aien-proof formal bind"; 55 56 /// Everything a formal job binds, as plain data. 57 #[derive(Debug, Clone, PartialEq, Eq)] 58 pub struct FormalBinding { 59 pub invariant_id: String, 60 pub invariant_version: u32, 61 /// Digest of the formal model files. 62 pub model_digest: String, 63 /// Oracle toolchain identity (version, commit, platform), free text. 64 pub oracle_toolchain: String, 65 /// Digest of all proof sources the oracle compiled (model, theorems, corpus, mutants). 66 pub proof_source_digest: String, 67 /// Digest of the implementation file(s) the model claims to cover. 68 pub covered_impl_digest: String, 69 /// Digest of the invariant manifest. 70 pub manifest_digest: String, 71 pub theorems_checked: Vec, 72 } 73 74 /// Paths (relative to `base`) that make up each slice of a formal job. 75 #[derive(Debug, Clone)] 76 pub struct FormalInputs { 77 pub base: PathBuf, 78 pub manifest: PathBuf, 79 pub model: Vec, 80 pub proof_source: Vec, 81 pub covered: Vec, 82 } 83 84 impl FormalInputs { 85 /// One digest over every input of the job. The job writes it into its 86 /// captured output so a receipt can refuse output from a different input set. 87 pub fn run_digest(&self) -> Result { 88 let mut all = vec![self.manifest.clone()]; 89 all.extend(self.model.iter().cloned()); 90 all.extend(self.proof_source.iter().cloned()); 91 all.extend(self.covered.iter().cloned()); 92 inputs_digest(&self.base, &all).map_err(|e| format!("cannot digest inputs: {e}")) 93 } 94 95 fn slice(&self, paths: &[PathBuf]) -> Result { 96 if paths.is_empty() { 97 return Err("formal binding needs at least one path per input slice".to_string()); 98 } 99 inputs_digest(&self.base, paths).map_err(|e| format!("cannot digest inputs: {e}")) 100 } 101 } 102 103 /// Read `id` and `version` from the top level of an invariant manifest. 104 /// Only the leading key/value block (before the first table header) is read. 105 pub fn manifest_identity(path: &Path) -> Result<(String, u32), String> { 106 let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read manifest: {e}"))?; 107 let (mut id, mut version) = (None, None); 108 for line in text.lines() { 109 if line.starts_with('[') { 110 break; 111 } 112 if let Some(rest) = line.strip_prefix("id = ") { 113 id = Some(rest.trim().trim_matches('"').to_string()); 114 } else if let Some(rest) = line.strip_prefix("version = ") { 115 version = rest.trim().parse::().ok(); 116 } 117 } 118 match (id, version) { 119 (Some(i), Some(v)) if !i.is_empty() => Ok((i, v)), 120 _ => Err("manifest has no top level id and numeric version".to_string()), 121 } 122 } 123 124 /// Result of the job taken from the oracle's own final line, `PREFIX: PASS|FAIL|NOT_RUN`. 125 /// Anything else is refused; there is no default. 126 pub fn parse_result_line(output: &str, prefix: &str) -> Result { 127 let last = output 128 .lines() 129 .rev() 130 .find(|l| !l.trim().is_empty()) 131 .ok_or_else(|| "output is empty".to_string())?; 132 match last.strip_prefix(prefix).and_then(|r| r.strip_prefix(": ")) { 133 Some("PASS") => Ok(Verdict::Pass), 134 Some("FAIL") => Ok(Verdict::Fail), 135 Some("NOT_RUN") => Ok(Verdict::Skipped), 136 _ => Err(format!( 137 "last output line is not a {prefix} result line: {last:?}" 138 )), 139 } 140 } 141 142 /// The job output must carry the digest of the exact inputs it ran on. 143 pub fn check_output_binds_inputs(output: &str, run_digest: &str) -> Result<(), String> { 144 let want = format!("inputs_digest: {run_digest}"); 145 if output.lines().any(|l| l == want) { 146 Ok(()) 147 } else { 148 Err("output does not carry this input set's digest (stale or foreign output)".to_string()) 149 } 150 } 151 152 /// Compute the binding from files on disk. 153 pub fn compute_binding( 154 inputs: &FormalInputs, 155 oracle_toolchain: &str, 156 theorems: &[String], 157 ) -> Result { 158 let (invariant_id, invariant_version) = manifest_identity(&inputs.base.join(&inputs.manifest))?; 159 Ok(FormalBinding { 160 invariant_id, 161 invariant_version, 162 model_digest: inputs.slice(&inputs.model)?, 163 oracle_toolchain: oracle_toolchain.to_string(), 164 proof_source_digest: inputs.slice(&inputs.proof_source)?, 165 covered_impl_digest: inputs.slice(&inputs.covered)?, 166 manifest_digest: inputs.slice(std::slice::from_ref(&inputs.manifest))?, 167 theorems_checked: theorems.to_vec(), 168 }) 169 } 170 171 fn fact(id: &str, value: &str) -> Assertion { 172 Assertion { 173 id: id.to_string(), 174 expected: String::new(), 175 observed: value.to_string(), 176 pass: true, 177 source: SOURCE.to_string(), 178 note: String::new(), 179 } 180 } 181 182 /// Assertions carrying the binding. Theorem assertions pass only when the 183 /// job's result is PASS. 184 pub fn binding_assertions(b: &FormalBinding, result: Verdict) -> Vec { 185 let mut out = vec![ 186 fact(A_INVARIANT_ID, &b.invariant_id), 187 fact(A_INVARIANT_VERSION, &b.invariant_version.to_string()), 188 fact(A_MODEL_DIGEST, &b.model_digest), 189 fact(A_ORACLE_TOOLCHAIN, &b.oracle_toolchain), 190 fact(A_PROOF_SOURCE_DIGEST, &b.proof_source_digest), 191 fact(A_COVERED_IMPL_DIGEST, &b.covered_impl_digest), 192 fact(A_MANIFEST_DIGEST, &b.manifest_digest), 193 ]; 194 for t in &b.theorems_checked { 195 let mut a = fact(&format!("{A_THEOREM_PREFIX}{t}"), "checked"); 196 a.pass = result == Verdict::Pass; 197 out.push(a); 198 } 199 out 200 } 201 202 fn get<'a>(r: &'a Receipt, id: &str) -> Result<&'a str, String> { 203 r.assertions 204 .iter() 205 .find(|a| a.id == id) 206 .map(|a| a.observed.as_str()) 207 .filter(|v| !v.trim().is_empty()) 208 .ok_or_else(|| format!("formal receipt lacks assertion {id}")) 209 } 210 211 /// Read the binding back out of a receipt, checking it is self consistent: 212 /// the four digests in `input_artifacts` equal the digest assertions, the 213 /// toolchain field equals the oracle toolchain, and at least one theorem is listed. 214 pub fn parse_binding(r: &Receipt) -> Result { 215 if r.kind != KIND { 216 return Err(format!("not a formal oracle binding: kind {:?}", r.kind)); 217 } 218 let b = FormalBinding { 219 invariant_id: get(r, A_INVARIANT_ID)?.to_string(), 220 invariant_version: get(r, A_INVARIANT_VERSION)? 221 .parse() 222 .map_err(|_| "invariant_version is not a number".to_string())?, 223 model_digest: get(r, A_MODEL_DIGEST)?.to_string(), 224 oracle_toolchain: get(r, A_ORACLE_TOOLCHAIN)?.to_string(), 225 proof_source_digest: get(r, A_PROOF_SOURCE_DIGEST)?.to_string(), 226 covered_impl_digest: get(r, A_COVERED_IMPL_DIGEST)?.to_string(), 227 manifest_digest: get(r, A_MANIFEST_DIGEST)?.to_string(), 228 theorems_checked: r 229 .assertions 230 .iter() 231 .filter_map(|a| a.id.strip_prefix(A_THEOREM_PREFIX)) 232 .map(str::to_string) 233 .collect(), 234 }; 235 if b.theorems_checked.is_empty() { 236 return Err("formal receipt lists no theorems".to_string()); 237 } 238 let want = artifact_digests(&b); 239 if r.input_artifacts != want { 240 return Err("input_artifacts do not match the bound digests".to_string()); 241 } 242 if r.toolchain != b.oracle_toolchain { 243 return Err("toolchain field differs from oracle_toolchain".to_string()); 244 } 245 Ok(b) 246 } 247 248 fn artifact_digests(b: &FormalBinding) -> Vec { 249 [ 250 &b.manifest_digest, 251 &b.model_digest, 252 &b.proof_source_digest, 253 &b.covered_impl_digest, 254 ] 255 .iter() 256 .map(|d| format!("blake3:{d}")) 257 .collect() 258 } 259 260 /// Profile checks for kind [`KIND`], called from `build_receipt`. 261 pub fn validate_formal_profile( 262 req: &ImportRequest, 263 assertions: &[Assertion], 264 result: Verdict, 265 ) -> Result<(), String> { 266 if !req.authority.trim().is_empty() { 267 return Err("a formal binding is evidence, not authority: authority must be empty".into()); 268 } 269 if req.toolchain.trim().is_empty() { 270 return Err("formal binding requires an oracle toolchain identity".to_string()); 271 } 272 if req.tier != "HOST_TEST" { 273 return Err(format!("formal binding refuses tier {:?}", req.tier)); 274 } 275 for id in [ 276 A_INVARIANT_ID, 277 A_INVARIANT_VERSION, 278 A_MODEL_DIGEST, 279 A_ORACLE_TOOLCHAIN, 280 A_PROOF_SOURCE_DIGEST, 281 A_COVERED_IMPL_DIGEST, 282 A_MANIFEST_DIGEST, 283 ] { 284 let ok = assertions 285 .iter() 286 .any(|a| a.id == id && !a.observed.trim().is_empty()); 287 if !ok { 288 return Err(format!("formal binding missing assertion {id}")); 289 } 290 } 291 if !assertions 292 .iter() 293 .any(|a| a.id.starts_with(A_THEOREM_PREFIX)) 294 { 295 return Err("formal binding lists no theorems".to_string()); 296 } 297 if result == Verdict::Pass && assertions.iter().any(|a| !a.pass) { 298 return Err("formal binding claims PASS but an assertion failed".to_string()); 299 } 300 if req.input_artifacts.len() != 4 { 301 return Err("formal binding needs the four input digests".to_string()); 302 } 303 Ok(()) 304 } 305 306 /// Facts a caller supplies beyond the binding itself. 307 #[derive(Debug, Clone)] 308 pub struct FormalRun { 309 /// Repository and commit of the covered implementation. 310 pub repo: String, 311 pub commit: String, 312 pub dirty: bool, 313 pub machine: String, 314 pub procedure: String, 315 pub result: Verdict, 316 pub output_digest: String, 317 pub dependencies: Vec, 318 pub external_refs: Vec, 319 pub timestamp: Option, 320 } 321 322 /// Mint the receipt for a formal job. 323 pub fn bind_receipt(b: &FormalBinding, run: &FormalRun) -> Result { 324 let req = ImportRequest { 325 repo: run.repo.clone(), 326 commit: run.commit.clone(), 327 dirty: run.dirty, 328 kind: KIND.to_string(), 329 tier: "HOST_TEST".to_string(), 330 toolchain: b.oracle_toolchain.clone(), 331 procedure: run.procedure.clone(), 332 machine: run.machine.clone(), 333 input_artifacts: artifact_digests(b), 334 dependencies: run.dependencies.clone(), 335 output_digest: Some(run.output_digest.clone()), 336 external_refs: run.external_refs.clone(), 337 timestamp: run.timestamp, 338 ..ImportRequest::default() 339 }; 340 build_receipt(&req, binding_assertions(b, run.result), run.result) 341 } 342 343 #[cfg(test)] 344 mod tests { 345 use super::*; 346 use crate::evidence::verify_bytes; 347 use crate::fingerprint::job_key; 348 use crate::testutil::temp_dir; 349 use std::fs; 350 351 const MANIFEST: &str = 352 "schema_version = 0\nid = \"AIEN.INV.TEST.V1\"\nversion = 3\n\n[[x]]\nid = \"nope\"\n"; 353 354 fn tree(root: &Path) -> FormalInputs { 355 fs::create_dir_all(root.join("inv")).unwrap(); 356 fs::create_dir_all(root.join("lean/Model")).unwrap(); 357 fs::create_dir_all(root.join("src")).unwrap(); 358 fs::write(root.join("inv/a.toml"), MANIFEST).unwrap(); 359 fs::write(root.join("lean/Model/Model.lean"), "def m := 1").unwrap(); 360 fs::write( 361 root.join("lean/Theorems.lean"), 362 "theorem t : True := trivial", 363 ) 364 .unwrap(); 365 fs::write(root.join("src/cap.rs"), "fn derive() {}").unwrap(); 366 FormalInputs { 367 base: root.to_path_buf(), 368 manifest: "inv/a.toml".into(), 369 model: vec!["lean/Model".into()], 370 proof_source: vec!["lean".into()], 371 covered: vec!["src/cap.rs".into()], 372 } 373 } 374 375 fn all_inputs(i: &FormalInputs) -> Vec { 376 let mut v = vec![i.manifest.clone()]; 377 v.extend(i.model.clone()); 378 v.extend(i.proof_source.clone()); 379 v.extend(i.covered.clone()); 380 v 381 } 382 383 fn key(i: &FormalInputs) -> String { 384 job_key( 385 &i.base, 386 "formal-test-v1", 387 &["sh".into(), "run.sh".into()], 388 "lean 4", 389 &all_inputs(i), 390 ) 391 .unwrap() 392 } 393 394 fn run() -> FormalRun { 395 FormalRun { 396 repo: "https://github.com/aien-dev/aienux".into(), 397 commit: "a".repeat(40), 398 dirty: false, 399 machine: "spark".into(), 400 procedure: "formal-test-v1".into(), 401 result: Verdict::Pass, 402 output_digest: "c".repeat(64), 403 dependencies: vec![], 404 external_refs: vec![], 405 timestamp: Some(1), 406 } 407 } 408 409 fn binding(i: &FormalInputs) -> FormalBinding { 410 compute_binding(i, "lean 4.34.1", &["t1".into(), "t2".into()]).unwrap() 411 } 412 413 #[test] 414 fn manifest_identity_reads_top_level_only() { 415 let root = temp_dir("formal-id"); 416 let i = tree(&root); 417 assert_eq!( 418 manifest_identity(&root.join(&i.manifest)).unwrap(), 419 ("AIEN.INV.TEST.V1".to_string(), 3) 420 ); 421 } 422 423 #[test] 424 fn receipt_round_trips_and_verifies() { 425 let root = temp_dir("formal-rt"); 426 let i = tree(&root); 427 let b = binding(&i); 428 let r = bind_receipt(&b, &run()).unwrap(); 429 let text = serde_json::to_vec(&r).unwrap(); 430 assert!(verify_bytes(&text).unwrap().1.ok()); 431 assert_eq!(parse_binding(&r).unwrap(), b); 432 assert_eq!(r.output_digest, "c".repeat(64)); 433 assert_eq!(r.authority, ""); 434 } 435 436 #[test] 437 fn changed_implementation_model_proof_or_manifest_changes_key_digest_and_receipt() { 438 for (rel, what) in [ 439 ("src/cap.rs", "implementation"), 440 ("lean/Model/Model.lean", "model"), 441 ("lean/Theorems.lean", "proof source"), 442 ("inv/a.toml", "manifest"), 443 ] { 444 let root = temp_dir("formal-inv"); 445 let i = tree(&root); 446 let (k0, d0, b0) = (key(&i), i.run_digest().unwrap(), binding(&i)); 447 let id0 = bind_receipt(&b0, &run()).unwrap().id; 448 let old = fs::read_to_string(root.join(rel)).unwrap(); 449 fs::write(root.join(rel), format!("{old}\n-- changed")).unwrap(); 450 assert_ne!(k0, key(&i), "{what}: job key must change"); 451 assert_ne!( 452 d0, 453 i.run_digest().unwrap(), 454 "{what}: run digest must change" 455 ); 456 let b1 = binding(&i); 457 assert_ne!(b0, b1, "{what}: binding must change"); 458 assert_ne!( 459 id0, 460 bind_receipt(&b1, &run()).unwrap().id, 461 "{what}: receipt id" 462 ); 463 } 464 } 465 466 #[test] 467 fn each_slice_digest_moves_only_with_its_own_files() { 468 let root = temp_dir("formal-slice"); 469 let i = tree(&root); 470 let b0 = binding(&i); 471 fs::write(root.join("src/cap.rs"), "fn derive() { /* x */ }").unwrap(); 472 let b1 = binding(&i); 473 assert_ne!(b0.covered_impl_digest, b1.covered_impl_digest); 474 assert_eq!(b0.model_digest, b1.model_digest); 475 assert_eq!(b0.proof_source_digest, b1.proof_source_digest); 476 assert_eq!(b0.manifest_digest, b1.manifest_digest); 477 } 478 479 #[test] 480 fn lake_build_output_does_not_change_the_key() { 481 let root = temp_dir("formal-lake"); 482 let i = tree(&root); 483 let k0 = key(&i); 484 fs::create_dir_all(root.join("lean/.lake/build")).unwrap(); 485 fs::write(root.join("lean/.lake/build/x.olean"), "bin").unwrap(); 486 assert_eq!(k0, key(&i)); 487 } 488 489 #[test] 490 fn result_line_must_match_the_oracle_prefix() { 491 assert_eq!( 492 parse_result_line("a\nCAP_FORMAL_BOOTSTRAP: PASS\n", "CAP_FORMAL_BOOTSTRAP"), 493 Ok(Verdict::Pass) 494 ); 495 assert_eq!( 496 parse_result_line("CAP_FORMAL_BOOTSTRAP: FAIL", "CAP_FORMAL_BOOTSTRAP"), 497 Ok(Verdict::Fail) 498 ); 499 assert_eq!( 500 parse_result_line("CAP_FORMAL_BOOTSTRAP: NOT_RUN", "CAP_FORMAL_BOOTSTRAP"), 501 Ok(Verdict::Skipped) 502 ); 503 assert!( 504 parse_result_line("RECEIPT_FORMAL_BOOTSTRAP: PASS", "CAP_FORMAL_BOOTSTRAP").is_err() 505 ); 506 assert!( 507 parse_result_line("CAP_FORMAL_BOOTSTRAP: PASS\nextra", "CAP_FORMAL_BOOTSTRAP").is_err() 508 ); 509 assert!(parse_result_line("", "CAP_FORMAL_BOOTSTRAP").is_err()); 510 } 511 512 #[test] 513 fn output_from_another_input_set_is_refused() { 514 let root = temp_dir("formal-stale"); 515 let i = tree(&root); 516 let d = i.run_digest().unwrap(); 517 let out = format!("inputs_digest: {d}\nCAP_FORMAL_BOOTSTRAP: PASS\n"); 518 assert!(check_output_binds_inputs(&out, &d).is_ok()); 519 fs::write(root.join("src/cap.rs"), "fn derive() { evil() }").unwrap(); 520 assert!(check_output_binds_inputs(&out, &i.run_digest().unwrap()).is_err()); 521 } 522 523 #[test] 524 fn failing_result_is_never_sealed_and_theorems_are_not_passing() { 525 let root = temp_dir("formal-fail"); 526 let b = binding(&tree(&root)); 527 let mut r = run(); 528 r.result = Verdict::Fail; 529 assert!( 530 bind_receipt(&b, &r).is_err(), 531 "the receipt layer refuses to seal FAIL" 532 ); 533 assert!(binding_assertions(&b, Verdict::Fail) 534 .iter() 535 .filter(|a| a.id.starts_with(A_THEOREM_PREFIX)) 536 .all(|a| !a.pass)); 537 } 538 539 #[test] 540 fn profile_refuses_incomplete_or_authoritative_bindings() { 541 let root = temp_dir("formal-refuse"); 542 let b = binding(&tree(&root)); 543 let mut no_theorems = b.clone(); 544 no_theorems.theorems_checked.clear(); 545 assert!(bind_receipt(&no_theorems, &run()).is_err()); 546 let mut no_tool = b.clone(); 547 no_tool.oracle_toolchain = " ".into(); 548 assert!(bind_receipt(&no_tool, &run()).is_err()); 549 let mut r = run(); 550 r.output_digest = "zz".into(); 551 assert!(bind_receipt(&b, &r).is_err()); 552 } 553 554 #[test] 555 fn tampered_artifacts_fail_binding_parse() { 556 let root = temp_dir("formal-tamper"); 557 let b = binding(&tree(&root)); 558 let mut r = bind_receipt(&b, &run()).unwrap(); 559 r.input_artifacts[3] = format!("blake3:{}", "e".repeat(64)); 560 assert!(parse_binding(&r).is_err()); 561 } 562 }