Skip to content

World's first open-source enterprise world model.

A pair of classes only needs approving once (#82)

WaylandYangd77cb6c19b9b
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 6f7ea1e2..77a7cc85 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -128,6 +128,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/ontology/type-resolution",
post(ontology_routes::type_resolution_apply),
)
+ .route(
+ "/kbs/{id}/ontology/type-resolution/approve",
+ post(ontology_routes::approve_refinement),
+ )
.route(
"/kbs/{id}/ontology/type-resolution/{batch_id}",
axum::routing::delete(ontology_routes::type_resolution_undo),
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 1008ca4a..287dac39 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -1301,6 +1301,60 @@ pub async fn type_resolution_undo(
Ok(Json(json!({ "reverted": reverted })))
}
+#[derive(Deserialize)]
+pub struct ApproveRefinementReq {
+ pub from_type_id: Uuid,
+ pub to_type_id: Uuid,
+ /// 这一次要一并改掉的实体。**认可的是类对,改的是实体**——
+ /// 两件事分开,所以调用方可以只认可规则而暂不动任何实体
+ #[serde(default)]
+ pub entity_ids: Vec<Uuid>,
+}
+
+/// 认可一个"粗类 → 细类"的配对,并把随请求带来的实体改过去。
+///
+/// 待人工那一档由"跨没跨分类轴"触发,而实测那条判据测的往往是**种子类跟导入
+/// 词汇表连没连上**,不是风险——schema.org 的 Place 另起 key,于是每个城市都
+/// 要问一遍。配对认可一次就不再问:那是类与类之间的判断,实体只是碰巧撞上它。
+pub async fn approve_refinement(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<ApproveRefinementReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::resolution::approve_refinement(
+ &state.pool,
+ kb_id,
+ req.from_type_id,
+ req.to_type_id,
+ user.id,
+ )
+ .await?;
+ let picks: Vec<(Uuid, Uuid)> = req
+ .entity_ids
+ .iter()
+ .map(|id| (*id, req.to_type_id))
+ .collect();
+ let (batch, moved) = if picks.is_empty() {
+ (None, 0)
+ } else {
+ let (b, n) = utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks).await?;
+ (Some(b), n)
+ };
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "ontology.refinement_approved",
+ "entity_type",
+ Some(req.to_type_id),
+ json!({ "from": req.from_type_id, "to": req.to_type_id, "moved": moved }),
+ )
+ .await;
+ Ok(Json(json!({ "moved": moved, "batch": batch })))
+}
+
#[cfg(test)]
mod tests {
use super::{normalize_name, resolve_map_targets};
diff --git a/crates/utopia-server/src/type_resolution.rs b/crates/utopia-server/src/type_resolution.rs
index eb1d380e..684cd9c1 100644
--- a/crates/utopia-server/src/type_resolution.rs
+++ b/crates/utopia-server/src/type_resolution.rs
@@ -39,6 +39,9 @@ pub struct TypeSuggestion {
pub entity_id: Uuid,
pub name: String,
pub coarse: String,
+ /// 粗类的 id。裁决要拿它跟目标类配成一对,去查"这一对人认可过没有"
+ #[serde(skip)]
+ pub coarse_id: Uuid,
pub proposed_type: Option<String>,
pub specific_type: Option<String>,
pub fact_count: i64,
@@ -98,11 +101,35 @@ pub async fn preview(state: &AppState, kb_id: Uuid) -> AppResult<Vec<TypeSuggest
if subjects.is_empty() {
return Ok(Vec::new());
}
+ // **每个实体两个查询,不是一个。**
+ //
+ // 画像里模型自己的说法排在最前,但后面整段是语境,一样进向量。实测
+ //「杭州拱墅区」的画像是 `district. 杭州拱墅区. located_in by 仁和堂连锁药房.
+ // 仁和堂连锁药房在杭州拱墅区开设了第 40 家门店`——整段讲的是药房,
+ // 于是候选给回 pharmacy、store,而 administrative_area 一次都没上来。
+ // 名字被稀释进了段落。
+ //
+ // 所以名字单独发一次:短查询对短标签,正是这个索引擅长的形状;
+ // 画像那一次仍然发,它照顾没有 specific_type 的实体和需要语境才判得出的。
+ // 两次结果取并集——多一次嵌入,换掉一整类漏检。
let profiles: Vec<String> = subjects.iter().map(profile_of).collect();
- let per_entity = ontology_index::nearest_for_each(
+ let names: Vec<Option<String>> = subjects.iter().map(name_query_of).collect();
+ let mut queries: Vec<String> = Vec::with_capacity(subjects.len() * 2);
+ // 每个实体在 queries 里占的下标:(画像, 名字)
+ let mut slots: Vec<(usize, Option<usize>)> = Vec::with_capacity(subjects.len());
+ for (p, n) in profiles.iter().zip(&names) {
+ let pi = queries.len();
+ queries.push(p.clone());
+ let ni = n.as_ref().map(|q| {
+ queries.push(q.clone());
+ queries.len() - 1
+ });
+ slots.push((pi, ni));
+ }
+ let hits = ontology_index::nearest_for_each(
state,
kb_id,
- &profiles,
+ &queries,
// 多取一些再按祖先过滤:过滤在检索之后,所以要留出被滤掉的余量
CANDIDATES * 4,
ontology_index::Target::Class,
@@ -126,14 +153,34 @@ pub async fn preview(state: &AppState, kb_id: Uuid) -> AppResult<Vec<TypeSuggest
.await?
.into_iter()
.collect();
- let mut ranked: Vec<_> = per_entity
- .get(i)
- .cloned()
- .unwrap_or_default()
+ // **两路交替取,不按距离合并。**
+ //
+ // 距离在两路之间不可比:短查询("医药集团")产生的距离系统性地小于
+ // 一整段画像,按距离排就等于让名字那一路独占前几名。实测这么做之后
+ // 仁和医药集团、国家药监局、中华医学会全被挤掉了正确候选——
+ // 上一轮它们是自动通过的。跟 A/B 两路那条"取并集不合分数"同一条,
+ // 我在这儿违反了它。
+ //
+ // 交替之后两路各占一半席位,谁的距离数值大小不再影响谁被看见。
+ let (pi, ni) = slots[i];
+ let lists: Vec<Vec<_>> = [Some(pi), ni]
.into_iter()
- .filter(|c| c.id != s.coarse_id)
+ .flatten()
+ .map(|idx| hits.get(idx).cloned().unwrap_or_default())
.collect();
- // 稳定排序:后代提前,同一档内保持检索给的距离序
+ let mut seen_ids: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
+ let mut ranked: Vec<utopia_core::models::TypeCandidate> = Vec::new();
+ let longest = lists.iter().map(Vec::len).max().unwrap_or(0);
+ for rank in 0..longest {
+ for list in &lists {
+ let Some(c) = list.get(rank) else { continue };
+ if c.id == s.coarse_id || !seen_ids.insert(c.id) {
+ continue;
+ }
+ ranked.push(c.clone());
+ }
+ }
+ // 稳定排序:后代提前,同一档内保持距离序
ranked.sort_by_key(|c| !descendants.contains(&c.id));
let candidates: Vec<_> = ranked.into_iter().take(CANDIDATES as usize).collect();
// 第二路:语境相似的已定类实体,按类投票
@@ -181,6 +228,7 @@ pub async fn preview(state: &AppState, kb_id: Uuid) -> AppResult<Vec<TypeSuggest
entity_id: s.id,
name: s.canonical_name.clone(),
coarse: s.coarse_key.clone(),
+ coarse_id: s.coarse_id,
proposed_type: s.proposed_type.clone(),
specific_type: s.specific_type.clone(),
fact_count: s.fact_count,
@@ -199,6 +247,8 @@ pub async fn preview(state: &AppState, kb_id: Uuid) -> AppResult<Vec<TypeSuggest
/// `label + description`——一个类名对一段类定义,比一串谓词对一段类定义近得多。
///
/// 名字、别名其次;谓词与引文垫后当语境。
+///
+/// 这一段是**语境查询**,跟 [`name_query_of`] 那个短查询各发一次、结果取并集。
fn profile_of(s: &utopia_store::resolution::TypeCandidateSubject) -> String {
let mut parts: Vec<String> = Vec::new();
// 模型自己的说法放最前面,两个都有就都写。它们是**名字**,而检索的目标
@@ -285,6 +335,9 @@ pub struct ReviewItem {
pub entity_id: Uuid,
pub name: String,
pub coarse: String,
+ /// 配对的两端。认可这一条时认可的是**这一对类**,不是这一个实体
+ pub from_type_id: Uuid,
+ pub to_type_id: Uuid,
pub choice: String,
pub confidence: f32,
pub reason: Option<String>,
@@ -330,6 +383,9 @@ pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutco
// 候选之外的 key(本体里可能根本没有),那种不该落库
let by_name: std::collections::HashMap<&str, &TypeSuggestion> =
items.iter().map(|i| (i.name.as_str(), i)).collect();
+ // 人认可过的配对:同一对不再进人工。跨轴是类与类之间的事,
+ // 实体只是碰巧撞上它——第二个城市不该再问一遍
+ let approved = utopia_store::resolution::approved_refinements(&state.pool, kb_id).await?;
let mut picks: Vec<(Uuid, Uuid)> = Vec::new();
let mut for_review: Vec<ReviewItem> = Vec::new();
let mut left_alone: Vec<DeclineNote> = Vec::new();
@@ -346,7 +402,13 @@ pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutco
continue;
};
decided.insert(item.name.as_str());
- let Some(choice) = v.choice.as_deref().map(str::trim).filter(|c| !c.is_empty()) else {
+ // **字符串 "null" 也是 null。** 模型时而给 JSON null、时而给这四个字母,
+ // 而当成 key 去查候选必然查不到,于是这条被记成"选了个候选之外的 key"——
+ // 一条编造的拒绝理由盖掉了模型真正给的那条。拒绝的理由是这一步最要紧的
+ // 输出,被自己的解析弄脏比没有更糟
+ let Some(choice) = v.choice.as_deref().map(str::trim).filter(|c| {
+ !c.is_empty() && !c.eq_ignore_ascii_case("null") && !c.eq_ignore_ascii_case("none")
+ }) else {
left_alone.push(decline(item, v.reason.clone()));
continue;
};
@@ -366,7 +428,8 @@ pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutco
// 不在 = 换了一条分类轴(判成 product 的东西落到了 CreativeWork 底下),
// 那是重新分类而不是精化,值得一个人看一眼。实测那一轮唯一明确的错
//(《中国数据智能》→ publication_issue)正是这一类。
- let crosses_axis = !item.descendants.contains(&target.id);
+ let crosses_axis = !item.descendants.contains(&target.id)
+ && !approved.contains(&(item.coarse_id, target.id));
if confidence >= AUTO_THRESHOLD && !crosses_axis {
picks.push((item.entity_id, target.id));
} else {
@@ -374,6 +437,8 @@ pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutco
entity_id: item.entity_id,
name: item.name.clone(),
coarse: item.coarse.clone(),
+ from_type_id: item.coarse_id,
+ to_type_id: target.id,
choice: choice.to_string(),
confidence,
reason: v.reason.clone(),
@@ -470,3 +535,22 @@ fn adjudication_prompt(items: &[TypeSuggestion]) -> String {
blocks.join("\n\n")
)
}
+
+/// 只有名字的那个查询:模型自己的说法,别的一概不放。
+///
+/// **分开发的理由是稀释。** 语境查询里这几个词排在最前,但后面整段一样进向量,
+/// 而语境讲的往往是别人:「杭州拱墅区」的引文在讲一家药房,于是候选回来的是
+/// pharmacy、store。短查询对短标签没有这个问题——检索目标(类的 label)
+/// 本来就是名字。
+///
+/// 两个说法都没有就返回 `None`:只剩实体名的查询跟语境查询的开头一模一样,
+/// 再发一次是白花一次嵌入。
+fn name_query_of(s: &utopia_store::resolution::TypeCandidateSubject) -> Option<String> {
+ let parts: Vec<&str> = [s.specific_type.as_deref(), s.proposed_type.as_deref()]
+ .into_iter()
+ .flatten()
+ .map(str::trim)
+ .filter(|x| !x.is_empty())
+ .collect();
+ (!parts.is_empty()).then(|| parts.join(". "))
+}
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 0de9773c..fb8f608f 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -1914,3 +1914,44 @@ pub async fn retype_entities(
}
Ok((batch_id, moved))
}
+
+/// 人认可过的"粗类 → 细类"配对。
+///
+/// 待人工那一档由"跨没跨分类轴"触发,而那条判据测的常常是**种子类跟导入词汇表
+/// 连没连上**,不是风险:schema.org 的 Place 另起 key,内置 location 零子类,
+/// 于是每个城市都要问一遍。配对是类与类之间的事,实体只是碰巧撞上它——
+/// 认可一次就该一直算数。
+pub async fn approved_refinements(
+ pool: &PgPool,
+ kb_id: Uuid,
+) -> AppResult<std::collections::HashSet<(Uuid, Uuid)>> {
+ let rows: Vec<(Uuid, Uuid)> = sqlx::query_as(
+ "SELECT from_type_id, to_type_id FROM type_refinement_pairs WHERE kb_id = $1",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().collect())
+}
+
+/// 记下一个被认可的配对。重复认可是幂等的。
+pub async fn approve_refinement(
+ pool: &PgPool,
+ kb_id: Uuid,
+ from_type_id: Uuid,
+ to_type_id: Uuid,
+ by: Uuid,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO type_refinement_pairs (kb_id, from_type_id, to_type_id, approved_by)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (kb_id, from_type_id, to_type_id) DO NOTHING",
+ )
+ .bind(kb_id)
+ .bind(from_type_id)
+ .bind(to_type_id)
+ .bind(by)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
diff --git a/docs/decisions/0001-ontology-import-and-governance.md b/docs/decisions/0001-ontology-import-and-governance.md
index 98e0292e..1417b111 100644
--- a/docs/decisions/0001-ontology-import-and-governance.md
+++ b/docs/decisions/0001-ontology-import-and-governance.md
@@ -1,6 +1,6 @@
# 0001 · 本体导入与治理路线
-- **状态**:进行中 · P0(实体可编辑)与 P1(停止静默丢弃)已建成;P3b 部分建成,见 [0003](0003-ontology-growth-loop.md)
+- **状态**:进行中 · P0(实体可编辑)、P1(停止静默丢弃)、P2(OWL 导入)、P2c(属性落库 / 关联表 / 类型签名 / 多继承)已建成;P3a(类型消解)已建成但检索命中率不足以自动跑,见下方修订记录;P3b 部分建成,见 [0003](0003-ontology-growth-loop.md)
- **成文**:2026-08-27 / 28,随调研持续修订(约定见 [README](README.md))
> 理由比清单重要——清单会过期,理由决定以后遇到新情况怎么判。所以本文把「贯穿性判据」放在分阶段之前,且推翻过的判断就地留痕(见 P1、P3 的修订记录)。
@@ -351,8 +351,78 @@ OWL 里一个属性有多个 domain 是常态。`datatype` 仍留在 `relation_t
2. **类型消解(新后台任务)**——类的 `label + description` 嵌入成向量(一次性);实体积累名字和事实后,用**合成文本**(名字 + 参与的谓词 + 粗类)嵌入检索 top-k 候选类,只把这 k 个交给 LLM 裁决。高置信自动升格,灰区进 Review,结果缓存。
3. **推理推出的类型**——有 `equivalentClass` 定义的类无需模型判断(等 P5)。
+> **修订记录(跑过真实本体之后)**。上面三条写在没人量过真实本体的时候,实测把
+> 其中两条推翻了。原文留着,因为推翻它的理由比结论有用。
+>
+> **一、「800 个类」是低估,而且类清单不是大头。** schema.org 当前版实测 1010 类 /
+> 1676 属性,抽取提示词 **109,083 tokens 一个分块**。三段的占比是
+> 类 38% / 关系 34% / 属性 28%——**第一层只碰得到 38% 的那一段**,且原文完全没提
+> 属性段。就算把类砍到只剩顶层,提示词仍有约 64k。
+>
+> **二、「只列基础类」是错的**,理由有三条,都在数据里:
+> - 它把用户自己编的本体从抽取里整个拿掉。40 个类约 2k tokens,**根本不构成问题**;
+> 拿 968 个类的数字去论证所有本体都只列 6 个,是过度外推。我们只有 12 个类(好)
+> 与 968 个类(坏)两个点,中间一片空白。
+> - 它是 `related_to` 那个坑的镜像:**给了逃生舱模型就会用**。只列基类等于让所有
+> 东西都只能是 `organization`。
+> - 抽取当场因粗类丢掉的事实**改类救不回来**(`type_matches_domain` 在落地时就
+> 校验 domain,实测见 `attr_domain_mismatch: position@person`);而粗类还会让
+> 实体互相更"像",`classify_type_drift` 判不出 `Disjoint`,可合并候选变多,
+> **合并是真写账本的**。
+>
+> **改成按预算**:本体小于预算就全列(今天就是这样且工作正常);超了才按分块检索
+> top-K 内联,**且种子基类永远在场**当兜底。属性按 domain 逐类展开,类被裁了它自动
+> 跟着裁。预算按 token 数而不是类数量——类描述长度差着数量级。**预算定在哪还没量**,
+> 那需要把内联类数从 12 逐级加到 968,看事实数与耗时在哪一档开始掉。
+>
+> **三、第二层建成了,但比原文写的复杂**,见下。
+
+#### P3a · 类型消解实测(已建成)
+
+抽取给粗类,另给一个 **`specific_type`**:自由文本、不校验、不入本体,就是模型自己
+对这个实体的说法。**它是这一步的关键**——没有它,实测 17 个实体的 `proposed_type`
+全是空的,因为清单里总有个"差不多"的(本体有 `product`,模型选了它,心里那个
+"向量数据库软件"就此丢失)。有了它,任务从「读懂这是什么」变回「本体里哪个类叫
+这个名字」:短名字对短标签,正是向量索引擅长的形状。加上它之后,检索命中从
+**4/17 变成约 13/20**。
+
+**候选两路来,取并集不合分数**:一路拿画像搜类的描述,一路拿语境向量搜已定类的
+实体、把它们的类当票投。第二路冷启动时结构性无效(库里已定类的实体全挂着基类,
+投不出更细的东西),它是第一路跑过一轮之后的放大器。
+
+**距离不可比,三处都栽过**:跨实体不可比(`清华大学计算机系→computer_store` 0.46
+比 `星云科技→corporation` 0.59 还近,而前者荒谬);两路之间不可比(类空间 vs
+实体空间);**同一路的两个查询之间也不可比**——短查询"医药集团"产生的距离系统性地
+小于一整段画像,按距离合并就让名字那一路独占前几名,实测挤掉了三个上一轮自动
+通过的正确答案。**一律交替取,不合分数。**
+
+**分档不能用模型自报的 confidence**:实测是双峰的(15 条全 ≥0.85、4 条 null,
+中间没有)——自报置信度是语气不是概率。改用「选中的类在不在粗类子树里」:在 =
+往下走一格,自动;不在 = 换了分类轴,进人工。
+
+> **但这条判据测的往往不是风险。** 第二份语料 24 个实体报了 14 条跨轴、条条正确,
+> 因为它实际在测**种子类跟导入词汇表的分类树连没连上**:`organization`/`product`
+> 的 key 撞上了 schema.org 的同名类(被认领,子树 167/8 个后代),而 `location`
+> 没撞上——schema.org 的 `Place` 另起一个 key、209 个后代全挂那边,内置 `location`
+> 零子类,于是每一次 `location → city` 都算跨轴。
+>
+> 缓解办法是**按类对认可,不按实体**(`type_refinement_pairs`):跨轴是
+> (粗类, 目标类) 这一对的属性,人认可一次就不再问。根治要把种子类接进导入本体的
+> 分类树——那是本体对齐,比这一步大。
+
+**拒绝必须给理由。** `left_alone` 一开始只是个数,而这一步的整个设计押在"选择
+'都不是'是个体面答案"上——最大的一档不透明。记上理由之后第一次跑就回答了此前
+答不出的问题:失败**全在检索一侧**(`administrative_area`、`periodical` 从没被端
+上来过),不在裁决。
+
+**改类不进时间轴**:它是 `entities` 上一次 UPDATE 加一行 `entity_retypes`,
+实体历史只读 `facts`。所以错了不会自己显形——可撤销不等于会被撤销。这是先做
+preview 再做 apply 的理由。**该补的是让改类在实体历史里显形**,而不是把类型搬上
+双时态账本(P0 明确把实体做成可变行)。
+
#### P3b · 关系清单同样会膨胀(原先漏掉的)
+
> **本节的抽取侧已建成**(撤逃生舱、提示词规则 8、表层谓词落在证据上);
> **映射回本体那一半也建成了,但形态与这里写的不同**——不是全自动的检索裁决,
> 而是「聚类 → 带影响面的提案 → 一键采纳并改写 → 可撤销」,加一个默认开启的开关。
diff --git a/migrations/0040_type_refinement_pairs.sql b/migrations/0040_type_refinement_pairs.sql
new file mode 100644
index 00000000..d35cf8ff
--- /dev/null
+++ b/migrations/0040_type_refinement_pairs.sql
@@ -0,0 +1,17 @@
+-- 人认可过的"粗类 → 细类"配对。认可一次,之后同一对不再进人工。
+--
+-- 为什么需要它:待人工那一档由"选中的类在不在粗类子树里"触发,而实测那条
+-- 判据测的往往不是风险,是**种子类跟导入词汇表的分类树连没连上**。
+-- schema.org 的 Place 另起了 place 这个 key,内置 location 一个子类都没有,
+-- 于是每一次 location → city 都算跨轴——24 个实体里报了 14 条,条条正确。
+--
+-- 跨轴是 (粗类, 目标类) 这一对的属性,不是实体的属性。人看过一次
+-- "location 下面的东西可以是 city",第二个城市就不该再问一遍。
+CREATE TABLE type_refinement_pairs (
+ kb_id uuid NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ from_type_id uuid NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,
+ to_type_id uuid NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,
+ approved_by uuid REFERENCES users(id),
+ approved_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, from_type_id, to_type_id)
+);