Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

shacl, enforce, unpack and monitor exit non-zero on a failing verdict (#329)

Fabio Rovai3e1817f88827
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f79dd71..66ffad98 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,13 @@ All notable changes to Open Ontologies are documented here.
### Fixed
+- **`shacl`, `enforce`, `unpack` and `monitor` exit non-zero on a failing
+ verdict** (#323, reported by @noahgift). They printed `conforms: false`, an
+ error-severity violation, `certificate_refused` or a blocking watcher and
+ exited 0, so `open-ontologies shacl shapes.ttl || exit 1` passed on the data
+ it exists to catch. Codes are 0 pass, 1 fail, 2 not determined (`conforms:
+ null`, or no checker re-ran the certificate), and each command's `--help`
+ lists them. `plan` and `drift` now exit 1 on an error, as `lint` does.
- Preserve carriage returns and CRLF text when importing dataframe rows into the Python engine.
- Report non-object JSON from a configured Python certificate checker as unchecked instead of raising an attribute error.
- Preserve RDF literal datatypes when comparing Python KGCL graph changes, while retaining lexical label and annotation values.
diff --git a/src/main.rs b/src/main.rs
index a99da0d0..0f166502 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -456,6 +456,9 @@ enum Commands {
base_iri: Option<String>,
},
/// Validate against SHACL shapes
+ ///
+ /// Exit code: 0 conforms, 1 does not conform or failed, 2 not determined
+ /// (`conforms: null`).
Shacl {
shapes: String,
/// Validate the snapshot that was TRUE at this instant (#108). Read as
@@ -844,6 +847,8 @@ enum Commands {
/// Detect drift between two ontology versions
Drift { file_a: String, file_b: String },
/// Run design pattern enforcement
+ ///
+ /// Exit code: 0 no error-severity violation, 1 at least one, or failed.
Enforce {
#[arg(default_value = "generic")]
pack: String,
@@ -856,6 +861,9 @@ enum Commands {
/// the load; or this build has no checker, so nothing was checked. The last
/// one is not a pass.
///
+ /// Exit code: 0 accepted or no certificate, 1 refused, unreadable, not
+ /// about this pack, or failed, 2 nothing was checked.
+ ///
/// `pack` stays MCP-only and this does not, on purpose. The receiver is the
/// party this exists for, and requiring them to run an MCP client to audit
/// a pack would defeat it.
@@ -879,6 +887,8 @@ enum Commands {
load_even_if_refused: bool,
},
/// Run active SPARQL watchers
+ ///
+ /// Exit code: 1 when a watcher blocked the next apply or rolled back, else 0.
Monitor,
/// Clear monitor block state
MonitorClear,
@@ -1603,6 +1613,73 @@ fn output_result_with_exit(result: &str, pretty: bool) {
}
}
+/// The commands whose output is a verdict, not just a result.
+#[derive(Clone, Copy)]
+enum Gate {
+ Shacl,
+ Enforce,
+ Unpack,
+ Monitor,
+}
+
+/// Map a gate command's own verdict to an exit code: 0 pass, 1 fail, 2 not
+/// determined.
+///
+/// `output_result_checked` sees only an `error` field, and the failures that
+/// matter here are not errors. `conforms: false` and `certificate_refused` are
+/// verdicts, so `shacl shapes.ttl || exit 1` and `unpack x.oopack || exit 1`
+/// passed on exactly the inputs they exist to catch (#323). An undetermined
+/// verdict (`conforms: null`, no checker to re-run the proof) is not a pass
+/// and not a failure, so it gets its own code rather than being folded into
+/// either.
+fn gate_exit_code(gate: Gate, result: &str) -> i32 {
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(result) else {
+ return 1;
+ };
+ if v.get("error").is_some() {
+ return 1;
+ }
+ match gate {
+ Gate::Shacl => match v.get("conforms") {
+ Some(serde_json::Value::Bool(true)) => 0,
+ Some(serde_json::Value::Bool(false)) => 1,
+ _ => 2,
+ },
+ Gate::Enforce => {
+ let errors = v
+ .get("violations")
+ .and_then(|x| x.as_array())
+ .is_some_and(|vs| vs.iter().any(|x| x["severity"] == "error"));
+ i32::from(errors)
+ }
+ Gate::Unpack => {
+ let verdict = v.pointer("/certificate/verdict").and_then(|x| x.as_str());
+ match verdict {
+ Some(
+ "certificate_refused"
+ | "certificate_unreadable"
+ | "certificate_not_about_this_pack",
+ ) => 1,
+ Some("checker_absent_nothing_was_checked") => 2,
+ _ if v.get("ok") == Some(&serde_json::Value::Bool(false)) => 1,
+ _ => 0,
+ }
+ }
+ Gate::Monitor => match v.get("status").and_then(|x| x.as_str()) {
+ Some("blocked" | "auto_rolled_back") => 1,
+ _ => 0,
+ },
+ }
+}
+
+fn output_result_gated(result: &str, pretty: bool, gate: Gate) {
+ let code = gate_exit_code(gate, result);
+ output_result(result, pretty);
+ if code != 0 {
+ std::process::exit(code);
+ }
+}
+
fn output_result(result: &str, pretty: bool) {
if json_mode() || pretty {
if pretty {
@@ -3117,7 +3194,7 @@ async fn async_main() -> anyhow::Result<()> {
open_ontologies::shacl_verified::validate_verified(&graph, &shapes_content)
.unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}))
};
- output_result(&result.to_string(), cli.pretty);
+ output_result_gated(&result.to_string(), cli.pretty, Gate::Shacl);
return Ok(());
}
let result = match open_ontologies::temporal::ScopeRequest::from_args(
@@ -3129,7 +3206,7 @@ async fn async_main() -> anyhow::Result<()> {
.unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),
Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),
};
- output_result(&result, cli.pretty);
+ output_result_gated(&result, cli.pretty, Gate::Shacl);
}
Commands::VocabCheck { data } => {
let (_db, graph) = setup(&cli.data_dir)?;
@@ -3438,7 +3515,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = planner
.plan_checked(&turtle, opts)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Apply { mode, plan_id } => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -3472,7 +3549,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = detector
.detect(&v1, &v2)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Enforce { pack } => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -3480,7 +3557,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = enforcer
.enforce_with_feedback(&pack, Some(&db))
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_gated(&result, cli.pretty, Gate::Enforce);
}
Commands::Unpack {
path,
@@ -3501,7 +3578,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = open_ontologies::pack::Packer::new(graph)
.unpack(&path, &opts)
.unwrap_or_else(|e| format!(r#"{{"error":"{e}"}}"#));
- output_result(&result, cli.pretty);
+ output_result_gated(&result, cli.pretty, Gate::Unpack);
}
Commands::Monitor => {
let (db, graph) = setup(&cli.data_dir)?;
@@ -3509,7 +3586,7 @@ async fn async_main() -> anyhow::Result<()> {
let result = monitor.run_watchers();
let json = serde_json::to_string(&result)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&json, cli.pretty);
+ output_result_gated(&json, cli.pretty, Gate::Monitor);
}
Commands::MonitorClear => {
let (db, graph) = setup(&cli.data_dir)?;
diff --git a/tests/cli_gate_exit_codes_test.rs b/tests/cli_gate_exit_codes_test.rs
new file mode 100644
index 00000000..841fa733
--- /dev/null
+++ b/tests/cli_gate_exit_codes_test.rs
@@ -0,0 +1,236 @@
+//! A gate command must tell the shell what its verdict was (#323).
+//!
+//! `cli_exit_codes_test.rs` covers commands whose failure is an `error` field.
+//! The commands here fail with a VERDICT instead: `shacl` with
+//! `conforms: false`, `unpack` with `certificate_refused`, `enforce` with an
+//! error-severity violation, `monitor` with a blocking watcher. All of them
+//! exited 0, so `open-ontologies shacl shapes.ttl || exit 1` passed on exactly
+//! the data it exists to catch. The codes are 0 pass, 1 fail, 2 not determined.
+
+mod common;
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::pack::{PackRequest, Packer};
+use open_ontologies::reason::{InferenceTarget, Reasoner};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::Arc;
+
+/// Every invocation shares one persistent store under `dir`, so a `load` in
+/// one process is what the next process validates. `--no-connect` keeps a
+/// developer's running daemon out of it.
+fn run(dir: &Path, args: &[&str]) -> (i32, String) {
+ let out = {
+ let _gate = common::exec_gate();
+ Command::new(env!("CARGO_BIN_EXE_open-ontologies"))
+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")
+ .arg("--data-dir")
+ .arg(dir.join("data"))
+ .arg("--no-connect")
+ .args(args)
+ .output()
+ .expect("binary should run")
+ };
+ let text = format!(
+ "{}{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ (out.status.code().unwrap_or(-1), text)
+}
+
+fn store_dir() -> tempfile::TempDir {
+ let d = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(d.path().join("data")).unwrap();
+ std::fs::write(
+ d.path().join("data").join("config.toml"),
+ "[storage]\nmode = 'persistent'\n",
+ )
+ .unwrap();
+ d
+}
+
+fn write(dir: &Path, name: &str, body: &str) -> String {
+ let p = dir.join(name);
+ std::fs::write(&p, body).unwrap();
+ p.to_str().unwrap().to_string()
+}
+
+const DATA: &str = r#"
+@prefix ex: <http://ex.org/> .
+ex:alice a ex:Person ; ex:name "Alice" .
+ex:bob a ex:Person .
+"#;
+
+const NAME_REQUIRED: &str = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix ex: <http://ex.org/> .
+ex:PersonShape a sh:NodeShape ;
+ sh:targetClass ex:Person ;
+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .
+"#;
+
+/// Targets only people with a name, so every focus node conforms.
+const NAME_REQUIRED_OF_ALICE: &str = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix ex: <http://ex.org/> .
+ex:AliceShape a sh:NodeShape ;
+ sh:targetNode ex:alice ;
+ sh:property [ sh:path ex:name ; sh:minCount 1 ] .
+"#;
+
+/// A length bound that is not an integer is skipped by name, so the engine
+/// cannot say the data conforms and reports `conforms: null`.
+const UNEVALUABLE: &str = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix ex: <http://ex.org/> .
+ex:PersonShape a sh:NodeShape ;
+ sh:targetClass ex:Person ;
+ sh:property [ sh:path ex:name ; sh:minLength "three" ] .
+"#;
+
+fn loaded_store() -> tempfile::TempDir {
+ let d = store_dir();
+ let data = write(d.path(), "data.ttl", DATA);
+ let (code, out) = run(d.path(), &["load", &data]);
+ assert_eq!(code, 0, "load failed: {out}");
+ d
+}
+
+#[test]
+fn shacl_exits_1_when_the_data_does_not_conform() {
+ let d = loaded_store();
+ let shapes = write(d.path(), "s.ttl", NAME_REQUIRED);
+ let (code, out) = run(d.path(), &["shacl", &shapes]);
+ assert!(out.contains("\"conforms\":false"), "precondition: {out}");
+ assert_eq!(code, 1, "non-conforming data must fail the process: {out}");
+}
+
+#[test]
+fn shacl_exits_0_when_the_data_conforms() {
+ let d = loaded_store();
+ let shapes = write(d.path(), "s.ttl", NAME_REQUIRED_OF_ALICE);
+ let (code, out) = run(d.path(), &["shacl", &shapes]);
+ assert!(out.contains("\"conforms\":true"), "precondition: {out}");
+ assert_eq!(code, 0, "{out}");
+}
+
+#[test]
+fn shacl_exits_2_when_conformance_was_not_determined() {
+ let d = loaded_store();
+ let shapes = write(d.path(), "s.ttl", UNEVALUABLE);
+ let (code, out) = run(d.path(), &["shacl", &shapes]);
+ assert!(out.contains("\"conforms\":null"), "precondition: {out}");
+ assert_eq!(code, 2, "an undetermined verdict is neither pass nor fail: {out}");
+}
+
+#[test]
+fn shacl_verified_exits_1_when_the_data_does_not_conform() {
+ let d = loaded_store();
+ let shapes = write(d.path(), "s.ttl", NAME_REQUIRED);
+ let (code, out) = run(d.path(), &["shacl", &shapes, "--verified"]);
+ // Without a Lean checker the verified path answers null, which is 2; with
+ // one it answers false, which is 1. Either way it is not a pass.
+ assert_ne!(code, 0, "{out}");
+ if out.contains("\"conforms\":false") {
+ assert_eq!(code, 1, "{out}");
+ }
+}
+
+/// `ies4_particular_class_overlap` is an error-severity rule.
+const IES4_CLASH: &str = r#"
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ies: <http://ies.data.gov.uk/ontology/ies4#> .
+@prefix ex: <http://ex.org/> .
+ex:Thing rdfs:subClassOf ies:Particular , ies:ClassOfEntity .
+"#;
+
+#[test]
+fn enforce_exits_1_on_an_error_severity_violation_and_0_without_one() {
+ let d = store_dir();
+ let f = write(d.path(), "ies.ttl", IES4_CLASH);
+ let (code, out) = run(d.path(), &["load", &f]);
+ assert_eq!(code, 0, "load failed: {out}");
+ let (code, out) = run(d.path(), &["enforce", "ies4"]);
+ assert!(out.contains("ies4_particular_class_overlap"), "precondition: {out}");
+ assert_eq!(code, 1, "an error-severity violation must fail the process: {out}");
+
+ let clean = store_dir();
+ let (code, out) = run(clean.path(), &["enforce", "ies4"]);
+ assert_eq!(code, 0, "an empty store has no violations: {out}");
+}
+
+#[test]
+fn monitor_exits_0_with_no_blocking_watcher() {
+ let d = store_dir();
+ let (code, out) = run(d.path(), &["monitor"]);
+ assert!(out.contains("\"status\":\"ok\""), "precondition: {out}");
+ assert_eq!(code, 0, "{out}");
+}
+
+fn fake_checker(dir: &Path, code: i32) -> PathBuf {
+ let ext = if cfg!(windows) { "cmd" } else { "sh" };
+ let p = dir.join(format!("exit{code}.{ext}"));
+ let say = r#"{"ok":true,"theorem":"OOCert.certificate_sound","checker":{"name":"fake","sha256":"0"}}"#;
+ 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")
+ };
+ let _gate = common::exec_gate();
+ 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();
+ }
+ p
+}
+
+fn certified_pack(dir: &Path) -> String {
+ let cert_dir = dir.join("cert");
+ std::fs::create_dir_all(&cert_dir).unwrap();
+ let store = Arc::new(GraphStore::new());
+ store
+ .load_turtle(
+ "@prefix : <http://ex.org/> . \
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \
+ :A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .",
+ None,
+ )
+ .unwrap();
+ Reasoner::run_full(&store, "owl-rl-ext", true, InferenceTarget::DefaultGraph, Some(&cert_dir))
+ .unwrap();
+ let path = dir.join("carried.oopack");
+ Packer::new(store)
+ .pack(&PackRequest {
+ path: path.to_str().unwrap(),
+ name: "carried",
+ version: "1.0.0",
+ evidence: None,
+ certificate_dir: Some(&cert_dir),
+ profile_claimed: Some("owl-rl-ext"),
+ })
+ .expect("pack with a certificate");
+ path.to_str().unwrap().to_string()
+}
+
+#[test]
+fn unpack_exit_code_follows_the_certificate_verdict() {
+ let d = store_dir();
+ let pack = certified_pack(d.path());
+ let accept = fake_checker(d.path(), 0);
+ let refuse = fake_checker(d.path(), 1);
+
+ let (code, out) = run(d.path(), &["unpack", &pack, "--checker", accept.to_str().unwrap()]);
+ assert!(out.contains("certificate_accepted"), "precondition: {out}");
+ assert_eq!(code, 0, "{out}");
+
+ let (code, out) = run(d.path(), &["unpack", &pack, "--checker", refuse.to_str().unwrap()]);
+ assert!(out.contains("certificate_refused"), "precondition: {out}");
+ assert_eq!(code, 1, "a refused certificate must fail the process: {out}");
+
+ let (code, out) = run(d.path(), &["unpack", &pack, "--no-check"]);
+ assert!(out.contains("checker_absent_nothing_was_checked"), "precondition: {out}");
+ assert_eq!(code, 2, "nothing was checked, which is not a pass: {out}");
+}