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(induce): namespace generated row IDs by source
Rudy Mizrahi Celekli3c5e19f6ead9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1808a841..ffbcc908 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Fixed++- Scope deterministic synthetic row identifiers to the original source stem,+ preserving distinct subjects across sheets and class overrides. Encode source+ names losslessly; identical stems require distinct base IRIs.+### Added- **A named profile hands a client one job's worth of the tool surface** (#263).diff --git a/src/batch.rs b/src/batch.rsindex a240a30a..8a75080a 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -1046,9 +1046,9 @@ impl BatchRunner {None => return json!({"error": "induce requires a data file path"}),};let base = Self::flag_value(args, "--base-iri").unwrap_or("http://example.org/data/".to_string());- let stem = Self::flag_value(args, "--class").unwrap_or_else(|| {- std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("Row").to_string()- });+ let source_stem = std::path::Path::new(&path).file_stem()+ .and_then(|s| s.to_str()).unwrap_or("Row").to_string();+ let stem = Self::flag_value(args, "--class").unwrap_or_else(|| source_stem.clone());let rows = match DataIngester::parse_file(&path) {Ok(r) => r,Err(e) => return json!({"error": e.to_string()}),@@ -1057,7 +1057,7 @@ impl BatchRunner {return json!({"error": "no data rows found; nothing to induce from"});}let headers = DataIngester::headers_in_order(&path, &rows);- let induced = crate::induce::induce(&rows, &headers, &stem, &base);+ let induced = crate::induce::induce_with_source(&rows, &headers, &stem, &source_stem, &base);if let Some(out) = Self::flag_value(args, "--out") {let dir = std::path::Path::new(&out);if let Err(e) = std::fs::create_dir_all(dir)diff --git a/src/induce.rs b/src/induce.rsindex b4e7824a..88950ceb 100644--- a/src/induce.rs+++ b/src/induce.rs@@ -192,8 +192,10 @@ pub struct Induced {pub class: String,pub class_iri: String,pub base_iri: String,+ /// Original source stem, independent of the normalized class name.+ pub source_stem: String,pub id_column: String,- /// `true` when no column identified the rows and a row number was used.+ /// `true` when no column identified the rows and a source-scoped row number was used.pub id_synthesised: bool,pub rows: usize,pub columns: Vec<Column>,@@ -210,21 +212,27 @@ pub struct Induced {impl Induced {/// Serialize the analyzed rows as instances of this induced class.///- /// When no input column identifies the rows, materialize the documented- /// 1-based row numbers in the unused internal ID field. Original cells are- /// retained. Explicit identifiers use the existing mapping unchanged.+ /// When no input column identifies the rows, materialize IDs formed from+ /// the percent-encoded original source stem, a hyphen, and the 1-based+ /// row number in the unused internal ID field. Original cells are retained.+ /// Explicit identifiers use the existing mapping unchanged.///- /// The exported `MappingConfig` alone cannot synthesize row numbers from- /// raw input: use this serializer, or supply its generated ID field first.+ /// Replaying the same source in the same row order mints the same IDs.+ /// Sources with the same stem share a namespace; use distinct base IRIs+ /// for unrelated sources with identical stems.+ ///+ /// The exported `MappingConfig` alone cannot synthesize these IDs from raw+ /// input: use this serializer, or supply its generated ID field first.pub fn instance_ntriples(&self, rows: &[HashMap<String, String>]) -> String {if !self.id_synthesised {return self.mapping.rows_to_ntriples(rows);}+ let prefix = source_id_prefix(&self.source_stem);rows.iter().enumerate().flat_map(|(index, original)| {let mut row = original.clone();- row.insert(self.id_column.clone(), (index + 1).to_string());+ row.insert(self.id_column.clone(), format!("{prefix}-{}", index + 1));self.mapping.row_to_triples(&row)}).collect::<Vec<_>>()@@ -232,6 +240,21 @@ impl Induced {}}+fn source_id_prefix(stem: &str) -> String {+ const HEX: &[u8; 16] = b"0123456789ABCDEF";+ let mut out = String::new();+ for &byte in stem.as_bytes() {+ if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {+ out.push(char::from(byte));+ } else {+ out.push('%');+ out.push(char::from(HEX[usize::from(byte >> 4)]));+ out.push(char::from(HEX[usize::from(byte & 15)]));+ }+ }+ out+}+const MEANS: &str = "an induced ontology is a HYPOTHESIS about the sheet, not a truth about the \domain. Every class, property, datatype and shape here was read off the rows \and carries the counts that produced it; the rows satisfy the shapes by \@@ -325,8 +348,23 @@ fn ttl_str(s: &str) -> String {/// Induce class, properties, shapes and mapping from `rows`.////// `headers` fixes the column order (a `HashMap` row has none); `stem` names-/// the class (a file stem, usually); `base_iri` roots every minted IRI.+/// the class and source namespace (a file stem, usually); `base_iri` roots every minted IRI.pub fn induce(rows: &[HashMap<String, String>], headers: &[String], stem: &str, base_iri: &str) -> Induced {+ induce_with_source(rows, headers, stem, stem, base_iri)+}++/// Induce a class while retaining an independent source namespace.+///+/// Class overrides affect schema names; source_stem identifies synthetic rows.+/// IDs encode UTF-8 bytes outside ASCII unreserved characters, then append a+/// hyphen and the 1-based row number.+pub fn induce_with_source(+ rows: &[HashMap<String, String>],+ headers: &[String],+ stem: &str,+ source_stem: &str,+ base_iri: &str,+) -> Induced {let n = rows.len();let class = class_name(stem);let ont = format!("{base_iri}ont#");@@ -503,7 +541,7 @@ pub fn induce(rows: &[HashMap<String, String>], headers: &[String], stem: &str,}// 4. Render.- let ctx = Ctx { ont: &ont, class: &class, class_iri: &class_iri, stem, n, id_synthesised, id_column: &id_column };+ let ctx = Ctx { ont: &ont, class: &class, class_iri: &class_iri, stem: source_stem, n, id_synthesised, id_column: &id_column };let ontology_ttl = render_ontology(&ctx, &columns);let shapes_ttl = render_shapes(&ctx, &columns);let mut mappings = Vec::new();@@ -529,6 +567,7 @@ pub fn induce(rows: &[HashMap<String, String>], headers: &[String], stem: &str,class,class_iri,base_iri: base_iri.to_string(),+ source_stem: source_stem.to_string(),id_column,id_synthesised,rows: n,@@ -574,7 +613,7 @@ fn render_ontology(ctx: &Ctx<'_>, columns: &[Column]) -> String {ttl_str(&format!("One instance per row of {stem:?}, {n} in the sheet. Identified by {}.",if id_synthesised {- "row number, because no column was filled and unique in every row".to_string()+ "percent-encoded source stem followed by a hyphen and a 1-based row number, because no column was filled and unique in every row".to_string()} else {format!("the column {id_column:?}, filled and unique in every row")}diff --git a/src/server.rs b/src/server.rsindex 5270f28e..a629c4bd 100644--- a/src/server.rs+++ b/src/server.rs@@ -1116,9 +1116,9 @@ impl OpenOntologiesServer {async fn onto_induce(&self, Parameters(input): Parameters<OntoInduceInput>) -> String {use crate::ingest::DataIngester;let base_iri = input.base_iri.clone().unwrap_or_else(|| "http://example.org/data/".to_string());- let stem = input.class_name.clone().unwrap_or_else(|| {- std::path::Path::new(&input.path).file_stem().and_then(|s| s.to_str()).unwrap_or("Row").to_string()- });+ let source_stem = std::path::Path::new(&input.path).file_stem()+ .and_then(|s| s.to_str()).unwrap_or("Row").to_string();+ let stem = input.class_name.clone().unwrap_or_else(|| source_stem.clone());let rows = match DataIngester::parse_file(&input.path) {Ok(r) => r,Err(e) => return Self::err_json(format!("Failed to parse {}: {}", input.path, e)),@@ -1127,7 +1127,7 @@ impl OpenOntologiesServer {return Self::err_json("no data rows found; nothing to induce from");}let headers = DataIngester::headers_in_order(&input.path, &rows);- let induced = crate::induce::induce(&rows, &headers, &stem, &base_iri);+ let induced = crate::induce::induce_with_source(&rows, &headers, &stem, &source_stem, &base_iri);let mut v = match serde_json::to_value(&induced) {Ok(v) => v,Err(e) => return Self::err_json(e),diff --git a/tests/induce_synthetic_identifier_test.rs b/tests/induce_synthetic_identifier_test.rsindex 5c757ad8..b7c3ecb7 100644--- a/tests/induce_synthetic_identifier_test.rs+++ b/tests/induce_synthetic_identifier_test.rs@@ -102,14 +102,14 @@ const BASE: &str = "https://example.org/orders/";const DATA: &str = "kind,__row,quantity\nretail,import-A,3\nretail,import-A,5\nretail,import-A,8\n";const QUERY: &str = "SELECT ?s ?kind ?source ?quantity WHERE { ?s <https://example.org/orders/ont#kind> ?kind; <https://example.org/orders/ont#__row> ?source; <https://example.org/orders/ont#quantity> ?quantity } ORDER BY ?quantity";-fn assert_three_retained_rows(result: &Value) {+fn assert_three_retained_rows(result: &Value, stem: &str) {let rows = result["results"].as_array().unwrap();assert_eq!(rows.len(), 3);let subjects: std::collections::HashSet<_> =rows.iter().map(|row| row["s"].as_str().unwrap()).collect();assert_eq!(subjects.len(), 3);for (index, row) in rows.iter().enumerate() {- assert_eq!(row["s"], format!("<{BASE}{}>", index + 1));+ assert_eq!(row["s"], format!("<{BASE}{stem}-{}>", index + 1));assert_eq!(row["kind"], "\"retail\"");assert_eq!(row["source"], "\"import-A\"");assert_eq!(@@ -144,11 +144,21 @@ fn synthetic_ids_preserve_original_cells_and_repeat_export_deterministically() {let export = induced.instance_ntriples(&rows);assert_eq!(export, induced.instance_ntriples(&rows));assert_eq!(rows, original);+ let materialized: Vec<_> = rows+ .iter()+ .enumerate()+ .map(|(index, original)| {+ let mut row = original.clone();+ row.insert(induced.id_column.clone(), format!("Orders-{}", index + 1));+ row+ })+ .collect();+ assert_eq!(export, induced.mapping.rows_to_ntriples(&materialized));let graph = GraphStore::new();graph.load_ntriples(&export).unwrap();assert_eq!(graph.triple_count(), 12);let result = serde_json::from_str(&graph.sparql_select(QUERY).unwrap()).unwrap();- assert_three_retained_rows(&result);+ assert_three_retained_rows(&result, "Orders");}#[test]@@ -177,8 +187,8 @@ fn synthetic_field_skips_all_existing_names_and_explicit_identifiers_stay_unchanlet synthesized = induce(&plain, &["kind".into(), "quantity".into()], "Orders", BASE);assert_eq!(synthesized.id_column, "__row");let export = synthesized.instance_ntriples(&plain);- assert!(export.contains("<https://example.org/orders/1>"));- assert!(export.contains("<https://example.org/orders/2>"));+ assert!(export.contains("<https://example.org/orders/Orders-1>"));+ assert!(export.contains("<https://example.org/orders/Orders-2>"));assert!(!export.contains("_auto_"));let rows =DataIngester::parse_csv("id,kind,quantity\norder-1,retail,3\norder-2,retail,5\n").unwrap();@@ -237,7 +247,7 @@ async fn batch_and_public_mcp_induction_load_the_same_three_rows() {.collect();assert_eq!(values[0]["result"]["id_synthesised"], true);assert_eq!(values[0]["result"]["id_column"], "__row_");- assert_three_retained_rows(&values[1]["result"]);+ assert_three_retained_rows(&values[1]["result"], "orders");let server_dir = tmp.path().join("mcp");std::fs::create_dir(&server_dir).unwrap();let mut mcp = Mcp::start(&server_dir).await;@@ -247,7 +257,172 @@ async fn batch_and_public_mcp_induction_load_the_same_three_rows() {assert_eq!(induced["id_synthesised"], true);assert_eq!(induced["id_column"], "__row_");let queried = mcp.call("onto_query", json!({"query":QUERY})).await;- assert_three_retained_rows(&queried);+ assert_three_retained_rows(&queried, "orders");assert_eq!(queried, values[1]["result"]);mcp.child.kill().await.unwrap();}++#[test]+fn synthetic_source_names_remain_distinct_after_class_normalization_and_iri_encoding() {+ let rows = DataIngester::parse_csv("kind,quantity\nretail,3\nretail,5\n").unwrap();+ let headers = vec!["kind".into(), "quantity".into()];+ assert_eq!(+ induce(&rows, &headers, "sheet_a", BASE).class,+ induce(&rows, &headers, "sheet-a", BASE).class+ );+ let graph = GraphStore::new();+ let sources = [+ ("sheet_a", "sheet_a"),+ ("sheet-a", "sheet-a"),+ ("sheet a", "sheet%20a"),+ ("sheet%20a", "sheet%2520a"),+ ("50%", "50%25"),+ ("données", "donn%C3%A9es"),+ ];+ for (stem, encoded) in sources {+ let induced = induce(&rows, &headers, stem, BASE);+ assert!(induced.id_synthesised);+ let export = induced.instance_ntriples(&rows);+ assert_eq!(export, induced.instance_ntriples(&rows));+ for row in 1..=2 {+ assert!(+ export.contains(&format!("<{BASE}{encoded}-{row}>")),+ "{export}"+ );+ }+ graph.load_ntriples(&export).unwrap();+ }+ let result: Value = serde_json::from_str(+ &graph+ .sparql_select("SELECT DISTINCT ?s WHERE { ?s a ?type }")+ .unwrap(),+ )+ .unwrap();+ assert_eq!(+ result["results"].as_array().unwrap().len(),+ 2 * sources.len()+ );+}++const TWO_SHEET_QUERY: &str = "SELECT ?s ?type ?name ?qty ?colour ?size WHERE { ?s a ?type . VALUES ?type { <http://example.org/data/ont#SheetA> <http://example.org/data/ont#SheetB> <http://example.org/data/ont#Row> } OPTIONAL { ?s <http://example.org/data/ont#name> ?name } OPTIONAL { ?s <http://example.org/data/ont#qty> ?qty } OPTIONAL { ?s <http://example.org/data/ont#colour> ?colour } OPTIONAL { ?s <http://example.org/data/ont#size> ?size } } ORDER BY ?s";++fn assert_two_sources_are_separate(result: &Value, same_class: bool) {+ let rows = result["results"].as_array().unwrap();+ assert_eq!(rows.len(), 4, "{result}");+ let subjects: std::collections::HashSet<_> =+ rows.iter().map(|row| row["s"].as_str().unwrap()).collect();+ assert_eq!(subjects.len(), 4, "{result}");+ for (offset, row) in rows.iter().enumerate() {+ let is_a = offset < 2;+ let number = offset % 2 + 1;+ let stem = if is_a { "sheet_a" } else { "sheet_b" };+ let class = if same_class {+ "Row"+ } else if is_a {+ "SheetA"+ } else {+ "SheetB"+ };+ assert_eq!(+ row["s"],+ format!("<http://example.org/data/{stem}-{number}>")+ );+ assert_eq!(+ row["type"],+ format!("<http://example.org/data/ont#{class}>")+ );+ if is_a {+ assert_eq!(row["name"], "\"foo\"");+ assert_eq!(+ row["qty"],+ format!("\"{number}\"^^<http://www.w3.org/2001/XMLSchema#integer>")+ );+ assert!(row.get("colour").is_none(), "{row}");+ assert!(row.get("size").is_none(), "{row}");+ } else {+ assert_eq!(row["colour"], "\"red\"");+ assert_eq!(+ row["size"],+ format!(+ "\"{}\"^^<http://www.w3.org/2001/XMLSchema#integer>",+ 10 * number+ )+ );+ assert!(row.get("name").is_none(), "{row}");+ assert!(row.get("qty").is_none(), "{row}");+ }+ }+}++#[tokio::test]+async fn batch_and_public_mcp_keep_two_sources_separate_even_with_the_same_class() {+ for same_class in [false, true] {+ let tmp = tempfile::tempdir().unwrap();+ let sheet_a = tmp.path().join("sheet_a.csv");+ let sheet_b = tmp.path().join("sheet_b.csv");+ let commands = tmp.path().join("commands.txt");+ let class_option = if same_class { " --class Row" } else { "" };+ let batch = {+ let _gate = common::exec_gate();+ std::fs::write(&sheet_a, "name,qty\nfoo,1\nfoo,2\n").unwrap();+ std::fs::write(&sheet_b, "colour,size\nred,10\nred,20\n").unwrap();+ std::fs::write(+ &commands,+ format!(+ "induce {}{class_option}\ninduce {}{class_option}\nquery {TWO_SHEET_QUERY}\n",+ sheet_a.display(),+ sheet_b.display()+ ),+ )+ .unwrap();+ std::process::Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .args(["--no-connect", "--data-dir"])+ .arg(tmp.path())+ .arg("batch")+ .arg(&commands)+ .output()+ .unwrap()+ };+ assert!(+ batch.status.success(),+ "{}",+ String::from_utf8_lossy(&batch.stderr)+ );+ let values: Vec<Value> = String::from_utf8(batch.stdout)+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ assert_eq!(values.len(), 3);+ for value in &values[..2] {+ assert_eq!(value["result"]["id_synthesised"], true, "{value}");+ }+ assert_two_sources_are_separate(&values[2]["result"], same_class);+ let server_dir = tmp.path().join("mcp");+ std::fs::create_dir(&server_dir).unwrap();+ let mut mcp = Mcp::start(&server_dir).await;+ for path in [&sheet_a, &sheet_b] {+ let mut arguments = json!({"path":path});+ if same_class {+ arguments["class_name"] = json!("Row");+ }+ let induced = mcp.call("onto_induce", arguments).await;+ assert_eq!(induced["id_synthesised"], true, "{induced}");+ }+ let queried = mcp+ .call("onto_query", json!({"query":TWO_SHEET_QUERY}))+ .await;+ assert_two_sources_are_separate(&queried, same_class);+ assert_eq!(queried, values[2]["result"]);+ let mut replay = json!({"path":sheet_a});+ if same_class {+ replay["class_name"] = json!("Row");+ }+ mcp.call("onto_induce", replay).await;+ let repeated = mcp+ .call("onto_query", json!({"query":TWO_SHEET_QUERY}))+ .await;+ assert_eq!(repeated, queried);+ mcp.child.kill().await.unwrap();+ }+}