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
Malformed SHACL count bounds fell back to bounds no data breaches; skip them by name and refuse them on the verified path
FABIOTESS44ba56c4f28d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d5b017d..75fc1e8d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,19 @@ All notable changes to Open Ontologies are documented here.`entity`, `original_severity`, `dismissals` and `message`. `issue_count`,`compliance` and `suppressed_count` are computed as before.`tests/feedback_suppression_test.rs` holds it for both tools.+- **A malformed SHACL count bound no longer turns a shape into a no-op** (#321,+ reported by @noahgift). `sh:minCount` fell back to 0 and `sh:maxCount` to+ `u64::MAX` when the bound did not parse, and a bad `sh:qualifiedMinCount` /+ `sh:qualifiedMaxCount` skipped the row in silence, so `sh:minCount "one"` or+ `sh:maxCount -1` over a node with no value returned `conforms: true`. All+ four now go to `skipped_constraints` with the reason, which makes the verdict+ `conforms: null`, as `sh:minLength` already did. The bound must be a+ non-negative `xsd:integer` literal: the datatype is checked because the+ store renders Turtle `1.0` as `"1"^^xsd:decimal`. The verified path+ (`verified: true`) refuses the same bounds before running `oo-shacl`, whose+ `readNat` declined "one" and -1 but evaluated `1.0` as 1. `onto_shacl_check`+ reports every ill-formed count or length literal as `ill_formed_literal`+ with its reason. `tests/shacl_count_bound_test.rs` holds it.## [2.1.0] - 2026-10-23diff --git a/src/server.rs b/src/server.rsindex d9b31b42..5c1112b1 100644--- a/src/server.rs+++ b/src/server.rs@@ -1368,7 +1368,7 @@ impl OpenOntologiesServer {result.to_string()}- #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true. An entry there is one CONSTRAINT-EVALUATION SITE and not one shape: a single `sh:property` block carrying both `sh:minCount` and `sh:node` can produce a violation from the first and a skip entry from the second, so the SAME shape can appear in `violations` and in `skipped_constraints` at once and that is not a contradiction. Every entry names the `shape` it was written on and the `constraint` predicate that was not evaluated, which is what separates a constraint that did not run from one that ran and selected nothing. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`, plus `scope`, which names the graphs the run READ. By default every graph in the store is read. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) that union is a state that held at no instant, so a run with no instant named is REFUSED rather than answered: pass `valid_at` (what was TRUE then), `as_of` (what was KNOWN then) or `all_versions: true` to say the union is what you meant. A scoped run evaluates every data-side query, `sh:sparql` included, against the in-scope named graphs plus the default graph and nothing else. A snapshot that selects no graph returns `conforms: null` with its own reason rather than conforming vacuously. Class and property DECLARATION lookups are never scoped: a declaration is context-free and has the same answer at every instant.")]+ #[tool(name = "onto_shacl", description = "Validate the loaded ontology data against SHACL shapes. Checks the core constraint components written under `sh:property`, including `sh:minCount`, `sh:maxCount`, `sh:datatype`, `sh:class`, `sh:nodeKind`, `sh:pattern`, `sh:in`, `sh:hasValue`, `sh:or` and `sh:not`, plus `sh:sparql`. A constraint it cannot execute is listed in `skipped_constraints` and the verdict is null rather than true; that includes a count or length bound that is not a non-negative integer (`sh:minCount \"one\"`, `sh:maxCount -1`), which is never read as 0 or as unbounded. An entry there is one CONSTRAINT-EVALUATION SITE and not one shape: a single `sh:property` block carrying both `sh:minCount` and `sh:node` can produce a violation from the first and a skip entry from the second, so the SAME shape can appear in `violations` and in `skipped_constraints` at once and that is not a contradiction. Every entry names the `shape` it was written on and the `constraint` predicate that was not evaluated, which is what separates a constraint that did not run from one that ran and selected nothing. Returns a conformance report with violations, `focus_nodes` and `unmatched_shapes`, plus `scope`, which names the graphs the run READ. By default every graph in the store is read. Over a store that describes its named graphs with the temporal vocabulary (https://open-ontologies.org/temporal#) that union is a state that held at no instant, so a run with no instant named is REFUSED rather than answered: pass `valid_at` (what was TRUE then), `as_of` (what was KNOWN then) or `all_versions: true` to say the union is what you meant. A scoped run evaluates every data-side query, `sh:sparql` included, against the in-scope named graphs plus the default graph and nothing else. A snapshot that selects no graph returns `conforms: null` with its own reason rather than conforming vacuously. Class and property DECLARATION lookups are never scoped: a declaration is context-free and has the same answer at every instant.")]async fn onto_shacl(&self, Parameters(input): Parameters<OntoShaclInput>) -> String {use crate::shacl::ShaclValidator;let shapes = if input.inline.unwrap_or(false) {@@ -1464,7 +1464,7 @@ impl OpenOntologiesServer {report.to_string()}- #[tool(name = "onto_shacl_check", description = "Dry-run structural check on proposed SHACL shapes against the loaded ontology. Verifies that shapes parse as Turtle and that every IRI they reference (sh:targetClass, sh:path, sh:class) exists in the ontology, plus a lightweight XSD-prefix check on sh:datatype. Does NOT validate data — use onto_shacl for that. Use this to iterate on LLM-generated SHACL before applying.")]+ #[tool(name = "onto_shacl_check", description = "Dry-run structural check on proposed SHACL shapes against the loaded ontology. Verifies that shapes parse as Turtle and that every IRI they reference (sh:targetClass, sh:path, sh:class) exists in the ontology, plus a lightweight XSD-prefix check on sh:datatype, and that every sh:minCount, sh:maxCount, sh:qualifiedMinCount, sh:qualifiedMaxCount, sh:minLength and sh:maxLength value is a non-negative xsd:integer literal (reported as kind ill_formed_literal with the reason). Does NOT validate data — use onto_shacl for that. Use this to iterate on LLM-generated SHACL before applying.")]async fn onto_shacl_check(&self, Parameters(input): Parameters<OntoShaclCheckInput>) -> String {use crate::shacl::ShaclValidator;let shapes = if input.inline.unwrap_or(false) {diff --git a/src/shacl.rs b/src/shacl.rsindex 5cc4f0ef..c040bedc 100644--- a/src/shacl.rs+++ b/src/shacl.rs@@ -1134,8 +1134,17 @@ impl ShaclValidator {}));continue;};- let q_min = row.get("qmin").and_then(|v| strip_quotes(v).parse::<i64>().ok());- let q_max = row.get("qmax").and_then(|v| strip_quotes(v).parse::<i64>().ok());+ // A malformed qualified bound used to `continue` past the whole+ // row with no record, so the qualified constraint vanished and+ // the verdict could still be true (#321). It is now skipped by+ // name, which nulls the verdict; a well-formed sibling bound on+ // the same row is still evaluated.+ let q_min = row+ .get("qmin")+ .and_then(|v| count_bound(v, "qualifiedMinCount", &shape_iri, Some(&q_path), &mut skipped));+ let q_max = row+ .get("qmax")+ .and_then(|v| count_bound(v, "qualifiedMaxCount", &shape_iri, Some(&q_path), &mut skipped));if q_min.is_none() && q_max.is_none() {continue;}@@ -1152,7 +1161,7 @@ impl ShaclValidator {let (Some(focus), Some(n_raw)) = (result.get("focus"), result.get("n")) else {continue;};- let Ok(n) = strip_quotes(n_raw).parse::<i64>() else {+ let Ok(n) = strip_quotes(n_raw).parse::<u64>() else {continue;};for (bound, breached, constraint, wording) in [@@ -1261,46 +1270,50 @@ impl ShaclValidator {}).unwrap_or_else(|| "Violation".to_string());- // sh:minCount- if let Some(min_count_str) = prop.get("minCount") {- let min_count = strip_quotes(min_count_str)- .parse::<u64>()- .unwrap_or(0);- if min_count > 0 {- let query = format!(- r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?cnt) WHERE {{- {focus_pattern}- OPTIONAL {{ ?focus {path_expr} ?val }}- }} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) < {min_count})"#- );- let results = graph_sparql_select(graph, scope, &query)?;- for row in &results {- if let Some(focus) = row.get("focus") {- let msg = if message.is_empty() {- format!(- "Property <{}> has fewer than {} values",- path, min_count- )- } else {- message.clone()- };- violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({- "severity": severity,- "focus_node": strip_angle_brackets(focus),- "path": path,- "constraint": "minCount",- "message": msg,- })));- }+ // sh:minCount. A bound that is not a non-negative integer is+ // recorded as skipped, as sh:minLength is. It used to read as 0+ // through `unwrap_or(0)`, so `sh:minCount "one"` ran no check and+ // a node with no value came back `conforms: true` (#321).+ // A bound of 0 holds of every focus node, so no query is run.+ if let Some(min_count) = prop+ .get("minCount")+ .and_then(|raw| count_bound(raw, "minCount", &shape_iri, Some(&path), &mut skipped))+ .filter(|&n| n > 0)+ {+ let query = format!(+ r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?cnt) WHERE {{+ {focus_pattern}+ OPTIONAL {{ ?focus {path_expr} ?val }}+ }} GROUP BY ?focus HAVING (COUNT(DISTINCT ?val) < {min_count})"#+ );+ let results = graph_sparql_select(graph, scope, &query)?;+ for row in &results {+ if let Some(focus) = row.get("focus") {+ let msg = if message.is_empty() {+ format!(+ "Property <{}> has fewer than {} values",+ path, min_count+ )+ } else {+ message.clone()+ };+ violations.push(attribute(&constraint_shape, &shape_iri, serde_json::json!({+ "severity": severity,+ "focus_node": strip_angle_brackets(focus),+ "path": path,+ "constraint": "minCount",+ "message": msg,+ })));}}}- // sh:maxCount- if let Some(max_count_str) = prop.get("maxCount") {- let max_count = strip_quotes(max_count_str)- .parse::<u64>()- .unwrap_or(u64::MAX);+ // sh:maxCount. The old fallback was `u64::MAX`, a bound no count+ // reaches, so `sh:maxCount -1` never fired (#321).+ if let Some(max_count) = prop+ .get("maxCount")+ .and_then(|raw| count_bound(raw, "maxCount", &shape_iri, Some(&path), &mut skipped))+ {let query = format!(r#"SELECT ?focus (COUNT(DISTINCT ?val) AS ?cnt) WHERE {{{focus_pattern}@@ -2202,7 +2215,10 @@ impl ShaclValidator {////// Verifies that the shapes parse as Turtle and that every IRI they reference/// (`sh:targetClass`, `sh:path`, `sh:class`) actually exists in the loaded- /// ontology, plus a lightweight XSD-prefix check on `sh:datatype`. Does NOT+ /// ontology, plus a lightweight XSD-prefix check on `sh:datatype`, and that+ /// every count and length bound (`sh:minCount`, `sh:maxCount`, the qualified+ /// pair, `sh:minLength`, `sh:maxLength`) is a non-negative `xsd:integer`+ /// literal (`kind: "ill_formed_literal"`, with the reason). Does NOT/// validate data against the shapes — that's `validate`. This is the primitive/// the orchestrating LLM needs to iterate on proposed SHACL before applying.///@@ -2362,6 +2378,13 @@ impl ShaclValidator {}));}+ // 3. Count and length literals, over every subject in the shapes graph+ // rather than only the shapes walked above, because a malformed+ // bound on a shape with no sh:targetClass is just as silent. The+ // validator skips such a bound and nulls its verdict (#321); this is+ // where the author learns which literal and why before running it.+ issues.extend(ill_formed_bounds(&shapes_store)?);+let ok = issues.is_empty();Ok(serde_json::json!({"ok": ok,@@ -2375,6 +2398,40 @@ impl ShaclValidator {}}+/// Every count or length bound in a shapes graph that `count_literal`+/// rejects, as `check_shapes` issues. Also the verified path's pre-check: see+/// `shacl_verified::validate_verified`.+pub(crate) fn ill_formed_bounds(shapes_store: &Store) -> anyhow::Result<Vec<serde_json::Value>> {+ let rows = query_solutions(+ shapes_store,+ r#"+ PREFIX sh: <http://www.w3.org/ns/shacl#>+ SELECT ?s ?p ?o WHERE {+ ?s ?p ?o .+ FILTER(?p IN (sh:minCount, sh:maxCount, sh:qualifiedMinCount,+ sh:qualifiedMaxCount, sh:minLength, sh:maxLength))+ }+ "#,+ )?;+ let mut issues = Vec::new();+ for row in &rows {+ let (Some(subject), Some(pred), Some(obj)) = (row.get("s"), row.get("p"), row.get("o")) else {+ continue;+ };+ if let Err(reason) = count_literal(obj) {+ let constraint = format!("sh:{}", short_sh(pred));+ issues.push(serde_json::json!({+ "shape": strip_angle_brackets(subject),+ "kind": "ill_formed_literal",+ "constraint": constraint,+ "value": obj.trim(),+ "message": format!("{constraint} {}: {reason}", obj.trim()),+ }));+ }+ }+ Ok(issues)+}+/// Run a SPARQL SELECT against a temporary shapes `Store` and return results/// as a vec of maps (variable name -> string value)./// Matches the property shapes of `?shape`: the ones hanging under@@ -3156,6 +3213,69 @@ fn strip_quotes(s: &str) -> String {}}+/// Read a cardinality bound (`sh:minCount`, `sh:maxCount` and the qualified+/// pair), or record it in `skipped` and return None.+///+/// "one", `1.0` and `-1` used to parse to a fallback (0, `u64::MAX`) or be+/// dropped without a trace, and each fallback is a bound no data can breach, so+/// the constraint disappeared and the shape passed vacuously (#321). The skip+/// entry uses the `sh:minLength` wording so a reader sees one rule, plus the+/// specific reason from `count_literal`.+fn count_bound(+ raw: &str,+ constraint: &str,+ shape_iri: &str,+ path: Option<&str>,+ skipped: &mut Vec<serde_json::Value>,+) -> Option<u64> {+ let detail = match count_literal(raw) {+ Ok(n) => return Some(n),+ Err(detail) => detail,+ };+ let mut entry = serde_json::json!({+ "shape": strip_angle_brackets(shape_iri),+ "constraint": format!("sh:{constraint}"),+ "value": raw.trim(),+ "reason": format!("bound is not a non-negative integer ({detail}); it was not evaluated"),+ });+ if let Some(path) = path {+ entry["path"] = serde_json::json!(path);+ }+ skipped.push(entry);+ None+}++/// The value of a count or length literal, or why it is ill-formed.+///+/// SHACL 4.2.1, 4.2.2, 4.4.1, 4.4.2 and 4.7.3 require these values to be+/// literals of datatype `xsd:integer`. The datatype is checked, not only the+/// lexical form, because the store does not keep the lexical form of a+/// decimal: Turtle `1.0` comes back as `"1"^^xsd:decimal`, which a lexical+/// parse reads as 1 (measured; the verified evaluator's `readNat` in+/// `lean/Shacl/Compile.lean` reads only the lexical form and does evaluate it).+/// A negative value is refused rather than read by the letter of the spec, where+/// `sh:minCount -1` holds of everything and `sh:maxCount -1` of nothing: no+/// author means either, and `readNat` refuses it too. Shared by the validator+/// (`count_bound`) and `check_shapes`, so the dry run reports exactly what the+/// run would skip.+fn count_literal(raw: &str) -> Result<u64, String> {+ const XSD_INTEGER: &str = "http://www.w3.org/2001/XMLSchema#integer";+ let Ok(Term::Literal(lit)) = raw.trim().parse::<Term>() else {+ return Err("value is not a literal".to_string());+ };+ if lit.datatype().as_str() != XSD_INTEGER {+ return Err(format!(+ "value has datatype <{}>; SHACL requires xsd:integer",+ lit.datatype().as_str()+ ));+ }+ match lit.value().parse::<i128>() {+ Ok(n) if n < 0 => Err("value is negative; a count or length cannot be".to_string()),+ Ok(n) => u64::try_from(n).map_err(|_| "value is too large to evaluate".to_string()),+ Err(_) => Err("value is not a valid xsd:integer".to_string()),+ }+}+/// Undo the N-Triples escaping that Oxigraph applies when rendering a literal/// through `Term::to_string()`.///diff --git a/src/shacl_verified.rs b/src/shacl_verified.rsindex 632fb226..fd3d4e45 100644--- a/src/shacl_verified.rs+++ b/src/shacl_verified.rs@@ -128,6 +128,30 @@ pub fn validate_verified(scratch.load_turtle(shapes_ttl, None)?;let shapes_nt = scratch.snapshot("ntriples")?;+ // Refuse an ill-formed count or length bound before the evaluator sees it.+ // `readNat` in `Shacl/Compile.lean` already declines "one" and -1, but it+ // reads only the lexical form, and the store renders Turtle `1.0` as+ // `"1"^^xsd:decimal`, which it then evaluates as 1 (#321). A refusal here+ // is outside the theorem and needs no cover from it: declining to judge is+ // never a false verdict.+ let bound_store = oxigraph::store::Store::new()?;+ for quad in oxigraph::io::RdfParser::from_format(oxigraph::io::RdfFormat::NTriples)+ .for_reader(std::io::Cursor::new(shapes_nt.as_bytes()))+ {+ bound_store.insert(&quad?)?;+ }+ let ill_formed = crate::shacl::ill_formed_bounds(&bound_store)?;+ if !ill_formed.is_empty() {+ return Ok(serde_json::json!({+ "verified": false,+ "conforms": serde_json::Value::Null,+ "error": "the shapes graph has count or length bounds that are not non-negative \+ xsd:integer literals; refused before evaluation",+ "ill_formed": ill_formed,+ "note": "a refusal, not a conformance answer. onto_shacl_check reports the same list.",+ }));+ }+// A directory per CALL, not per process.//// This was keyed on the pid alone, which is the same for every call in adiff --git a/tests/shacl_count_bound_test.rs b/tests/shacl_count_bound_test.rsnew file mode 100644index 00000000..1df502e5--- /dev/null+++ b/tests/shacl_count_bound_test.rs@@ -0,0 +1,182 @@+//! A malformed count bound must never turn a shape into a no-op (#321).+//!+//! `sh:minCount` was read with `unwrap_or(0)` and `sh:maxCount` with+//! `unwrap_or(u64::MAX)`, so `sh:minCount "one"`, `sh:minCount 1.0` or+//! `sh:maxCount -1` became a bound no data can breach, and a focus node with no+//! value came back `conforms: true`. A malformed `sh:qualifiedMinCount` /+//! `sh:qualifiedMaxCount` made the row `continue` with no record. The same file+//! already refused a malformed `sh:minLength` by naming it in+//! `skipped_constraints`, which nulls the verdict; the counts now do the same.+//!+//! Pinned:+//! 1. each malformed spelling of each of the four count bounds yields+//! `conforms: null` and a named `skipped_constraints` entry, never true;+//! 2. a well-formed bound still produces its violation (the fix did not+//! turn every count into a skip);+//! 3. `onto_shacl_check` (`check_shapes`) reports each ill-formed literal+//! with its reason;+//! 4. the verified evaluator refuses the same bounds (UNDETERMINED), when+//! the `oo-shacl` binary is available.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::shacl::ShaclValidator;+use std::sync::Arc;++const PREFIXES: &str = r#"+@prefix sh: <http://www.w3.org/ns/shacl#> .+@prefix ex: <http://ex.org/> .+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+"#;++/// A Person with no ex:name at all, which is exactly what a minimum count+/// exists to catch.+const DATA: &str = "ex:Person a owl:Class . ex:name a owl:DatatypeProperty . ex:bob a ex:Person .";++fn graph() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(&format!("{PREFIXES}{DATA}"), None).unwrap();+ g+}++fn shape(constraint: &str) -> String {+ format!(+ "{PREFIXES} ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; {constraint} ] ."+ )+}++fn qualified_shape(constraint: &str) -> String {+ format!(+ "{PREFIXES} ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:qualifiedValueShape [ sh:datatype xsd:string ] ; {constraint} ] ."+ )+}++fn validate(shapes: &str) -> serde_json::Value {+ serde_json::from_str(&ShaclValidator::validate(&graph(), shapes).unwrap()).unwrap()+}++fn assert_refused(shapes: &str, constraint: &str) {+ let r = validate(shapes);+ assert_ne!(r["conforms"], serde_json::json!(true), "{constraint} passed vacuously: {r}");+ assert!(r["conforms"].is_null(), "a skipped bound must null the verdict: {r}");+ let skipped = r["skipped_constraints"].as_array().unwrap_or_else(|| panic!("no skipped_constraints: {r}"));+ assert!(+ skipped.iter().any(|e| e["constraint"] == format!("sh:{constraint}")+ && e["reason"].as_str().unwrap_or("").contains("not a non-negative integer")),+ "sh:{constraint} must be named in skipped_constraints: {r}"+ );+}++const MALFORMED: [&str; 4] = ["\"one\"", "1.0", "-1", "\"1.5\"^^xsd:decimal"];++#[test]+fn malformed_min_count_never_conforms() {+ for v in MALFORMED {+ assert_refused(&shape(&format!("sh:minCount {v}")), "minCount");+ }+}++#[test]+fn malformed_max_count_never_conforms() {+ for v in MALFORMED {+ assert_refused(&shape(&format!("sh:maxCount {v}")), "maxCount");+ }+}++#[test]+fn malformed_qualified_counts_never_conform() {+ for v in MALFORMED {+ assert_refused(&qualified_shape(&format!("sh:qualifiedMinCount {v}")), "qualifiedMinCount");+ assert_refused(&qualified_shape(&format!("sh:qualifiedMaxCount {v}")), "qualifiedMaxCount");+ }+}++/// The control: a well-formed bound is still evaluated, and the same data+/// violates it. Without this the four tests above would pass on a validator+/// that skipped every count.+#[test]+fn well_formed_bounds_still_run() {+ for (shapes, constraint) in [+ (shape("sh:minCount 1"), "minCount"),+ (shape("sh:minCount \"1\"^^xsd:integer"), "minCount"),+ (qualified_shape("sh:qualifiedMinCount 1"), "qualifiedMinCount"),+ ] {+ let r = validate(&shapes);+ assert_eq!(r["conforms"], serde_json::json!(false), "{r}");+ assert!(+ r["violations"].as_array().unwrap().iter().any(|v| v["constraint"] == constraint),+ "{r}"+ );+ assert!(r.get("skipped_constraints").is_none(), "{r}");+ }+ let r = validate(&shape("sh:maxCount 0"));+ assert_eq!(r["conforms"], serde_json::json!(true), "no value, maxCount 0 holds: {r}");+}++#[test]+fn shacl_check_reports_ill_formed_count_and_length_literals() {+ let shapes = format!(+ "{PREFIXES} ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:minCount \"one\" ] ;+ sh:property [ sh:path ex:name ; sh:maxCount -1 ] ;+ sh:property [ sh:path ex:name ; sh:minLength 2.5 ] ;+ sh:property [ sh:path ex:name ; sh:maxLength 4 ; sh:minCount 1 ] ."+ );+ let r: serde_json::Value =+ serde_json::from_str(&ShaclValidator::check_shapes(&graph(), &shapes).unwrap()).unwrap();+ assert_eq!(r["ok"], serde_json::json!(false), "{r}");+ let ill: Vec<&serde_json::Value> = r["issues"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|i| i["kind"] == "ill_formed_literal")+ .collect();+ assert_eq!(ill.len(), 3, "exactly the three malformed bounds, not the good ones: {r}");+ let reason_for = |c: &str| {+ ill.iter()+ .find(|i| i["constraint"] == c)+ .unwrap_or_else(|| panic!("{c} not reported: {r}"))["message"]+ .as_str()+ .unwrap()+ .to_string()+ };+ assert!(reason_for("sh:minCount").contains("xsd:integer"), "{r}");+ assert!(reason_for("sh:maxCount").contains("negative"), "{r}");+ assert!(reason_for("sh:minLength").contains("xsd:integer"), "{r}");+}++#[test]+fn shacl_check_passes_well_formed_bounds() {+ let shapes = format!(+ "{PREFIXES} ex:S a sh:NodeShape ; sh:targetClass ex:Person ;+ sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:maxCount \"3\"^^xsd:integer ; sh:maxLength 0 ] ."+ );+ let r: serde_json::Value =+ serde_json::from_str(&ShaclValidator::check_shapes(&graph(), &shapes).unwrap()).unwrap();+ assert_eq!(r["ok"], serde_json::json!(true), "{r}");+}++/// The verified path refuses the same bounds. `readNat` in+/// `lean/Shacl/Compile.lean` declined "one" and -1 on its own but evaluated+/// `1.0` as 1, because the store hands it `"1"^^xsd:decimal`; the pre-check in+/// `validate_verified` closes that, so the two paths cannot drift apart.+#[test]+fn verified_evaluator_refuses_the_same_bounds() {+ if let Err(why) = open_ontologies::shacl_verified::find_checker()+ && common::skip_unless(false, &why, "the verified half of this test needs the oo-shacl binary")+ {+ return;+ }+ for constraint in ["sh:minCount \"one\"", "sh:maxCount -1", "sh:maxCount 1.0"] {+ let v = open_ontologies::shacl_verified::validate_verified(&graph(), &shape(constraint)).unwrap();+ assert!(v["conforms"].is_null(), "{constraint} must be refused: {v}");+ assert!(v["ill_formed"].as_array().is_some_and(|a| !a.is_empty()), "{constraint}: {v}");+ }+ // Control: a well-formed bound still reaches the evaluator and is judged.+ let v = open_ontologies::shacl_verified::validate_verified(&graph(), &shape("sh:minCount 1")).unwrap();+ assert_eq!(v["conforms"], serde_json::json!(false), "{v}");+}