Elffuss BraidHub

kikocis/utopia public

Merge pull request #235 from deeplethe/dev

Fixes from the end-to-end pass, and compose points at rc2
Changeset8afa1e7023505bb714693889f6110cd74c637012c174762649ea9f7eef7cd097
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 06:10 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 06:10 +08:00
Parentsfa91ee90e6a9, 0ef209005f0f

Browse the files at this changeset

19 files changed

modified .github/workflows/release.yml +1 −1
@@ -9,7 +9,7 @@
99 workflow_dispatch:
1010 inputs:
1111 tag:
12- description: "Image tag to publish (e.g. 0.1.0-rc1)"
12+ description: "Image tag to publish (e.g. 0.1.0-rc2)"
1313 required: true
1414
1515 permissions:
modified crates/utopia-core/src/models.rs +3 −0
@@ -194,6 +194,9 @@
194194 pub target_kind: String,
195195 pub target_id: Option<Uuid>,
196196 pub detail: serde_json::Value,
197+ /// NULL = 引擎自动(裁决器合并、一致性检查、推理物化……)。界面靠它把
198+ /// 「没有人」和「人已被移除」分开:后者 actor_id 还在,只是查不到显示名
199+ pub actor_id: Option<Uuid>,
197200 pub actor_name: Option<String>,
198201 pub created_at: DateTime<Utc>,
199202 }
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/api/sources_routes.rs +41 −10
@@ -285,6 +285,10 @@
285285 #[derive(Deserialize)]
286286 pub struct IngestBody {
287287 pub filename: String,
288+ /// 墓碑推送(`deleted: true`)可以不带 content——指南一直这么写,而字段
289+ /// 从前是必填,缺了就在反序列化那一步被拒。其余情况仍然必填:空串在
290+ /// 下面的校验里挡
291+ #[serde(default)]
288292 pub content: String,
289293 #[serde(default)]
290294 pub doc_time: Option<DateTime<Utc>>,
@@ -341,14 +345,33 @@
341345 Ok(Json(json!({ "action": action_str(action) })))
342346 }
343347
348+/// 推送失败的两种性质。**调用方发错了**和**我们这边没接住**得分开:前者记进
349+/// run 供集成调试,但不算来源同步失败——来源没坏,是那一次请求不合格;
350+/// 后者才该把来源标成 failed 并进告警中心。从前两者都走 `finish_sync(error)`,
351+/// 一次格式错误就让铃铛说"来源同步失败,没有新内容进来"
352+enum PushError {
353+ /// 4xx:负载不合格(JSON 解析、缺字段)
354+ Rejected(String),
355+ /// 摄入本身失败
356+ Failed(String),
357+}
358+
359+impl PushError {
360+ fn message(&self) -> &str {
361+ match self {
362+ PushError::Rejected(m) | PushError::Failed(m) => m,
363+ }
364+ }
365+}
366+
344367 /// 认证之后的推送处理:解析 + 校验 + 摄入/墓碑。错误一律返回文字(记进 run)。
345368 async fn handle_push(
346369 state: &AppState,
347370 source: &utopia_core::models::Source,
348371 bytes: &[u8],
349-) -> Result<crate::ingest_sources::IngestAction, String> {
350- let body: IngestBody =
351- serde_json::from_slice(bytes).map_err(|e| format!("Invalid JSON payload: {e}"))?;
372+) -> Result<crate::ingest_sources::IngestAction, PushError> {
373+ let body: IngestBody = serde_json::from_slice(bytes)
374+ .map_err(|e| PushError::Rejected(format!("Invalid JSON payload: {e}")))?;
352375 let identity = body
353376 .external_id
354377 .as_deref()
@@ -357,7 +380,9 @@
357380 .unwrap_or_else(|| body.filename.trim())
358381 .to_string();
359382 if identity.is_empty() {
360- return Err("external_id or filename is required".into());
383+ return Err(PushError::Rejected(
384+ "external_id or filename is required".into(),
385+ ));
361386 }
362387 let key = format!("api:{identity}");
363388
@@ -365,12 +390,14 @@
365390 if body.deleted {
366391 utopia_store::documents::mark_missing_keys(&state.pool, source.id, &[key])
367392 .await
368- .map_err(|e| e.to_string())?;
393+ .map_err(|e| PushError::Failed(e.to_string()))?;
369394 return Ok(crate::ingest_sources::IngestAction::Tombstoned);
370395 }
371396
372397 if body.filename.trim().is_empty() || body.content.trim().is_empty() {
373- return Err("filename and content are required".into());
398+ return Err(PushError::Rejected(
399+ "filename and content are required".into(),
400+ ));
374401 }
375402 let action = crate::ingest_sources::ingest_item(
376403 state,
@@ -383,11 +410,11 @@
383410 body.doc_time,
384411 )
385412 .await
386- .map_err(|e| e.to_string())?;
413+ .map_err(|e| PushError::Failed(e.to_string()))?;
387414 // 失而复得:曾被墓碑标记的身份再次正常推送,摘掉 missing 标记
388415 utopia_store::documents::clear_missing_keys(&state.pool, source.id, &[key])
389416 .await
390- .map_err(|e| e.to_string())?;
417+ .map_err(|e| PushError::Failed(e.to_string()))?;
391418 Ok(action)
392419 }
393420
@@ -434,10 +461,14 @@
434461 state.emit_source(source.kb_id);
435462 Ok(Json(json!({ "action": action_str(action) })))
436463 }
437- Err(msg) => {
464+ Err(err) => {
465+ let msg = err.message().to_string();
438466 utopia_store::sources::finish_run(&state.pool, run, source.id, Some(&msg), 0, 0)
439467 .await?;
440- utopia_store::sources::finish_sync(&state.pool, source.id, Some(&msg), 0).await?;
468+ // 只有我们这边没接住才算来源失败;调用方发错了留在 run 历史里就够
469+ if let PushError::Failed(_) = err {
470+ utopia_store::sources::finish_sync(&state.pool, source.id, Some(&msg), 0).await?;
471+ }
441472 state.emit_source(source.kb_id);
442473 Err(utopia_core::AppError::Validation(msg).into())
443474 }
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/mappings.rs +55 −0
@@ -15,6 +15,39 @@
1515
1616 const MAX_SCHEMA_CHARS: usize = 12_000;
1717
18+/// 探索把 schema 里的量与维度落成 Metric / Dimension 实体,而这两个类不在任何
19+/// 内置本体包里——0009 之后建库不再自带类。没有它们,下面的 `type_id` 查不到,
20+/// 每条提议都被 `continue` 吞掉,页面只说"已排队"就再无下文(#223)。
21+/// 所以探索前把两个类补上:builtin,描述给抽取提示词,本体页可以改
22+async fn ensure_concept_types(pool: &sqlx::PgPool, kb_id: Uuid) -> anyhow::Result<()> {
23+ for (key, label, description) in [
24+ (
25+ "metric",
26+ "Metric",
27+ "An aggregatable business quantity (revenue, order count, average ticket) that maps to a definition in a mounted database.",
28+ ),
29+ (
30+ "dimension",
31+ "Dimension",
32+ "A group-by attribute (region, month, product line) that maps to a column in a mounted database.",
33+ ),
34+ ] {
35+ sqlx::query(
36+ "INSERT INTO entity_types (id, kb_id, key, label, builtin, description)
37+ SELECT $1, $2, $3, $4, TRUE, $5
38+ WHERE NOT EXISTS (SELECT 1 FROM entity_types WHERE kb_id = $2 AND key = $3)",
39+ )
40+ .bind(Uuid::now_v7())
41+ .bind(kb_id)
42+ .bind(key)
43+ .bind(label)
44+ .bind(description)
45+ .execute(pool)
46+ .await?;
47+ }
48+ Ok(())
49+}
50+
1851 pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
1952 let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
2053 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
@@ -27,6 +60,7 @@
2760 if sources.is_empty() {
2861 anyhow::bail!("No data sources mounted");
2962 }
63+ ensure_concept_types(&state.pool, kb_id).await?;
3064
3165 // 各源 schema(引擎直读,保证新鲜;限量防 prompt 爆炸)
3266 let mut schema_txt = String::new();
@@ -168,6 +202,27 @@
168202 }
169203
170204 tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列");
205+ // 一条都没提出来时页面上什么都不会变——Pending 还是 0,而"已排队"那句
206+ // 早就翻篇了。走告警中心说一声,人才知道该去刷新结构或给列加注释
207+ if accepted == 0 {
208+ if let Err(e) = utopia_store::alerts::raise(
209+ &state.pool,
210+ utopia_store::alerts::NewAlert {
211+ kb_id: Some(kb_id),
212+ severity: "info",
213+ kind: utopia_store::alerts::kind::MAPPING_EXPLORATION_EMPTY,
214+ min_role: utopia_core::models::Role::Editor,
215+ subject_type: None,
216+ subject_id: None,
217+ detail: serde_json::json!({ "proposals": 0, "sources": source_names }),
218+ },
219+ )
220+ .await
221+ {
222+ tracing::warn!(%kb_id, error = %e, "映射探索空结果的告警没写进去");
223+ }
224+ state.emit_alert();
225+ }
171226 state.emit_review(kb_id);
172227 Ok(())
173228 }
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/alerts.rs +3 −0
@@ -51,6 +51,9 @@
5151 /// 哪些表——`query_data` 照样入列,模型却只能瞎猜列名。挂载那一刻的报错
5252 /// 只有点按钮的人看得见,此后这个库就一直这样静默地缺着。
5353 pub const SCHEMA_SYNC_FAILED: &str = "data_source.schema_sync_failed";
54+ /// 库级:映射探索跑完了,一条口径都没提出来。`severity = info`,`min_role = editor`——
55+ /// 不是故障,是"你在等的那件事没有结果",而页面上没有别的地方能说这句话(#223)
56+ pub const MAPPING_EXPLORATION_EMPTY: &str = "mapping.exploration_empty";
5457 }
5558
5659 /// 一次故障。打包成结构体不只是为了参数个数——调用点写 `severity: "error"`
modified crates/utopia-store/src/audit.rs +2 −2
@@ -101,7 +101,7 @@
101101 OR e.action LIKE 'conflict.%' OR e.action LIKE 'merge.%')";
102102 let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
103103 "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
104- u.display_name AS actor_name, e.created_at
104+ e.actor_id, u.display_name AS actor_name, e.created_at
105105 FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
106106 WHERE {COND} ORDER BY e.created_at DESC LIMIT $2 OFFSET $3"
107107 ))
@@ -152,7 +152,7 @@
152152
153153 let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
154154 "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
155- u.display_name AS actor_name, e.created_at
155+ e.actor_id, u.display_name AS actor_name, e.created_at
156156 FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
157157 {WHERE}
158158 ORDER BY e.created_at DESC LIMIT $6 OFFSET $7"
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。
modified crates/utopia-store/src/resolution.rs +47 −2
@@ -445,6 +445,8 @@
445445 canonical_name: String,
446446 // None = 这个候选还没判出类型(0009)
447447 type_key: Option<String>,
448+ // 同上;`types_are_kin` 要按 id 走类层级
449+ type_id: Option<Uuid>,
448450 // 抽取升格要看它:人说过「就是没有类型」时,那也是一个决定
449451 type_source: String,
450452 profile_embedding: Option<Vector>,
@@ -464,6 +466,40 @@
464466 }
465467 }
466468
469+/// 两个类是不是一家的:一方是另一方的祖先,或者两者共有一个**不是根**的祖先。
470+///
471+/// `CONFUSABLE_TYPE_KEYS` 那张三 key 的硬表是给没装包的库准备的;装了 schema.org
472+/// 之后同一家公司会被抽成 Organization / Corporation / OnlineBusiness 三种类型,
473+/// 全都在 Organization 之下,却一对都过不了硬表,于是三个同名实体并存、
474+/// 审阅队列里一条都没有,面板还指着 Review 说"去那里合并"(#226)。
475+///
476+/// 根不算共同祖先:schema.org 里万物皆 Thing,算上它 Person 与 Organization
477+/// 也成了一家。没有根的词汇表(W3C Org 的 Organization 自己就是顶)靠
478+/// 祖先/后代那一半接住
479+async fn types_are_kin(pool: &PgPool, a: Uuid, b: Uuid) -> AppResult<bool> {
480+ let (kin,): (bool,) = sqlx::query_as(
481+ "WITH RECURSIVE up_a(id) AS (
482+ SELECT $1::uuid
483+ UNION
484+ SELECT p.parent_id FROM entity_type_parents p JOIN up_a ON p.child_id = up_a.id
485+ ), up_b(id) AS (
486+ SELECT $2::uuid
487+ UNION
488+ SELECT p.parent_id FROM entity_type_parents p JOIN up_b ON p.child_id = up_b.id
489+ )
490+ SELECT EXISTS (SELECT 1 FROM up_a WHERE id = $2)
491+ OR EXISTS (SELECT 1 FROM up_b WHERE id = $1)
492+ OR EXISTS (SELECT 1 FROM up_a JOIN up_b USING (id)
493+ WHERE EXISTS (SELECT 1 FROM entity_type_parents p
494+ WHERE p.child_id = up_a.id))",
495+ )
496+ .bind(a)
497+ .bind(b)
498+ .fetch_one(pool)
499+ .await?;
500+ Ok(kin)
501+}
502+
467503 fn confusable_reviews(
468504 // None = 这一侧还没判出类型(0009)
469505 mention_key: Option<&str>,
@@ -510,7 +546,7 @@
510546 None => None,
511547 };
512548 let cross: Vec<CrossCandidate> = sqlx::query_as(
513- "SELECT e.id, e.canonical_name, t.key AS type_key, e.type_source,
549+ "SELECT e.id, e.canonical_name, t.key AS type_key, e.type_id, e.type_source,
514550 e.profile_embedding, e.profile_n
515551 FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id
516552 -- IS DISTINCT FROM 而不是 <>:后者遇 NULL 返回 NULL,被 WHERE 当假,
@@ -528,7 +564,16 @@
528564 let mut recall_cands: Vec<&CrossCandidate> = Vec::new();
529565 let mut review_cands: Vec<&CrossCandidate> = Vec::new();
530566 for c in &cross {
531- match classify_type_drift(mention_key.as_deref(), c.type_key.as_deref()) {
567+ let mut drift = classify_type_drift(mention_key.as_deref(), c.type_key.as_deref());
568+ // 硬表判不上的,再看类层级:同一支系下的同名当易混,进审阅队列
569+ if drift == TypeDrift::Disjoint {
570+ if let (Some(a), Some(b)) = (type_id, c.type_id) {
571+ if types_are_kin(pool, a, b).await? {
572+ drift = TypeDrift::Review;
573+ }
574+ }
575+ }
576+ match drift {
532577 TypeDrift::Recall => recall_cands.push(c),
533578 TypeDrift::Review => review_cands.push(c),
534579 TypeDrift::Disjoint => {}
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+}
modified docker-compose.yml +1 −1
@@ -37,7 +37,7 @@
3737 # 写一个不存在的标签,clone 下来第一步就是 manifest unknown。
3838 # 所以撤掉一个版本时必须连它一起改——0.1.0 撤了,现在指向 rc。
3939 # 转正之后改回 0.1.0(或改成 latest 让它自动跟随)。
40- image: ${UTOPIA_IMAGE:-ghcr.io/deeplethe/utopia:0.1.0-rc1}
40+ image: ${UTOPIA_IMAGE:-ghcr.io/deeplethe/utopia:0.1.0-rc2}
4141 profiles: ["app"]
4242 environment:
4343 # 默认以 owner 身份运行。要启用受限角色(业务表随便读写、台账只增不改),
modified web/src/api.ts +2 −0
@@ -132,6 +132,8 @@
132132 target_kind: string;
133133 target_id: string | null;
134134 detail: Record<string, unknown>;
135+ /** null = 引擎自动(裁决器、一致性检查、推理);有 id 没名字 = 账号已移除 */
136+ actor_id: string | null;
135137 actor_name: string | null;
136138 created_at: string;
137139 }
modified web/src/i18n/en.ts +9 −1
@@ -201,6 +201,10 @@
201201 title: "A data source is mounted, but its schema is not",
202202 hint: "Ask cannot see which tables exist, so it will guess column names. Check the connection, then use Refresh schema.",
203203 },
204+ "mapping.exploration_empty": {
205+ title: "Mapping exploration proposed nothing",
206+ hint: "The model read the mounted schema but found no metric or dimension to propose. Refresh the schema under Data mapping > Data sources, add column comments if you can, then run Explore again.",
207+ },
204208 "llm.unreachable": {
205209 title: "The model endpoint gave no usable answer",
206210 hint: "Extraction and embedding are stopped. Check the endpoint URL in system settings.",
@@ -1214,7 +1218,8 @@
12141218 explore: "Explore mappings",
12151219 exploreHint:
12161220 "An agent reads these schemas and proposes metric and dimension definitions. Proposals land in Pending; Ask uses them only once confirmed.",
1217- exploreQueued: "Exploration queued — proposals will appear under Pending.",
1221+ exploreQueued:
1222+ "Exploration queued — proposals will appear under Pending. If nothing can be proposed, the alert bell will say so.",
12181223 sourcesEmpty: "No data sources mounted.",
12191224 sourcesNoneAvailable:
12201225 "No data sources registered yet — ask a deployment admin to register one.",
@@ -1448,6 +1453,9 @@
14481453 auditTotal: (n: number) => `${n} events`,
14491454 activityEmpty: "Nothing recorded yet.",
14501455 deletedUser: "a removed user",
1456+ // actor_id 为空的两种引擎动作:审阅队列里的自动裁决,和其余后台工作
1457+ adjudicator: "AI adjudicator",
1458+ engine: "the engine",
14511459 auditActions: {
14521460 "entity_type.created": "created entity type",
14531461 "entity_type.updated": "updated entity type",
modified web/src/i18n/zh.ts +7 −1
@@ -180,6 +180,10 @@
180180 title: "数据源挂上了,库表结构没进来",
181181 hint: "问数看不见有哪些表,只能猜列名。检查连接串,然后点「刷新结构」。",
182182 },
183+ "mapping.exploration_empty": {
184+ title: "映射探索没有提出任何口径",
185+ hint: "模型读了挂载的库表结构,但没找到可提的指标或维度。到「数据映射 > 数据源」刷新结构、给列加注释,再探索一次。",
186+ },
183187 "llm.unreachable": {
184188 title: "模型端点没有给出可用的回答",
185189 hint: "抽取与向量化已停摆。去系统设置里检查端点地址。",
@@ -1095,7 +1099,7 @@
10951099 explore: "探查映射",
10961100 exploreHint:
10971101 "一个智能体读这些库表结构,提出指标/维度的口径。提出来的落在「待审批」,确认之后问数才会用。",
1098- exploreQueued: "探查已排队——提案稍后出现在「待审批」。",
1102+ exploreQueued: "探索已排队,提议会出现在「待确认」里;一条都提不出来时,铃铛会告诉你。",
10991103 sourcesEmpty: "没有挂载任何数据源。",
11001104 sourcesNoneAvailable: "还没有登记数据源——请部署管理员登记一个。",
11011105 newConn: "登记新连接",
@@ -1306,6 +1310,8 @@
13061310 auditTotal: (n: number) => `共 ${n} 条`,
13071311 activityEmpty: "还没有记录。",
13081312 deletedUser: "一位已移除的用户",
1313+ adjudicator: "AI 裁决器",
1314+ engine: "引擎",
13091315 auditActions: {
13101316 "entity_type.created": "创建了实体类型",
13111317 "entity_type.updated": "更新了实体类型",
modified web/src/pages/KbSettings.tsx +6 −1
@@ -492,7 +492,12 @@
492492 </span>
493493 <span className="min-w-0 truncate">
494494 <span className="text-neutral-200">
495- {e.actor_name ?? S.kbset.deletedUser}
495+ {e.actor_name ??
496+ (e.actor_id
497+ ? S.kbset.deletedUser
498+ : e.action.startsWith("review.")
499+ ? S.kbset.adjudicator
500+ : S.kbset.engine)}
496501 </span>{" "}
497502 <span className="text-neutral-500">
498503 {S.kbset.auditActions[e.action] ?? e.action}
modified web/src/pages/Library.tsx +10 −5
@@ -483,17 +483,22 @@
483483 [kb, upload, canUpload],
484484 );
485485
486- if (!kb) return <Loading>{S.nav.loading}</Loading>;
487-
488- // 服务端已经切好了这一页:筛选、作用域、页码都在请求里
489- const pagedDocs = docs.data?.docs ?? [];
490- const totalDocs = docs.data?.total ?? 0;
491486 // 整库可抽的篇数。**重建是库级动作**,不该显示当前来源的数字
492487 const kbStats = useQuery({
493488 queryKey: ["docCount", kb?.id],
494489 queryFn: () => api.documents(kb!.id, { limit: 1, offset: 0 }),
495490 enabled: !!kb,
496491 });
492+
493+ // **最后一个 hook 之后才能提前返回。** 这一行从前排在 kbStats 前面:整页
494+ // 刷新或直接打开链接时第一次渲染 kb 还没到,提前返回跳过了后面的 hook,
495+ // 下一次渲染多出一个 hook,React 直接抛 "Rendered more hooks"。站内导航
496+ // 时 kb 已在缓存里,所以只有深链和刷新会撞上
497+ if (!kb) return <Loading>{S.nav.loading}</Loading>;
498+
499+ // 服务端已经切好了这一页:筛选、作用域、页码都在请求里
500+ const pagedDocs = docs.data?.docs ?? [];
501+ const totalDocs = docs.data?.total ?? 0;
497502 const kbReady = kbStats.data?.ready ?? 0;
498503 const sourceList = sources.data?.sources ?? [];
499504 const selectedSource = sourceList.find((s) => s.id === selection);
modified web/src/useKbEvents.ts +2 −0
@@ -18,6 +18,8 @@
1818 });
1919 es.addEventListener("review", () => {
2020 queryClient.invalidateQueries({ queryKey: ["review", kbId] });
21+ // 映射探索跑完发的也是 review:Pending 那一栏得跟着刷新
22+ queryClient.invalidateQueries({ queryKey: ["mappings", kbId] });
2123 });
2224 // 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来
2325 es.addEventListener("pending", () => {