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.

fix(cli): fail the process when a command fails; add sh:in and sh:nodeKind

FABIOTESS494f64540a81
diff --git a/src/main.rs b/src/main.rs
index 1ec9d464..0e2582da 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -853,6 +853,25 @@ fn output_json(value: &serde_json::Value, pretty: bool) {
/// Print a JSON string result, with optional pretty-printing.
/// Handles the common pattern of domain functions returning String results.
+/// Print a tool result and fail the process if the payload carries an `error`.
+///
+/// `output_result` prints whatever it is handed and returns, so a command whose
+/// work failed still exited 0 while printing `{"error": ...}`. That is fine for a
+/// human reading the line and useless for a gate: `open-ontologies lint x.ttl ||
+/// exit 1` passed on exactly the input it exists to catch, because the shell was
+/// told success while the JSON said otherwise. Commands that can fail this way
+/// use this instead.
+fn output_result_checked(result: &str, pretty: bool) {
+ let failed = serde_json::from_str::<serde_json::Value>(result)
+ .ok()
+ .and_then(|v| v.get("error").cloned())
+ .is_some();
+ output_result(result, pretty);
+ if failed {
+ std::process::exit(1);
+ }
+}
+
fn output_result(result: &str, pretty: bool) {
if json_mode() || pretty {
if pretty {
@@ -1875,7 +1894,7 @@ async fn async_main() -> anyhow::Result<()> {
let new = std::fs::read_to_string(&new_path)?;
let result = OntologyService::diff(&old, &new)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Lint { input } => {
use open_ontologies::ontology::OntologyService;
@@ -1890,11 +1909,22 @@ async fn async_main() -> anyhow::Result<()> {
// lint reasons over Turtle. Sniff the serialisation first, exactly as
// validate does, so an RDF/XML document is converted rather than
// handed to a Turtle parser that can only fail on it.
- let content = GraphStore::content_as_turtle(&input, raw)
- .unwrap_or_else(|e| format!("# could not read as RDF: {e}\n"));
+ // A parse failure must not become a Turtle comment. It used to:
+ // the fallback string is a valid Turtle document containing zero
+ // triples, so lint parsed it happily, found nothing to complain
+ // about, and reported `issue_count: 0` with exit 0 over a file it
+ // had never read. A clean bill of health for an unreadable document
+ // is the one answer this command must never give.
+ let content = match GraphStore::content_as_turtle(&input, raw) {
+ Ok(c) => c,
+ Err(e) => {
+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
+ std::process::exit(1);
+ }
+ };
let result = OntologyService::lint_with_feedback(&content, Some(&db))
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Convert { path, to, output } => {
let store = GraphStore::new();
@@ -2215,14 +2245,14 @@ async fn async_main() -> anyhow::Result<()> {
let data_content = std::fs::read_to_string(&data)?;
let result = open_ontologies::vocab_check::check_data_vocab(&graph, &data_content, &[])
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Reason { profile } => {
use open_ontologies::reason::Reasoner;
let (_db, graph) = setup(&cli.data_dir)?;
let result = Reasoner::run(&graph, &profile, true)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
- output_result(&result, cli.pretty);
+ output_result_checked(&result, cli.pretty);
}
Commands::Extend {
data_path,
diff --git a/src/shacl.rs b/src/shacl.rs
index 6c2f9b2c..a7797153 100644
--- a/src/shacl.rs
+++ b/src/shacl.rs
@@ -237,7 +237,7 @@ impl ShaclValidator {
&format!(
r#"
PREFIX sh: <http://www.w3.org/ns/shacl#>
- SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?minInclusive ?maxInclusive ?minExclusive ?maxExclusive ?message ?severity WHERE {{
+ SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?nodeKind ?minInclusive ?maxInclusive ?minExclusive ?maxExclusive ?message ?severity WHERE {{
{} sh:property ?prop .
?prop sh:path ?path .
OPTIONAL {{ ?path sh:inversePath ?invPath }}
@@ -247,6 +247,7 @@ impl ShaclValidator {
OPTIONAL {{ ?prop sh:datatype ?datatype }}
OPTIONAL {{ ?prop sh:pattern ?pattern }}
OPTIONAL {{ ?prop sh:hasValue ?hasValue }}
+ OPTIONAL {{ ?prop sh:nodeKind ?nodeKind }}
OPTIONAL {{ ?prop sh:minInclusive ?minInclusive }}
OPTIONAL {{ ?prop sh:maxInclusive ?maxInclusive }}
OPTIONAL {{ ?prop sh:minExclusive ?minExclusive }}
@@ -277,7 +278,7 @@ impl ShaclValidator {
sh:class, sh:pattern, sh:hasValue, sh:message, sh:severity,
sh:minInclusive, sh:maxInclusive,
sh:minExclusive, sh:maxExclusive,
- sh:or,
+ sh:or, sh:in, sh:nodeKind,
sh:name, sh:description, sh:order, sh:group,
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
))
@@ -363,6 +364,33 @@ impl ShaclValidator {
}));
}
+ // sh:in alternatives, collected per shape and keyed by path for the
+ // same blank-node reason as sh:or above.
+ let mut in_alternatives: HashMap<String, Vec<String>> = HashMap::new();
+ let in_rows = query_solutions(
+ &shapes_store,
+ &format!(
+ r#"
+ PREFIX sh: <http://www.w3.org/ns/shacl#>
+ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
+ SELECT ?path ?member WHERE {{
+ {} sh:property ?prop .
+ ?prop sh:path ?path .
+ ?prop sh:in/rdf:rest*/rdf:first ?member .
+ }}
+ "#,
+ shape_iri
+ ),
+ )?;
+ for row in &in_rows {
+ if let (Some(p), Some(m)) = (row.get("path"), row.get("member")) {
+ in_alternatives
+ .entry(strip_angle_brackets(p))
+ .or_default()
+ .push(m.trim().to_string());
+ }
+ }
+
// 4. For each constraint, run SPARQL queries against the main graph
for prop in &props {
let raw_path = match prop.get("path") {
@@ -613,6 +641,90 @@ impl ShaclValidator {
}
}
+ // sh:in: the value must be one of an enumerated list of terms.
+ // Members arrive from the shapes store in N-Triples form, which is
+ // valid SPARQL as written, so no term needs rebuilding.
+ if let Some(members) = in_alternatives.get(&path) {
+ let list = members.join(", ");
+ let query = format!(
+ r#"SELECT ?focus ?val WHERE {{
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
+ ?focus {path_expr} ?val .
+ FILTER(?val NOT IN ({list}))
+ }}"#
+ );
+ let results = graph_sparql_select(graph, &query)?;
+ for row in &results {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ "Value is not one of the permitted sh:in terms".to_string()
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "in",
+ "message": msg,
+ }));
+ }
+ }
+ }
+
+ // sh:nodeKind. A node kind this implementation does not recognise
+ // reaches skipped rather than passing: an unrecognised kind is not
+ // a satisfied one.
+ if let Some(nk_raw) = prop.get("nodeKind") {
+ let nk = strip_angle_brackets(nk_raw);
+ let kind = nk.rsplit('#').next().unwrap_or_default();
+ let test = match kind {
+ "IRI" => Some("isIRI(?val)".to_string()),
+ "Literal" => Some("isLiteral(?val)".to_string()),
+ "BlankNode" => Some("isBlank(?val)".to_string()),
+ "BlankNodeOrIRI" => Some("(isBlank(?val) || isIRI(?val))".to_string()),
+ "IRIOrLiteral" => Some("(isIRI(?val) || isLiteral(?val))".to_string()),
+ "BlankNodeOrLiteral" => {
+ Some("(isBlank(?val) || isLiteral(?val))".to_string())
+ }
+ _ => None,
+ };
+ match test {
+ Some(t) => {
+ let query = format!(
+ r#"SELECT ?focus ?val WHERE {{
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
+ ?focus {path_expr} ?val .
+ FILTER(!{t})
+ }}"#
+ );
+ let results = graph_sparql_select(graph, &query)?;
+ for row in &results {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ format!("Value is not of node kind {}", kind)
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "nodeKind",
+ "message": msg,
+ }));
+ }
+ }
+ }
+ None => skipped.push(serde_json::json!({
+ "shape": strip_angle_brackets(&shape_iri),
+ "constraint": "sh:nodeKind",
+ "path": path,
+ "reason": "node kind not recognised; it was not evaluated",
+ })),
+ }
+ }
+
// sh:hasValue: every focus node must carry the exact term at
// least once on the path. The term arrives from the shapes
// store in N-Triples form (`<iri>` or `"lit"^^<dt>`), which is
diff --git a/tests/cli_exit_codes_test.rs b/tests/cli_exit_codes_test.rs
new file mode 100644
index 00000000..61fbca0b
--- /dev/null
+++ b/tests/cli_exit_codes_test.rs
@@ -0,0 +1,77 @@
+//! A command that failed must tell the shell it failed.
+//!
+//! `lint`, `vocab-check` and `diff` printed `{"error": ...}` and exited 0, so
+//! `open-ontologies lint x.ttl || exit 1` passed on exactly the input it exists
+//! to catch: a malformed ontology, a truncated download, a soft-404 body.
+//!
+//! `lint` was worse than the others. It swallowed a serialisation failure into
+//! the string `# could not read as RDF: ...`, which is a valid Turtle document
+//! containing zero triples, so lint parsed that happily and reported
+//! `issue_count: 0` with exit 0 over a file it had never read. A clean bill of
+//! health for an unreadable document is the one answer this command must not give.
+
+use std::process::Command;
+
+fn run(args: &[&str]) -> (i32, String) {
+ let out = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))
+ .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 write(dir: &std::path::Path, name: &str, body: &str) -> String {
+ let p = dir.join(name);
+ std::fs::write(&p, body).unwrap();
+ p.to_str().unwrap().to_string()
+}
+
+const GARBAGE: &str = "this is not turtle at all <<<>>> @@@\n";
+const BROKEN_XML: &str = "<?xml version=\"1.0\"?><rdf:RDF this is broken <<<\n";
+const GOOD: &str = "@prefix : <http://ex.org/> .\n@prefix owl: <http://www.w3.org/2002/07/owl#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n:C a owl:Class ; rdfs:label \"C\" ; rdfs:comment \"a class\" .\n";
+
+#[test]
+fn lint_fails_the_process_on_unparseable_turtle() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "g.ttl", GARBAGE);
+ let (code, out) = run(&["lint", &f]);
+ assert_eq!(code, 1, "lint must exit non-zero. output: {out}");
+ assert!(out.contains("error"), "output: {out}");
+}
+
+/// The silent-clean-pass case. This one reported no error at all.
+#[test]
+fn lint_does_not_report_a_clean_bill_of_health_for_unreadable_rdfxml() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "broken.rdf", BROKEN_XML);
+ let (code, out) = run(&["lint", &f]);
+ assert_eq!(code, 1, "lint must exit non-zero. output: {out}");
+ assert!(
+ !out.contains("\"issue_count\":0"),
+ "lint reported a clean result for a file it could not read: {out}"
+ );
+ assert!(out.contains("error"), "output: {out}");
+}
+
+#[test]
+fn diff_fails_the_process_on_unparseable_input() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "g.ttl", GARBAGE);
+ let (code, out) = run(&["diff", &f, &f]);
+ assert_eq!(code, 1, "diff must exit non-zero. output: {out}");
+}
+
+#[test]
+fn valid_input_still_succeeds() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "ok.ttl", GOOD);
+ let (code, out) = run(&["lint", &f]);
+ assert_eq!(code, 0, "a readable ontology must still exit 0: {out}");
+ let (code, out) = run(&["diff", &f, &f]);
+ assert_eq!(code, 0, "two readable ontologies must still exit 0: {out}");
+}
diff --git a/tests/shacl_or_test.rs b/tests/shacl_or_test.rs
index 059834f7..9b907c03 100644
--- a/tests/shacl_or_test.rs
+++ b/tests/shacl_or_test.rs
@@ -133,3 +133,72 @@ fn unsupported_member_form_skips_rather_than_narrowing() {
"a skipped disjunction must not report violations: {r}"
);
}
+
+/// `sh:in`: the value must be one of an enumerated list of terms.
+#[test]
+fn sh_in_enumerates_permitted_values() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+:S a sh:NodeShape ; sh:targetClass :T ;
+ sh:property [ sh:path :status ; sh:in ( "ISSUED" "LAPSED" ) ] .
+"#;
+ let good = r#"
+@prefix : <http://ex.org/> .
+:a a :T ; :status "ISSUED" .
+:b a :T ; :status "LAPSED" .
+"#;
+ let r = validate(good, shapes);
+ assert_eq!(r["violation_count"], 0, "permitted values must pass: {r}");
+ assert_eq!(r["conforms"], true, "{r}");
+
+ let bad = r#"
+@prefix : <http://ex.org/> .
+:c a :T ; :status "RETIRED" .
+"#;
+ let r = validate(bad, shapes);
+ assert_eq!(r["violation_count"], 1, "{r}");
+ assert_eq!(r["violations"][0]["constraint"], "in");
+}
+
+/// `sh:nodeKind`: an identifier field typed as a literal where an IRI is required
+/// is one of the commonest register defects, so this must be caught rather than skipped.
+#[test]
+fn sh_node_kind_separates_iris_from_literals() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+:S a sh:NodeShape ; sh:targetClass :T ;
+ sh:property [ sh:path :ref ; sh:nodeKind sh:IRI ] .
+"#;
+ let r = validate(
+ "@prefix : <http://ex.org/> .\n:a a :T ; :ref <http://ex.org/target> .\n",
+ shapes,
+ );
+ assert_eq!(r["violation_count"], 0, "an IRI must pass: {r}");
+
+ let r = validate(
+ "@prefix : <http://ex.org/> .\n:b a :T ; :ref \"http://ex.org/target\" .\n",
+ shapes,
+ );
+ assert_eq!(r["violation_count"], 1, "a literal must fail: {r}");
+ assert_eq!(r["violations"][0]["constraint"], "nodeKind");
+}
+
+/// An unrecognised node kind must reach `skipped`, never pass silently.
+#[test]
+fn unrecognised_node_kind_is_skipped_not_passed() {
+ let shapes = r#"
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix : <http://ex.org/> .
+:S a sh:NodeShape ; sh:targetClass :T ;
+ sh:property [ sh:path :ref ; sh:nodeKind :NotARealKind ] .
+"#;
+ let r = validate("@prefix : <http://ex.org/> .\n:a a :T ; :ref \"x\" .\n", shapes);
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(
+ skipped.iter().any(|s| s["constraint"] == "sh:nodeKind"),
+ "an unrecognised node kind must be reported: {r}"
+ );
+ assert!(r["conforms"].is_null(), "verdict must be suppressed: {r}");
+}