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.

defects counts the classes a finding is about, and lists past fifty when asked

FABIOTESSc86895058eda
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad73c3aa..49ce9c9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,18 @@ All notable changes to Open Ontologies are documented here.
### Added
+- **`defects` says how many classes are affected, and its 50-a-kind listing
+ can be lifted** (#341). `defect_count` counts findings, one per query row,
+ and for `inherited_disjoint` a row is a (class, disjoint pair), so a class
+ under two disjoint pairs counted twice and the headline ran higher than the
+ reasoner's list of unsatisfiable classes with nothing saying why. The report
+ now carries `affected_classes` and `affected_properties` (distinct subjects)
+ beside it, and `kind_counts` gives `findings` and the affected count for each
+ of the eight kinds. `defects --limit N` on the CLI and `limit` on
+ `onto_defects` set the per-kind listing bound (default 50, `0` lists every
+ row), and `truncated` names a kind only when the bound in force cut it. On
+ the issue's reproduction: `defect_count` 2, `affected_classes` 1; with 80
+ classes under one disjoint pair, `--limit 0` lists all 80.
- **`onto_convert`, the CLI `convert` and `batch` `convert` write OWL 2
functional syntax (`--to ofn`)** (requested by @noahgift in #322). #311 gave
the engine an OFN reader and no writer, so handing an ontology to the OWL
diff --git a/src/defects.rs b/src/defects.rs
index eda01d9c..31959611 100644
--- a/src/defects.rs
+++ b/src/defects.rs
@@ -22,6 +22,13 @@ const RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#";
/// sentence that says why the reader should care.
struct Check {
kind: &'static str,
+ /// The query variable naming the thing the finding is ABOUT, and whether
+ /// that thing is a class or a property. One subject can appear in several
+ /// rows: `inherited_disjoint` returns one row per (class, disjoint pair),
+ /// so a class under two disjoint pairs is two findings and one affected
+ /// class (#341).
+ subject: &'static str,
+ subject_is: SubjectIs,
/// How much the finding should weigh on the reader.
///
/// `error` means something can have no instances at all. `warning` means
@@ -35,64 +42,136 @@ struct Check {
explanation: &'static str,
}
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum SubjectIs {
+ Class,
+ Property,
+}
+
+/// One row of one check, kept whole so two graphs' findings can be compared.
+///
+/// `plan` uses this to report only the defects a change INTRODUCES (#336): a
+/// store that already had a cycle should not make every later plan look as
+/// though it caused one.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Finding {
+ pub kind: &'static str,
+ pub severity: &'static str,
+ /// The class or property the finding is about.
+ pub subject: String,
+ /// Every binding of the row, sorted by variable name, subject included.
+ pub bindings: Vec<(String, String)>,
+}
+
+impl Finding {
+ /// The finding as it is listed in a report: kind, severity, the reason to
+ /// care, and the row's bindings.
+ pub fn to_json(&self) -> serde_json::Value {
+ let mut entry = serde_json::Map::new();
+ entry.insert("kind".into(), serde_json::json!(self.kind));
+ entry.insert("severity".into(), serde_json::json!(self.severity));
+ let explanation = Defects::checks()
+ .into_iter()
+ .find(|c| c.kind == self.kind)
+ .map(|c| c.explanation)
+ .unwrap_or_default();
+ entry.insert("explanation".into(), serde_json::json!(explanation));
+ for (var, value) in &self.bindings {
+ entry.insert(var.clone(), serde_json::json!(value));
+ }
+ serde_json::Value::Object(entry)
+ }
+}
+
pub struct Defects;
impl Defects {
- /// The most rows of any one kind that are listed individually.
+ /// The most rows of any one kind that are listed individually, unless the
+ /// caller asks for another bound.
///
/// 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.
+ /// hides the listing and never the scale. It is a DEFAULT and not a wall:
+ /// `--limit N` on the CLI and `limit` on `onto_defects` move it, and `0`
+ /// lists every row, because a total the reader can see and cannot reach is
+ /// a report that stops one step short (#341).
pub const MAX_PER_KIND: usize = 50;
+ /// The report, listing at most [`Defects::MAX_PER_KIND`] rows of each kind.
pub fn check(graph: &Arc<GraphStore>) -> anyhow::Result<String> {
+ Self::check_with_limit(graph, Self::MAX_PER_KIND)
+ }
+
+ /// The report, listing at most `limit` rows of each kind. `0` lists all.
+ ///
+ /// Two counts, because they answer two questions. `defect_count` counts
+ /// FINDINGS, one per query row: for `inherited_disjoint` a row is a
+ /// (class, disjoint pair), so a class under two disjoint pairs is two
+ /// findings. `affected_classes` and `affected_properties` count the
+ /// DISTINCT subjects those findings are about, which is the number to
+ /// hold against a reasoner's list of unsatisfiable classes. `kind_counts`
+ /// gives both per kind. Before #341 only the first existed, and on a large
+ /// ontology it read as a count of broken classes that was larger than the
+ /// reasoner's, with nothing in the output to say why.
+ pub fn check_with_limit(graph: &Arc<GraphStore>, limit: usize) -> anyhow::Result<String> {
let checks = Self::checks();
let kinds_checked: Vec<&str> = checks.iter().map(|c| c.kind).collect();
+ let findings = Self::findings(graph)?;
+ let cap = if limit == 0 { usize::MAX } else { limit };
let mut defects: Vec<serde_json::Value> = Vec::new();
let mut truncated = serde_json::Map::new();
- let mut total = 0usize;
+ let mut kind_counts = serde_json::Map::new();
let (mut errors, mut warnings, mut infos) = (0usize, 0usize, 0usize);
+ let mut classes: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
+ let mut properties: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
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();
+ let rows: Vec<&Finding> = findings.iter().filter(|f| f.kind == check.kind).collect();
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());
- }
+ let subjects: std::collections::BTreeSet<&str> =
+ rows.iter().map(|f| f.subject.as_str()).collect();
+ let affected_key = match check.subject_is {
+ SubjectIs::Class => {
+ classes.extend(subjects.iter().copied());
+ "affected_classes"
+ }
+ SubjectIs::Property => {
+ properties.extend(subjects.iter().copied());
+ "affected_properties"
}
- defects.push(serde_json::Value::Object(entry));
+ };
+ kind_counts.insert(
+ check.kind.to_string(),
+ serde_json::json!({"findings": rows.len(), affected_key: subjects.len()}),
+ );
+ // `truncated` names a kind exactly when some of its rows are not
+ // listed, so it is keyed on the bound in force rather than on the
+ // default one.
+ if rows.len() > cap {
+ truncated.insert(check.kind.to_string(), serde_json::json!(rows.len()));
}
+ defects.extend(rows.iter().take(cap).map(|f| f.to_json()));
}
Ok(serde_json::json!({
- "defect_count": total,
+ // FINDINGS, one per query row. See `affected_classes` for the
+ // number of distinct classes they are about.
+ "defect_count": findings.len(),
+ "affected_classes": classes.len(),
+ "affected_properties": properties.len(),
+ "kind_counts": kind_counts,
// 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(),
+ "limit_per_kind": limit,
"defects": defects,
"kinds_checked": kinds_checked,
"truncated": truncated,
@@ -100,10 +179,53 @@ impl Defects {
.to_string())
}
+ /// Every finding of every kind, uncapped, in check order and then in the
+ /// order of the subject and bindings.
+ pub fn findings(graph: &Arc<GraphStore>) -> anyhow::Result<Vec<Finding>> {
+ let mut out = Vec::new();
+ for check in Self::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();
+ let mut these: Vec<Finding> = rows
+ .iter()
+ .filter_map(|row| row.as_object())
+ .map(|bindings| {
+ let mut b: Vec<(String, String)> = bindings
+ .iter()
+ .map(|(k, v)| {
+ let v = v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string());
+ (k.clone(), v)
+ })
+ .collect();
+ b.sort();
+ let subject = b
+ .iter()
+ .find(|(k, _)| k == check.subject)
+ .map(|(_, v)| v.clone())
+ .unwrap_or_default();
+ Finding {
+ kind: check.kind,
+ severity: check.severity,
+ subject,
+ bindings: b,
+ }
+ })
+ .collect();
+ these.sort();
+ out.extend(these);
+ }
+ Ok(out)
+ }
+
fn checks() -> Vec<Check> {
vec![
Check {
kind: "transitive_and_functional",
+ subject: "property",
+ subject_is: SubjectIs::Property,
severity: "warning",
query: format!(
"SELECT DISTINCT ?property WHERE {{
@@ -118,6 +240,8 @@ impl Defects {
},
Check {
kind: "symmetric_and_asymmetric",
+ subject: "property",
+ subject_is: SubjectIs::Property,
severity: "error",
query: format!(
"SELECT DISTINCT ?property WHERE {{
@@ -130,6 +254,8 @@ impl Defects {
},
Check {
kind: "subclass_cycle",
+ subject: "class",
+ subject_is: SubjectIs::Class,
severity: "warning",
query: format!(
"SELECT DISTINCT ?class WHERE {{
@@ -143,6 +269,8 @@ impl Defects {
},
Check {
kind: "sub_property_cycle",
+ subject: "property",
+ subject_is: SubjectIs::Property,
severity: "warning",
query: format!(
"SELECT DISTINCT ?property WHERE {{
@@ -156,6 +284,8 @@ impl Defects {
},
Check {
kind: "disjoint_with_ancestor",
+ subject: "class",
+ subject_is: SubjectIs::Class,
severity: "error",
query: format!(
"SELECT DISTINCT ?class ?ancestor WHERE {{
@@ -170,6 +300,8 @@ impl Defects {
},
Check {
kind: "inherited_disjoint",
+ subject: "class",
+ subject_is: SubjectIs::Class,
severity: "error",
query: format!(
"SELECT DISTINCT ?class ?first ?second WHERE {{
@@ -186,6 +318,8 @@ impl Defects {
},
Check {
kind: "self_inverse",
+ subject: "property",
+ subject_is: SubjectIs::Property,
severity: "info",
query: format!(
"SELECT DISTINCT ?property WHERE {{
@@ -198,6 +332,8 @@ impl Defects {
},
Check {
kind: "inverse_not_mutual",
+ subject: "property",
+ subject_is: SubjectIs::Property,
severity: "info",
query: format!(
"SELECT DISTINCT ?property ?inverse WHERE {{
diff --git a/src/inputs.rs b/src/inputs.rs
index b6be96b9..54aef40b 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -12,6 +12,15 @@ pub struct OntoValidateInput {
pub inline: Option<bool>,
}
+#[derive(Deserialize, JsonSchema, Default)]
+pub struct OntoDefectsInput {
+ /// The most rows of any one kind to list. Default 50. `0` lists every row.
+ /// The full count of a kind cut short is reported under `truncated`
+ /// whatever the limit, so the limit hides the listing and never the scale.
+ #[serde(default)]
+ pub limit: Option<usize>,
+}
+
#[derive(Deserialize, JsonSchema)]
pub struct OntoConvertInput {
/// Path to the source file: any format onto_load reads, OWL functional
diff --git a/src/main.rs b/src/main.rs
index 9b2c2c31..bdcbf993 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -384,8 +384,17 @@ enum Commands {
Diff { old_path: String, new_path: String },
/// Lint: check for missing labels, domains, ranges
Lint { input: String },
- /// Defects: check the ONTOLOGY against itself, before any data is judged by it
- Defects { input: String },
+ /// Defects: check the ONTOLOGY against itself, before any data is judged by it.
+ ///
+ /// `defect_count` counts findings, one per row: a class under two disjoint
+ /// pairs is two findings. `affected_classes` counts the distinct classes.
+ Defects {
+ input: String,
+ /// The most rows of any one kind to list. `0` lists every row. The full
+ /// count of a kind cut short is still reported under `truncated`.
+ #[arg(long, default_value_t = open_ontologies::defects::Defects::MAX_PER_KIND)]
+ limit: usize,
+ },
/// Convert between RDF formats, or to OWL 2 functional syntax (`--to ofn`)
Convert {
path: String,
@@ -1077,7 +1086,10 @@ 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::Defects { input, limit } => cmd(
+ "defects",
+ vec![absolutize(input), "--limit".into(), limit.to_string()],
+ ),
Commands::Reason {
profile,
certificate,
@@ -2774,7 +2786,7 @@ async fn async_main() -> anyhow::Result<()> {
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result_checked(&result, cli.pretty);
}
- Commands::Defects { input } => {
+ Commands::Defects { input, limit } => {
use open_ontologies::defects::Defects;
let (_db, graph) = setup(&cli.data_dir)?;
let raw = if input == "-" {
@@ -2809,7 +2821,7 @@ async fn async_main() -> anyhow::Result<()> {
output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
std::process::exit(1);
}
- let result = Defects::check(&graph)
+ let result = Defects::check_with_limit(&graph, limit)
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));
output_result_checked(&result, cli.pretty);
}
diff --git a/src/server.rs b/src/server.rs
index 7e22cfc6..99631692 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -543,12 +543,13 @@ 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 {
+ #[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. `defect_count` counts FINDINGS, one per row, and a class under two disjoint pairs is two findings; `affected_classes` and `affected_properties` count the distinct subjects, which is the number to compare with a reasoner's unsatisfiable classes, and `kind_counts` gives both per kind. Each kind is listed at most `limit` times (default 50, 0 lists all); the full total of a kind cut short is reported under `truncated`.")]
+ pub fn onto_defects(&self, Parameters(input): Parameters<OntoDefectsInput>) -> 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)
+ let limit = input.limit.unwrap_or(crate::defects::Defects::MAX_PER_KIND);
+ crate::defects::Defects::check_with_limit(&self.graph, limit).unwrap_or_else(Self::err_json)
}
#[tool(name = "onto_dlp_boundary", description = "Ask which of YOUR axioms the rule engine can actually SEE, before trusting a reasoning result. A certificate from onto_reason is a sound proof about the axioms the rules read, and it says nothing at all about the ones no rule fires on. A user can reason, get a green machine-checked certificate, and never learn that a third of the TBox was invisible to the rule table. This is that second question, and it is in the same register as onto_defects: run it after onto_load and BEFORE trusting any onto_reason result. TWO DIMENSIONS THAT ARE NEVER MERGED, because one is a rewrite of your ontology and the other is a patch to this engine. (1) THE FRAGMENT: is the axiom expressible as Horn rules over triple patterns at all? The line drawn is OWL 2 RL's class grammar (OWL 2 Profiles section 4.3), and `outside` there is a fact about the LANGUAGE that would hold of a perfect OWL 2 RL engine: a disjunction in the consequent, an existential in the head, a cardinality restriction, a negation in the antecedent. Each such axiom is listed individually with the reason. (2) THIS ENGINE: is there a rule in the table that fires on it? owl:hasKey and owl:propertyChainAxiom are perfectly Horn, OWL 2 RL has prp-key and prp-spo2 for them, and this engine implements neither, so those axioms are INSIDE the fragment and still invisible. They are reported in `inside_the_fragment_but_a_rule_is_not_implemented` and never in `outside_the_fragment`. An axiom that splits soundly gets a third bucket of its own, `partially_inside_the_fragment`, because a bucket called `outside` holding an axiom the rules half evaluate would be false in its own name: `A subClassOf (B and Out)` keeps its `A subClassOf B` half, and an owl:equivalentClass with an existential on one side keeps the direction cls-svf1 evaluates. `not_fully_seen_by_the_rule_table` is the headline and carries the three causes separately, because they are fixed in three different places. A conjunction in the ANTECEDENT does not split, because dropping a conjunct from a rule body makes it fire more often. The rule-table figures (78 OWL 2 RL rules, 29 evaluated in the fixpoint, 10 more detected only as a clash, 7 that conclude false and are not looked for, and the names of the rest) are DERIVED from reason::RULES_EVALUATED and reason::CLASH_RULES_NOT_DETECTED rather than typed. Every triple in the store lands in an axiom bucket or in a counted `not_classified` bucket, so nothing is passed over in silence. This is NOT a consistency check and states no verdict about satisfiability.")]
diff --git a/tests/defects_cli_test.rs b/tests/defects_cli_test.rs
index fb40b345..32dc4ef2 100644
--- a/tests/defects_cli_test.rs
+++ b/tests/defects_cli_test.rs
@@ -91,3 +91,42 @@ fn defects_on_a_clean_ontology_reports_none() {
let parsed: serde_json::Value = serde_json::from_str(out.trim()).expect(&out);
assert_eq!(parsed["defect_count"].as_u64(), Some(0), "{parsed:#}");
}
+
+/// 80 classes each under a disjoint pair, so 80 rows of `inherited_disjoint`.
+fn eighty() -> String {
+ let mut ttl = String::from(
+ "@prefix ex: <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\
+ ex:A owl:disjointWith ex:B .\n",
+ );
+ for i in 0..80 {
+ ttl.push_str(&format!("ex:C{i} rdfs:subClassOf ex:A, ex:B .\n"));
+ }
+ ttl
+}
+
+/// #341: the 50-a-kind listing could not be lifted, so rows 51 to 80 were
+/// counted under `truncated` and could not be obtained by any means.
+#[test]
+fn defects_limit_zero_lists_every_row() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "eighty.ttl", &eighty());
+ let (code, out) = run(d.path(), &["defects", "--limit", "0", &f]);
+ assert_eq!(code, 0, "output: {out}");
+ let parsed: serde_json::Value = serde_json::from_str(out.trim()).expect(&out);
+ assert_eq!(parsed["reported_count"].as_u64(), Some(80), "{parsed:#}");
+ assert_eq!(parsed["truncated"], serde_json::json!({}), "{parsed:#}");
+}
+
+#[test]
+fn defects_limit_n_lists_n_and_reports_the_total() {
+ let d = tempfile::tempdir().unwrap();
+ let f = write(d.path(), "eighty.ttl", &eighty());
+ let (code, out) = run(d.path(), &["defects", "--limit", "10", &f]);
+ assert_eq!(code, 0, "output: {out}");
+ let parsed: serde_json::Value = serde_json::from_str(out.trim()).expect(&out);
+ assert_eq!(parsed["reported_count"].as_u64(), Some(10), "{parsed:#}");
+ assert_eq!(parsed["truncated"]["inherited_disjoint"].as_u64(), Some(80), "{parsed:#}");
+ assert_eq!(parsed["affected_classes"].as_u64(), Some(80), "{parsed:#}");
+}
diff --git a/tests/defects_test.rs b/tests/defects_test.rs
index 13eacc9b..b4474b76 100644
--- a/tests/defects_test.rs
+++ b/tests/defects_test.rs
@@ -258,3 +258,147 @@ fn the_report_totals_each_severity_so_the_serious_ones_are_not_buried() {
assert_eq!(report["severity_counts"]["error"].as_u64(), Some(1), "{report:#}");
assert_eq!(report["severity_counts"]["info"].as_u64(), Some(2), "{report:#}");
}
+
+// #341. `defect_count` counts query rows, and for `inherited_disjoint` a row is
+// one (class, disjoint pair). A class under two disjoint pairs was two defects,
+// so the headline count on a large ontology ran higher than the reasoner's list
+// of unsatisfiable classes and nothing in the output said why. The listing was
+// also capped at 50 a kind with no way to reach row 51.
+
+/// The reproduction from the issue: one class, two disjoint pairs above it.
+const DOUBLE: &str = r#"
+ @prefix ex: <https://example.org/x/> .
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ ex:A1 a owl:Class . ex:B1 a owl:Class . ex:A2 a owl:Class . ex:B2 a owl:Class .
+ ex:A1 owl:disjointWith ex:B1 .
+ ex:A2 owl:disjointWith ex:B2 .
+ ex:X a owl:Class ; rdfs:subClassOf ex:A1, ex:B1, ex:A2, ex:B2 .
+"#;
+
+/// `n` classes, each under `A` and `B`, which are disjoint.
+fn many_under_a_disjoint_pair(n: usize) -> String {
+ let mut ttl = format!("{PREFIXES} ex:A owl:disjointWith ex:B .\n");
+ for i in 0..n {
+ ttl.push_str(&format!("ex:C{i} rdfs:subClassOf ex:A, ex:B .\n"));
+ }
+ ttl
+}
+
+#[test]
+fn a_class_under_two_disjoint_pairs_is_two_findings_and_one_affected_class() {
+ let report = check(DOUBLE);
+ assert_eq!(
+ report["defect_count"].as_u64(),
+ Some(2),
+ "defect_count counts findings, one per row: {report:#}"
+ );
+ assert_eq!(
+ report["affected_classes"].as_u64(),
+ Some(1),
+ "both findings are about ex:X, and the reasoner reports ONE unsatisfiable class: \
+ {report:#}"
+ );
+ assert_eq!(
+ report["kind_counts"]["inherited_disjoint"],
+ serde_json::json!({"findings": 2, "affected_classes": 1}),
+ "{report:#}"
+ );
+}
+
+#[test]
+fn affected_properties_are_counted_apart_from_affected_classes() {
+ let report = check(&format!(
+ "{PREFIXES}
+ ex:partOf a owl:TransitiveProperty, owl:FunctionalProperty .
+ ex:Plant owl:disjointWith ex:Animal .
+ ex:Coral rdfs:subClassOf ex:Plant, ex:Animal ."
+ ));
+ assert_eq!(report["affected_classes"].as_u64(), Some(1), "{report:#}");
+ assert_eq!(report["affected_properties"].as_u64(), Some(1), "{report:#}");
+ assert_eq!(
+ report["kind_counts"]["transitive_and_functional"],
+ serde_json::json!({"findings": 1, "affected_properties": 1}),
+ "{report:#}"
+ );
+}
+
+#[test]
+fn every_kind_has_a_count_even_when_it_found_nothing() {
+ let report = check(&format!("{PREFIXES} ex:Dog rdfs:subClassOf ex:Animal ."));
+ let counts = report["kind_counts"].as_object().expect("kind_counts");
+ assert_eq!(counts.len(), 8, "{report:#}");
+ assert_eq!(report["affected_classes"].as_u64(), Some(0), "{report:#}");
+}
+
+fn check_limited(ttl: &str, limit: usize) -> serde_json::Value {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(ttl, None).unwrap();
+ serde_json::from_str(&Defects::check_with_limit(&store, limit).unwrap()).unwrap()
+}
+
+#[test]
+fn a_limit_of_zero_lists_every_row_and_truncates_nothing() {
+ let report = check_limited(&many_under_a_disjoint_pair(80), 0);
+ assert_eq!(report["defect_count"].as_u64(), Some(80), "{report:#}");
+ assert_eq!(
+ report["reported_count"].as_u64(),
+ Some(80),
+ "rows 51 to 80 must be reachable: {report:#}"
+ );
+ assert_eq!(report["truncated"], serde_json::json!({}), "{report:#}");
+ assert_eq!(report["affected_classes"].as_u64(), Some(80), "{report:#}");
+}
+
+#[test]
+fn a_limit_below_the_default_truncates_at_the_limit_and_says_so() {
+ let report = check_limited(&many_under_a_disjoint_pair(80), 10);
+ assert_eq!(report["reported_count"].as_u64(), Some(10), "{report:#}");
+ assert_eq!(
+ report["truncated"]["inherited_disjoint"].as_u64(),
+ Some(80),
+ "the full total is still reported: {report:#}"
+ );
+}
+
+#[test]
+fn a_limit_that_covers_every_row_truncates_nothing() {
+ // `truncated` names a kind when some of its rows are NOT listed. Keyed on
+ // the default instead of the limit in force, this would claim a cut that
+ // did not happen.
+ let report = check_limited(&many_under_a_disjoint_pair(60), 60);
+ assert_eq!(report["reported_count"].as_u64(), Some(60), "{report:#}");
+ assert_eq!(report["truncated"], serde_json::json!({}), "{report:#}");
+}
+
+#[test]
+fn the_default_is_still_fifty_a_kind() {
+ let report = check(&many_under_a_disjoint_pair(80));
+ assert_eq!(report["reported_count"].as_u64(), Some(50), "{report:#}");
+ assert_eq!(report["truncated"]["inherited_disjoint"].as_u64(), Some(80));
+}
+
+#[tokio::test]
+async fn onto_defects_takes_the_same_limit() {
+ use open_ontologies::inputs::OntoDefectsInput;
+ use open_ontologies::server::OpenOntologiesServer;
+ use open_ontologies::state::StateDb;
+ use rmcp::handler::server::wrapper::Parameters;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(&many_under_a_disjoint_pair(80), None).unwrap();
+ let server = OpenOntologiesServer::new_with_graph(db, graph);
+
+ let all: serde_json::Value =
+ serde_json::from_str(&server.onto_defects(Parameters(OntoDefectsInput { limit: Some(0) })))
+ .unwrap();
+ assert_eq!(all["reported_count"].as_u64(), Some(80), "{all:#}");
+
+ let default: serde_json::Value =
+ serde_json::from_str(&server.onto_defects(Parameters(OntoDefectsInput { limit: None })))
+ .unwrap();
+ assert_eq!(default["reported_count"].as_u64(), Some(50), "{default:#}");
+ assert_eq!(default["affected_classes"].as_u64(), Some(80), "{default:#}");
+}