World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Preserve declared inverse and subproperty links in RDF exports (#824)
Maya Kid1e14fcf5f3e4
diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rsindex 5e9651b8..4b0c1a1f 100644--- a/crates/utopia-server/src/api/mcp_tests.rs+++ b/crates/utopia-server/src/api/mcp_tests.rs@@ -1053,6 +1053,265 @@ async fn remembered_clock_times_do_not_receive_the_date_only_offset() -> anyhow:f.clean().await}+#[tokio::test]+async fn declared_property_links_survive_authenticated_rdf_export() -> anyhow::Result<()> {+ use axum::body::{to_bytes, Body};+ use axum::http::{Request, StatusCode};+ use tower::ServiceExt;+ use utopia_core::models::RelationAxioms;+ use utopia_store::ontology::{+ create_relation_type, create_relation_with_iri, update_relation_type,+ };++ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ async fn check(f: &Fixture) -> anyhow::Result<()> {+ const IMPORTED: &str = "https://example.test/worksFor";+ let root = create_relation_with_iri(+ &f.state.pool,+ f.kb,+ "employment",+ "Employment",+ "",+ IMPORTED,+ false,+ false,+ &[],+ &[],+ )+ .await?+ .ok_or_else(|| anyhow::anyhow!("missing imported relation"))?;+ let mut declared = Vec::new();+ let mut parent = root;+ for key in ["manages", "directs", "leads"] {+ let ax = RelationAxioms {+ sub_property_of: Some(parent),+ ..Default::default()+ };+ let id = create_relation_type(+ &f.state.pool,+ f.kb,+ key,+ key,+ "state",+ ax,+ "",+ "relation",+ &[],+ &[],+ None,+ None,+ )+ .await?;+ declared.push((id, key, parent));+ parent = id;+ }+ let inverse = create_relation_type(+ &f.state.pool,+ f.kb,+ "employs",+ "Employs",+ "state",+ RelationAxioms {+ inverse_of: Some(root),+ ..Default::default()+ },+ "",+ "relation",+ &[],+ &[],+ None,+ None,+ )+ .await?;+ // Store exactly the reciprocal declaration too; export must not manufacture it.+ update_relation_type(+ &f.state.pool,+ f.kb,+ root,+ "Employment",+ "state",+ RelationAxioms {+ inverse_of: Some(inverse),+ ..Default::default()+ },+ "",+ None,+ None,+ None,+ None,+ )+ .await?;+ let other = create_relation_type(+ &f.state.pool,+ f.other_kb,+ "employment",+ "Employment",+ "state",+ Default::default(),+ "",+ "relation",+ &[],+ &[],+ None,+ None,+ )+ .await?;+ anyhow::ensure!(+ create_relation_type(+ &f.state.pool,+ f.kb,+ "bad_cross_base",+ "Bad",+ "state",+ RelationAxioms {+ inverse_of: Some(other),+ ..Default::default()+ },+ "",+ "relation",+ &[],+ &[],+ None,+ None+ )+ .await+ .is_err(),+ "cross-base input must be refused by the real write path"+ );+ let auth = utopia_store::tokens::authenticate(&f.state.pool, &f.token).await?;+ let jwt = crate::auth::issue_token(&f.state, auth.user_id)?;+ let app = crate::api::router(f.state.clone(), &Default::default());+ let names = crate::rdf::Names::new(f.kb, None).map_err(anyhow::Error::msg)?;+ let relation_iri = |key: &str| format!("<urn:utopia:kb:{}:relation:{key}>", f.kb);+ let inverse_term = "<http://www.w3.org/2002/07/owl#inverseOf>".to_string();+ let sub_term = "<http://www.w3.org/2000/01/rdf-schema#subPropertyOf>".to_string();+ let expected: std::collections::HashSet<_> = [+ (+ relation_iri("employs"),+ inverse_term.clone(),+ format!("<{IMPORTED}>"),+ ),+ (+ format!("<{IMPORTED}>"),+ inverse_term.clone(),+ relation_iri("employs"),+ ),+ (+ relation_iri("manages"),+ sub_term.clone(),+ format!("<{IMPORTED}>"),+ ),+ (+ relation_iri("directs"),+ sub_term.clone(),+ relation_iri("manages"),+ ),+ (+ relation_iri("leads"),+ sub_term.clone(),+ relation_iri("directs"),+ ),+ ]+ .into_iter()+ .collect();+ for renamed in [false, true] {+ if renamed {+ update_relation_type(+ &f.state.pool,+ f.kb,+ declared[0].0,+ "New label",+ "state",+ RelationAxioms {+ sub_property_of: Some(root),+ ..Default::default()+ },+ "",+ None,+ None,+ None,+ None,+ )+ .await?;+ }+ let snapshot_sql = "SELECT jsonb_build_array(+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM relation_types t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM facts t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM derived_facts t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM jobs t WHERE payload->>'kb_id'=$1::text))";+ let before: Value = sqlx::query_scalar(snapshot_sql)+ .bind(f.kb)+ .fetch_one(&f.state.pool)+ .await?;+ let mut exports = Vec::new();+ for (format, parser_format) in [+ ("turtle", oxrdfio::RdfFormat::Turtle),+ (+ "jsonld",+ oxrdfio::RdfFormat::JsonLd {+ profile: oxrdfio::JsonLdProfileSet::empty(),+ },+ ),+ ] {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .uri(format!("/api/v1/kbs/{}/export?format={format}", f.kb))+ .header("authorization", format!("Bearer {jwt}"))+ .body(Body::empty())?,+ )+ .await?;+ anyhow::ensure!(response.status() == StatusCode::OK, "export rejected");+ let bytes = to_bytes(response.into_body(), 1024 * 1024).await?;+ let quads = oxrdfio::RdfParser::from_format(parser_format)+ .for_slice(&bytes)+ .collect::<Result<std::collections::HashSet<_>, _>>()?;+ let links: std::collections::HashSet<_> = quads+ .iter()+ .filter(|q| {+ [inverse_term.as_str(), sub_term.as_str()]+ .contains(&q.predicate.to_string().as_str())+ })+ .map(|q| {+ (+ q.subject.to_string(),+ q.predicate.to_string(),+ q.object.to_string(),+ )+ })+ .collect();+ anyhow::ensure!(+ links == expected,+ "declared property links missing or invented: {links:?}"+ );+ anyhow::ensure!(+ quads+ .iter()+ .any(|q| q.subject == names.fact(f.corrected).into()),+ "lost existing facts"+ );+ exports.push(quads);+ }+ anyhow::ensure!(exports[0] == exports[1], "formats disagree");+ let after: Value = sqlx::query_scalar(snapshot_sql)+ .bind(f.kb)+ .fetch_one(&f.state.pool)+ .await?;+ anyhow::ensure!(+ before == after,+ "export changed stored declarations/facts/jobs"+ );+ }+ Ok(())+ }+ let result = check(&f).await;+ let cleanup = f.clean().await;+ result.and(cleanup)+}+#[tokio::test]async fn failed_reads_do_not_become_successful_empty_results() -> anyhow::Result<()> {let Some(f) = Fixture::new().await? else {diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rsindex 35e91763..0da8f3fc 100644--- a/crates/utopia-server/src/rdf.rs+++ b/crates/utopia-server/src/rdf.rs@@ -378,6 +378,15 @@ pub fn emit_relation(sink.r(&iri, &nn(rdf::TYPE.as_str()), &owl(term))?;}}+ // 只复制已声明的边;不补反向声明或传递闭包,目标也只在本库词汇表中找。+ for (target, predicate) in [+ (r.inverse_of, owl("inverseOf")),+ (r.sub_property_of, nn(rdfs::SUB_PROPERTY_OF.as_str())),+ ] {+ if let Some(target) = target.and_then(|id| vocab.relation(id)) {+ sink.r(&iri, &predicate, target)?;+ }+ }// 时间语义也照抄(0031):一个 event 谓词的事实两端是同一刻,一个 eternal 谓词的// 事实没有日期——读的人不看这一条,会把前者读成一天的状态、后者读成从不知何时起。// 状态是默认,不写@@ -709,6 +718,8 @@ mod tests {is_symmetric: false,is_asymmetric: false,is_irreflexive: false,+ inverse_of: None,+ sub_property_of: None,domains: vec![],ranges: vec![],}@@ -1196,6 +1207,67 @@ mod tests {);}+ #[test]+ fn declared_property_links_are_local_explicit_and_order_independent() {+ let root = relation(21, "root", Some("https://example.test/root"), "relation");+ let mut inverse = relation(22, "inverse", None, "relation");+ inverse.inverse_of = Some(root.id);+ let mut child = relation(23, "child", None, "relation");+ child.sub_property_of = Some(root.id);+ let mut leaf = relation(24, "leaf", None, "relation");+ leaf.sub_property_of = Some(child.id);+ let mut missing = relation(25, "unresolved", None, "relation");+ missing.inverse_of = Some(id(98));+ missing.sub_property_of = Some(id(99));+ let mut relations = vec![root, inverse, child, leaf, missing];+ let mut sets = Vec::new();+ for reverse in [false, true] {+ if reverse {+ relations.reverse();+ }+ for format in [Format::Turtle, Format::JsonLd] {+ let quads = export(format, |sink, names, _| {+ let vocab = vocabulary(names, &[], &relations);+ for r in &relations {+ emit_relation(sink, &vocab, r).unwrap();+ }+ });+ let names = Names::new(kb(), None).unwrap();+ let iri = |n| names.relation(relations.iter().find(|r| r.id == id(n)).unwrap());+ let expected: std::collections::HashSet<_> = [+ (iri(22).into(), owl("inverseOf"), Term::from(iri(21))),+ (+ iri(23).into(),+ nn(rdfs::SUB_PROPERTY_OF.as_str()),+ Term::from(iri(21)),+ ),+ (+ iri(24).into(),+ nn(rdfs::SUB_PROPERTY_OF.as_str()),+ Term::from(iri(23)),+ ),+ ]+ .into_iter()+ .collect();+ let links: std::collections::HashSet<_> = quads+ .iter()+ .filter(|q| {+ q.predicate == owl("inverseOf") || q.predicate == rdfs::SUB_PROPERTY_OF+ })+ .map(|q| (q.subject.clone(), q.predicate.clone(), q.object.clone()))+ .collect();+ assert_eq!(+ links, expected,+ "only stored, local links should be emitted"+ );+ sets.push(quads.into_iter().collect::<std::collections::HashSet<_>>());+ }+ }+ for set in &sets[1..] {+ assert_eq!(&sets[0], set);+ }+ }+#[test]fn a_derivation_says_it_is_one_and_names_its_premises() {let derived = ExportDerived {diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rsindex 46ef2fcb..33fdc130 100644--- a/crates/utopia-store/src/export.rs+++ b/crates/utopia-store/src/export.rs@@ -46,6 +46,8 @@ pub struct ExportRelation {pub is_symmetric: bool,pub is_asymmetric: bool,pub is_irreflexive: bool,+ pub inverse_of: Option<Uuid>,+ pub sub_property_of: Option<Uuid>,pub domains: Vec<Uuid>,pub ranges: Vec<Uuid>,}@@ -148,6 +150,7 @@ pub async fn relations(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ExportRelati"SELECT r.id, r.key, r.label, r.description, r.iri, r.kind, r.datatype, r.unit,r.temporal, r.functional, r.inverse_functional,r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,+ r.inverse_of, r.sub_property_of,COALESCE(ARRAY(SELECT d.entity_type_id FROM relation_type_domains dWHERE d.relation_type_id = r.id ORDER BY 1), '{}') AS domains,COALESCE(ARRAY(SELECT g.entity_type_id FROM relation_type_ranges gdiff --git a/web/src/docs/mcp.md b/web/src/docs/mcp.mdindex 85f784b8..ba52cc2e 100644--- a/web/src/docs/mcp.md+++ b/web/src/docs/mcp.md@@ -66,6 +66,11 @@ rebuilding a graph is not an identity-preserving operation. `?base=https://exampinstead mints `https://example.org/kb/{kb_id}/{kind}/{id}`. Keep the same base whenjoining exports. Imported classes and relations retain their original IRIs.+Ontology export includes explicitly stored `owl:inverseOf` and+`rdfs:subPropertyOf` links, using the target property's imported IRI or existing+key-based IRI. It copies declarations within the base; it does not add reciprocal+links or compute a transitive closure.+MCP remains the agent-facing surface. The structured results below use the sameUUIDs, so an integration can join a selected result to the exported ledger.Ordinary `/api/v1` UI response shapes are **not** a compatibility promise: they