World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Axioms the ontology states now reach the database, functional included (#123)
WaylandYang0eb566d62194
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex afd5f6d7..e04dc3bb 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -461,6 +461,21 @@ pub async fn apply(// 换一个"发现得早一点",不划算utopia_store::ontology::set_parents_bulk(&state.pool, &parent_edges).await?;+ // 类互斥同理攒一批(0054)。指向没被建出来的类的那些自然落选——+ // 一条互斥声明的两端都得在这个库里,才谈得上拿它判矛盾+ let mut disjoint_edges: Vec<(Uuid, Uuid)> = Vec::new();+ for c in &proj.classes {+ let Some(&a) = id_of.get(&c.iri) else {+ continue;+ };+ for other in &c.disjoint_with {+ if let Some(&b) = id_of.get(other) {+ disjoint_edges.push((a, b));+ }+ }+ }+ utopia_store::ontology::set_disjoint_bulk(&state.pool, kb_id, &disjoint_edges).await?;+let by_prop_iri: HashMap<&str, &_> = proj.properties.iter()@@ -518,6 +533,10 @@ pub async fn apply(datatype: None,functional: p.functional,inverse_functional: p.inverse_functional,+ transitive: p.transitive,+ symmetric: p.symmetric,+ asymmetric: p.asymmetric,+ irreflexive: p.irreflexive,});pending_links.push((p.key.clone(), domains, ranges));}@@ -570,9 +589,14 @@ pub async fn apply(iri: p.iri.clone(),kind: "attribute",datatype: Some(dt.to_string()),- // 属性不参与时态闭合,这两位对它没有意义+ // 属性不参与时态闭合,也不参与一致性检查:那几类判定都是关于+ // **实体之间**的边,而属性的宾语是字面值functional: false,inverse_functional: false,+ transitive: false,+ symmetric: false,+ asymmetric: false,+ irreflexive: false,});pending_attr_domains.push((p.key.clone(), domain_ids));}diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex c2cdfcb5..87050444 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -1251,6 +1251,13 @@ pub struct BulkRelation {pub datatype: Option<String>,pub functional: bool,pub inverse_functional: bool,+ /// OWL 属性公理,一致性检查的判定依据(0002 R0)。+ /// 同样必须照词汇表写下去——`alias_of` 双向是对的、`produces` 双向是错的,+ /// 分开这两者的只能是本体+ pub transitive: bool,+ pub symmetric: bool,+ pub asymmetric: bool,+ pub irreflexive: bool,}/// 一次插完一批关系或属性,返回 key → id。语义同 [`create_entity_types_bulk`]。@@ -1277,13 +1284,20 @@ pub async fn create_relation_types_bulk(let dts: Vec<Option<&str>> = rows.iter().map(|r| r.datatype.as_deref()).collect();let funcs: Vec<bool> = rows.iter().map(|r| r.functional).collect();let invs: Vec<bool> = rows.iter().map(|r| r.inverse_functional).collect();+ let trans: Vec<bool> = rows.iter().map(|r| r.transitive).collect();+ let syms: Vec<bool> = rows.iter().map(|r| r.symmetric).collect();+ let asyms: Vec<bool> = rows.iter().map(|r| r.asymmetric).collect();+ let irrefs: Vec<bool> = rows.iter().map(|r| r.irreflexive).collect();let out: Vec<(Uuid, String)> = sqlx::query_as("INSERT INTO relation_types(id, kb_id, key, label, temporal, functional, inverse_functional,- description, kind, datatype, iri)- SELECT gen_random_uuid(), $1, k, l, 'state', FALSE, FALSE, d, kind, dt, i- FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])- AS t(k, l, d, i, kind, dt)+ description, kind, datatype, iri,+ is_transitive, is_symmetric, is_asymmetric, is_irreflexive)+ SELECT gen_random_uuid(), $1, k, l, 'state', fu, iv, d, kind, dt, i,+ tr, sy, asym, irr+ FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[],+ $8::bool[], $9::bool[], $10::bool[], $11::bool[], $12::bool[], $13::bool[])+ AS t(k, l, d, i, kind, dt, fu, iv, tr, sy, asym, irr)ON CONFLICT (kb_id, key) DO NOTHINGRETURNING id, key",)@@ -1296,6 +1310,10 @@ pub async fn create_relation_types_bulk(.bind(&dts).bind(&funcs).bind(&invs)+ .bind(&trans)+ .bind(&syms)+ .bind(&asyms)+ .bind(&irrefs).fetch_all(pool).await?;Ok(out.into_iter().map(|(id, k)| (k, id)).collect())@@ -1361,6 +1379,38 @@ pub async fn set_parents_bulk(pool: &PgPool, pairs: &[(Uuid, Uuid)]) -> AppResulOk(())}+/// 类互斥落库(迁移 0054)。语义同 [`set_parents_bulk`]。+///+/// **两个方向都写。** 解析侧已经把 `owl:disjointWith` 的对称性展开成两条,+/// 这里照写即可——查"A 与 B 互斥吗"因此不必关心从哪一头问。+///+/// `a <> b` 挡自指:自己跟自己互斥是无意义的声明,而它会让一致性检查+/// 把每个实体都报成矛盾。表上也有同样的 CHECK,两道都留着——+/// 约束是最后一道,过滤在这里是为了不让一整批插入因为一条脏数据整个失败。+pub async fn set_disjoint_bulk(+ pool: &PgPool,+ kb_id: Uuid,+ pairs: &[(Uuid, Uuid)],+) -> AppResult<()> {+ if pairs.is_empty() {+ return Ok(());+ }+ let a: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();+ let b: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();+ sqlx::query(+ "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)+ SELECT $1, x, y FROM UNNEST($2::uuid[], $3::uuid[]) AS t(x, y)+ WHERE x <> y+ ON CONFLICT DO NOTHING",+ )+ .bind(kb_id)+ .bind(&a)+ .bind(&b)+ .execute(pool)+ .await?;+ Ok(())+}+// ---------------------------------------------------------------------------// 本体提案(见迁移 0049)// ---------------------------------------------------------------------------diff --git a/crates/utopia-store/tests/axioms_reach_the_database.rs b/crates/utopia-store/tests/axioms_reach_the_database.rsnew file mode 100644index 00000000..9ee60f46--- /dev/null+++ b/crates/utopia-store/tests/axioms_reach_the_database.rs@@ -0,0 +1,110 @@+//! 本体声明的公理要真的落到库里——打在真库上。+//!+//! 这条防线的由来是一个既存缺陷:`create_relation_types_bulk` 的文档写着+//! 「`functional` / `inverse_functional` 必须照词汇表写下去,不能默认 false」,+//! 而它的 SQL 里是硬编码的 `FALSE, FALSE`——两个数组绑定了却没进 `UNNEST`。+//! 实测装 FOAF(声明了 17 条 FunctionalProperty)之后,库里 functional 为真的+//! **一条都没有**。+//!+//! 那两位是时态引擎自动闭合事实的依据。写错的方向不同,后果也不同:标错成真+//! 会成批造假冲突(`part_of` 那次 59 条),而这次是反方向——该为真的全成了假,+//! 于是**该检测出的时态冲突一条都检测不到**,静悄悄地。+//!+//! `cargo check` 看不见这种错(类型全对),单元测试也看不见(它在 SQL 字符串里)。+//! 只有把一行真的写进去再读回来才行。++use sqlx::PgPool;+use uuid::Uuid;++/// 造一个最小的库:公理落库跟本体大小无关,一条就够。+async fn kb(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid)> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'ax-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'ax-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'ax-test')")+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ Ok((kb, org))+}++#[tokio::test]+async fn every_axiom_survives_the_bulk_insert() -> anyhow::Result<()> {+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let (kb_id, org) = kb(&pool).await?;++ let run = async {+ let row = |key: &str, f: bool, i: bool, t: bool, s: bool, a: bool, r: bool| {+ utopia_store::ontology::BulkRelation {+ key: key.into(),+ label: key.into(),+ description: String::new(),+ iri: format!("http://ax.test/#{key}"),+ kind: "relation",+ datatype: None,+ functional: f,+ inverse_functional: i,+ transitive: t,+ symmetric: s,+ asymmetric: a,+ irreflexive: r,+ }+ };+ // 一条全真、一条全假:全假那条守的是"没声明的不该被写成真"+ utopia_store::ontology::create_relation_types_bulk(+ &pool,+ kb_id,+ &[+ row("all_true", true, true, true, true, true, true),+ row("all_false", false, false, false, false, false, false),+ ],+ )+ .await?;++ let got: Vec<(String, bool, bool, bool, bool, bool, bool)> = sqlx::query_as(+ "SELECT key, functional, inverse_functional,+ is_transitive, is_symmetric, is_asymmetric, is_irreflexive+ FROM relation_types WHERE kb_id = $1 ORDER BY key",+ )+ .bind(kb_id)+ .fetch_all(&pool)+ .await?;++ let t = got+ .iter()+ .find(|r| r.0 == "all_true")+ .expect("all_true 落库");+ assert!(+ t.1 && t.2 && t.3 && t.4 && t.5 && t.6,+ "六个公理位都该照写下去,实得 {t:?}"+ );+ let f = got+ .iter()+ .find(|r| r.0 == "all_false")+ .expect("all_false 落库");+ assert!(+ !f.1 && !f.2 && !f.3 && !f.4 && !f.5 && !f.6,+ "没声明的公理不该凭空为真,实得 {f:?}"+ );+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(org)+ .execute(&pool)+ .await?;+ run+}diff --git a/migrations/0054_owl_axioms.sql b/migrations/0054_owl_axioms.sqlnew file mode 100644index 00000000..75b4c7bf--- /dev/null+++ b/migrations/0054_owl_axioms.sql@@ -0,0 +1,44 @@+-- 本体自己声明的公理落库,给一致性检查当判定依据(0002 R0)。+--+-- 解析那一步已经做完(#121):`TransitiveProperty` / `SymmetricProperty` /+-- `AsymmetricProperty` / `IrreflexiveProperty` / `disjointWith` 现在都投影得出来,+-- 但字段只活在内存里,投影完就丢。这个迁移给它们腾位置。+--+-- **为什么非要有它们**:开发库里 143 对双向事实,`alias_of` 那 14 条是**对的**+-- (别名本来就双向),`produces` 那 88 条几乎肯定是错的。区分这两者的东西只能+-- 来自本体——没有公理,一致性检查就只能拿启发式冒充判定,而 0001 判据 2+-- 写着「本体是引导不是执法」,0002 的整个立论是「用公理裁决」。++-- 属性公理。跟 `functional` / `inverse_functional` 并排——它们本来就是同一族,+-- 只是那两个先落库了。+--+-- **默认 false 而不是 NULL**:OWL 是开放世界,但一致性检查只能按写下来的判。+-- 「没声明」与「声明为否」在这里后果相同——都不构成报矛盾的依据——所以不必+-- 用三态去区分一个不影响行为的差别。+-- **列名带 is_ 前缀不是风格洁癖**:`symmetric` 与 `asymmetric` 都是 Postgres+-- 保留字(`BETWEEN SYMMETRIC`),裸用会在 `ADD COLUMN` 那一行就报语法错。+-- 加引号能绕过去,但那要求之后每一处写这两列的 SQL 都记得加——漏一处就是+-- 运行时才炸。改名一次,后面都不必记。+ALTER TABLE relation_types+ ADD COLUMN is_transitive BOOLEAN NOT NULL DEFAULT FALSE,+ ADD COLUMN is_symmetric BOOLEAN NOT NULL DEFAULT FALSE,+ ADD COLUMN is_asymmetric BOOLEAN NOT NULL DEFAULT FALSE,+ ADD COLUMN is_irreflexive BOOLEAN NOT NULL DEFAULT FALSE;++-- 类互斥。**存成一张表而不是数组列**:要查的问题是「A 与 B 互斥吗」,+-- 那是一次点查;数组列查起来要么全表扫要么建 GIN,而这里的语义就是一条边。+--+-- 与 `entity_type_parents` 同构——同样是类与类之间的一条关系。+CREATE TABLE entity_type_disjoint (+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,+ a_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,+ b_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,+ -- 两个方向各存一行(导入侧已经把公理的对称性展开了)。主键因此天然去重,+ -- 而查询不必关心调用方从哪一头问+ PRIMARY KEY (kb_id, a_id, b_id),+ -- 自己跟自己互斥是无意义的声明,挡在门口比留着让检查去猜好+ CHECK (a_id <> b_id)+);++-- 「跟这个类互斥的有哪些」是唯一的查法(一致性检查拿实体的类去问)+CREATE INDEX entity_type_disjoint_a_idx ON entity_type_disjoint (kb_id, a_id);