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
feat(defects): check the ontology against itself before any data is judged by it
FABIOTESScb77f1c751ac
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8ff3cea6..02b59d73 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,28 +17,29 @@ When building or modifying ontologies, follow this workflow. Claude decides whic### Reason-6. Call `onto_reason` with profile `rdfs` or `owl-rl` to materialize inferred triples (transitive subclass chains, domain/range propagation, equivalentClass expansion)-7. Call `onto_stats` again to verify inferred triple counts are reasonable+6. Call `onto_defects` FIRST. A reasoner amplifies whatever the declarations say, so a self-contradicting ontology makes every inference suspect. Fix what it reports before materializing anything+7. Call `onto_reason` with profile `rdfs` or `owl-rl` to materialize inferred triples (transitive subclass chains, domain/range propagation, equivalentClass expansion)+8. Call `onto_stats` again to verify inferred triple counts are reasonable### Verify-8. Call `onto_lint` to check for missing labels, comments, domains, ranges — fix any issues found-9. Call `onto_enforce` with rule pack `generic` to check design pattern compliance — fix any violations-10. Call `onto_query` with SPARQL to verify structure:+9. Call `onto_lint` to check for missing labels, comments, domains, ranges — fix any issues found+10. Call `onto_enforce` with rule pack `generic` to check design pattern compliance — fix any violations+11. Call `onto_query` with SPARQL to verify structure:- Are all expected classes present?- Do subclass hierarchies match the spec?- Can competency questions be answered?-11. If a reference ontology exists, call `onto_diff` to compare+12. If a reference ontology exists, call `onto_diff` to compare### Iterate-12. If any step above reveals problems, fix the Turtle and restart from step 3-13. This loop continues until validation passes, stats match, lint is clean, enforce has no violations, and SPARQL queries return expected results+13. If any step above reveals problems, fix the Turtle and restart from step 3+14. This loop continues until validation passes, stats match, lint is clean, enforce has no violations, and SPARQL queries return expected results### Persist-14. Call `onto_save` to write the final ontology to a .ttl file-15. Call `onto_version` to save a named snapshot for rollback — always version after save+15. Call `onto_save` to write the final ontology to a .ttl file+16. Call `onto_version` to save a named snapshot for rollback — always version after save### Key Principle@@ -73,7 +74,8 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_ossie_import` | To compile an Apache Ossie (incubating, formerly Open Semantic Interchange) ontology document into OWL 2 DL + SHACL and optionally load it, making a vendor semantic model reasonable/validatable for the first time. Reports the four constructs OWL 2 DL cannot express (`OneToOne` onto a `ValueType`, `ManyToOne` on arity>=3, `derived_by`, non-scalar `requires`) instead of dropping them || `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) || `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` |-| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples |+| `onto_defects` | BEFORE trusting any fact-level result, and on every marketplace pack before adopting it. Checks the ONTOLOGY against itself with no data present: `transitive_and_functional`, `symmetric_and_asymmetric`, `subclass_cycle`, `sub_property_cycle`, `disjoint_with_ancestor`, `inherited_disjoint`, `self_inverse`, `inverse_not_mutual`. A different question from `onto_dl_check`: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions the moment instances arrive. Each kind is listed at most 50 times, with the full total under `truncated` |+| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl` || `onto_reason_incremental` | After adding facts to an already-materialised graph. Derives the consequences of the ADDED triples only (semi-naive evaluation, joining the delta against the closure), so the cost tracks what changed rather than the size of the store: effectively instant against a 1.9M-triple store where full re-materialisation takes seconds. Refuses schema axioms (subClassOf, domain, range, inverseOf, equivalentClass) with an explanation, because those change what the whole store entails: run `onto_reason` for them || `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call || `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |diff --git a/src/defects.rs b/src/defects.rsnew file mode 100644index 00000000..eda01d9c--- /dev/null+++ b/src/defects.rs@@ -0,0 +1,214 @@+//! Defects in the ontology itself, found before any data is judged against it.+//!+//! A self-contradicting ontology makes every fact-level conclusion suspect, so+//! the declarations are checked on their own first. This asks a different+//! question from `onto_dl_check`. Satisfiability asks whether a model exists;+//! these checks ask whether a pair of declarations will manufacture+//! contradictions once instances arrive. A property declared both transitive+//! and functional is satisfiable and is still a trap, so the tableaux reasoner+//! is right to pass it and it is still worth reporting.+//!+//! Every kind here is decided from the declarations alone. Nothing is inferred,+//! and no data is required.++use std::sync::Arc;++use crate::graph::GraphStore;++const OWL: &str = "http://www.w3.org/2002/07/owl#";+const RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#";++/// One check: the name it is reported under, the query that finds it, and the+/// sentence that says why the reader should care.+struct Check {+ kind: &'static str,+ /// How much the finding should weigh on the reader.+ ///+ /// `error` means something can have no instances at all. `warning` means+ /// the declarations will manufacture contradictions once data arrives, or+ /// that a hierarchy says nothing. `info` means the entailment is unaffected+ /// and only a reader is left uninformed. Without the rank the useful+ /// finding is buried: a sweep over the 153 readable ontologies in this repo+ /// returned 27 findings, 25 of them the mildest kind.+ severity: &'static str,+ query: String,+ explanation: &'static str,+}++pub struct Defects;++impl Defects {+ /// The most rows of any one kind that are listed individually.+ ///+ /// Anything reported item by item needs an upper bound. One bad+ /// declaration in a shared vocabulary produces thousands of identical+ /// rows, and a reader facing a thousand identical rows decides nothing+ /// from them. The total is still reported under `truncated`, so the cap+ /// hides the listing and never the scale.+ pub const MAX_PER_KIND: usize = 50;++ pub fn check(graph: &Arc<GraphStore>) -> anyhow::Result<String> {+ let checks = Self::checks();+ let kinds_checked: Vec<&str> = checks.iter().map(|c| c.kind).collect();++ let mut defects: Vec<serde_json::Value> = Vec::new();+ let mut truncated = serde_json::Map::new();+ let mut total = 0usize;+ let (mut errors, mut warnings, mut infos) = (0usize, 0usize, 0usize);++ for check in &checks {+ // The union dataset, so the answer does not depend on whether the+ // ontology arrived as Turtle or inside a named graph.+ let raw = graph.sparql_select_union(&check.query)?;+ let parsed: serde_json::Value = serde_json::from_str(&raw)?;+ let rows = parsed["results"].as_array().cloned().unwrap_or_default();++ total += rows.len();+ match check.severity {+ "error" => errors += rows.len(),+ "warning" => warnings += rows.len(),+ _ => infos += rows.len(),+ }+ if rows.len() > Self::MAX_PER_KIND {+ truncated.insert(check.kind.to_string(), serde_json::json!(rows.len()));+ }++ for row in rows.iter().take(Self::MAX_PER_KIND) {+ let mut entry = serde_json::Map::new();+ entry.insert("kind".into(), serde_json::json!(check.kind));+ entry.insert("severity".into(), serde_json::json!(check.severity));+ entry.insert("explanation".into(), serde_json::json!(check.explanation));+ if let Some(bindings) = row.as_object() {+ for (var, value) in bindings {+ entry.insert(var.clone(), value.clone());+ }+ }+ defects.push(serde_json::Value::Object(entry));+ }+ }++ Ok(serde_json::json!({+ "defect_count": total,+ // Always all three keys, so a reader never has to tell "none of+ // this kind" from "this key was not written".+ "severity_counts": {"error": errors, "warning": warnings, "info": infos},+ "reported_count": defects.len(),+ "defects": defects,+ "kinds_checked": kinds_checked,+ "truncated": truncated,+ })+ .to_string())+ }++ fn checks() -> Vec<Check> {+ vec![+ Check {+ kind: "transitive_and_functional",+ severity: "warning",+ query: format!(+ "SELECT DISTINCT ?property WHERE {{+ ?property a <{OWL}TransitiveProperty> .+ ?property a <{OWL}FunctionalProperty> .+ }}"+ ),+ explanation: "A transitive property chains and a functional property admits one \+ object, so any chain of length two forces two objects to be the \+ same. The pair is satisfiable and will produce contradictions as \+ soon as instances arrive.",+ },+ Check {+ kind: "symmetric_and_asymmetric",+ severity: "error",+ query: format!(+ "SELECT DISTINCT ?property WHERE {{+ ?property a <{OWL}SymmetricProperty> .+ ?property a <{OWL}AsymmetricProperty> .+ }}"+ ),+ explanation: "Symmetric requires the reverse edge and asymmetric forbids it, so \+ the property can never hold between two distinct individuals.",+ },+ Check {+ kind: "subclass_cycle",+ severity: "warning",+ query: format!(+ "SELECT DISTINCT ?class WHERE {{+ ?class <{RDFS}subClassOf>+ ?other .+ ?other <{RDFS}subClassOf>+ ?class .+ FILTER(?class != ?other)+ }}"+ ),+ explanation: "Classes on a subclass cycle are all equivalent, which is almost \+ never what a hierarchy was meant to say.",+ },+ Check {+ kind: "sub_property_cycle",+ severity: "warning",+ query: format!(+ "SELECT DISTINCT ?property WHERE {{+ ?property <{RDFS}subPropertyOf>+ ?other .+ ?other <{RDFS}subPropertyOf>+ ?property .+ FILTER(?property != ?other)+ }}"+ ),+ explanation: "Properties on a sub-property cycle are all equivalent, so the \+ hierarchy asserts nothing.",+ },+ Check {+ kind: "disjoint_with_ancestor",+ severity: "error",+ query: format!(+ "SELECT DISTINCT ?class ?ancestor WHERE {{+ ?class <{RDFS}subClassOf>+ ?ancestor .+ {{ ?class <{OWL}disjointWith> ?ancestor }}+ UNION+ {{ ?ancestor <{OWL}disjointWith> ?class }}+ }}"+ ),+ explanation: "A class that is a kind of something it is also disjoint from can \+ have no instances at all.",+ },+ Check {+ kind: "inherited_disjoint",+ severity: "error",+ query: format!(+ "SELECT DISTINCT ?class ?first ?second WHERE {{+ ?class <{RDFS}subClassOf>+ ?first .+ ?class <{RDFS}subClassOf>+ ?second .+ {{ ?first <{OWL}disjointWith> ?second }}+ UNION+ {{ ?second <{OWL}disjointWith> ?first }}+ FILTER(STR(?first) < STR(?second))+ }}"+ ),+ explanation: "The class sits under two ancestors declared disjoint, so it can \+ have no instances.",+ },+ Check {+ kind: "self_inverse",+ severity: "info",+ query: format!(+ "SELECT DISTINCT ?property WHERE {{+ ?property <{OWL}inverseOf> ?property .+ FILTER NOT EXISTS {{ ?property a <{OWL}SymmetricProperty> }}+ }}"+ ),+ explanation: "A property declared its own inverse is symmetric by consequence. \+ Declare it symmetric and say so, or the inverse was a slip.",+ },+ Check {+ kind: "inverse_not_mutual",+ severity: "info",+ query: format!(+ "SELECT DISTINCT ?property ?inverse WHERE {{+ ?property <{OWL}inverseOf> ?inverse .+ FILTER NOT EXISTS {{ ?inverse <{OWL}inverseOf> ?property }}+ }}"+ ),+ explanation: "One direction of the pair was declared and the other was not. The \+ entailment holds either way, but a reader consulting the second \+ property alone learns nothing about the first.",+ },+ ]+ }+}diff --git a/src/lib.rs b/src/lib.rsindex 4c44cd01..f8936ea0 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -18,6 +18,7 @@ pub mod coevolve;pub mod communities;pub mod config;pub mod cq;+pub mod defects;pub mod drift;pub mod dynamics;pub mod dynamics_bcplus;diff --git a/src/main.rs b/src/main.rsindex 0e2582da..170c97b8 100644--- a/src/main.rs+++ b/src/main.rs@@ -348,6 +348,8 @@ enum Commands {Diff { old_path: String, new_path: String },/// Lint: check for missing labels, domains, rangesLint { input: String },+ /// Defects: check the ONTOLOGY against itself, before any data is judged by it+ Defects { input: String },/// Convert between RDF formatsConvert {path: String,@@ -616,6 +618,7 @@ impl Commands {Commands::Stats => cmd("stats", vec![]),Commands::Query { query } => cmd("query", vec![query.clone()]),Commands::Lint { input } => cmd("lint", vec![absolutize(input)]),+ Commands::Defects { input } => cmd("defects", vec![absolutize(input)]),Commands::Reason { profile } => {cmd("reason", vec!["--profile".into(), profile.clone()])}@@ -1896,6 +1899,45 @@ async fn async_main() -> anyhow::Result<()> {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result_checked(&result, cli.pretty);}+ Commands::Defects { input } => {+ use open_ontologies::defects::Defects;+ let (_db, graph) = setup(&cli.data_dir)?;+ let raw = if input == "-" {+ let mut buf = String::new();+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;+ buf+ } else {+ match std::fs::read_to_string(&input) {+ Ok(c) => c,+ Err(e) => {+ // JSON on every path, including this one. `lint` used to+ // answer a missing file with a bare `Error: No such file`,+ // so `open-ontologies lint f | jq` crashed on the case it+ // most needs to handle (flaw hunt D4).+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);+ std::process::exit(1);+ }+ }+ };+ // Sniff the serialisation rather than assume Turtle, and fail the+ // process when the document cannot be read. A clean bill of health+ // over a file that was never parsed is the one answer a checker must+ // never give (flaw hunt D1).+ 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);+ }+ };+ if let Err(e) = graph.load_turtle(&content, None) {+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);+ std::process::exit(1);+ }+ let result = Defects::check(&graph)+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ output_result_checked(&result, cli.pretty);+ }Commands::Lint { input } => {use open_ontologies::ontology::OntologyService;let (db, _graph) = setup(&cli.data_dir)?;diff --git a/src/server.rs b/src/server.rsindex 3bbb8465..8f3bb3a3 100644--- a/src/server.rs+++ b/src/server.rs@@ -437,6 +437,14 @@ impl OpenOntologiesServer {}}+ #[tool(name = "onto_defects", description = "Check the ONTOLOGY itself, before any data is judged against it. Reports eight kinds of self-contradicting or self-defeating declaration: transitive_and_functional, symmetric_and_asymmetric, subclass_cycle, sub_property_cycle, disjoint_with_ancestor, inherited_disjoint, self_inverse, inverse_not_mutual. This is a different question from onto_dl_check: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions as soon as instances arrive. Run it after onto_load and before trusting any fact-level result, and on every marketplace pack before adopting it. Each kind is listed at most 50 times; the full total is reported under `truncated`.")]+ fn onto_defects(&self) -> String {+ if let Err(e) = self.registry.ensure_loaded() {+ return Self::err_json(format!("ensure_loaded: {e}"));+ }+ crate::defects::Defects::check(&self.graph).unwrap_or_else(Self::err_json)+ }+#[tool(name = "onto_stats", description = "Get statistics about the loaded ontology (triple count, classes, properties, individuals)")]fn onto_stats(&self) -> String {if let Err(e) = self.registry.ensure_loaded() {@@ -1868,12 +1876,17 @@ impl OpenOntologiesServer {body.to_string()}- #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (Full OWL2-DL SHOIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning). Materializes inferred triples.")]+ #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (Full OWL2-DL SHOIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one.")]async fn onto_reason(&self, Parameters(input): Parameters<OntoReasonInput>) -> String {use crate::reason::Reasoner;let profile = input.profile.as_deref().unwrap_or("rdfs");let materialize = input.materialize.unwrap_or(true);- Reasoner::run(&self.graph, profile, materialize)+ let target = if input.inference_graph.unwrap_or(false) {+ crate::reason::InferenceTarget::Inferred+ } else {+ crate::reason::InferenceTarget::DefaultGraph+ };+ Reasoner::run_with_target(&self.graph, profile, materialize, target).unwrap_or_else(Self::err_json)}diff --git a/tests/defects_cli_test.rs b/tests/defects_cli_test.rsnew file mode 100644index 00000000..fb40b345--- /dev/null+++ b/tests/defects_cli_test.rs@@ -0,0 +1,93 @@+//! The `defects` command as a shell citizen.+//!+//! Written before the command exists, and the exit-code case is written first+//! on purpose. `lint`, `vocab-check` and `diff` each shipped printing+//! `{"error": ...}` and exiting 0, so `open-ontologies lint x.ttl || exit 1`+//! passed on exactly the input it existed to catch. A new checker that repeats+//! that is worse than no checker, because a CI gate built on it reports a pass+//! over a file it never read.++use std::process::Command;++/// Every invocation gets its own `--data-dir`, the discipline `cli_test.rs` and+/// `cli_exit_codes_test.rs` both keep: without it these tests open the+/// developer's real database and race each other.+fn run(dir: &std::path::Path, args: &[&str]) -> (i32, String) {+ let out = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .arg("--data-dir")+ .arg(dir.join("data"))+ .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 CLEAN: &str = r#"+@prefix ex: <http://ex.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ex:Animal a owl:Class .+ex:Dog rdfs:subClassOf ex:Animal .+"#;++const DEFECTIVE: &str = r#"+@prefix ex: <http://ex.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+ex:partOf a owl:TransitiveProperty, owl:FunctionalProperty .+"#;++#[test]+fn defects_fails_the_process_on_unparseable_input() {+ let d = tempfile::tempdir().unwrap();+ let f = write(d.path(), "g.ttl", GARBAGE);+ let (code, out) = run(d.path(), &["defects", &f]);+ assert_eq!(+ code, 1,+ "a checker that cannot read its input must say so to the shell: {out}"+ );+ assert!(out.contains("error"), "output: {out}");+}++#[test]+fn defects_fails_the_process_on_a_missing_file() {+ let d = tempfile::tempdir().unwrap();+ let missing = d.path().join("nope.ttl");+ let (code, out) = run(d.path(), &["defects", missing.to_str().unwrap()]);+ assert_eq!(code, 1, "output: {out}");+ assert!(+ out.contains("error"),+ "the JSON contract has to hold for the case it most needs to: {out}"+ );+}++#[test]+fn defects_reports_a_defect_it_finds() {+ let d = tempfile::tempdir().unwrap();+ let f = write(d.path(), "bad.ttl", DEFECTIVE);+ let (code, out) = run(d.path(), &["defects", &f]);+ assert_eq!(code, 0, "a readable file with a defect is a successful run: {out}");+ assert!(out.contains("transitive_and_functional"), "output: {out}");+}++#[test]+fn defects_on_a_clean_ontology_reports_none() {+ let d = tempfile::tempdir().unwrap();+ let f = write(d.path(), "good.ttl", CLEAN);+ let (code, out) = run(d.path(), &["defects", &f]);+ assert_eq!(code, 0, "output: {out}");+ let parsed: serde_json::Value = serde_json::from_str(out.trim()).expect(&out);+ assert_eq!(parsed["defect_count"].as_u64(), Some(0), "{parsed:#}");+}diff --git a/tests/defects_test.rs b/tests/defects_test.rsnew file mode 100644index 00000000..13eacc9b--- /dev/null+++ b/tests/defects_test.rs@@ -0,0 +1,260 @@+//! The ontology is checked before the data is.+//!+//! A self-contradicting ontology makes every fact-level conclusion suspect, so+//! the declarations are examined first, on their own, with no data present.+//!+//! This is a different question from satisfiability, which `onto_dl_check`+//! already answers. A property declared both transitive and functional is+//! perfectly satisfiable; it is still a trap, because the two declarations+//! together manufacture contradictions the moment instances arrive. The+//! tableaux reasoner is right to call it consistent and it is still worth+//! reporting.++use open_ontologies::defects::Defects;+use open_ontologies::graph::GraphStore;+use std::sync::Arc;++fn check(ttl: &str) -> serde_json::Value {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(ttl, None).unwrap();+ let json = Defects::check(&store).unwrap();+ serde_json::from_str(&json).unwrap()+}++fn kinds(report: &serde_json::Value) -> Vec<String> {+ report["defects"]+ .as_array()+ .unwrap()+ .iter()+ .map(|d| d["kind"].as_str().unwrap().to_string())+ .collect()+}++const PREFIXES: &str = r#"+ @prefix ex: <http://example.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+"#;++#[test]+fn a_property_both_transitive_and_functional_is_reported() {+ let report = check(&format!(+ "{PREFIXES} ex:partOf a owl:TransitiveProperty, owl:FunctionalProperty ."+ ));+ assert!(+ kinds(&report).contains(&"transitive_and_functional".to_string()),+ "{report:#}"+ );+}++#[test]+fn a_property_both_symmetric_and_asymmetric_is_reported() {+ let report = check(&format!(+ "{PREFIXES} ex:sibling a owl:SymmetricProperty, owl:AsymmetricProperty ."+ ));+ assert!(+ kinds(&report).contains(&"symmetric_and_asymmetric".to_string()),+ "{report:#}"+ );+}++#[test]+fn a_subclass_cycle_is_reported() {+ let report = check(&format!(+ "{PREFIXES}+ ex:A rdfs:subClassOf ex:B .+ ex:B rdfs:subClassOf ex:C .+ ex:C rdfs:subClassOf ex:A ."+ ));+ assert!(kinds(&report).contains(&"subclass_cycle".to_string()), "{report:#}");+}++#[test]+fn a_sub_property_cycle_is_reported() {+ let report = check(&format!(+ "{PREFIXES}+ ex:p rdfs:subPropertyOf ex:q .+ ex:q rdfs:subPropertyOf ex:p ."+ ));+ assert!(+ kinds(&report).contains(&"sub_property_cycle".to_string()),+ "{report:#}"+ );+}++#[test]+fn a_class_disjoint_with_its_own_ancestor_is_reported() {+ let report = check(&format!(+ "{PREFIXES}+ ex:Puppy rdfs:subClassOf ex:Dog .+ ex:Dog rdfs:subClassOf ex:Animal .+ ex:Puppy owl:disjointWith ex:Animal ."+ ));+ assert!(+ kinds(&report).contains(&"disjoint_with_ancestor".to_string()),+ "a class that is disjoint from something it is also a kind of can have \+ no instances: {report:#}"+ );+}++#[test]+fn a_class_under_two_disjoint_parents_is_reported() {+ let report = check(&format!(+ "{PREFIXES}+ ex:Plant owl:disjointWith ex:Animal .+ ex:Coral rdfs:subClassOf ex:Plant, ex:Animal ."+ ));+ assert!(+ kinds(&report).contains(&"inherited_disjoint".to_string()),+ "{report:#}"+ );+}++#[test]+fn an_inverse_pair_that_is_not_mutual_is_reported() {+ let report = check(&format!(+ "{PREFIXES} ex:parentOf owl:inverseOf ex:childOf ."+ ));+ assert!(+ kinds(&report).contains(&"inverse_not_mutual".to_string()),+ "one direction was declared and the other was not: {report:#}"+ );+}++#[test]+fn a_mutual_inverse_pair_is_not_reported() {+ let report = check(&format!(+ "{PREFIXES}+ ex:parentOf owl:inverseOf ex:childOf .+ ex:childOf owl:inverseOf ex:parentOf ."+ ));+ assert!(+ !kinds(&report).contains(&"inverse_not_mutual".to_string()),+ "{report:#}"+ );+}++#[test]+fn a_property_declared_its_own_inverse_without_being_symmetric_is_reported() {+ let report = check(&format!("{PREFIXES} ex:marriedTo owl:inverseOf ex:marriedTo ."));+ assert!(kinds(&report).contains(&"self_inverse".to_string()), "{report:#}");+}++#[test]+fn a_clean_ontology_reports_nothing() {+ let report = check(&format!(+ "{PREFIXES}+ ex:Animal a owl:Class .+ ex:Dog rdfs:subClassOf ex:Animal .+ ex:Cat rdfs:subClassOf ex:Animal .+ ex:Dog owl:disjointWith ex:Cat .+ ex:parentOf a owl:ObjectProperty ; owl:inverseOf ex:childOf .+ ex:childOf a owl:ObjectProperty ; owl:inverseOf ex:parentOf ."+ ));+ assert_eq!(report["defect_count"].as_u64(), Some(0), "{report:#}");+}++#[test]+fn the_report_names_every_kind_it_looked_for() {+ // A check that finds nothing and a check that never ran look identical+ // unless the report says what was examined.+ let report = check(&format!("{PREFIXES} ex:Animal a owl:Class ."));+ let checked: Vec<String> = report["kinds_checked"]+ .as_array()+ .unwrap()+ .iter()+ .map(|k| k.as_str().unwrap().to_string())+ .collect();+ assert_eq!(checked.len(), 8, "eight kinds are implemented: {checked:?}");+ assert!(checked.contains(&"transitive_and_functional".to_string()));+ assert!(checked.contains(&"disjoint_with_ancestor".to_string()));+}++#[test]+fn a_kind_that_fires_in_bulk_is_capped_and_says_so() {+ // Anything reported item by item needs an upper bound. A shared vocabulary+ // with one bad declaration can produce thousands of identical rows, and a+ // reader facing a thousand identical cards decides nothing from them.+ let mut ttl = String::from(PREFIXES);+ for i in 0..(Defects::MAX_PER_KIND + 20) {+ ttl.push_str(&format!("ex:p{i} a owl:TransitiveProperty, owl:FunctionalProperty .\n"));+ }+ let report = check(&ttl);++ let reported = kinds(&report)+ .iter()+ .filter(|k| *k == "transitive_and_functional")+ .count();+ assert_eq!(+ reported,+ Defects::MAX_PER_KIND,+ "the listing must stop at the cap: {report:#}"+ );+ assert_eq!(+ report["truncated"]["transitive_and_functional"].as_u64(),+ Some((Defects::MAX_PER_KIND + 20) as u64),+ "the total must still be reported, or the cap hides the scale of the problem"+ );+}++// A sweep over the 153 readable ontologies in this repo returned 27 findings,+// 25 of them `inverse_not_mutual`. That kind is real and it is also harmless:+// `p owl:inverseOf q` entails the reverse, so nothing is broken, a reader is+// merely not told. Reporting it beside `disjoint_with_ancestor`, which makes a+// class uninstantiable, buries the finding that matters under the finding that+// does not. The kinds need to be ranked.++fn severity_of(report: &serde_json::Value, kind: &str) -> String {+ report["defects"]+ .as_array()+ .unwrap()+ .iter()+ .find(|d| d["kind"] == kind)+ .unwrap_or_else(|| panic!("{kind} not in {report:#}"))["severity"]+ .as_str()+ .unwrap()+ .to_string()+}++#[test]+fn a_class_that_can_have_no_instances_is_an_error() {+ let report = check(&format!(+ "{PREFIXES}+ ex:Puppy rdfs:subClassOf ex:Dog .+ ex:Dog rdfs:subClassOf ex:Animal .+ ex:Puppy owl:disjointWith ex:Animal ."+ ));+ assert_eq!(severity_of(&report, "disjoint_with_ancestor"), "error");+}++#[test]+fn a_pair_that_will_manufacture_contradictions_is_a_warning() {+ let report = check(&format!(+ "{PREFIXES} ex:partOf a owl:TransitiveProperty, owl:FunctionalProperty ."+ ));+ assert_eq!(severity_of(&report, "transitive_and_functional"), "warning");+}++#[test]+fn a_declaration_that_costs_nothing_but_clarity_is_info() {+ let report = check(&format!("{PREFIXES} ex:parentOf owl:inverseOf ex:childOf ."));+ assert_eq!(+ severity_of(&report, "inverse_not_mutual"),+ "info",+ "the entailment holds either way, so this is hygiene and must not \+ outrank a class that can have no instances"+ );+}++#[test]+fn the_report_totals_each_severity_so_the_serious_ones_are_not_buried() {+ let report = check(&format!(+ "{PREFIXES}+ ex:Plant owl:disjointWith ex:Animal .+ ex:Coral rdfs:subClassOf ex:Plant, ex:Animal .+ ex:parentOf owl:inverseOf ex:childOf .+ ex:ownerOf owl:inverseOf ex:ownedBy ."+ ));+ assert_eq!(report["severity_counts"]["error"].as_u64(), Some(1), "{report:#}");+ assert_eq!(report["severity_counts"]["info"].as_u64(), Some(2), "{report:#}");+}