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
fix: red-team pass on correctness, soundness, graph-blindness and DoS (#129)
Fabio Rovaia62b91c8d392
diff --git a/src/align.rs b/src/align.rsindex 512b2b6f..c8b96270 100644--- a/src/align.rs+++ b/src/align.rs@@ -64,7 +64,7 @@ impl AlignmentEngine {}"#;- let result = match store.sparql_select(query) {+ let result = match store.sparql_select_union(query) {Ok(r) => r,Err(_) => return Vec::new(),};@@ -158,7 +158,7 @@ impl AlignmentEngine {/// Helper: run a SPARQL SELECT and extract a single variable's values.fn extract_iris(store: &GraphStore, query: &str, var: &str) -> Vec<String> {- let result = match store.sparql_select(query) {+ let result = match store.sparql_select_union(query) {Ok(r) => r,Err(_) => return Vec::new(),};@@ -233,7 +233,7 @@ impl AlignmentEngine {let extract_restriction_sigs = |store: &GraphStore, class: &str| -> Vec<String> {let query = restriction_query(class);- let result = match store.sparql_select(&query) {+ let result = match store.sparql_select_union(&query) {Ok(r) => r,Err(_) => return Vec::new(),};diff --git a/src/align_fuzzy.rs b/src/align_fuzzy.rsindex 0d2c76d9..ab06443c 100644--- a/src/align_fuzzy.rs+++ b/src/align_fuzzy.rs@@ -138,7 +138,7 @@ fn tnorm_n(values: &[f64], t: TNorm) -> f64 {if values.is_empty() {return 0.0;}- values+ values[1..].iter().copied().fold(values[0], |acc, x| tnorm(acc, x, t))@@ -267,6 +267,20 @@ mod tests {}}+ #[test]+ fn tnorm_n_combines_each_value_once() {+ // Min is idempotent so it hides a double-count; Product and Lukasiewicz expose it.+ // Three equal 0.75 inputs under Product must be 0.75^3, not 0.75^4.+ assert!((tnorm_n(&[0.75, 0.75, 0.75], TNorm::Product) - 0.421875).abs() < 1e-9);+ // Product of three distinct values combines each exactly once.+ assert!((tnorm_n(&[0.5, 0.4, 0.2], TNorm::Product) - 0.04).abs() < 1e-9);+ // Lukasiewicz chain over three 0.8 inputs: max(0,1.6-1)=0.6 then max(0,1.4-1)=0.4.+ assert!((tnorm_n(&[0.8, 0.8, 0.8], TNorm::Lukasiewicz) - 0.4).abs() < 1e-9);+ // Single value is itself under every t-norm; empty is 0.+ assert_eq!(tnorm_n(&[0.6], TNorm::Product), 0.6);+ assert_eq!(tnorm_n(&[], TNorm::Product), 0.0);+ }+#[test]fn membership_triangles_have_expected_peaks() {assert!((mu_low(0.0) - 1.0).abs() < 1e-9);diff --git a/src/cache.rs b/src/cache.rsindex 24e98dfa..cc7cb8cd 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -349,10 +349,18 @@ impl CacheManager {/// Atomically write `content` to `path` (writes to `<path>.tmp` then renames).pub fn atomic_write(path: &Path, content: &str) -> Result<()> {+ use std::sync::atomic::{AtomicU64, Ordering};+ static TMP_SEQ: AtomicU64 = AtomicU64::new(0);if let Some(parent) = path.parent() {fs::create_dir_all(parent).ok();}- let tmp = path.with_extension("nt.tmp");+ // Unique temp name per write: a fixed `.nt.tmp` collides when two writers+ // target the same cache path at once (two concurrent loads of one source, or+ // a load racing an eviction snapshot), so one's partial write is renamed over+ // the other and the reader gets a torn file. Process id plus a monotonic+ // counter keeps each writer's temp private; the final rename stays atomic.+ let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);+ let tmp = path.with_extension(format!("nt.{}.{}.tmp", std::process::id(), seq));fs::write(&tmp, content).with_context(|| format!("write {}", tmp.display()))?;fs::rename(&tmp, path)diff --git a/src/daemon.rs b/src/daemon.rsindex af1bfaad..dca622f8 100644--- a/src/daemon.rs+++ b/src/daemon.rs@@ -61,6 +61,34 @@ pub fn is_daemon_alive(pid: u32) -> bool {}}+/// Whether the process with `pid` looks like an open-ontologies daemon, by+/// inspecting its command line for the `serve-http` subcommand every daemon is+/// started with (see `start_daemon`). This is the identity check that keeps a+/// recycled PID in a stale daemon.json from being signalled as if it were ours.+#[cfg(unix)]+fn pid_is_open_ontologies_daemon(pid: u32) -> bool {+ std::process::Command::new("ps")+ .args(["-p", &pid.to_string(), "-o", "command="])+ .output()+ .map(|o| String::from_utf8_lossy(&o.stdout).contains("serve-http"))+ .unwrap_or(false)+}++#[cfg(not(unix))]+fn pid_is_open_ontologies_daemon(pid: u32) -> bool {+ std::process::Command::new("wmic")+ .args([+ "process",+ "where",+ &format!("ProcessId={pid}"),+ "get",+ "CommandLine",+ ])+ .output()+ .map(|o| String::from_utf8_lossy(&o.stdout).contains("serve-http"))+ .unwrap_or(false)+}+/// Start `serve-http` in the background and write daemon.json./// Returns the `DaemonInfo` on success.pub fn start_daemon(@@ -151,6 +179,19 @@ pub fn stop_daemon(data_dir: &str) -> anyhow::Result<()> {anyhow::bail!("daemon PID {} is not running (stale daemon.json removed)", info.pid);}+ // A live PID is not proof it is OUR daemon. daemon.json survives a crash or+ // reboot, and the OS recycles PIDs, so a stale record can point at an unrelated+ // process. Verify the process is actually an open-ontologies daemon before+ // signalling it, or `daemon stop` becomes a way to kill an arbitrary process.+ if !pid_is_open_ontologies_daemon(info.pid) {+ remove_daemon_info(data_dir);+ anyhow::bail!(+ "PID {} is running but is not an open-ontologies daemon; refusing to \+ signal an unrelated process (stale daemon.json removed)",+ info.pid+ );+ }+#[cfg(unix)]{let status = std::process::Command::new("kill")@@ -192,6 +233,15 @@ mod tests {assert!(!is_daemon_alive(u32::MAX - 1));}+ #[test]+ fn an_unrelated_live_process_is_not_taken_for_the_daemon() {+ // This test binary is alive but is not a `serve-http` daemon, so the+ // identity check must reject it. This is exactly the recycled-PID case+ // stop_daemon must refuse to kill.+ assert!(is_daemon_alive(std::process::id()));+ assert!(!pid_is_open_ontologies_daemon(std::process::id()));+ }+#[test]fn daemon_info_round_trips_through_the_data_dir() {let dir = tempfile::tempdir().unwrap();diff --git a/src/enforce.rs b/src/enforce.rsindex 7835fadc..44ef1559 100644--- a/src/enforce.rs+++ b/src/enforce.rs@@ -419,7 +419,7 @@ impl Enforcer {"ASK {{ <{}> <http://www.w3.org/2002/07/owl#disjointWith> <{}> }}",children[i], children[j]);- if let Ok(result) = self.graph.sparql_select(&disjoint_query)+ if let Ok(result) = self.graph.sparql_select_union(&disjoint_query)&& !result.contains("true") {all_disjoint = false;break;@@ -480,7 +480,7 @@ impl Enforcer {} GROUP BY ?class \}";- if let Ok(json) = self.graph.sparql_select(depth_query)+ if let Ok(json) = self.graph.sparql_select_union(depth_query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array()&& let Some(first) = results.first()@@ -518,7 +518,7 @@ impl Enforcer {} GROUP BY ?class \}";- if let Ok(json) = self.graph.sparql_select(avg_query)+ if let Ok(json) = self.graph.sparql_select_union(avg_query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array()&& let Some(first) = results.first()@@ -584,7 +584,7 @@ impl Enforcer {fn query_flat_hierarchy(&self, query: &str) -> Vec<(String, u64, Vec<String>)> {let mut results = Vec::new();- if let Ok(json) = self.graph.sparql_select(query)+ if let Ok(json) = self.graph.sparql_select_union(query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(rows) = parsed["results"].as_array(){@@ -621,7 +621,7 @@ impl Enforcer {}fn query_count(&self, query: &str) -> u64 {- if let Ok(json) = self.graph.sparql_select(query)+ if let Ok(json) = self.graph.sparql_select_union(query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array()&& let Some(first) = results.first()@@ -676,7 +676,7 @@ impl Enforcer {}fn query_iris(&self, query: &str, var: &str) -> Vec<String> {- if let Ok(json) = self.graph.sparql_select(query)+ if let Ok(json) = self.graph.sparql_select_union(query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array() {return resultsdiff --git a/src/flora_pipeline.rs b/src/flora_pipeline.rsindex 2e98fd06..cf5d6f64 100644--- a/src/flora_pipeline.rs+++ b/src/flora_pipeline.rs@@ -153,7 +153,7 @@ pub fn list_classes(graph: &Arc<GraphStore>) -> Vec<String> {}fn sparql_iri_list(graph: &Arc<GraphStore>, q: &str, var: &str) -> Vec<String> {- let js = match graph.sparql_select(q) {+ let js = match graph.sparql_select_union(q) {Ok(s) => s,Err(_) => return Vec::new(),};diff --git a/src/graph.rs b/src/graph.rsindex ef77b01b..c99b55ac 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -574,7 +574,18 @@ impl GraphStore {auth: &SparqlAuth,) -> anyhow::Result<String> {let update = match graph {- Some(g) => format!("INSERT DATA {{ GRAPH <{g}> {{ {content} }} }}"),+ Some(g) => {+ // The graph name is spliced into a SPARQL 1.1 Update sent verbatim to+ // the remote endpoint, which parses it with no store in between. A+ // value like `x> {} }; DROP ALL ; INSERT DATA { GRAPH <x` would close+ // the GRAPH IRI and append arbitrary destructive operations. Validate+ // it as an absolute IRI first; NamedNode::new rejects '>', whitespace,+ // braces and quotes, so a value that survives cannot break out.+ NamedNode::new(g).map_err(|e| {+ anyhow::anyhow!("graph is not a valid absolute IRI: {e}")+ })?;+ format!("INSERT DATA {{ GRAPH <{g}> {{ {content} }} }}")+ }None => format!("INSERT DATA {{ {content} }}"),};let client = reqwest::Client::new();diff --git a/src/ingest.rs b/src/ingest.rsindex b3ede618..dcd2f432 100644--- a/src/ingest.rs+++ b/src/ingest.rs@@ -367,41 +367,51 @@ impl DataIngester {}}+ /// Read a whole text file into memory, refusing anything over the ingest cap.+ /// Ingest reads the entire file at once, so an unbounded read is an+ /// out-of-memory lever for any caller that can point the tool at a large file.+ fn read_to_string_capped(path: &str) -> Result<String> {+ const MAX_INGEST_BYTES: u64 = 512 * 1024 * 1024;+ let meta =+ fs::metadata(path).with_context(|| format!("Failed to stat file: {path}"))?;+ if meta.len() > MAX_INGEST_BYTES {+ anyhow::bail!(+ "file {path} is {} bytes, over the {MAX_INGEST_BYTES}-byte ingest cap",+ meta.len()+ );+ }+ fs::read_to_string(path).with_context(|| format!("Failed to read file: {path}"))+ }+/// Dispatch to the correct parser based on detected format./// For text formats, reads the file content first.pub fn parse_file(path: &str) -> Result<Vec<HashMap<String, String>>> {let format = Self::detect_format(path);match format {"csv" => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_csv(&content)}"json" => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_json(&content)}"ndjson" => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_ndjson(&content)}"yaml" => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_yaml(&content)}"xml" => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_xml(&content)}"xlsx" => Self::parse_xlsx_file(path),"parquet" => Self::parse_parquet_file(path),_ => {- let content = fs::read_to_string(path)- .with_context(|| format!("Failed to read file: {path}"))?;+ let content = Self::read_to_string_capped(path)?;Self::parse_csv(&content)}}diff --git a/src/plan.rs b/src/plan.rsindex 9488e67e..13b7bd58 100644--- a/src/plan.rs+++ b/src/plan.rs@@ -607,7 +607,7 @@ impl Planner {fn extract_iris(&self, store: &GraphStore, query: &str, var: &str) -> HashSet<String> {let mut set = HashSet::new();- if let Ok(json) = store.sparql_select(query)+ if let Ok(json) = store.sparql_select_union(query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array() {for row in results {@@ -626,7 +626,7 @@ impl Planner {{{ <{iri}> ?p ?o }} UNION {{ ?s <{iri}> ?o }} UNION {{ ?s ?p <{iri}> }} \}}");- if let Ok(json) = self.graph.sparql_select(&query)+ if let Ok(json) = self.graph.sparql_select_union(&query)&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json)&& let Some(results) = parsed["results"].as_array()&& let Some(first) = results.first()diff --git a/src/reason_incremental.rs b/src/reason_incremental.rsindex 6fa3efbb..fc7dcc02 100644--- a/src/reason_incremental.rs+++ b/src/reason_incremental.rs@@ -32,8 +32,22 @@ const RDFS_DOMAIN: &str = "<http://www.w3.org/2000/01/rdf-schema#domain>";const RDFS_RANGE: &str = "<http://www.w3.org/2000/01/rdf-schema#range>";const OWL_TRANSITIVE: &str = "<http://www.w3.org/2002/07/owl#TransitiveProperty>";const OWL_SYMMETRIC: &str = "<http://www.w3.org/2002/07/owl#SymmetricProperty>";+const OWL_FUNCTIONAL: &str = "<http://www.w3.org/2002/07/owl#FunctionalProperty>";+const OWL_INVERSE_FUNCTIONAL: &str = "<http://www.w3.org/2002/07/owl#InverseFunctionalProperty>";const OWL_INVERSE: &str = "<http://www.w3.org/2002/07/owl#inverseOf>";const OWL_SAMEAS: &str = "<http://www.w3.org/2002/07/owl#sameAs>";++/// Classes whose assertion `p rdf:type <class>` gives an EXISTING property a new+/// characteristic, changing what the store already entails over that property's+/// existing edges. Like the schema predicates, such a delta is not incremental:+/// the semi-naive loop only revisits triples reachable from the delta frontier,+/// so a newly-declared characteristic never reprocesses the edges it now governs.+const PROPERTY_CHARACTERISTICS: [&str; 4] = [+ OWL_TRANSITIVE,+ OWL_SYMMETRIC,+ OWL_FUNCTIONAL,+ OWL_INVERSE_FUNCTIONAL,+];const OWL_EQUIV_CLASS: &str = "<http://www.w3.org/2002/07/owl#equivalentClass>";const OWL_EQUIV_PROP: &str = "<http://www.w3.org/2002/07/owl#equivalentProperty>";@@ -64,8 +78,17 @@ struct Schema {transitive: HashSet<String>,symmetric: HashSet<String>,inverses: HashMap<String, Vec<String>>,+ /// True if any schema-reading query hit its row cap, so the schema this+ /// closure was computed against is incomplete and the derived closure may be+ /// missing consequences. Surfaced, never swallowed.+ truncated: bool,}+/// The row cap on every internally-authored scan here. A scan that returns+/// exactly this many rows is reported as possibly truncated rather than assumed+/// complete.+const SCAN_LIMIT: usize = 100_000;+fn close(direct: &HashMap<String, HashSet<String>>) -> HashMap<String, HashSet<String>> {let mut out: HashMap<String, HashSet<String>> = HashMap::new();for key in direct.keys() {@@ -94,11 +117,15 @@ impl Schema {/// most, so they are fetched directly and everything else is joined on/// demand.fn read(graph: &Arc<GraphStore>) -> anyhow::Result<Self> {+ // Any scan that returns exactly SCAN_LIMIT rows may have been cut. Record+ // it so the caller can report an incomplete closure instead of a wrong one+ // presented as complete.+ let truncated = std::cell::Cell::new(false);let pairs = |pred: &str| -> anyhow::Result<Vec<(String, String)>> {- let q = format!("SELECT ?s ?o WHERE {{ ?s {pred} ?o }} LIMIT 100000");+ let q = format!("SELECT ?s ?o WHERE {{ ?s {pred} ?o }} LIMIT {SCAN_LIMIT}");let raw = graph.sparql_select(&q)?;let parsed: serde_json::Value = serde_json::from_str(&raw)?;- Ok(parsed+ let rows: Vec<(String, String)> = parsed.get("results").and_then(|r| r.as_array()).map(|rows| {@@ -111,13 +138,17 @@ impl Schema {}).collect()})- .unwrap_or_default())+ .unwrap_or_default();+ if rows.len() >= SCAN_LIMIT {+ truncated.set(true);+ }+ Ok(rows)};let typed = |cls: &str| -> anyhow::Result<HashSet<String>> {- let q = format!("SELECT ?s WHERE {{ ?s {RDF_TYPE} {cls} }} LIMIT 100000");+ let q = format!("SELECT ?s WHERE {{ ?s {RDF_TYPE} {cls} }} LIMIT {SCAN_LIMIT}");let raw = graph.sparql_select(&q)?;let parsed: serde_json::Value = serde_json::from_str(&raw)?;- Ok(parsed+ let rows: HashSet<String> = parsed.get("results").and_then(|r| r.as_array()).map(|rows| {@@ -125,7 +156,11 @@ impl Schema {.filter_map(|r| Some(r.get("s")?.as_str()?.to_string())).collect()})- .unwrap_or_default())+ .unwrap_or_default();+ if rows.len() >= SCAN_LIMIT {+ truncated.set(true);+ }+ Ok(rows)};let mut sub_class: HashMap<String, HashSet<String>> = HashMap::new();@@ -168,6 +203,7 @@ impl Schema {transitive: typed(OWL_TRANSITIVE)?,symmetric: typed(OWL_SYMMETRIC)?,inverses,+ truncated: truncated.get(),})}}@@ -175,13 +211,20 @@ impl Schema {impl IncrementalReasoner {/// Whether an addition can be reasoned over incrementally, and why not.pub fn applies_to(delta: &[Triple]) -> Result<(), String> {- for (_, p, _) in delta {+ for (_, p, o) in delta {if SCHEMA_PREDICATES.contains(&p.as_str()) {return Err(format!("{p} is a schema axiom: it changes what the existing store entails, \so the closure must be recomputed with onto_reason"));}+ if p == RDF_TYPE && PROPERTY_CHARACTERISTICS.contains(&o.as_str()) {+ return Err(format!(+ "{o} declares a property characteristic: it changes what the existing \+ store entails over that property's existing edges, which the delta \+ cannot reach, so the closure must be recomputed with onto_reason"+ ));+ }}Ok(())}@@ -277,8 +320,10 @@ impl IncrementalReasoner {}}if p == OWL_SAMEAS && o.starts_with('<') {+ // The subject's existing triples are a question about the+ // whole store, so read every graph, not the default alone.let q = format!("SELECT ?p ?v WHERE {{ {s} ?p ?v }} LIMIT 10000");- if let Ok(raw) = graph.sparql_select(&q)+ if let Ok(raw) = graph.sparql_select_union(&q)&& let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw){{@@ -317,7 +362,7 @@ impl IncrementalReasoner {.map(|(s, p, o)| format!("{s} {p} {o}")).collect();- Ok(serde_json::json!({+ let mut out = serde_json::json!({"ok": true,"incremental": true,"delta_triples": delta.len(),@@ -325,8 +370,16 @@ impl IncrementalReasoner {"rounds": rounds,"materialized": materialize && !derived.is_empty(),"sample_inferences": sample,- })- .to_string())+ "complete": !schema.truncated,+ });+ if schema.truncated {+ out["warning"] = serde_json::Value::String(format!(+ "a schema scan hit the {SCAN_LIMIT}-row cap, so the schema this closure was \+ computed against is incomplete and consequences may be missing; run onto_reason \+ for a full pass"+ ));+ }+ Ok(out.to_string())}}@@ -348,3 +401,38 @@ pub fn parse_ntriples(text: &str) -> Vec<Triple> {}out}++#[cfg(test)]+mod tests {+ use super::*;++ fn t(s: &str, p: &str, o: &str) -> Triple {+ (s.to_string(), p.to_string(), o.to_string())+ }++ #[test]+ fn schema_axiom_deltas_are_refused() {+ // A new subClassOf changes what the existing store entails.+ assert!(IncrementalReasoner::applies_to(&[t("<x>", RDFS_SUBCLASS, "<y>")]).is_err());+ }++ #[test]+ fn a_new_property_characteristic_is_not_incremental() {+ // Declaring an EXISTING property transitive/symmetric/functional retroactively+ // changes what its existing edges entail; the delta frontier cannot reach them,+ // so this must route to a full onto_reason rather than silently under-derive.+ for c in [OWL_TRANSITIVE, OWL_SYMMETRIC, OWL_FUNCTIONAL, OWL_INVERSE_FUNCTIONAL] {+ assert!(+ IncrementalReasoner::applies_to(&[t("<p>", RDF_TYPE, c)]).is_err(),+ "declaring {c} must be refused as non-incremental"+ );+ }+ }++ #[test]+ fn an_ordinary_type_assertion_is_still_incremental() {+ // A normal individual typing is exactly what incremental reasoning is for.+ assert!(IncrementalReasoner::applies_to(&[t("<a>", RDF_TYPE, "<C>")]).is_ok());+ assert!(IncrementalReasoner::applies_to(&[t("<a>", "<http://ex/knows>", "<b>")]).is_ok());+ }+}diff --git a/src/registry.rs b/src/registry.rsindex fe7bfe50..8c0d7fd7 100644--- a/src/registry.rs+++ b/src/registry.rs@@ -234,10 +234,23 @@ impl OntologyRegistry {}}+ // A source change discards in-memory mutations by design, so the stale+ // eviction snapshot must go with them.+ if refreshed {+ let _ = std::fs::remove_file(Self::evict_snapshot_path(&cache_path));+ }+if needs_reload && !refreshed {- // Reload from N-Triples cache; fall back to source if cache file- // is missing for some reason.- if cache_path.exists() {+ // Prefer the eviction snapshot: it holds the live state at eviction time+ // (mutations included), where the compile cache holds only the source's+ // compiled form. Consume it so it cannot go stale against a later load.+ let evict_path = Self::evict_snapshot_path(&cache_path);+ if evict_path.exists() {+ let quads = std::fs::read_to_string(&evict_path)?;+ self.graph.clear()?;+ self.graph.load_nquads(&quads)?;+ let _ = std::fs::remove_file(&evict_path);+ } else if cache_path.exists() {let quads = std::fs::read_to_string(&cache_path)?;self.graph.clear()?;self.graph.load_nquads(&quads)?;@@ -275,7 +288,27 @@ impl OntologyRegistry {}let elapsed = entry.last_access.lock().unwrap().elapsed();if elapsed >= ttl {- // Clear the in-memory store to release memory; cache file remains.+ // Write the LIVE in-memory state to an eviction snapshot before+ // clearing. The compile cache holds only the source's compiled form, so+ // reloading from it after eviction silently discards everything derived+ // in memory since load: materialised reasoning, SPARQL UPDATE inserts,+ // onto_ingest / onto_extend output. Serialising to N-Quads captures named+ // graphs too, and ensure_loaded prefers this snapshot when restoring.+ let evict_path = Self::evict_snapshot_path(&entry.cache_path);+ match self.graph.serialize("nquads") {+ Ok(quads) => {+ if let Err(e) = CacheManager::atomic_write(&evict_path, &quads) {+ // A snapshot we cannot write must not cause silent data loss:+ // leave the store in memory and try again on the next tick.+ eprintln!("eviction snapshot write failed, not evicting: {e}");+ return Ok(false);+ }+ }+ Err(e) => {+ eprintln!("eviction snapshot serialise failed, not evicting: {e}");+ return Ok(false);+ }+ }self.graph.clear()?;*entry.evicted.lock().unwrap() = true;return Ok(true);@@ -283,6 +316,20 @@ impl OntologyRegistry {Ok(false)}+ /// Path of the eviction snapshot beside an entry's compile cache. Kept+ /// distinct from the compile cache so a later plain `load_file` of the same+ /// source never mistakes in-memory mutations for the source's compiled form.+ fn evict_snapshot_path(cache_path: &Path) -> PathBuf {+ let mut p = cache_path.to_path_buf();+ let ext = p+ .extension()+ .and_then(|x| x.to_str())+ .map(|x| format!("{x}.evicted"))+ .unwrap_or_else(|| "evicted".to_string());+ p.set_extension(ext);+ p+ }+/// Manually unload the active ontology (clear graph + drop active slot)./// The cache file is preserved unless `delete_cache` is true.pub fn unload(&self, delete_cache: bool) -> Result<Option<String>> {diff --git a/src/server.rs b/src/server.rsindex e6b9be08..9e9bdb84 100644--- a/src/server.rs+++ b/src/server.rs@@ -574,21 +574,21 @@ impl OpenOntologiesServer {match GraphStore::fetch_sparql_auth(&input.url, query, &auth).await {Ok(content) => {match self.graph.load_turtle(&content, None) {- Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"source":"{}"}}"#, count, input.url),- Err(e) => format!(r#"{{"error":"Parse error: {}"}}"#, e),+ Ok(count) => serde_json::json!({"ok": true, "triples_loaded": count, "source": input.url}).to_string(),+ Err(e) => serde_json::json!({"error": format!("Parse error: {e}")}).to_string(),}}- Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),}} else {match GraphStore::fetch_url(&input.url).await {Ok(content) => {match self.graph.load_turtle(&content, None) {- Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"source":"{}"}}"#, count, input.url),- Err(e) => format!(r#"{{"error":"Parse error: {}"}}"#, e),+ Ok(count) => serde_json::json!({"ok": true, "triples_loaded": count, "source": input.url}).to_string(),+ Err(e) => serde_json::json!({"error": format!("Parse error: {e}")}).to_string(),}}- Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),}}}@@ -600,11 +600,11 @@ impl OpenOntologiesServer {match self.graph.serialize("ntriples") {Ok(content) => {match GraphStore::push_sparql_auth(&input.endpoint, &content, input.graph.as_deref(), &auth).await {- Ok(msg) => format!(r#"{{"ok":true,"message":"{}"}}"#, msg),- Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ Ok(msg) => serde_json::json!({"ok": true, "message": msg}).to_string(),+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),}}- Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ Err(e) => serde_json::json!({"error": e.to_string()}).to_string(),}}@@ -1420,7 +1420,7 @@ impl OpenOntologiesServer {#[tool(name = "onto_shape_induce", description = "Kastor-style data-driven SHACL shape induction (#36, K-CAP 2025). For each property subset up to `max_size`, compute support (fraction of class instances having all properties) and confidence (fraction of any-instances-with-properties that are class members). Returns the top-k candidates ranked by `support × confidence`, each carrying a ready-to-use SHACL NodeShape Turtle block. Filter via `min_support` (default 0.1) and `min_confidence` (default 0.5).")]async fn onto_shape_induce(&self, Parameters(input): Parameters<OntoShapeInduceInput>) -> String {- let max = input.max_size.unwrap_or(3);+ let max = input.max_size.unwrap_or(3).min(8); // hard cap: guards the combinatorial blow-up at the tool boundarylet top_k = input.top_k.unwrap_or(10);let min_support = input.min_support.unwrap_or(0.1);let min_confidence = input.min_confidence.unwrap_or(0.5);@@ -1433,7 +1433,7 @@ impl OpenOntologiesServer {#[tool(name = "onto_shape_combinatorics", description = "Enumerate the property-combination lattice for a class (#36, K-CAP 2025 Kastor). Returns subsets of the class's rdfs:domain properties up to `max_size` (default 3). Used by shape-induction algorithms to enumerate candidate SHACL shapes from data.")]async fn onto_shape_combinatorics(&self, Parameters(input): Parameters<OntoShapeCombinatoricsInput>) -> String {- let max = input.max_size.unwrap_or(3);+ let max = input.max_size.unwrap_or(3).min(8); // hard cap: guards the combinatorial blow-up at the tool boundarymatch crate::shape_combinatorics::enumerate(&self.graph, &input.class_iri, max) {Ok(r) => serde_json::to_string(&r).unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),@@ -2459,7 +2459,9 @@ impl OpenOntologiesServer {}"#;- let result = match self.graph.sparql_select(classes_query) {+ // Enumerating the store's classes is a question about the whole store,+ // so read the union of all graphs, not the default graph alone.+ let result = match self.graph.sparql_select_union(classes_query) {Ok(r) => r,Err(e) => return format!(r#"{{"error":"{}"}}"#, e),};diff --git a/src/shacl.rs b/src/shacl.rsindex 3f42d99c..8032caec 100644--- a/src/shacl.rs+++ b/src/shacl.rs@@ -535,15 +535,20 @@ impl ShaclValidator {}// sh:minInclusive, sh:maxInclusive, sh:minExclusive and- // sh:maxExclusive. Each value node on the path must satisfy the- // comparison; a value that fails is one violation. The bound- // arrives from the shapes store in N-Triples form, which is- // valid SPARQL as-is, exactly as for sh:hasValue above.- for (key, op, label) in [- ("minInclusive", "<", "sh:minInclusive"),- ("maxInclusive", ">", "sh:maxInclusive"),- ("minExclusive", "<=", "sh:minExclusive"),- ("maxExclusive", ">=", "sh:maxExclusive"),+ // sh:maxExclusive. SHACL 4.6.1/4.6.2: a value node is a violation+ // wherever the SATISFYING comparison does not return true. A type+ // error (a string or date against a numeric bound) and NaN both+ // "do not return true", so they are violations, not passes. We flag+ // on the negated satisfying comparison wrapped in COALESCE(_, false):+ // an errored comparison collapses to false, whose negation flags it,+ // instead of an affirmative FILTER silently dropping the row. The+ // bound arrives from the shapes store in N-Triples form, valid SPARQL+ // as-is, exactly as for sh:hasValue above.+ for (key, satisfy_op, label) in [+ ("minInclusive", ">=", "sh:minInclusive"),+ ("maxInclusive", "<=", "sh:maxInclusive"),+ ("minExclusive", ">", "sh:minExclusive"),+ ("maxExclusive", "<", "sh:maxExclusive"),] {if let Some(bound_raw) = prop.get(key) {let bound = bound_raw.trim();@@ -551,7 +556,7 @@ impl ShaclValidator {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 {op} {bound})+ FILTER(!COALESCE(?val {satisfy_op} {bound}, false))}}"#);let results = graph_sparql_select(graph, &query)?;diff --git a/src/shape_combinatorics.rs b/src/shape_combinatorics.rsindex ed09df8f..0f3f361d 100644--- a/src/shape_combinatorics.rs+++ b/src/shape_combinatorics.rs@@ -83,6 +83,24 @@ pub fn enumerate(graph: &Arc<GraphStore>, class_iri: &str, max_size: usize) -> alet k = props.len();let cap = max_size.min(k);++ // Guard the combinatorial blow-up BEFORE materialising anything. max_size is a+ // caller-supplied usize with no upper bound, and a moderately wide class makes+ // the subset count astronomical (C(100, 50) ≈ 1e29), each subset an allocated+ // Vec — an out-of-memory kill from one tool call. Sum the binomials and refuse+ // past a budget instead.+ const SUBSET_BUDGET: u64 = 200_000;+ let mut estimate: u64 = 0;+ for size in 1..=cap {+ estimate = estimate.saturating_add(binomial(k as u64, size as u64));+ if estimate > SUBSET_BUDGET {+ anyhow::bail!(+ "shape enumeration for {class_iri} would produce more than {SUBSET_BUDGET} \+ subsets ({k} properties up to size {cap}); lower max_size"+ );+ }+ }+let mut subsets: Vec<Vec<String>> = vec![Vec::new()];for size in 1..=cap {@@ -103,6 +121,23 @@ pub fn enumerate(graph: &Arc<GraphStore>, class_iri: &str, max_size: usize) -> a})}+/// C(n, k) with a u128 intermediate, saturating to u64::MAX so an enormous+/// binomial cannot overflow the budget check that guards enumeration.+fn binomial(n: u64, k: u64) -> u64 {+ if k > n {+ return 0;+ }+ let k = k.min(n - k);+ let mut result: u128 = 1;+ for i in 1..=k {+ result = result.saturating_mul((n - k + i) as u128) / (i as u128);+ if result > u64::MAX as u128 {+ return u64::MAX;+ }+ }+ result as u64+}+/// Enumerate k-subsets of `items` in lexicographic order. Iterative/// implementation; no recursion-depth risk for k up to a handful.fn combinations(items: &[String], k: usize) -> Vec<Vec<String>> {@@ -314,6 +349,41 @@ mod tests {g}+ #[test]+ fn binomial_is_exact_and_saturates() {+ assert_eq!(binomial(3, 2), 3);+ assert_eq!(binomial(100, 2), 4950);+ assert_eq!(binomial(52, 5), 2_598_960);+ assert_eq!(binomial(5, 9), 0);+ // A huge central binomial saturates rather than overflowing.+ assert_eq!(binomial(100, 50), u64::MAX);+ }++ #[test]+ fn enumerate_refuses_a_combinatorial_blowup() {+ // A class wide enough that the requested max_size explodes the lattice.+ let g = Arc::new(GraphStore::new());+ let mut ttl = String::from(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://ex.org/> .\n ex:Wide a owl:Class .\n",+ );+ for i in 0..40 {+ ttl.push_str(&format!(+ "ex:p{i} a owl:DatatypeProperty ; rdfs:domain ex:Wide .\n"+ ));+ }+ g.load_turtle(&ttl, None).unwrap();+ // C(40,20) alone is ~1.4e11: must refuse instead of allocating it.+ let err = enumerate(&g, "http://ex.org/Wide", 20).unwrap_err();+ assert!(+ err.to_string().contains("more than"),+ "must refuse the blow-up, got: {err}"+ );+ // A small max_size on the same wide class is fine.+ assert!(enumerate(&g, "http://ex.org/Wide", 2).is_ok());+ }+#[test]fn enumerate_full_lattice_for_three_properties_max_3() {let g = graph_with_properties();diff --git a/src/structembed.rs b/src/structembed.rsindex 991790a9..6610cd76 100644--- a/src/structembed.rs+++ b/src/structembed.rs@@ -30,7 +30,8 @@ impl StructuralTrainer {}"#;- let result = match store.sparql_select(query) {+ // The hierarchy is a question about the whole store, so read every graph.+ let result = match store.sparql_select_union(query) {Ok(r) => r,Err(_) => return Vec::new(),};@@ -61,7 +62,8 @@ impl StructuralTrainer {}"#;- let result = match store.sparql_select(query) {+ // Class enumeration is a question about the whole store, so read every graph.+ let result = match store.sparql_select_union(query) {Ok(r) => r,Err(_) => return Vec::new(),};diff --git a/src/support.rs b/src/support.rsindex a944f12b..e2f8461f 100644--- a/src/support.rs+++ b/src/support.rs@@ -98,7 +98,11 @@ impl SupportChecker {}fn rows(&self, query: &str) -> anyhow::Result<Vec<serde_json::Value>> {- let raw = self.graph.sparql_select(query)?;+ // Every query here is an internally-authored question about the whole+ // store (which claims cite no source, the source-of map, labels), so it+ // must read the union of all graphs, not the default graph alone. See+ // GraphStore::sparql_select.+ let raw = self.graph.sparql_select_union(query)?;let parsed: serde_json::Value = serde_json::from_str(&raw)?;Ok(parsed.get("results")diff --git a/src/tableaux.rs b/src/tableaux.rsindex ad890d1c..6af00c65 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -285,6 +285,7 @@ impl OwlParser {let mut inv_functional_roles: HashSet<u32> = HashSet::new();let mut object_properties: HashSet<u32> = HashSet::new();let mut individual_types: HashMap<u32, HashSet<u32>> = HashMap::new();+ let mut individual_anon_types: HashMap<u32, Vec<Concept>> = HashMap::new();let mut role_assertions: Vec<(u32, u32, u32)> = Vec::new();let mut data_assertions: Vec<(u32, u32, u32)> = Vec::new();@@ -379,6 +380,23 @@ impl OwlParser {inverse_roles.insert(b, a);}+ // owl:{Transitive,Symmetric,Functional,InverseFunctional}Property and any+ // property named by owl:inverseOf are object properties by OWL semantics,+ // whether or not they are also explicitly typed owl:ObjectProperty. Without+ // this, a role declared only by its characteristic has its ABox role+ // assertions dropped at edge-building time and the characteristic is inert.+ for &r in transitive_roles+ .iter()+ .chain(functional_roles.iter())+ .chain(inv_functional_roles.iter())+ {+ object_properties.insert(r);+ }+ for (&a, &b) in &inverse_roles {+ object_properties.insert(a);+ object_properties.insert(b);+ }+// Collect sub-property relationslet subprop_pairs: Vec<(String, String)> = self.index@@ -526,7 +544,10 @@ impl OwlParser {named_classes.contains(&id)}});- if explicit || typed_by_known_class {+ // An individual typed only by an anonymous class expression is still an+ // individual, and its constraint still has to be checked.+ let typed_by_anon_class = types.iter().any(|t| t.starts_with("_:"));+ if explicit || typed_by_known_class || typed_by_anon_class {individual_subjects.push(subject.clone());}}@@ -535,6 +556,14 @@ impl OwlParser {let ind_id = self.interner.intern(ind_str);let types = self.index.objects(ind_str, RDF_TYPE);for t in &types {+ if t.starts_with("_:") {+ // Anonymous class expression: parse it and attach the concept+ // so the constraint reaches the tableau. A blank node is never a+ // named class, so this is disjoint from the branch below.+ let concept = self.parse_class_expr(t).to_nnf();+ individual_anon_types.entry(ind_id).or_default().push(concept);+ continue;+ }let t_id = self.interner.intern(t);if named_classes.contains(&t_id) {individual_types.entry(ind_id).or_default().insert(t_id);@@ -581,6 +610,7 @@ impl OwlParser {functional_roles,inv_functional_roles,individual_types,+ individual_anon_types,role_assertions,data_assertions,definitions,@@ -722,6 +752,12 @@ struct ParseResult {functional_roles: HashSet<u32>,inv_functional_roles: HashSet<u32>,individual_types: HashMap<u32, HashSet<u32>>,+ /// Individuals typed directly by an ANONYMOUS class expression+ /// (`:a rdf:type [ owl:Restriction … ]`, an intersection/union/complement).+ /// These carry no named-class id, so they cannot live in `individual_types`,+ /// but the constraint they impose is real and an inconsistency arising from+ /// it must be found rather than silently dropped.+ individual_anon_types: HashMap<u32, Vec<Concept>>,role_assertions: Vec<(u32, u32, u32)>,/// Datatype-property assertions, for realization only; never tableau edges.data_assertions: Vec<(u32, u32, u32)>,@@ -1258,7 +1294,18 @@ impl Tableau {}).count();if matching < n {+ // Guard EVERY iteration: n comes from an owl:minCardinality+ // literal with no magnitude cap, so an ingested value in the+ // billions would allocate that many nodes before the outer+ // fixpoint check (which only runs between passes) ever sees+ // them. Hitting the node budget is not a clash; record it and+ // unwind so the caller reports Unknown, not a fabricated answer.+ let max_nodes = crate::runtime::tableaux_max_nodes();for _ in 0..(n - matching) {+ if self.nodes.len() > max_nodes || self.budget.expired() {+ self.budget.exhausted = true;+ return false;+ }self.create_successor(nid, role, filler.clone());}changed = true;@@ -1567,6 +1614,7 @@ pub struct DlReasoner {thing_id: u32,nothing_id: u32,individual_types: HashMap<u32, HashSet<u32>>,+ individual_anon_types: HashMap<u32, Vec<Concept>>,role_assertions: Vec<(u32, u32, u32)>,data_assertions: Vec<(u32, u32, u32)>,definitions: HashMap<u32, Concept>,@@ -1626,6 +1674,7 @@ impl DlReasoner {thing_id: result.thing_id,nothing_id: result.nothing_id,individual_types: result.individual_types,+ individual_anon_types: result.individual_anon_types,role_assertions: result.role_assertions,data_assertions: result.data_assertions,definitions: result.definitions,@@ -2001,7 +2050,7 @@ impl DlReasoner {}pub fn check_abox(&self) -> ABoxResult {- if self.individual_types.is_empty() {+ if self.individual_types.is_empty() && self.individual_anon_types.is_empty() {return ABoxResult {consistent: true,undecided: false,@@ -2017,12 +2066,31 @@ impl DlReasoner {let mut tableau = Tableau::with_deadline(Arc::clone(&self.tbox), self.deadline);let mut ind_to_node: HashMap<u32, u32> = HashMap::new();- // Create nodes for each individual- for (&ind, types) in &self.individual_types {+ // Create nodes for each individual carrying a named-class OR an anonymous+ // class type. An individual typed only by an anonymous class expression+ // (`:a rdf:type [ owl:Restriction … ]`) has no entry in individual_types,+ // and dropping it here is how a restriction-borne inconsistency was missed.+ let mut all_individuals: Vec<u32> = self.individual_types.keys().copied().collect();+ for &ind in self.individual_anon_types.keys() {+ if !self.individual_types.contains_key(&ind) {+ all_individuals.push(ind);+ }+ }+ all_individuals.sort_unstable();+ let individuals_checked = all_individuals.len();+ for ind in all_individuals {let node_id = tableau.fresh_node(None, None);ind_to_node.insert(ind, node_id);- for &cls in types {- tableau.add_label(node_id, Concept::Atom(cls));+ if let Some(types) = self.individual_types.get(&ind) {+ for &cls in types {+ tableau.add_label(node_id, Concept::Atom(cls));+ }+ }+ // Anonymous class expressions the individual is directly typed by.+ if let Some(anon) = self.individual_anon_types.get(&ind) {+ for concept in anon {+ tableau.add_label(node_id, concept.clone());+ }}// The nominal {a} is approximated as the atomic concept named by a's own IRI// (see RawConcept::Named). That approximation only works if a's node actually@@ -2055,7 +2123,13 @@ impl DlReasoner {tableau.add_label(node_id, Concept::Atom(b));}- // Add role assertions as edges+ // Add role assertions as edges. An asserted edge a R b also means b has an+ // R-inverse edge to a: without it, a ForAll or cardinality constraint on b+ // never propagates backward across the edge, and an inconsistency reachable+ // only through the inverse (or, since a symmetric role is its own inverse in+ // `inverse_roles`, a symmetric) role is silently missed. Unlike the tree+ // tableau, ABox individuals form an arbitrary graph, so the parent back-link+ // successors() uses cannot stand in for the inverse neighbour. Materialise it.for &(a, r, b) in &self.role_assertions {if let (Some(&a_node), Some(&b_node)) = (ind_to_node.get(&a), ind_to_node.get(&b)) {tableau@@ -2066,6 +2140,16 @@ impl DlReasoner {.entry(r).or_default().insert(b_node);+ if let Some(&r_inv) = tableau.tbox.inverse_roles.get(&r) {+ tableau+ .nodes+ .get_mut(&b_node)+ .unwrap()+ .edges+ .entry(r_inv)+ .or_default()+ .insert(a_node);+ }}}@@ -2103,7 +2187,7 @@ impl DlReasoner {ABoxResult {consistent,undecided: abox_undecided,- individuals_checked: self.individual_types.len(),+ individuals_checked,inferred_types: inferred,}}diff --git a/src/temporal.rs b/src/temporal.rsindex 35877166..58a7431c 100644--- a/src/temporal.rs+++ b/src/temporal.rs@@ -1593,10 +1593,28 @@ impl Temporal {/// dropped before returning, so an untruncated scan yields exactly the/// rows it yielded in 1.2.0.fn rows(&self, query: &str, cap: usize) -> anyhow::Result<Scan> {+ self.rows_with(query, cap, false)+ }++ /// As `rows`, but evaluates against the union of all graphs so that a query's+ /// UNGUARDED triple patterns (those not inside a `GRAPH` block) see every named+ /// graph rather than the default graph alone. `GRAPH ?g` patterns still range+ /// over named graphs under the union default, so a query that mixes graph-scoped+ /// and schema-level patterns keeps the first and widens the second. Used by+ /// `conflicts`, whose disjointWith/subClassOf* schema half is unguarded and may+ /// live in a named graph.+ fn rows_union(&self, query: &str, cap: usize) -> anyhow::Result<Scan> {+ self.rows_with(query, cap, true)+ }++ fn rows_with(&self, query: &str, cap: usize, union: bool) -> anyhow::Result<Scan> {let probe = cap.saturating_add(1);- let raw = self- .graph- .sparql_select(&format!("{query} LIMIT {probe}"))?;+ let limited = format!("{query} LIMIT {probe}");+ let raw = if union {+ self.graph.sparql_select_union(&limited)?+ } else {+ self.graph.sparql_select(&limited)?+ };let parsed: serde_json::Value = serde_json::from_str(&raw)?;let mut rows: Vec<serde_json::Value> = parsed.get("results")@@ -1630,7 +1648,7 @@ impl Temporal {UNION {{ ?g <{NS}recordedAt> ?rec }} \UNION {{ ?g <{NS}recordedUntil> ?until }} \UNION {{ ?g <{NS}supersedes> ?sup }} \- UNION {{ ?g <{NS}retracts> ?ret }} }}"+ UNION {{ ?g <{NS}retracts> ?ret }} }} ORDER BY ?g");let scan = self.rows(&query, self.limits.validity_scan)?;// 1.2.0 ASSIGNED each field here, so the last row of the UNION won@@ -1670,8 +1688,10 @@ impl Temporal {/// Named graphs holding assertions, whether or not they are described.fn all_graphs(&self) -> anyhow::Result<(BTreeSet<String>, Capped)> {+ // ORDER BY so that, if the scan is truncated at the cap, which graphs are+ // dropped is deterministic rather than dependent on hash iteration order.let scan = self.rows(- "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }",+ "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } } ORDER BY ?g",self.limits.graph_scan,)?;let graphs = scan@@ -1903,13 +1923,23 @@ impl Temporal {.map(|g| format!("<{g}>")).collect::<Vec<_>>().join(" ");+ // FROM NAMED confines the dataset to exactly the in-scope graphs. The body is+ // the caller-supplied pattern, spliced as text; without this a crafted pattern+ // could close the GRAPH block and open its own `GRAPH <out-of-scope>` (or a+ // top-level group over the default graph), defeating temporal scope. With only+ // FROM NAMED and no FROM, a graph the caller names that is not in scope has no+ // triples in the dataset and the default graph is empty, so neither escape+ // reads anything. The pattern is wrapped in its own braces rather than having a+ // level stripped, so a legitimate top-level `{…} UNION {…}` stays well-formed.+ let from_named = graphs+ .iter()+ .map(|g| format!("FROM NAMED <{g}>"))+ .collect::<Vec<_>>()+ .join(" ");let body = pattern.trim();- let body = body- .strip_prefix('{')- .and_then(|b| b.strip_suffix('}'))- .unwrap_or(body);- let wrapped =- format!("SELECT * WHERE {{ VALUES ?__g {{ {values} }} GRAPH ?__g {{ {body} }} }}");+ let wrapped = format!(+ "SELECT * {from_named} WHERE {{ VALUES ?__g {{ {values} }} GRAPH ?__g {{ {body} }} }}"+ );let scan = self.rows(&wrapped, self.limits.query_rows)?;cuts.extend(scan.capped.report("query_rows",@@ -1977,7 +2007,13 @@ impl Temporal {/// specially here.pub fn conflicts(&self) -> anyhow::Result<String> {let (validities, validity_scan, _lineage) = self.validities()?;- let scan = self.rows(+ // Union scope: the ABox halves stay graph-scoped via GRAPH ?ga/?gb, while+ // the disjointWith/subClassOf* schema half is unguarded and must see every+ // graph. Under the plain default dataset it read the default graph alone,+ // so a store whose schema sits in a named graph (the normal per-version+ // temporal layout, or any TriG/N-Quads schema graph) formed no pair and+ // returned a clean zero contradictions.+ let scan = self.rows_union("PREFIX owl: <http://www.w3.org/2002/07/owl#> \PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \SELECT DISTINCT ?s ?a ?b ?ga ?gb WHERE { \@@ -2234,6 +2270,58 @@ ex:g_after { ex:X a ex:Suspension . }serde_json::from_str(&raw).expect("tool output is JSON")}+ /// A crafted query_at pattern must not escape temporal scope. g_live is valid+ /// at the query instant; g_expired stopped being valid in 2020. A pattern that+ /// closes the GRAPH block and opens `GRAPH <g_expired>` (or a top-level group)+ /// must read nothing from out-of-scope graphs, and a legitimate top-level UNION+ /// must still parse.+ const SCOPE_ESCAPE_FIXTURE: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .+ex:g_live { ex:live_secret ex:says "IN_SCOPE" . }+ex:g_expired { ex:expired_secret ex:says "OUT_OF_SCOPE" . }+{+ ex:g_live t:validFrom "2020-01-01" .+ ex:g_expired t:validFrom "2010-01-01" ; t:validTo "2020-01-01" .+}+"#;++ #[test]+ fn query_at_pattern_cannot_escape_temporal_scope() {+ let t = Temporal::new(store(SCOPE_ESCAPE_FIXTURE));++ let benign = json(t.query_at("{ ?s ?p ?o }", Some("2025-01-01"), None).unwrap());+ let benign_str = benign.to_string();+ assert!(benign_str.contains("IN_SCOPE"), "control: g_live must be in scope: {benign}");+ assert!(!benign_str.contains("OUT_OF_SCOPE"), "control: g_expired excluded at 2025: {benign}");++ // Escape attempt: close GRAPH ?__g, open an explicit out-of-scope GRAPH.+ let escaped = json(+ t.query_at(+ "{ ?s ?p ?o } GRAPH <http://example.org/g_expired> { ?a ?b ?c }",+ Some("2025-01-01"),+ None,+ )+ .unwrap(),+ );+ assert!(+ !escaped.to_string().contains("OUT_OF_SCOPE"),+ "SCOPE ESCAPE: an out-of-scope graph was read through a crafted pattern: {escaped}"+ );++ // A legitimate top-level UNION must remain valid (no one-level brace strip).+ let unioned = json(+ t.query_at(+ "{ ?s ?p ?o } UNION { ?s ?p ?o }",+ Some("2025-01-01"),+ None,+ )+ .unwrap(),+ );+ assert_eq!(unioned["ok"], true, "a top-level UNION must parse: {unioned}");+ assert!(unioned.to_string().contains("IN_SCOPE"), "union must still return in-scope rows: {unioned}");+ }+/// Two raw valid bounds, as the validity scan would hand them over.fn valid(from: &str, to: &str) -> Bounds {Bounds {@@ -2615,6 +2703,37 @@ ex:g1 { ex:X ex:p ex:one . });}+ /// A live contradiction whose disjointWith/subClassOf schema lives in a NAMED+ /// graph, the normal layout for per-version temporal data. The ABox halves of+ /// the conflicts query are GRAPH-scoped, but the TBox halves were unguarded and+ /// so read the default graph alone: with the schema in a named graph the pair+ /// never formed and the tool returned a clean zero. Overlapping periods, disjoint+ /// types, no supersedes link, so exactly one contradiction.+ const NAMED_SCHEMA_CONFLICT: &str = r#"+@prefix ex: <http://example.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g_before { ex:X a ex:Adherent . ex:Adherent owl:disjointWith ex:Suspension . }+ex:g_after { ex:X a ex:Suspension . }++{+ ex:g_before t:validFrom "2024-01-01" ; t:validTo "2026-05-01" .+ ex:g_after t:validFrom "2025-01-01" .+}+"#;++ #[test]+ fn conflicts_reads_disjointness_schema_from_a_named_graph() {+ let out = json(Temporal::new(store(NAMED_SCHEMA_CONFLICT)).conflicts().unwrap());+ assert_eq!(+ out["contradiction_count"], 1,+ "a live contradiction with named-graph schema must be found, not silently zero: {out}"+ );+ assert_eq!(out["superseded_count"], 0, "{out}");+ assert_eq!(out["complete"], true, "{out}");+ }+/// The pair scan is the mild cap: fewer pairs examined, no claim turned/// upside down, so it is reported without the warning.#[test]diff --git a/tests/cache_management_test.rs b/tests/cache_management_test.rsindex cc3f14cf..156aeebf 100644--- a/tests/cache_management_test.rs+++ b/tests/cache_management_test.rs@@ -346,3 +346,48 @@ fn recompile_named_garbage_collects_old_cache_file_when_sha_changes() {"old cache file should be cleaned up");assert!(std::path::Path::new(&new_a_cache).exists());}++#[test]+fn eviction_preserves_in_memory_mutations() {+ // Idle-TTL eviction must not discard state derived in memory since load+ // (materialised reasoning, SPARQL UPDATE, ingest). Before the fix it cleared+ // the store and ensure_loaded reloaded the stale source compile cache.+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("a.ttl");+ std::fs::write(&path, TTL_A).unwrap();+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();+ let graph = Arc::new(GraphStore::new());+ let graph_ref = Arc::clone(&graph);+ let cfg = CacheConfig {+ enabled: true,+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),+ idle_ttl_secs: 1,+ evictor_interval_secs: 30,+ auto_refresh: false,+ hash_prefix_bytes: 64 * 1024,+ };+ let reg = OntologyRegistry::new(graph, db, cfg).unwrap();+ reg.load_file(path.to_str().unwrap(), LoadOptions::default()).unwrap();+ let base = graph_ref.triple_count();++ // Mutate the live store the way onto_reason(materialize)/onto_ingest would.+ graph_ref+ .load_turtle(+ "@prefix ex: <http://example.org/> . ex:derived a ex:Inferred .",+ None,+ )+ .unwrap();+ let mutated = graph_ref.triple_count();+ assert_eq!(mutated, base + 1, "the mutation added one triple");++ sleep(Duration::from_millis(1100));+ assert!(reg.evictor_tick().unwrap(), "idle past TTL, must evict");+ assert_eq!(graph_ref.triple_count(), 0, "evicted from memory");++ reg.ensure_loaded().unwrap();+ assert_eq!(+ graph_ref.triple_count(),+ mutated,+ "the in-memory mutation must survive eviction, not be lost to the source cache"+ );+}diff --git a/tests/graph_remote_test.rs b/tests/graph_remote_test.rsindex 5bd2fcbe..4aeda762 100644--- a/tests/graph_remote_test.rs+++ b/tests/graph_remote_test.rs@@ -39,3 +39,25 @@ fn test_load_ntriples() {assert!(result.is_ok());assert_eq!(store.triple_count(), 1);}++// Red-team #7: the onto_push graph-name argument is spliced into a remote SPARQL+// UPDATE. A malicious value must be rejected as a bad IRI BEFORE any request, so+// it can never break out of the GRAPH clause into a DROP ALL.+#[tokio::test]+async fn push_rejects_a_graph_name_that_would_inject_an_update() {+ use open_ontologies::graph::{GraphStore, SparqlAuth};+ let auth = SparqlAuth::from_parts(None, None, None);+ let evil = "x> {} }; DROP ALL ; INSERT DATA { GRAPH <x";+ let result = GraphStore::push_sparql_auth(+ "http://localhost:1/never-reached",+ "<http://ex/s> <http://ex/p> <http://ex/o> .",+ Some(evil),+ &auth,+ )+ .await;+ let err = result.expect_err("a malicious graph name must be rejected");+ assert!(+ err.to_string().contains("not a valid absolute IRI"),+ "must fail IRI validation before any network I/O, got: {err}"+ );+}diff --git a/tests/reasoner_soundness_test.rs b/tests/reasoner_soundness_test.rsindex 7d8a961c..1267d700 100644--- a/tests/reasoner_soundness_test.rs+++ b/tests/reasoner_soundness_test.rs@@ -190,3 +190,127 @@ fn incomplete_runs_are_declared_in_the_output() {tell a proof from a timeout. Full result: {result}");}++// ── Inverse and symmetric roles over asserted ABox edges ────────────────────+//+// An asserted role edge a R b means b has an R-inverse edge to a. A ForAll or+// cardinality constraint that must propagate BACKWARD across the edge relies on+// that. check_abox installed asserted edges one-directional with no inverse+// neighbour, so an inconsistency reachable only through an inverse (or, since a+// symmetric role is its own inverse, a symmetric) role was silently missed and+// the KB reported consistent. The direct-role control isolates the inverse+// handling as the sole cause.+const RS_PREFIXES: &str = "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://example.org/> .\n\+ ex:D a owl:Class . ex:E a owl:Class . ex:D owl:disjointWith ex:E .\n\+ ex:r a owl:ObjectProperty . ex:s a owl:ObjectProperty ; owl:inverseOf ex:r .\n";++fn is_consistent(body: &str) -> bool {+ classify(&format!("{RS_PREFIXES}{body}"))+ .get("consistent")+ .and_then(|v| v.as_bool())+ .expect("consistent must be present")+}++#[test]+fn direct_role_clash_is_detected_control() {+ // B forces its r-fillers to be D; b is E; D disjoint E. a r b => clash on b.+ let inconsistent = !is_consistent(+ "ex:B a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:allValuesFrom ex:D ] .\n\+ ex:a a ex:B ; ex:r ex:b .\n\+ ex:b a ex:E .\n",+ );+ assert!(inconsistent, "a direct-role clash must be detected, or the probe below proves nothing");+}++#[test]+fn inverse_role_clash_is_detected() {+ // Same clash but reachable only through the inverse role s = r-inverse.+ // b:B forces its s-fillers to be D; a r b => b s a => a:D; a also E => clash.+ let inconsistent = !is_consistent(+ "ex:B a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:s ; owl:allValuesFrom ex:D ] .\n\+ ex:b a ex:B .\n\+ ex:a a ex:E ; ex:unused ex:noop .\n\+ ex:a ex:r ex:b .\n",+ );+ assert!(inconsistent, "an inconsistency reachable only through an inverse role must be detected");+}++#[test]+fn symmetric_role_clash_is_detected() {+ // A symmetric role is its own inverse. p symmetric, a p b => b p a.+ // B forces p-fillers to D; a:B and a p b => b:D; b:E; D disjoint E => clash.+ let inconsistent = !is_consistent(+ "ex:p a owl:SymmetricProperty .\n\+ ex:B a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:p ; owl:allValuesFrom ex:D ] .\n\+ ex:m a ex:B, ex:E ; ex:p ex:n .\n\+ ex:n a ex:B .\n",+ );+ assert!(inconsistent, "a clash reachable only through a symmetric role's own-inverse edge must be detected");+}++// ── Min-cardinality is not an allocation weapon ─────────────────────────────+//+// The >=-rule materialises n successors from an owl:minCardinality literal that+// has no magnitude cap. The node budget was checked only between fixpoint passes,+// so the inner loop would allocate billions of nodes before the outer guard ran.+// A per-iteration guard turns this into the honest "undecided" answer. (The+// pre-fix behaviour is an out-of-memory kill, not safely run in CI.)+#[test]+fn a_giant_min_cardinality_is_bounded_not_an_oom() {+ let ttl = "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://example.org/> .\n\+ ex:R a owl:ObjectProperty .\n\+ ex:C a owl:Class ; rdfs:subClassOf \+ [ a owl:Restriction ; owl:onProperty ex:R ; owl:minCardinality 2000000000 ] .\n\+ ex:x a ex:C .\n";+ let result = classify(ttl);+ // Budget exhaustion is never a proof of inconsistency.+ assert_eq!(+ result["consistent"], true,+ "a giant min-cardinality must not be reported inconsistent: {result}"+ );+ // And the reasoner reports it could not decide the ABox rather than fabricating one.+ assert_eq!(+ result["abox"]["undecided"], true,+ "a giant min-cardinality must be reported undecided, not silently completed: {result}"+ );+}++// ── Anonymous class types on individuals are checked, not dropped ────────────+//+// `:a rdf:type [ owl:Restriction ; owl:onProperty :r ; owl:allValuesFrom :C ]`+// directly types an individual with an anonymous class expression. The collector+// kept only NAMED-class types, so the restriction never reached the tableau and+// an inconsistency arising from it was reported consistent.+#[test]+fn anonymous_class_type_on_individual_is_enforced() {+ // a is directly typed by the anonymous (∀r.D); a r b; b is E.+ // ∀r.D forces b:D; b is E; D disjoint E => clash. Requires the anonymous type+ // to be enforced, which it was not before the fix.+ let inconsistent = !is_consistent(+ "ex:a a [ a owl:Restriction ; owl:onProperty ex:r ; owl:allValuesFrom ex:D ] ; ex:r ex:b .\n\+ ex:b a ex:E .\n\+ ex:a2 a ex:E .\n",+ );+ assert!(+ inconsistent,+ "an inconsistency from an anonymous class type on an individual must be detected"+ );+}++#[test]+fn anonymous_class_type_only_individual_is_still_checked() {+ // b typed ONLY by an anonymous restriction (∀r.D). No named class on b at all.+ // b r c ; c is E ; ∀r.D => c:D ; D disjoint E => clash.+ let inconsistent = !is_consistent(+ "ex:b a [ a owl:Restriction ; owl:onProperty ex:r ; owl:allValuesFrom ex:D ] ; ex:r ex:c .\n\+ ex:c a ex:E .\n",+ );+ assert!(+ inconsistent,+ "an individual typed only by an anonymous class expression must still be checked"+ );+}diff --git a/tests/serialisation_invariance_test.rs b/tests/serialisation_invariance_test.rsindex 8c7197ca..f09657df 100644--- a/tests/serialisation_invariance_test.rs+++ b/tests/serialisation_invariance_test.rs@@ -231,3 +231,170 @@ fn shape_induction_reads_every_graph() {"the same instances must induce the same lattice");}++#[test]+fn support_check_reads_claims_from_every_graph() {+ // onto_support_check audits provenance: which claims cite no source, plus a+ // verification task per sourced claim. Built on the default-graph select, it+ // reported an empty spotless corpus for any TriG/N-Quads store.+ use open_ontologies::state::StateDb;+ use open_ontologies::support::SupportChecker;+ let claim = "@prefix ex: <http://example.org/> . @prefix prov: <http://www.w3.org/ns/prov#> . \+ ex:claim1 ex:about ex:Bridge ; prov:wasDerivedFrom ex:src1 .";+ let turtle = Arc::new(GraphStore::new());+ turtle.load_turtle(claim, None).unwrap();+ let trig = Arc::new(GraphStore::new());+ trig.load_content(+ "@prefix ex: <http://example.org/> . @prefix prov: <http://www.w3.org/ns/prov#> . \+ ex:g { ex:claim1 ex:about ex:Bridge ; prov:wasDerivedFrom ex:src1 . }",+ RdfFormat::TriG,+ )+ .unwrap();++ let dt = tempfile::TempDir::new().unwrap();+ let t: serde_json::Value = serde_json::from_str(+ &SupportChecker::new(turtle, StateDb::open(&dt.path().join("s.db")).unwrap())+ .check(None, 100)+ .unwrap(),+ )+ .unwrap();+ let dq = tempfile::TempDir::new().unwrap();+ let q: serde_json::Value = serde_json::from_str(+ &SupportChecker::new(trig, StateDb::open(&dq.path().join("s.db")).unwrap())+ .check(None, 100)+ .unwrap(),+ )+ .unwrap();+ assert_eq!(t["claims_total"].as_u64(), Some(1), "turtle side must see the claim: {t}");+ assert_eq!(t["claims_total"], q["claims_total"], "turtle {t}\ntrig {q}");+ assert_eq!(t["tasks"], q["tasks"], "turtle {t}\ntrig {q}");+}++#[cfg(feature = "embeddings")]+#[test]+fn structural_embeddings_train_on_every_graph() {+ // Poincare structural training reads the class hierarchy; on the default+ // graph alone it trained on nothing for a TriG store, degrading+ // onto_embed(structure)/onto_search/onto_similarity to noise with no error.+ use open_ontologies::structembed::StructuralTrainer;+ let onto = "ex:Animal a owl:Class . ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal . \+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .";+ let prefixes = "@prefix ex: <http://example.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .";+ let turtle = Arc::new(GraphStore::new());+ turtle.load_turtle(&format!("{prefixes} {onto}"), None).unwrap();+ let trig = Arc::new(GraphStore::new());+ trig.load_content(&format!("{prefixes} ex:g {{ {onto} }}"), RdfFormat::TriG).unwrap();++ let t = StructuralTrainer::new(8, 5, 0.1).train(&turtle).unwrap();+ let q = StructuralTrainer::new(8, 5, 0.1).train(&trig).unwrap();+ assert_eq!(t.len(), 3, "turtle side must embed all three classes: {}", t.len());+ assert_eq!(t.len(), q.len(), "turtle {} vs trig {}", t.len(), q.len());+}++#[test]+fn align_extracts_target_classes_from_every_graph() {+ // onto_align with target=None aligns a source ontology against the loaded+ // store. Class extraction on the default graph alone saw zero target classes+ // for a TriG store and reported nothing to align.+ use open_ontologies::align::AlignmentEngine;+ use open_ontologies::state::StateDb;+ let target_onto = "ex:Dog a owl:Class ; rdfs:label \"Dog\" .";+ let prefixes = "@prefix ex: <http://example.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .";+ let source = format!("{prefixes} ex:Dog2 a owl:Class ; rdfs:label \"Dog\" .");++ let turtle = Arc::new(GraphStore::new());+ turtle.load_turtle(&format!("{prefixes} {target_onto}"), None).unwrap();+ let trig = Arc::new(GraphStore::new());+ trig.load_content(&format!("{prefixes} ex:g {{ {target_onto} }}"), RdfFormat::TriG).unwrap();++ let dt = tempfile::TempDir::new().unwrap();+ let t: serde_json::Value = serde_json::from_str(+ &AlignmentEngine::new(StateDb::open(&dt.path().join("s.db")).unwrap(), turtle)+ .align(&source, None, 0.3, true)+ .unwrap(),+ )+ .unwrap();+ let dq = tempfile::TempDir::new().unwrap();+ let q: serde_json::Value = serde_json::from_str(+ &AlignmentEngine::new(StateDb::open(&dq.path().join("s.db")).unwrap(), trig)+ .align(&source, None, 0.3, true)+ .unwrap(),+ )+ .unwrap();+ assert!(+ t["total_candidates"].as_u64().unwrap_or(0) >= 1,+ "turtle side must find the Dog/Dog2 candidate, or this proves nothing: {t}"+ );+ assert_eq!(t["total_candidates"], q["total_candidates"], "turtle {t}\ntrig {q}");+}++#[test]+fn enforce_reads_design_pattern_data_from_every_graph() {+ // onto_enforce checks design-pattern compliance with internally-authored+ // SELECTs. On the default graph alone it saw no classes in a TriG store and+ // reported a false clean (compliance 1.0, zero violations). The value_partition+ // pack flags a parent whose >=2 children are not pairwise disjoint.+ use open_ontologies::enforce::Enforcer;+ use open_ontologies::state::StateDb;+ let onto = "ex:Animal a owl:Class . \+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal . \+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .";+ let prefixes = "@prefix ex: <http://example.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .";+ let turtle = Arc::new(GraphStore::new());+ turtle.load_turtle(&format!("{prefixes} {onto}"), None).unwrap();+ let trig = Arc::new(GraphStore::new());+ trig.load_content(&format!("{prefixes} ex:g {{ {onto} }}"), RdfFormat::TriG).unwrap();++ let dt = tempfile::TempDir::new().unwrap();+ let t: serde_json::Value = serde_json::from_str(+ &Enforcer::new(StateDb::open(&dt.path().join("s.db")).unwrap(), turtle)+ .enforce("value_partition").unwrap(),+ ).unwrap();+ let dq = tempfile::TempDir::new().unwrap();+ let q: serde_json::Value = serde_json::from_str(+ &Enforcer::new(StateDb::open(&dq.path().join("s.db")).unwrap(), trig)+ .enforce("value_partition").unwrap(),+ ).unwrap();+ let tv = t["violations"].as_array().unwrap().len();+ assert!(tv >= 1, "turtle side must find the non-disjoint partition, or this proves nothing: {t}");+ assert_eq!(tv, q["violations"].as_array().unwrap().len(), "turtle {t}\ntrig {q}");+ assert_eq!(t["compliance"], q["compliance"], "turtle {t}\ntrig {q}");+}++#[test]+fn plan_blast_radius_reads_dependents_from_every_graph() {+ // onto_plan's blast radius counts how many triples reference an IRI being+ // removed. Computed over the default graph alone, it read zero dependents for+ // a TriG store, so a removal that breaks references looked safe.+ use open_ontologies::plan::Planner;+ use open_ontologies::state::StateDb;+ let onto = "ex:Building a owl:Class . \+ ex:Bridge a owl:Class ; rdfs:subClassOf ex:Building . \+ ex:height a owl:DatatypeProperty ; rdfs:domain ex:Building .";+ let prefixes = "@prefix ex: <http://example.org/> . @prefix owl: <http://www.w3.org/2002/07/owl#> . \+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .";+ // Proposed change removes ex:Building (still referenced by Bridge and height).+ let new_turtle = format!("{prefixes} ex:Bridge a owl:Class .");++ let turtle = Arc::new(GraphStore::new());+ turtle.load_turtle(&format!("{prefixes} {onto}"), None).unwrap();+ let trig = Arc::new(GraphStore::new());+ trig.load_content(&format!("{prefixes} ex:g {{ {onto} }}"), RdfFormat::TriG).unwrap();++ let dt = tempfile::TempDir::new().unwrap();+ let t: serde_json::Value = serde_json::from_str(+ &Planner::new(StateDb::open(&dt.path().join("s.db")).unwrap(), turtle)+ .plan(&new_turtle).unwrap(),+ ).unwrap();+ let dq = tempfile::TempDir::new().unwrap();+ let q: serde_json::Value = serde_json::from_str(+ &Planner::new(StateDb::open(&dq.path().join("s.db")).unwrap(), trig)+ .plan(&new_turtle).unwrap(),+ ).unwrap();+ let ta = t["blast_radius"]["triples_affected"].as_u64().unwrap();+ assert!(ta >= 1, "turtle side must count Building's dependents, or this proves nothing: {t}");+ assert_eq!(ta, q["blast_radius"]["triples_affected"].as_u64().unwrap(), "turtle {t}\ntrig {q}");+}diff --git a/tests/shacl_test.rs b/tests/shacl_test.rsindex dc580c7a..1ab9dd92 100644--- a/tests/shacl_test.rs+++ b/tests/shacl_test.rs@@ -934,3 +934,49 @@ fn test_shacl_exclusive_range() {assert_eq!(parsed["conforms"], false);assert_eq!(parsed["violation_count"].as_u64().unwrap(), 4);}++// Red-team regression: a value node whose datatype cannot be compared to the bound+// (a string against a numeric range, a date against an integer, or NaN) must be a+// VIOLATION, not a silent pass. SHACL 4.6.1/4.6.2: a value where the satisfying+// comparison "does not return true" is a validation result, and a type error does+// not return true. The affirmative-only FILTER previously dropped these to conforms.+#[test]+fn test_shacl_range_flags_incomparable_values_not_silent_pass() {+ let store = Arc::new(GraphStore::new());+ store+ .load_turtle(+ r#"+ @prefix ex: <http://example.org/> .+ ex:ok a ex:Thing ; ex:n 7 .+ ex:low a ex:Thing ; ex:n 1 .+ ex:garbage a ex:Thing ; ex:n "not a number" .+ ex:dateval a ex:Thing ; ex:n "2020-01-01"^^<http://www.w3.org/2001/XMLSchema#date> .+ "#,+ None,+ )+ .unwrap();+ let shapes = r#"+ @prefix sh: <http://www.w3.org/ns/shacl#> .+ @prefix ex: <http://example.org/> .+ ex:RangeShape a sh:NodeShape ;+ sh:targetClass ex:Thing ;+ sh:property [ sh:path ex:n ; sh:minInclusive 5 ; sh:maxInclusive 10 ] .+ "#;+ let result = ShaclValidator::validate(&store, shapes).unwrap();+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();+ let flagged: Vec<String> = parsed["violations"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v["focus_node"].as_str().unwrap().to_string())+ .collect();++ assert_eq!(parsed["conforms"], false, "store must not conform: {parsed}");+ // In-range numeric passes.+ assert!(!flagged.iter().any(|f| f.ends_with("ok")), "ex:ok (7) is in range: {flagged:?}");+ // Out-of-range numeric is caught (control that the check runs).+ assert!(flagged.iter().any(|f| f.ends_with("low")), "ex:low (1) is below 5: {flagged:?}");+ // The bug: incomparable values must be flagged, never silently pass.+ assert!(flagged.iter().any(|f| f.ends_with("garbage")), "non-numeric value silently passed: {flagged:?}");+ assert!(flagged.iter().any(|f| f.ends_with("dateval")), "date-vs-integer value silently passed: {flagged:?}");+}