Elffuss BraidHub

kikocis/utopia public

Signatures reach across packs, and direction is judged by range too (#233)

* Signatures reach across packs, and direction is judged by range too

Closes #222

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* A test pins direction to the range as well as the domain

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Changeset2e8c07aca15a876b226e2cab7e55a48bf4b8a7b851bd013f17898be868a876f0
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 05:56 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 05:56 +08:00
Parentsa5cb6ee00a00

Browse the files at this changeset

5 files changed

modified crates/utopia-server/src/api/kbs.rs +18 −2
@@ -359,14 +359,30 @@
359359 if pack_ids.is_empty() {
360360 return Ok(());
361361 }
362+ let mut packs = Vec::with_capacity(pack_ids.len());
362363 for id in pack_ids {
363364 let pack = crate::ontology_packs::get(id)
364365 .ok_or_else(|| AppError::invalid("unknown_pack", format!("未知的本体包:{id}")))?;
365- let bytes = crate::ontology_packs::bytes(pack)?;
366- crate::owl_import::apply(state, kb_id, actor, pack.filename, &bytes)
366+ packs.push((pack, crate::ontology_packs::bytes(pack)?));
367+ }
368+ for (pack, bytes) in &packs {
369+ crate::owl_import::apply(state, kb_id, actor, pack.filename, bytes)
367370 .await
368371 .map_err(|e| AppError::Other(anyhow::anyhow!("装本体包 {} 失败:{e}", pack.id)))?;
369372 }
373+ // 第二遍:跨包的 domain / range。包是挨个装的,先装的看不见后装的类——
374+ // W3C Org 的 headOf 要等 FOAF 的 Agent(#222)。只装一个包时没有"别的包"
375+ if packs.len() > 1 {
376+ for (pack, bytes) in &packs {
377+ let (d, r) =
378+ crate::owl_import::relink_domains_ranges(state, kb_id, pack.filename, bytes)
379+ .await
380+ .map_err(|e| {
381+ AppError::Other(anyhow::anyhow!("补本体包 {} 的签名失败:{e}", pack.id))
382+ })?;
383+ tracing::debug!(%kb_id, pack = pack.id, domains = d, ranges = r, "跨包签名补链");
384+ }
385+ }
370386 Ok(())
371387 }
372388
modified crates/utopia-server/src/extraction.rs +35 −0
@@ -300,6 +300,8 @@
300300 utopia_store::documents::set_graph_status(&state.pool, document_id, "extracting").await?;
301301 state.emit_document(doc.kb_id, document_id);
302302 let etypes = utopia_store::graph::entity_types(&state.pool, doc.kb_id).await?;
303+ // 这一轮落过的事实(新建或重复观察):结尾对它们跑一遍签名检查
304+ let mut touched_facts: Vec<Uuid> = Vec::new();
303305 let rtypes = utopia_store::graph::relation_types(&state.pool, doc.kb_id).await?;
304306 // 关系与属性分道:属性走字面值通道,不进关系清单。
305307 //
@@ -762,6 +764,7 @@
762764 confidence,
763765 )
764766 .await?;
767+ touched_facts.push(fact_id);
765768 // 属性谓词也留原词:模型偶尔照抄 "person.salary" 全限定名,
766769 // 命中的是剥掉前缀后的 key,原样是什么值得留着
767770 utopia_store::graph::add_evidence(
@@ -882,6 +885,7 @@
882885 confidence,
883886 )
884887 .await?;
888+ touched_facts.push(fact_id);
885889 utopia_store::graph::add_evidence(
886890 &state.pool,
887891 fact_id,
@@ -1126,6 +1130,7 @@
11261130 confidence,
11271131 )
11281132 .await?;
1133+ touched_facts.push(fact_id);
11291134 // 重复观察也要挂证据:多来源相互印证,任一来源删除后事实不孤儿化。
11301135 // 表层谓词随每次观察落笔——甲块说 "runs on"、乙块说 "optimized for"
11311136 // 会并进同一条事实,放事实上就是先写者胜,放证据上两个都留着
@@ -1221,6 +1226,36 @@
12211226 if let Some(msg) = incomplete_reason(&unextracted, chunks.len()) {
12221227 return Err(anyhow::anyhow!(msg));
12231228 }
1229+ // 刚落的事实立刻过一遍签名。写入时只掰方向(judge_direction);掰不动的
1230+ // ——两个方向都对不上、或宾语没类型判不了——从前要等人按 Review 里的
1231+ // Run check 才露面,Axioms 一直是 0,图里却躺着反向事实(#222)。
1232+ // 检查失败不影响抽取本身:事实已经在库里,下一次 Run check 仍然查得到
1233+ if !touched_facts.is_empty() {
1234+ match utopia_store::reasoning::signature_breaks(
1235+ &state.pool,
1236+ doc.kb_id,
1237+ Some(&touched_facts),
1238+ )
1239+ .await
1240+ {
1241+ Ok(broken) if !broken.is_empty() => {
1242+ match utopia_store::reasoning::record_signature_breaks(
1243+ &state.pool,
1244+ doc.kb_id,
1245+ &broken,
1246+ )
1247+ .await
1248+ {
1249+ Ok(_) => state.emit_review(doc.kb_id),
1250+ Err(e) => {
1251+ tracing::warn!(%document_id, error = %e, "抽取后的签名违规没记进队列")
1252+ }
1253+ }
1254+ }
1255+ Ok(_) => {}
1256+ Err(e) => tracing::warn!(%document_id, error = %e, "抽取后的签名检查失败"),
1257+ }
1258+ }
12241259 utopia_store::documents::set_graph_status(&state.pool, document_id, "done").await?;
12251260 state.emit_document(doc.kb_id, document_id);
12261261
modified crates/utopia-server/src/owl_import.rs +71 −2
@@ -323,6 +323,64 @@
323323 Ok((plan, proj, format))
324324 }
325325
326+/// 装完一组包之后再过一遍:把 domain / range 指向**别的包里的类**的那些关系接上。
327+///
328+/// 单次导入认本文件里的类和库里已有的类(见 [`apply`] 里的 resolve),但包是挨个
329+/// 装的:装 W3C Org 时 FOAF 还没来,`headOf` 的 `rdfs:domain foaf:Agent` 就落了空;
330+/// 等 FOAF 装好,没人回头补。没有 domain 的谓词 `judge_direction` 不判方向,
331+/// 反向的 `Project Aurora head_of Li Ting` 就原样进图(#222)。
332+///
333+/// 只补不删,关联表 ON CONFLICT DO NOTHING,重复跑无害。属性不在这里:属性的
334+/// 去向在计划阶段就定了(没有 domain 的根本建不出来),事后补 domain 改不了它
335+/// 已经是不是一列的事实
336+pub async fn relink_domains_ranges(
337+ state: &AppState,
338+ kb_id: Uuid,
339+ filename: &str,
340+ bytes: &[u8],
341+) -> AppResult<(usize, usize)> {
342+ let format = RdfFormat::detect(filename, bytes);
343+ let proj = ontology_rdf::project(bytes, format).map_err(|e| {
344+ utopia_core::AppError::invalid_detail(
345+ "bad_ontology_file",
346+ "Could not parse this ontology file",
347+ e.to_string(),
348+ )
349+ })?;
350+ let classes: HashMap<String, Uuid> = utopia_store::graph::entity_types(&state.pool, kb_id)
351+ .await?
352+ .into_iter()
353+ .filter_map(|t| t.iri.clone().map(|i| (i, t.id)))
354+ .collect();
355+ let relations: HashMap<String, Uuid> = utopia_store::graph::relation_types(&state.pool, kb_id)
356+ .await?
357+ .into_iter()
358+ .filter_map(|r| r.iri.clone().map(|i| (i, r.id)))
359+ .collect();
360+ let mut link_d: Vec<(Uuid, Uuid)> = Vec::new();
361+ let mut link_r: Vec<(Uuid, Uuid)> = Vec::new();
362+ for p in &proj.properties {
363+ if p.is_datatype {
364+ continue;
365+ }
366+ let Some(&rid) = relations.get(&p.iri) else {
367+ continue;
368+ };
369+ link_d.extend(
370+ p.domains
371+ .iter()
372+ .filter_map(|d| classes.get(d).map(|&t| (rid, t))),
373+ );
374+ link_r.extend(
375+ p.ranges
376+ .iter()
377+ .filter_map(|r| classes.get(r).map(|&t| (rid, t))),
378+ );
379+ }
380+ utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &link_d, &link_r).await?;
381+ Ok((link_d.len(), link_r.len()))
382+}
383+
326384 /// 执行计划。属性在类之后落库——它们要挂在 domain 上,而 domain 要等
327385 /// 类先建好并解析 IRI → id(就是下面那个 `id_of`)。
328386 pub async fn apply(
@@ -500,9 +558,20 @@
500558 continue;
501559 };
502560 // domain/range 指向没被建出来的类时只丢那一个,不丢整条关系:
503- // 关系不像属性那样必须挂在类上,没有 domain 就是"不限主语类型"
561+ // 关系不像属性那样必须挂在类上,没有 domain 就是"不限主语类型"。
562+ //
563+ // **库里已有的类也算数。** 从前只认本文件里的类,于是 W3C Org 的
564+ // `headOf rdfs:domain foaf:Agent` 在 FOAF 已经装好的库里照样丢 domain,
565+ // 而没有 domain 的谓词 `judge_direction` 根本不判方向(#222)
504566 let resolve = |iris: &[String]| -> Vec<Uuid> {
505- iris.iter().filter_map(|i| id_of.get(i).copied()).collect()
567+ iris.iter()
568+ .filter_map(|i| {
569+ id_of
570+ .get(i)
571+ .copied()
572+ .or_else(|| existing_by_iri.get(i).copied())
573+ })
574+ .collect()
506575 };
507576 let domains = resolve(&p.domains);
508577 let ranges = resolve(&p.ranges);
modified crates/utopia-store/src/ontology.rs +50 −10
@@ -1784,23 +1784,63 @@
17841784 /// **三条写谓词的路共用的那一道判断**(#190 / #196):抽取落新事实、采纳把谓词
17851785 /// 挂回旧事实、合并换掉主语——从前只有抽取查,另外两条各自绕了过去。
17861786 ///
1787-/// 判据刻意窄(0012):只看 domain,只在**主语违反且宾语符合**时对调,两边都对不上
1788-/// 就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体在这一处
1789-/// 是执法的;哪些类型能参与仍是引导,不在这里裁。
1787+/// 判据刻意窄(0012):只看签名,只在**正向违反而反向成立**时对调,两个方向都
1788+/// 对不上就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体
1789+/// 在这一处是执法的;哪些类型能参与仍是引导,不在这里裁。
1790+///
1791+/// **range 也算进来**(#222)。从前只看 domain:`headOf` 的 domain 是 Agent,
1792+/// schema.org 里 Project 也是 Organization 也是 Agent,于是 `Project Aurora head_of
1793+/// Li Ting` 主语过关就 Keep,宾语是个人、range 要 Organization 这件事没人看。
1794+/// 现在两端各看各的:正向两端都不违反才 Keep;否则反过来两端都不违反才 Swap。
1795+/// 没判出类型的实体在 range 这一端不算违反("不知道"不是"不符合",与
1796+/// `signature_breaks` 同一条纪律);domain 那一端沿用旧规矩,那是 0012 定下的
17901797 pub async fn judge_direction(
17911798 pool: &PgPool,
17921799 relation_type_id: Uuid,
17931800 subject_id: Uuid,
17941801 object_id: Uuid,
17951802 ) -> AppResult<Fit> {
1796- match entity_fits_domain(pool, relation_type_id, subject_id).await? {
1797- None => Ok(Fit::Unchecked),
1798- Some(true) => Ok(Fit::Keep),
1799- Some(false) => match entity_fits_domain(pool, relation_type_id, object_id).await? {
1800- Some(true) => Ok(Fit::Swap),
1801- _ => Ok(Fit::Neither),
1802- },
1803+ let subject_in_domain = entity_fits_domain(pool, relation_type_id, subject_id).await?;
1804+ let object_in_range = entity_fits_range(pool, relation_type_id, object_id).await?;
1805+ if subject_in_domain.is_none() && object_in_range.is_none() {
1806+ return Ok(Fit::Unchecked);
18031807 }
1808+ if subject_in_domain != Some(false) && object_in_range != Some(false) {
1809+ return Ok(Fit::Keep);
1810+ }
1811+ let object_in_domain = entity_fits_domain(pool, relation_type_id, object_id).await?;
1812+ let subject_in_range = entity_fits_range(pool, relation_type_id, subject_id).await?;
1813+ if object_in_domain != Some(false) && subject_in_range != Some(false) {
1814+ return Ok(Fit::Swap);
1815+ }
1816+ Ok(Fit::Neither)
1817+}
1818+
1819+/// [`entity_fits_domain`] 的 range 版。多一条规矩:实体还没判出类型 → None,
1820+/// 不当违反——range 这一端是新加的判据(#222),不该让未分类实体的事实因此
1821+/// 丢掉谓词
1822+pub async fn entity_fits_range(
1823+ pool: &PgPool,
1824+ relation_type_id: Uuid,
1825+ entity_id: Uuid,
1826+) -> AppResult<Option<bool>> {
1827+ let (declared, typed, ok): (i64, bool, i64) = sqlx::query_as(
1828+ "WITH RECURSIVE up(id) AS (
1829+ SELECT type_id FROM entities WHERE id = $2
1830+ UNION
1831+ SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
1832+ )
1833+ SELECT (SELECT count(*) FROM relation_type_ranges WHERE relation_type_id = $1),
1834+ (SELECT type_id IS NOT NULL FROM entities WHERE id = $2),
1835+ (SELECT count(*) FROM relation_type_ranges g
1836+ JOIN up ON up.id = g.entity_type_id
1837+ WHERE g.relation_type_id = $1)",
1838+ )
1839+ .bind(relation_type_id)
1840+ .bind(entity_id)
1841+ .fetch_one(pool)
1842+ .await?;
1843+ Ok((declared > 0 && typed).then_some(ok > 0))
18041844 }
18051845
18061846 /// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
added crates/utopia-store/tests/a_direction_is_judged_by_range_too.rs +140 −0
@@ -0,0 +1,140 @@
1+//! `judge_direction` 看 range,不只看 domain(#222)。
2+//!
3+//! 从前只要主语过了 domain 就 Keep,宾语违反 range 没人看:`headOf` 的 domain 是
4+//! Agent,schema.org 里 Project 也是 Agent,于是 `Project Aurora head_of Li Ting`
5+//! 原样进图。这里用最小的本体复现那一形:一个两端都允许的 domain,一个只认
6+//! 公司的 range,反过来读才成立的事实必须被对调。
7+
8+use sqlx::PgPool;
9+use utopia_store::ontology::{judge_direction, Fit};
10+use uuid::Uuid;
11+
12+struct Fixture {
13+ /// domain = person | company,range = company
14+ leads: Uuid,
15+ alice: Uuid,
16+ acme: Uuid,
17+ globex: Uuid,
18+ /// 还没判出类型的实体
19+ mystery: Uuid,
20+}
21+
22+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
23+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
24+ let (person, company, leads) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
25+ let (alice, acme, globex, mystery) = (
26+ Uuid::now_v7(),
27+ Uuid::now_v7(),
28+ Uuid::now_v7(),
29+ Uuid::now_v7(),
30+ );
31+
32+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'direction-test')")
33+ .bind(org)
34+ .execute(pool)
35+ .await?;
36+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'direction-test')")
37+ .bind(ws)
38+ .bind(org)
39+ .execute(pool)
40+ .await?;
41+ sqlx::query(
42+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'direction-test')",
43+ )
44+ .bind(kb)
45+ .bind(ws)
46+ .execute(pool)
47+ .await?;
48+ for (id, key, label) in [
49+ (person, "person", "Person"),
50+ (company, "company", "Company"),
51+ ] {
52+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
53+ .bind(id)
54+ .bind(kb)
55+ .bind(key)
56+ .bind(label)
57+ .execute(pool)
58+ .await?;
59+ }
60+ sqlx::query(
61+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'leads', 'leads')",
62+ )
63+ .bind(leads)
64+ .bind(kb)
65+ .execute(pool)
66+ .await?;
67+ for ty in [person, company] {
68+ sqlx::query(
69+ "INSERT INTO relation_type_domains (relation_type_id, entity_type_id) VALUES ($1, $2)",
70+ )
71+ .bind(leads)
72+ .bind(ty)
73+ .execute(pool)
74+ .await?;
75+ }
76+ sqlx::query(
77+ "INSERT INTO relation_type_ranges (relation_type_id, entity_type_id) VALUES ($1, $2)",
78+ )
79+ .bind(leads)
80+ .bind(company)
81+ .execute(pool)
82+ .await?;
83+ for (id, ty, name) in [
84+ (alice, Some(person), "Alice"),
85+ (acme, Some(company), "Acme"),
86+ (globex, Some(company), "Globex"),
87+ (mystery, None, "Mystery"),
88+ ] {
89+ sqlx::query(
90+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
91+ )
92+ .bind(id)
93+ .bind(kb)
94+ .bind(ty)
95+ .bind(name)
96+ .execute(pool)
97+ .await?;
98+ }
99+ Ok(Fixture {
100+ leads,
101+ alice,
102+ acme,
103+ globex,
104+ mystery,
105+ })
106+}
107+
108+#[tokio::test]
109+async fn direction_is_judged_by_range_too() -> anyhow::Result<()> {
110+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
111+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
112+ return Ok(());
113+ };
114+ let pool = PgPool::connect(&url).await?;
115+ let f = seed(&pool).await?;
116+
117+ // 正向两端都符合:照旧
118+ assert_eq!(
119+ judge_direction(&pool, f.leads, f.alice, f.acme).await?,
120+ Fit::Keep
121+ );
122+ // 主语过了 domain(公司也允许当主语),宾语却是个人、range 只认公司。
123+ // 从前这里是 Keep——正是 Project Aurora head_of Li Ting 那一形;
124+ // 反过来读两端都成立,所以对调
125+ assert_eq!(
126+ judge_direction(&pool, f.leads, f.acme, f.alice).await?,
127+ Fit::Swap
128+ );
129+ // 宾语还没判出类型:range 这一端"不知道"不算违反,不能因此丢谓词
130+ assert_eq!(
131+ judge_direction(&pool, f.leads, f.alice, f.mystery).await?,
132+ Fit::Keep
133+ );
134+ // 两个公司:正向宾语 range 符合、主语 domain 也符合 → Keep
135+ assert_eq!(
136+ judge_direction(&pool, f.leads, f.acme, f.globex).await?,
137+ Fit::Keep
138+ );
139+ Ok(())
140+}