Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Take the theorem from the checker, not from a Rust literal (#203) (#220)
Fabio Rovai35769bcaf7ae
diff --git a/src/closure_diff.rs b/src/closure_diff.rsindex ff5ce561..3b95c58a 100644--- a/src/closure_diff.rs+++ b/src/closure_diff.rs@@ -908,7 +908,8 @@ mod tests {/// Accepted`, whose only constructor takes a `verdict::Certified`, which/// nothing outside `src/verdict.rs` can build. A test that wants an/// acceptance has to EARN one, so this one runs a process that exits zero- /// — which is exactly the condition the test is named after.+ /// AND prints the theorem name, the way `lean/Main.lean` does. Exit zero on+ /// its own is checked below too: it mints nothing.#[test]fn a_checked_word_needs_exit_zero() {let dir = std::env::temp_dir().join("oo-closure-diff-exit-zero");@@ -920,16 +921,32 @@ mod tests {// A script rather than `/bin/true`, which is `/usr/bin/true` on macOS// and absent from `/bin` entirely. The suite found that itself. A `.sh`// is not executable on Windows either, which CI then found.+ let report = r#"{"verdict":"checked","theorem":"OOCert.certificate_sound"}"#;let ok = dir.join(if cfg!(windows) { "exit0.cmd" } else { "exit0.sh" });- let body = if cfg!(windows) { "@echo off\r\nexit /b 0\r\n" } else { "#!/bin/sh\nexit 0\n" };+ let body = if cfg!(windows) {+ format!("@echo off\r\necho {report}\r\nexit /b 0\r\n")+ } else {+ format!("#!/bin/sh\necho '{report}'\nexit 0\n")+ };std::fs::write(&ok, body).unwrap();+ // The same exit code with nothing on stdout: not an acceptance.+ let mute = dir.join(if cfg!(windows) { "mute.cmd" } else { "mute.sh" });+ let mute_body = if cfg!(windows) { "@echo off\r\nexit /b 0\r\n" } else { "#!/bin/sh\nexit 0\n" };+ std::fs::write(&mute, mute_body).unwrap();#[cfg(unix)]{use std::os::unix::fs::PermissionsExt as _;- std::fs::set_permissions(&ok, std::fs::Permissions::from_mode(0o755)).unwrap();+ for f in [&ok, &mute] {+ std::fs::set_permissions(f, std::fs::Permissions::from_mode(0o755)).unwrap();+ }}let accepted = pe::run_checker(CertKind::OoCert, Some(ok.as_path()), &a, &d, None);assert!(matches!(accepted, CheckerStatus::Accepted(_)), "{accepted:?}");+ let unnamed = pe::run_checker(CertKind::OoCert, Some(mute.as_path()), &a, &d, None);+ assert!(+ matches!(unnamed, CheckerStatus::Unreadable { .. }),+ "exit zero without a theorem name must not be an acceptance: {unnamed:?}"+ );for (status, want) in [(accepted, "checked"),diff --git a/src/fol_solve.rs b/src/fol_solve.rsindex daa0b6a6..4f5b2d12 100644--- a/src/fol_solve.rs+++ b/src/fol_solve.rs@@ -669,7 +669,7 @@ pub fn solve(problem: &FolProblem, opts: &SolveOptions, dir: &Path) -> anyhow::Rlet exit = run.exit();out.checker_exit = Some(exit);out.checker_report = Some(report.clone());- if let Some(cert) = run.accepted(FOL_THEOREM) {+ if let Some(cert) = run.accepted_naming(&[FOL_THEOREM]) {out.verdict = FolVerdict::ModelChecked(cert);out.theorem = Some(cert.theorem().to_string());// Read the goal flag back off the CHECKER's report, notdiff --git a/src/projection_entailment.rs b/src/projection_entailment.rsindex 571937d0..b9488462 100644--- a/src/projection_entailment.rs+++ b/src/projection_entailment.rs@@ -822,12 +822,25 @@ pub fn run_checker(};let text = run.output();// The theorem name is handed to the evidence rather than to the report, so- // a status with no acceptance behind it has no way to name one.- let theorem = match kind {- CertKind::OoCert => "OOCert.certificate_sound",- CertKind::OoHorn => "OOCert.horn_certificate_sound",+ // a status with no acceptance behind it has no way to name one. What is+ // listed here is what this call site will ACCEPT; which of them the token+ // ends up carrying is read out of the checker's own stdout.+ //+ // `oo-horn` has two. `lean/HMain.lean` earns the absolute+ // `OOCert.entails_of_builtin_horn` when the rule table is exactly the+ // built-ins, and the relativised `OOCert.horn_certificate_sound` for any+ // other table, and it prints which. Naming one literal here reported the+ // relativised statement for both, which is the safe direction to be wrong+ // in and still wrong: the field that exists to distinguish an entailment+ // from an entailment-under-supplied-rules did not distinguish them.+ let theorems: &[&'static str] = match kind {+ CertKind::OoCert => &["OOCert.certificate_sound"],+ CertKind::OoHorn => &[+ "OOCert.horn_certificate_sound",+ "OOCert.entails_of_builtin_horn",+ ],};- match run.accepted(theorem) {+ match run.accepted_naming(theorems) {Some(cert) => CheckerStatus::Accepted(Accepted::from_run(cert, text)),// `lean/Main.lean` reserves 1 for a rejection and 2 for a file it// could not read. Anything else is not a verdict in either direction.diff --git a/src/shacl_verified.rs b/src/shacl_verified.rsindex 723bbabf..62df6057 100644--- a/src/shacl_verified.rs+++ b/src/shacl_verified.rs@@ -168,7 +168,7 @@ pub fn validate_verified(run.stdout())})?;- let token = run.accepted("Shacl.validate_spec").ok_or_else(|| {+ let token = run.accepted_naming(&["Shacl.validate_spec"]).ok_or_else(|| {anyhow::anyhow!("exit 0 did not yield a certificate token, which cannot happen")})?;let v = ShaclVerified::Checked(conforms, token);diff --git a/src/verdict.rs b/src/verdict.rsindex 05c3efff..58e6bf0f 100644--- a/src/verdict.rs+++ b/src/verdict.rs@@ -150,13 +150,45 @@ impl CheckerRun {format!("{}{}", self.stdout, self.stderr)}+ /// The theorem this run named in its own stdout, if it named one.+ ///+ /// Every `lean/` entry point that mints a verdict prints a `theorem` field+ /// saying which statement its acceptance discharges. Reading it here is+ /// what lets a report quote the checker rather than describe it.+ pub fn named_theorem(&self) -> Option<String> {+ let v: serde_json::Value = serde_json::from_str(&self.stdout).ok()?;+ Some(v.get("theorem")?.as_str()?.to_string())+ }+/// The one function in this crate that returns a [`Certified`].///- /// `Some` exactly when the checker exited zero. `theorem` is the Lean- /// statement that binary's acceptance discharges, and it travels inside- /// the token so that no report can name a theorem without an acceptance.- pub fn accepted(&self, theorem: &'static str) -> Option<Certified> {- (self.exit == 0).then_some(Certified { theorem })+ /// `Some` exactly when the checker exited zero AND its own stdout named one+ /// of `allowed` as the theorem it discharged. The returned token carries+ /// the name the CHECKER printed, not the caller's guess at it, so no report+ /// can name a theorem without an acceptance that named the same one.+ ///+ /// The list is a list because one checker legitimately proves one of two+ /// statements depending on its input: `lean/HMain.lean` earns the absolute+ /// `OOCert.entails_of_builtin_horn` when the rule table is exactly the+ /// built-ins and the relativised `OOCert.horn_certificate_sound` for any+ /// other table. Passing a single literal made the Rust side report the+ /// relativised name for both, so a caller could not tell an entailment from+ /// an entailment-under-supplied-rules by reading the field that exists to+ /// tell them.+ ///+ /// A checker that exits zero while naming a statement NOT on the list mints+ /// nothing. That is the case worth refusing: a renamed or weakened theorem+ /// would otherwise keep the label this call site was written against.+ pub fn accepted_naming(&self, allowed: &[&'static str]) -> Option<Certified> {+ if self.exit != 0 {+ return None;+ }+ let named = self.named_theorem()?;+ allowed+ .iter()+ .copied()+ .find(|t| *t == named.as_str())+ .map(|theorem| Certified { theorem })}}@@ -164,7 +196,8 @@ impl CheckerRun {/// theorem its acceptance discharges.////// The field is private to this module. A value of this type exists only-/// because [`CheckerRun::accepted`] read a zero exit code, so a variant that+/// because [`CheckerRun::accepted_naming`] read a zero exit code and a matching+/// theorem name, so a variant that/// carries one is unreachable on any path that did not run a checker.////// ```compile_fail@@ -452,16 +485,40 @@ mod tests {/// it, so the exec fails with ETXTBSY no matter how unique the filename is./// Both were observed in CI. `/bin/sh` and `cmd` are already there.fn shell_exiting(code: i32) -> (CheckerBinary, Command) {+ shell_saying(code, Some("OOCert.certificate_sound"))+ }++ /// A shell that prints a checker's JSON line and then exits.+ ///+ /// The fake used to exit in silence, which no real checker does, and which+ /// meant the mint could not be tested against the thing it now reads: the+ /// theorem the binary NAMED. `None` is the checker that prints nothing.+ fn shell_saying(code: i32, theorem: Option<&str>) -> (CheckerBinary, Command) {#[cfg(unix)]{+ let say = match theorem {+ Some(t) => format!("echo '{{\"ok\":true,\"theorem\":\"{t}\"}}'; "),+ None => String::new(),+ };let mut c = Command::new("/bin/sh");- c.arg("-c").arg(format!("exit {code}"));+ c.arg("-c").arg(format!("{say}exit {code}"));(CheckerBinary::found_at(PathBuf::from("/bin/sh")), c)}#[cfg(windows)]{+ // `arg` quotes for a C-runtime parser, turning every `"` into `\"`.+ // cmd.exe has no such parser: it echoed the backslashes and the+ // line was not JSON, so `named_theorem` saw nothing and all three+ // minting tests failed on windows-latest. `raw_arg` hands cmd the+ // line verbatim. The `&` follows the brace with no space so the+ // echoed line carries no trailing blank either.+ use std::os::windows::process::CommandExt;+ let say = match theorem {+ Some(t) => format!("echo {{\"ok\":true,\"theorem\":\"{t}\"}}& "),+ None => String::new(),+ };let mut c = Command::new("cmd");- c.arg("/C").arg(format!("exit {code}"));+ c.raw_arg(format!("/C {say}exit {code}"));(CheckerBinary::found_at(PathBuf::from("cmd")), c)}}@@ -472,19 +529,59 @@ mod tests {let (bin, c) = shell_exiting(1);let run = CheckerRun::spawn(&bin, c).expect("the system shell runs");assert_eq!(run.exit(), 1);- assert!(run.accepted("OOCert.certificate_sound").is_none());+ assert!(run.accepted_naming(&["OOCert.certificate_sound"]).is_none());}#[test]- fn a_zero_exit_mints_the_theorem_it_was_given() {+ fn a_zero_exit_mints_the_theorem_the_checker_named() {let (bin, c) = shell_exiting(0);let run = CheckerRun::spawn(&bin, c).expect("the system shell runs");- let cert = run.accepted("OOCert.certificate_sound").expect("exit 0");+ let cert = run.accepted_naming(&["OOCert.certificate_sound"]).expect("exit 0");assert_eq!(cert.theorem(), "OOCert.certificate_sound");assert_eq!(FolVerdict::ModelChecked(cert).word(), "model_checked");assert_eq!(FolVerdict::ModelChecked(cert).theorem(), Some("OOCert.certificate_sound"));}+ /// The case the old signature could not see. A checker that exits zero+ /// while discharging a DIFFERENT statement used to mint a token labelled+ /// with whatever the Rust call site had typed, which is the one thing the+ /// field is supposed to rule out.+ #[test]+ fn a_zero_exit_naming_another_theorem_mints_nothing() {+ let (bin, c) = shell_saying(0, Some("OOCert.something_weaker"));+ let run = CheckerRun::spawn(&bin, c).expect("the system shell runs");+ assert_eq!(run.exit(), 0);+ assert_eq!(run.named_theorem().as_deref(), Some("OOCert.something_weaker"));+ assert!(run.accepted_naming(&["OOCert.certificate_sound"]).is_none());+ }++ /// And a checker that names nothing at all mints nothing, rather than+ /// having a name supplied for it.+ #[test]+ fn a_zero_exit_naming_no_theorem_mints_nothing() {+ let (bin, c) = shell_saying(0, None);+ let run = CheckerRun::spawn(&bin, c).expect("the system shell runs");+ assert_eq!(run.exit(), 0);+ assert_eq!(run.named_theorem(), None);+ assert!(run.accepted_naming(&["OOCert.certificate_sound"]).is_none());+ }++ /// Two statements, and the token carries the one that was printed.+ #[test]+ fn a_checker_with_two_theorems_reports_the_one_it_proved() {+ let allowed = ["OOCert.horn_certificate_sound", "OOCert.entails_of_builtin_horn"];+ for named in allowed {+ let (bin, c) = shell_saying(0, Some(named));+ let run = CheckerRun::spawn(&bin, c).expect("the system shell runs");+ let cert = run.accepted_naming(&allowed).expect("exit 0 naming an allowed theorem");+ assert_eq!(+ cert.theorem(),+ named,+ "the token must carry what the checker printed, not the first entry in the list"+ );+ }+ }+/// A checker that could not be started is an error, not a run, so it can/// never be asked whether it accepted anything.#[test]diff --git a/tests/fol_solver_verdict_test.rs b/tests/fol_solver_verdict_test.rsindex 3348849e..7a896360 100644--- a/tests/fol_solver_verdict_test.rs+++ b/tests/fol_solver_verdict_test.rs@@ -259,17 +259,35 @@ fn an_unchecked_result_never_reports_the_certified_word() {assert_eq!(r3.checker_exit, None);assert!(r3.skipped.is_some(), "a missing checker must be reported: {r3:?}");- // And a checker that ACCEPTS does reach it, so the branch is live and the- // three results above are about the exit code rather than about the stub.- let accepting = stub(+ // (d) A checker that exits zero but names NO theorem. Exit zero used to be+ // the whole test; the theorem is now read off the checker's own report, so+ // a report that does not carry one is not an acceptance, whatever the exit+ // code said.+ let unnamed = stub(&d,- "accept.sh",+ "accept_unnamed.sh","#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"goal_negated_present\":false}'\nexit 0\n",);let mut o4 = opts(4);- o4.checker = Some(accepting);+ o4.checker = Some(unnamed);let r4 = solve(&easy(), &o4, &d.join("d")).expect("runs");- assert_eq!(r4.verdict, "model_checked");+ assert_ne!(r4.verdict, "model_checked", "{r4:?}");+ assert_eq!(r4.checker_exit, Some(0));+ assert!(r4.theorem.is_none(), "{r4:?}");++ // And a checker that ACCEPTS, naming the theorem the way lean/FolMain.lean+ // prints it, does reach it, so the branch is live and the results above are+ // about the report rather than about the stub.+ let accepting = stub(+ &d,+ "accept.sh",+ "#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"theorem\":\"Fol.satisfiable_of_check\",\"goal_negated_present\":false}'\nexit 0\n",+ );+ let mut o5 = opts(4);+ o5.checker = Some(accepting);+ let r5 = solve(&easy(), &o5, &d.join("e")).expect("runs");+ assert_eq!(r5.verdict, "model_checked", "{r5:?}");+ assert_eq!(r5.theorem.as_deref(), Some("Fol.satisfiable_of_check"));}// ── Rule 2: a bounded unsat is not unsatisfiability ─────────────────────────@@ -395,7 +413,7 @@ fn the_owl_reading_is_read_off_the_checkers_own_report() {let silent = stub(&d,"accept_no_goal.sh",- "#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"goal_negated_present\":false}'\nexit 0\n",+ "#!/bin/sh\necho '{\"verdict\":\"model_checked\",\"theorem\":\"Fol.satisfiable_of_check\",\"goal_negated_present\":false}'\nexit 0\n",);let mut o2 = opts(3);o2.checker = Some(silent);diff --git a/tests/verdict_vocabulary_test.rs b/tests/verdict_vocabulary_test.rsindex c5d21910..160ae282 100644--- a/tests/verdict_vocabulary_test.rs+++ b/tests/verdict_vocabulary_test.rs@@ -49,52 +49,39 @@ use open_ontologies::verdict::{/// its name is. CI failed that way twice. Writing before the parallel phase/// begins means there is no open write fd left to inherit.fn script_exiting(code: i32) -> PathBuf {- static SCRIPTS: std::sync::OnceLock<std::collections::HashMap<i32, PathBuf>> =- std::sync::OnceLock::new();- SCRIPTS- .get_or_init(|| {- let dir = std::env::temp_dir().join("oo-verdict-vocabulary-scripts");- std::fs::create_dir_all(&dir).unwrap();- let ext = if cfg!(windows) { "cmd" } else { "sh" };- (0..=3)- .map(|c| {- let p = dir.join(format!("exit{c}.{ext}"));- let body = if cfg!(windows) {- format!("@echo off\r\nexit /b {c}\r\n")- } else {- format!("#!/bin/sh\nexit {c}\n")- };- std::fs::write(&p, body).unwrap();- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt as _;- std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755))- .unwrap();- }- (c, p)- })- .collect()- })- .get(&code)- .expect("only exit codes 0 to 3 are used")- .clone()+ script_saying(code, "OOCert.certificate_sound")}-fn shell_exiting(code: i32) -> (CheckerBinary, std::process::Command) {+/// A fake checker that prints the theorem it is told to and then exits.+///+/// Keyed by BOTH, because which theorem a checker names is now part of what+/// the mint reads: `oo-horn` legitimately names one of two depending on its+/// rule table, and a checker naming a third mints nothing.+fn script_saying(code: i32, theorem: &str) -> PathBuf {+ let dir = std::env::temp_dir().join("oo-verdict-vocabulary-scripts");+ std::fs::create_dir_all(&dir).unwrap();+ let ext = if cfg!(windows) { "cmd" } else { "sh" };+ let slug: String = theorem.chars().filter(|c| c.is_alphanumeric()).collect();+ let p = dir.join(format!("exit{code}_{slug}.{ext}"));+ // The fake PRINTS its theorem, because a real checker does and the mint now+ // reads it. A script that exits zero in silence named nothing and correctly+ // mints nothing; accepting with one would be testing the old contract.+ let say = format!(r#"{{"ok":true,"theorem":"{theorem}"}}"#);+ let body = if cfg!(windows) {+ format!("@echo off\r\necho {say}\r\nexit /b {code}\r\n")+ } else {+ format!("#!/bin/sh\necho '{say}'\nexit {code}\n")+ };+ std::fs::write(&p, body).unwrap();#[cfg(unix)]{- let mut c = std::process::Command::new("/bin/sh");- c.arg("-c").arg(format!("exit {code}"));- (CheckerBinary::found_at(PathBuf::from("/bin/sh")), c)- }- #[cfg(windows)]- {- let mut c = std::process::Command::new("cmd");- c.arg("/C").arg(format!("exit {code}"));- (CheckerBinary::found_at(PathBuf::from("cmd")), c)+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();}+ p}+/// A `Certified`, obtained the only way anything can obtain one: by running/// something that exits zero.///@@ -103,10 +90,34 @@ fn shell_exiting(code: i32) -> (CheckerBinary, std::process::Command) {/// ran and exited zero, and that is exactly what this borrows in order to name/// the certified variants below.fn earned(theorem: &'static str) -> Certified {- let (bin, cmd) = shell_exiting(0);+ // The fake has to PRINT the theorem, because that is now what the mint+ // reads. A shell that exits zero in silence is a checker that named+ // nothing, and it correctly mints nothing.+ let (bin, cmd) = shell_naming(theorem);let run = CheckerRun::spawn(&bin, cmd).expect("the system shell must be runnable");assert_eq!(run.exit(), 0);- run.accepted(theorem).expect("exit 0 mints the token")+ run.accepted_naming(&[theorem]).expect("exit 0 naming it mints the token")+}++fn shell_naming(theorem: &str) -> (CheckerBinary, std::process::Command) {+ #[cfg(unix)]+ {+ let mut c = std::process::Command::new("/bin/sh");+ c.arg("-c")+ .arg(format!("echo '{{\"ok\":true,\"theorem\":\"{theorem}\"}}'"));+ (CheckerBinary::found_at(PathBuf::from("/bin/sh")), c)+ }+ #[cfg(windows)]+ {+ // `raw_arg`, not `arg`: `arg` escapes the quotes for a C-runtime+ // parser and cmd.exe has none, so it echoed the backslashes and the+ // line was not JSON. Same defect, same fix as `shell_saying` in+ // `src/verdict.rs`.+ use std::os::windows::process::CommandExt;+ let mut c = std::process::Command::new("cmd");+ c.raw_arg(format!("/C echo {{\"ok\":true,\"theorem\":\"{theorem}\"}}"));+ (CheckerBinary::found_at(PathBuf::from("cmd")), c)+ }}/// Every word this crate may print as a verdict, with the exact bytes it must@@ -329,12 +340,33 @@ fn only_a_zero_exit_produces_an_acceptance() {// And the acceptance carries the theorem the KIND names, not one the// caller chose afterwards.- let script = script_exiting(0);- match pe::run_checker(CertKind::OoHorn, Some(script.as_path()), &a, &d, Some(a.as_path())) {- CheckerStatus::Accepted(acc) => {- assert_eq!(acc.theorem(), "OOCert.horn_certificate_sound");- assert_eq!(acc.certified().theorem(), "OOCert.horn_certificate_sound");+ // `oo-horn` names ONE OF TWO, and the token carries whichever it named.+ // `lean/HMain.lean` prints the absolute `OOCert.entails_of_builtin_horn`+ // when the rule table is exactly the built-ins and the relativised+ // `OOCert.horn_certificate_sound` for any other table. The Rust side used+ // to hardcode the relativised name for both, so the field that exists to+ // tell an entailment from an entailment-under-supplied-rules told neither.+ for named in ["OOCert.horn_certificate_sound", "OOCert.entails_of_builtin_horn"] {+ let script = script_saying(0, named);+ match pe::run_checker(CertKind::OoHorn, Some(script.as_path()), &a, &d, Some(a.as_path())) {+ CheckerStatus::Accepted(acc) => {+ assert_eq!(acc.theorem(), named, "the token must carry what oo-horn printed");+ assert_eq!(acc.certified().theorem(), named);+ }+ other => panic!("exit 0 naming {named} must be an acceptance: {other:?}"),}- other => panic!("exit 0 must be an acceptance: {other:?}"),}++ // And a checker that exits zero while naming a statement this call site+ // was not written against mints nothing. That is the case the old+ // signature could not see: it would have minted a token labelled with+ // whatever the Rust literal said.+ let wrong = script_saying(0, "OOCert.something_else_entirely");+ assert!(+ !matches!(+ pe::run_checker(CertKind::OoHorn, Some(wrong.as_path()), &a, &d, Some(a.as_path())),+ CheckerStatus::Accepted(_)+ ),+ "a checker naming an unexpected theorem must not mint an acceptance"+ );}