Elffuss BraidHub

kikocis/utopia public

b7cca7fa81d9 · 84.1 KiBRawPermalink
1//! 实体消解 v2:同名≠同人(设计见 DESIGN.md §4 实体消解 v2)。
2//!
3//! 漏斗:名字候选召回(免费,含泛用后缀词干互推)→ 画像向量相似度分层(毫秒,复用摄入阶段的 chunk embedding)
4//! → 灰区新建实体 + 疑似重复审核项(宁分勿合),LLM 攒批裁决在独立后台任务里跑,
5//! 人工终审兜底。LLM 永远不在抽取写入的关键路径上。
6//!
7//! 类型漂移:同名在同类型下无候选时再查其它类型(同一团队被抽成 organization/
8//! project/concept 是常态),按类型对的互斥强度分流——concept 兜底型当召回候选走
9//! 画像分层,易混具体类型照建实体但入队审核对,硬互斥(person vs organization)完全分开。
10
11use chrono::{DateTime, Utc};
12use pgvector::Vector;
13use sqlx::PgPool;
14use std::collections::HashSet;
15use utopia_core::models::{MergeLogView, ReviewItem, ReviewSide};
16use utopia_core::{AppError, AppResult};
17use uuid::Uuid;
18
19/// 上下文相似度阈值(bge-m3 类模型余弦相似度经验值,后续可调)。
20/// ≥ ATTACH 归并到既有实体;< NEW 判为不同实体;中间灰区宁分勿合 + 审核项。
21pub const SIM_ATTACH: f32 = 0.55;
22pub const SIM_NEW: f32 = 0.35;
23
24/// 名称规范化:全角 ASCII → 半角、全角空格 → 半角、空白折叠。
25/// 返回展示形态(保留大小写);匹配一律再套 SQL lower()。
26pub fn normalize_name(raw: &str) -> String {
27 let mapped: String = raw
28 .chars()
29 .map(|c| match c {
30 '\u{3000}' => ' ',
31 '\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c),
32 _ => c,
33 })
34 .collect();
35 mapped.split_whitespace().collect::<Vec<_>>().join(" ")
36}
37
38/// 泛用后缀词表:中文直接拼在词干后;英文按独立词算、首尾两种语序都认
39/// ("Phoenix Project" / "Project Phoenix")。只影响召回,判定仍走画像相似度。
40const GENERIC_SUFFIXES_CJK: &[&str] = &["项目", "公司", "集团", "部门", "团队"];
41const GENERIC_WORDS_EN: &[&str] = &["project", "corp", "inc", "team"];
42
43/// 词干:剥去一个泛用后缀后的 lower 形态。未命中、剥空、或词干本身就是
44/// 泛用词("项目团队")时返回 None。输入应已过 normalize_name。
45pub fn name_stem(name: &str) -> Option<String> {
46 let lower = name.to_lowercase();
47 let strip_punct = |w: &str| w.trim_end_matches(['.', ',']).to_string();
48 let generic = |s: &str| {
49 GENERIC_SUFFIXES_CJK.contains(&s) || GENERIC_WORDS_EN.contains(&strip_punct(s).as_str())
50 };
51 for suf in GENERIC_SUFFIXES_CJK {
52 if let Some(stem) = lower.strip_suffix(suf) {
53 let stem = stem.trim_end();
54 if !stem.is_empty() && !generic(stem) {
55 return Some(stem.to_string());
56 }
57 }
58 }
59 let words: Vec<&str> = lower.split(' ').collect();
60 if words.len() >= 2 {
61 if generic(words[words.len() - 1]) {
62 let stem = words[..words.len() - 1].join(" ");
63 if !generic(&stem) {
64 return Some(stem);
65 }
66 }
67 if generic(words[0]) {
68 let stem = words[1..].join(" ");
69 if !generic(&stem) {
70 return Some(stem);
71 }
72 }
73 }
74 None
75}
76
77/// mention 的召回键集合(全 lower):本名 + 词干 + 词干的泛用后缀增广。
78/// 增广覆盖反方向(库内是"星尘项目"、mention 只说"星尘");词干含 CJK 拼中文
79/// 尾缀,否则拼英文词(两种语序)。键数 ≤10,走 (kb,type,lower(name)) 索引多点查。
80pub fn recall_keys(name: &str) -> Vec<String> {
81 let lower = name.to_lowercase();
82 let base = name_stem(name).unwrap_or_else(|| lower.clone());
83 let mut keys = vec![lower];
84 fn add(keys: &mut Vec<String>, k: String) {
85 if !keys.contains(&k) {
86 keys.push(k);
87 }
88 }
89 add(&mut keys, base.clone());
90 if base.chars().any(|c| ('\u{4E00}'..='\u{9FFF}').contains(&c)) {
91 for suf in GENERIC_SUFFIXES_CJK {
92 add(&mut keys, format!("{base}{suf}"));
93 }
94 } else {
95 for w in GENERIC_WORDS_EN {
96 add(&mut keys, format!("{base} {w}"));
97 add(&mut keys, format!("{w} {base}"));
98 }
99 }
100 keys
101}
102
103// ---------------------------------------------------------------------------
104// 类型漂移:同名实体被抽成了不同类型("Orion platform team" ↔ organization/project)
105// ---------------------------------------------------------------------------
106
107/// 易混具体类型:抽取常在这几类间摇摆(一个团队算组织还是项目?平台算项目还是产品?)。
108/// 同名跨这组类型 → 照建实体(宁分勿合),但入队审核对交 LLM/人工裁决。
109/// DESIGN.md §3.2 的 disjoint 公理目前只是设计面(0005 仅落了 subClassOf 数据面),
110/// 公理落库后这张表应改从本体读取。
111pub const CONFUSABLE_TYPE_KEYS: &[&str] = &["organization", "project", "product"];
112
113/// 单次消解最多入队的漂移审核对(防同名大组刷爆审核队列)。
114const MAX_DRIFT_REVIEWS: usize = 4;
115
116/// 跨类型同名的处置分类。
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118enum TypeDrift {
119 /// 一侧是兜底类型:当召回候选,走画像相似度分层(可 ATTACH)
120 Recall,
121 /// 两个易混具体类型:新建 + 审核对
122 Review,
123 /// 硬互斥(person vs organization 等,含未知自定义类型):完全分开
124 Disjoint,
125}
126
127fn classify_type_drift(a: Option<&str>, b: Option<&str>) -> TypeDrift {
128 // **同一个类型当然可能是同一个东西。**
129 //
130 // 这一档原本不存在,因为这个函数生来只服务"类型漂移"——同名被抽成两种
131 // 类型——那里两边相同根本不会发生。后来 containment_reviews 借它当相容性
132 // 判据,而那里**两边相同才是最常见的情形**,于是 person 对 person 落进了
133 // 最后那行 Disjoint,被读成"永不可能是同一个东西"。
134 //
135 // 代价是全文最明显的同指关系一对都进不了队列:福尔摩斯前六篇里
136 // Sherlock Holmes 与 Holmes 是两个实体,488 个实体只合并掉 14 个。
137 // 原有的 12 个单元测试全在测跨类型,一个都没测相同类型。
138 if a == b {
139 return TypeDrift::Recall;
140 }
141 // **一侧还没判出来** → 当召回候选,走画像相似度分层。
142 // 从前比的是 `== FALLBACK_TYPE_KEY`,那个 key 已经没有了:
143 // 「还没判出来」现在由 `None` 表达(0009)。两边都是 None
144 // 已经被上面 `a == b` 那行接住
145 let (Some(a), Some(b)) = (a, b) else {
146 return TypeDrift::Recall;
147 };
148 if CONFUSABLE_TYPE_KEYS.contains(&a) && CONFUSABLE_TYPE_KEYS.contains(&b) {
149 return TypeDrift::Review;
150 }
151 TypeDrift::Disjoint
152}
153
154fn cosine(a: &[f32], b: &[f32]) -> Option<f32> {
155 if a.len() != b.len() || a.is_empty() {
156 return None;
157 }
158 let (mut dot, mut na, mut nb) = (0f32, 0f32, 0f32);
159 for (x, y) in a.iter().zip(b) {
160 dot += x * y;
161 na += x * x;
162 nb += y * y;
163 }
164 if na == 0.0 || nb == 0.0 {
165 return None;
166 }
167 Some(dot / (na.sqrt() * nb.sqrt()))
168}
169
170#[derive(Debug, sqlx::FromRow)]
171struct Candidate {
172 id: Uuid,
173 profile_embedding: Option<Vector>,
174 profile_n: i32,
175 degree: i64,
176}
177
178/// 消解结果:mention 落到了哪个实体;附带需要入队的疑似重复审核对
179/// (同名灰区 / 类型漂移),由调用方写入审核队列并触发裁决任务。
180#[derive(Debug)]
181pub struct Resolution {
182 pub entity_id: Uuid,
183 pub created: bool,
184 pub reviews: Vec<ReviewRequest>,
185}
186
187/// 待入队的审核对:`Resolution::entity_id` vs `other_id`。
188#[derive(Debug)]
189pub struct ReviewRequest {
190 pub other_id: Uuid,
191 pub score: f32,
192 pub reason: String,
193}
194
195/// 单条 mention 消解。`context` 为 mention 所在分块的向量(无 embedding 模型时为 None,
196/// 退化为 v1 行为:同名归并到事实最多的候选)。
197pub async fn resolve_mention(
198 pool: &PgPool,
199 kb_id: Uuid,
200 // None = 抽取器给的类型不在本体里,或库里根本没有类(0009)
201 type_id: Option<Uuid>,
202 raw_name: &str,
203 context: Option<&[f32]>,
204) -> AppResult<Resolution> {
205 let name = normalize_name(raw_name);
206 // 召回键 = 本名 + 泛用后缀词干及其增广("星尘"↔"星尘项目"互为候选)。
207 // 只扩召回,归并与否仍由下方画像相似度分层定夺。
208 let keys = recall_keys(&name);
209 let candidates: Vec<Candidate> = sqlx::query_as(
210 "SELECT e.id, e.profile_embedding, e.profile_n,
211 (SELECT count(*) FROM facts f
212 WHERE (f.subject_id = e.id OR f.object_id = e.id)
213 AND f.invalidated_at IS NULL) AS degree
214 FROM entities e
215 WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL
216 AND (lower(e.canonical_name) = ANY($3)
217 OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",
218 )
219 .bind(kb_id)
220 .bind(type_id)
221 .bind(&keys)
222 .fetch_all(pool)
223 .await?;
224
225 if candidates.is_empty() {
226 // 同类型无候选 ≠ 新名字:类型标签会漂(同一团队被抽成 organization/project/
227 // concept),先查其它类型下的同名实体,按类型对的互斥强度分流。
228 return resolve_type_drift(pool, kb_id, type_id, &name, &keys, context).await;
229 }
230
231 let Some(ctx) = context else {
232 // 无向量可比:v1 兼容 —— 归并到事实最多的同名候选
233 let best = candidates
234 .iter()
235 .max_by_key(|c| c.degree)
236 .expect("non-empty");
237 touch_entity(pool, best.id).await?;
238 return Ok(Resolution {
239 entity_id: best.id,
240 created: false,
241 reviews: Vec::new(),
242 });
243 };
244
245 // 有画像的候选算相似度;无画像(历史数据/无 embedding 期创建)单独归类
246 let mut best_scored: Option<(&Candidate, f32)> = None;
247 let mut unprofiled: Option<&Candidate> = None;
248 for c in &candidates {
249 match c
250 .profile_embedding
251 .as_ref()
252 .and_then(|p| cosine(p.as_slice(), ctx))
253 {
254 Some(sim) => {
255 if best_scored.map(|(_, s)| sim > s).unwrap_or(true) {
256 best_scored = Some((c, sim));
257 }
258 }
259 None => {
260 if unprofiled.map(|u| c.degree > u.degree).unwrap_or(true) {
261 unprofiled = Some(c);
262 }
263 }
264 }
265 }
266
267 if let Some((best, sim)) = best_scored {
268 if sim >= SIM_ATTACH {
269 update_profile(pool, best.id, best.profile_n, ctx).await?;
270 return Ok(Resolution {
271 entity_id: best.id,
272 created: false,
273 reviews: Vec::new(),
274 });
275 }
276 }
277 if let Some(c) = unprofiled {
278 // 无画像候选无从判别:v1 兼容归并,并用本次上下文初始化画像
279 update_profile(pool, c.id, c.profile_n, ctx).await?;
280 return Ok(Resolution {
281 entity_id: c.id,
282 created: false,
283 reviews: Vec::new(),
284 });
285 }
286
287 // 走到这里:所有候选都有画像且最高分 < ATTACH → 新建实体(同名不同人)
288 let id = create_entity(pool, kb_id, type_id, &name, context).await?;
289 refresh_disambiguators(pool, kb_id, &name).await?;
290 let mut reviews = best_scored
291 .filter(|(_, sim)| *sim >= SIM_NEW)
292 .map(|(c, sim)| {
293 vec![ReviewRequest {
294 other_id: c.id,
295 score: sim,
296 reason: format!("ambiguous_name|{sim:.2}"),
297 }]
298 })
299 .unwrap_or_default();
300 // 名字互相包含的既有实体:等值召回看不见它们(前缀枚举不完),
301 // 于是简称会静默变成第二个实体。只入队,不合并
302 reviews.extend(containment_reviews(pool, kb_id, type_id, &name, id, context).await?);
303 Ok(Resolution {
304 entity_id: id,
305 created: true,
306 reviews,
307 })
308}
309
310/// 包含关系候选的最短边:两个名字里**较短的那个**至少这么长才算数。
311/// 低于它的多是「研究院」「中心」这类通名,配对没有信息量,只会刷爆队列。
312const MIN_CONTAIN_CHARS: i32 = 4;
313
314/// 单次最多产出的包含关系审阅对。与 `MAX_DRIFT_REVIEWS` 同理:
315/// 一个通名可能包含在几十个实体里,全放进去就把队列淹了。
316const MAX_CONTAIN_REVIEWS: usize = 4;
317
318/// SQL 侧多取几行:类型硬互斥的在 Rust 侧才筛得掉,
319/// 只取 4 行的话可能 4 行全是互斥类型,真正那一对反而被 LIMIT 切掉。
320const CONTAIN_SCAN_LIMIT: i64 = 16;
321
322/// 新建实体之后,找出**名字互相包含**的既有实体,作为审阅候选。
323///
324/// 中文商业文本在一篇之内就会全称转简称(「星云科技上海研究院」→「上海研究院」),
325/// 而 [`recall_keys`] 是等值查:它靠枚举泛用后缀命中反向,可前缀是任意组织名,
326/// **枚举不完**。于是这三类全部漏网,静默变成第二个实体:
327///
328/// ```text
329/// 上海研究院 ⊂ 星云科技上海研究院 后缀被限定
330/// 启明 X7 加速卡 ~ 启明 X7 推理加速卡 中间插词(靠 LIKE 覆盖不到,见下)
331/// 沧海 ⊂ 沧海分布式推理平台 2.0 前缀被扩展
332/// ```
333///
334/// **只出候选,永不自动合并。** 同名候选那条路在相似度 ≥ [`SIM_ATTACH`] 时直接归并,
335/// 包含关系绝不能走它:`华瑞集团技术中心` 与 `星云科技技术中心` 都含「技术中心」,
336/// 同一篇文档里上下文相似度很容易过线,而它们是两个部门。宁分勿合。
337///
338/// **别名一并参与**:合并会把名字搬进 `aliases`,只查 `canonical_name` 的话,
339/// 每成功合并一次就少一条召回的桥——`Holmes` 并入 `Sherlock Holmes` 之后,
340/// 后来的 `Mr. Holmes` 就再也搭不上了(它跟 `Sherlock Holmes` 谁也不含谁)。
341/// 合并越成功、漏得越多,是个会自我加剧的洞。
342///
343/// **已知不覆盖**:两个名字既不互相包含、又没有共同别名做桥的情形
344///(`启明 X7 加速卡` 与 `启明 X7 推理加速卡`)。那要三元组相似度,而
345/// `CREATE EXTENSION pg_trgm` 需要超级权限——本仓库是受限角色连库(见 `migrations/0010_least_privilege_role.sql`),
346/// 装扩展会在部署上失败。留给需要时再说。
347///
348/// **性能**:反向那半(新名字包含旧名字)用不上任何索引,别名那半同样,
349/// 所以这里靠 `kb_id` 收窄行集并设上限,且只在**新建实体时**跑一次,
350/// 不是每条 mention。大库上如果不够,正解是建一张「后缀键」表走等值查,
351/// 而不是加模糊索引。
352async fn containment_reviews(
353 pool: &PgPool,
354 kb_id: Uuid,
355 // None = 抽取器给的类型不在本体里,或库里根本没有类(0009)
356 type_id: Option<Uuid>,
357 name: &str,
358 new_id: Uuid,
359 ctx: Option<&[f32]>,
360) -> AppResult<Vec<ReviewRequest>> {
361 let lower = name.to_lowercase();
362 if lower.chars().count() < MIN_CONTAIN_CHARS as usize {
363 return Ok(Vec::new());
364 }
365 // 实体可能还没判出类型(0009),那时没有 key 可查
366 let mention_key: Option<String> = match type_id {
367 Some(t) => sqlx::query_as::<_, (String,)>("SELECT key FROM entity_types WHERE id = $1")
368 .bind(t)
369 .fetch_optional(pool)
370 .await?
371 .map(|(k,)| k),
372 None => None,
373 };
374 // **不按类型过滤**:简称经常掉进 concept 兜底,而全称是具体类型
375 //(实测 上海研究院→concept vs 星云科技上海研究院→organization,
376 // 启明 X7 加速卡→concept vs 启明 X7 推理加速卡→product),
377 // 按类型相等去查,这两对一个都捞不到。相容性交给下面的 classify_type_drift。
378 // 多取一些行,因为硬互斥的会在 Rust 侧被筛掉
379 // 第三列可空:未分类实体也要参与包含关系扫描(0009)
380 let rows: Vec<(Uuid, String, Option<String>, Option<Vector>)> = sqlx::query_as(
381 "SELECT e.id, e.canonical_name, t.key, e.profile_embedding
382 FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id
383 WHERE e.kb_id = $1 AND e.merged_into IS NULL
384 AND e.id <> $2
385 AND lower(e.canonical_name) <> $3
386 AND (
387 (char_length(e.canonical_name) >= $4
388 AND (lower(e.canonical_name) LIKE '%' || $3 || '%'
389 OR $3 LIKE '%' || lower(e.canonical_name) || '%'))
390 -- **别名也要参与召回,否则每合并一次就少一条桥。**
391 --
392 -- 合并把名字搬进 aliases:Holmes 并入 Sherlock Holmes 之后,
393 -- Holmes 那一行 merged_into 非空、被上面第一个条件滤掉了。可十分钟后
394 -- 出现的 Mr. Holmes 跟 Sherlock Holmes 谁也不含谁——本来正是靠
395 -- Holmes 才桥得上。实测就是这么漏的:同类型那个 bug 修好、Holmes
396 -- 正确合并之后,Mr. Holmes 反而永远进不了队列。
397 --
398 -- 合并越成功,桥拆得越多。这个洞会自我加剧。
399 OR EXISTS (
400 SELECT 1 FROM unnest(e.aliases) AS alias
401 WHERE char_length(alias) >= $4
402 AND (lower(alias) LIKE '%' || $3 || '%'
403 OR $3 LIKE '%' || lower(alias) || '%'))
404 )
405 ORDER BY char_length(e.canonical_name)
406 LIMIT $5",
407 )
408 .bind(kb_id)
409 .bind(new_id)
410 .bind(&lower)
411 .bind(MIN_CONTAIN_CHARS)
412 .bind(CONTAIN_SCAN_LIMIT)
413 .fetch_all(pool)
414 .await?;
415
416 Ok(rows
417 .into_iter()
418 // 哪些类型对可能指同一个东西,既有规则已经想清楚了,别另发明一套:
419 // person vs organization 永不合并,concept 兜底与谁都可能是一个
420 .filter(|(_, _, type_key, _)| {
421 classify_type_drift(mention_key.as_deref(), type_key.as_deref()) != TypeDrift::Disjoint
422 })
423 .take(MAX_CONTAIN_REVIEWS)
424 .map(|(id, other_name, _, emb)| {
425 // 分数只是给队列排序用的参考,**不参与是否合并的判断**——
426 // 那个判断本来就不在这条路上
427 let score = ctx
428 .and_then(|x| emb.as_ref().and_then(|p| cosine(p.as_slice(), x)))
429 .unwrap_or(0.0);
430 ReviewRequest {
431 other_id: id,
432 score,
433 reason: format!("contains|{other_name}"),
434 }
435 })
436 .collect())
437}
438
439#[derive(Debug, sqlx::FromRow)]
440struct CrossCandidate {
441 id: Uuid,
442 canonical_name: String,
443 // None = 这个候选还没判出类型(0009)
444 type_key: Option<String>,
445 // 抽取升格要看它:人说过「就是没有类型」时,那也是一个决定
446 type_source: String,
447 profile_embedding: Option<Vector>,
448 profile_n: i32,
449}
450
451/// `reason` 存 code,措辞归界面(docs/decisions/0004)——这一列不该一半 code
452/// 一半英文句子,那样中文界面上就是一半能翻一半不能。
453fn drift_reason(mention_key: Option<&str>, other_key: Option<&str>, sim: Option<f32>) -> String {
454 // 未分类的一侧写成 `(untyped)`。这一列存 code 供界面翻译,
455 // 留空会让 `a vs b` 变成 `a vs `,读起来像被截断而不像"没有"
456 let a = mention_key.unwrap_or("(untyped)");
457 let b = other_key.unwrap_or("(untyped)");
458 match sim {
459 Some(s) => format!("type_drift|{a} vs {b} {s:.2}"),
460 None => format!("type_drift|{a} vs {b}"),
461 }
462}
463
464fn confusable_reviews(
465 // None = 这一侧还没判出类型(0009)
466 mention_key: Option<&str>,
467 cands: &[&CrossCandidate],
468 ctx: Option<&[f32]>,
469) -> Vec<ReviewRequest> {
470 cands
471 .iter()
472 .map(|c| {
473 let sim = ctx.and_then(|x| {
474 c.profile_embedding
475 .as_ref()
476 .and_then(|p| cosine(p.as_slice(), x))
477 });
478 ReviewRequest {
479 other_id: c.id,
480 score: sim.unwrap_or(0.0),
481 reason: drift_reason(mention_key, c.type_key.as_deref(), sim),
482 }
483 })
484 .collect()
485}
486
487/// 同类型召回为空时的跨类型处置(类型漂移)。
488/// concept 兜底型候选跑既有画像分层:高相似直接 ATTACH(漂移的召回修复,concept
489/// 侧类型升格为具体类型),灰区/无从判别 → 宁分勿合新建 + 审核对;易混具体类型
490/// 一律新建 + 审核对(同名 + 类型摇摆本身就是信号,不设相似度门槛);硬互斥忽略。
491async fn resolve_type_drift(
492 pool: &PgPool,
493 kb_id: Uuid,
494 // None = 抽取器给的类型不在本体里,或库里根本没有类(0009)
495 type_id: Option<Uuid>,
496 name: &str,
497 keys: &[String],
498 context: Option<&[f32]>,
499) -> AppResult<Resolution> {
500 // 这一侧也可能还没判出类型(0009),那时没有 key 可查
501 let mention_key: Option<String> = match type_id {
502 Some(t) => sqlx::query_as::<_, (String,)>("SELECT key FROM entity_types WHERE id = $1")
503 .bind(t)
504 .fetch_optional(pool)
505 .await?
506 .map(|(k,)| k),
507 None => None,
508 };
509 let cross: Vec<CrossCandidate> = sqlx::query_as(
510 "SELECT e.id, e.canonical_name, t.key AS type_key, e.type_source,
511 e.profile_embedding, e.profile_n
512 FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id
513 -- IS DISTINCT FROM 而不是 <>:后者遇 NULL 返回 NULL,被 WHERE 当假,
514 -- 未分类实体会被整个漏掉(0009)
515 WHERE e.kb_id = $1 AND e.type_id IS DISTINCT FROM $2 AND e.merged_into IS NULL
516 AND (lower(e.canonical_name) = ANY($3)
517 OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",
518 )
519 .bind(kb_id)
520 .bind(type_id)
521 .bind(keys)
522 .fetch_all(pool)
523 .await?;
524
525 let mut recall_cands: Vec<&CrossCandidate> = Vec::new();
526 let mut review_cands: Vec<&CrossCandidate> = Vec::new();
527 for c in &cross {
528 match classify_type_drift(mention_key.as_deref(), c.type_key.as_deref()) {
529 TypeDrift::Recall => recall_cands.push(c),
530 TypeDrift::Review => review_cands.push(c),
531 TypeDrift::Disjoint => {}
532 }
533 }
534
535 if let Some(ctx) = context {
536 let best = recall_cands
537 .iter()
538 .filter_map(|c| {
539 c.profile_embedding
540 .as_ref()
541 .and_then(|p| cosine(p.as_slice(), ctx))
542 .map(|sim| (*c, sim))
543 })
544 .max_by(|a, b| a.1.total_cmp(&b.1));
545 if let Some((best, sim)) = best {
546 if sim >= SIM_ATTACH {
547 update_profile(pool, best.id, best.profile_n, ctx).await?;
548 // 候选还没判出类型而这次抽取判出来了 → 升格。
549 // 不是合并(没有第二个实体),不入 entity_merges;本体页可手工改回
550 //
551 // **人说过的「没有类型」不算「还没判出来」。** 0009 之后两者都是
552 // NULL,只看 type_key.is_none() 分不出——于是一个人看过、认为
553 // 本体里没有合适类的实体,会在下一次抽取时被安上一个类型
554 if best.type_key.is_none() && best.type_source != "human" && type_id.is_some() {
555 sqlx::query(
556 "UPDATE entities
557 SET type_id = $2, type_source = 'extracted', updated_at = now()
558 WHERE id = $1",
559 )
560 .bind(best.id)
561 .bind(type_id)
562 .execute(pool)
563 .await?;
564 // 类型标签兜底的消歧后缀可能已过时
565 refresh_disambiguators(pool, kb_id, &best.canonical_name).await?;
566 }
567 // mention 已定居到召回实体;同名易混类型实体的疑点仍在 → 照常入队
568 let mut reviews =
569 confusable_reviews(mention_key.as_deref(), &review_cands, Some(ctx));
570 reviews.truncate(MAX_DRIFT_REVIEWS);
571 return Ok(Resolution {
572 entity_id: best.id,
573 created: false,
574 reviews,
575 });
576 }
577 }
578 }
579
580 let id = create_entity(pool, kb_id, type_id, name, context).await?;
581 if !cross.is_empty() {
582 // 跨类型同名并存:消歧后缀按名字分组(不分类型),需要刷新
583 refresh_disambiguators(pool, kb_id, name).await?;
584 }
585 let mut reviews = confusable_reviews(mention_key.as_deref(), &review_cands, context);
586 for c in &recall_cands {
587 let sim = context.and_then(|ctx| {
588 c.profile_embedding
589 .as_ref()
590 .and_then(|p| cosine(p.as_slice(), ctx))
591 });
592 match sim {
593 // 画像明确不像:完全分开,不打扰审核队列
594 Some(s) if s < SIM_NEW => {}
595 // 灰区或无从判别(无 embedding / 候选无画像):宁分勿合 + 审核对
596 _ => reviews.push(ReviewRequest {
597 other_id: c.id,
598 score: sim.unwrap_or(0.0),
599 reason: drift_reason(mention_key.as_deref(), c.type_key.as_deref(), sim),
600 }),
601 }
602 }
603 reviews.truncate(MAX_DRIFT_REVIEWS);
604 // 漂移这条路一样会新建实体,包含关系照查
605 reviews.extend(containment_reviews(pool, kb_id, type_id, name, id, context).await?);
606 Ok(Resolution {
607 entity_id: id,
608 created: true,
609 reviews,
610 })
611}
612
613async fn create_entity(
614 pool: &PgPool,
615 kb_id: Uuid,
616 // None = 抽取器给的类型不在本体里,或库里根本没有类(0009)
617 type_id: Option<Uuid>,
618 name: &str,
619 context: Option<&[f32]>,
620) -> AppResult<Uuid> {
621 let id = Uuid::now_v7();
622 sqlx::query(
623 "INSERT INTO entities (id, kb_id, type_id, canonical_name, profile_embedding, profile_n)
624 VALUES ($1, $2, $3, $4, $5, $6)",
625 )
626 .bind(id)
627 .bind(kb_id)
628 .bind(type_id)
629 .bind(name)
630 .bind(context.map(|c| Vector::from(c.to_vec())))
631 .bind(i32::from(context.is_some()))
632 .execute(pool)
633 .await?;
634 Ok(id)
635}
636
637async fn touch_entity(pool: &PgPool, id: Uuid) -> AppResult<()> {
638 sqlx::query("UPDATE entities SET updated_at = now() WHERE id = $1")
639 .bind(id)
640 .execute(pool)
641 .await?;
642 Ok(())
643}
644
645/// 画像增量质心:profile ← (profile·n + ctx) / (n+1)。
646/// 维度不匹配(换过 embedding 模型)时用新向量重置画像。
647async fn update_profile(pool: &PgPool, id: Uuid, n: i32, ctx: &[f32]) -> AppResult<()> {
648 let existing: Option<(Option<Vector>,)> =
649 sqlx::query_as("SELECT profile_embedding FROM entities WHERE id = $1")
650 .bind(id)
651 .fetch_optional(pool)
652 .await?;
653 let old = existing.and_then(|(v,)| v);
654 let (new_vec, new_n) = match old {
655 Some(p) if p.as_slice().len() == ctx.len() && n > 0 => {
656 let nf = n as f32;
657 let merged: Vec<f32> = p
658 .as_slice()
659 .iter()
660 .zip(ctx)
661 .map(|(a, b)| (a * nf + b) / (nf + 1.0))
662 .collect();
663 (merged, n + 1)
664 }
665 _ => (ctx.to_vec(), 1),
666 };
667 sqlx::query(
668 "UPDATE entities SET profile_embedding = $2, profile_n = $3, updated_at = now()
669 WHERE id = $1",
670 )
671 .bind(id)
672 .bind(Vector::from(new_vec))
673 .bind(new_n)
674 .execute(pool)
675 .await?;
676 Ok(())
677}
678
679/// 同名组展示消歧:组内 ≥2 个存活实体时,各自取最强区分性事实
680/// (works_at/part_of/located_in/leads 的宾语名),否则退回类型标签;组内唯一则清空。
681pub async fn refresh_disambiguators(pool: &PgPool, kb_id: Uuid, name: &str) -> AppResult<()> {
682 let group: Vec<(Uuid,)> = sqlx::query_as(
683 "SELECT id FROM entities
684 WHERE kb_id = $1 AND merged_into IS NULL AND lower(canonical_name) = lower($2)",
685 )
686 .bind(kb_id)
687 .bind(name)
688 .fetch_all(pool)
689 .await?;
690
691 if group.len() < 2 {
692 for (id,) in &group {
693 sqlx::query("UPDATE entities SET disambiguator = NULL WHERE id = $1")
694 .bind(id)
695 .execute(pool)
696 .await?;
697 }
698 return Ok(());
699 }
700
701 for (id,) in &group {
702 let label: Option<(String,)> = sqlx::query_as(
703 "SELECT o.canonical_name FROM facts f
704 JOIN relation_types r ON r.id = f.predicate_id
705 JOIN entities o ON o.id = f.object_id
706 WHERE f.kb_id = $1 AND f.subject_id = $2
707 AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
708 AND r.key IN ('works_at', 'part_of', 'located_in', 'leads')
709 ORDER BY (r.key = 'works_at') DESC, f.confidence DESC, f.recorded_at DESC
710 LIMIT 1",
711 )
712 .bind(kb_id)
713 .bind(id)
714 .fetch_optional(pool)
715 .await?;
716 // 关联事实找不着就退到类型标签;**类型也可能没有**(0009),
717 // 那就没有可写的后缀——留 NULL,界面按同名并列显示,别编一个出来
718 let disambiguator: Option<String> = match label {
719 Some((l,)) => Some(l),
720 None => sqlx::query_as::<_, (String,)>(
721 "SELECT t.label FROM entities e JOIN entity_types t ON t.id = e.type_id
722 WHERE e.id = $1",
723 )
724 .bind(id)
725 .fetch_optional(pool)
726 .await?
727 .map(|(l,)| l),
728 };
729 sqlx::query("UPDATE entities SET disambiguator = $2 WHERE id = $1")
730 .bind(id)
731 .bind(disambiguator)
732 .execute(pool)
733 .await?;
734 }
735 Ok(())
736}
737
738// ---------------------------------------------------------------------------
739// 审核队列
740// ---------------------------------------------------------------------------
741
742/// 灰区疑似重复对入队(同一 pending 对幂等)。
743pub async fn create_review(
744 pool: &PgPool,
745 kb_id: Uuid,
746 left_id: Uuid,
747 right_id: Uuid,
748 score: f32,
749 reason: &str,
750) -> AppResult<()> {
751 sqlx::query(
752 "INSERT INTO resolution_reviews (id, kb_id, left_id, right_id, score, reason)
753 VALUES ($1, $2, $3, $4, $5, $6)
754 ON CONFLICT (kb_id, least(left_id, right_id), greatest(left_id, right_id))
755 WHERE status = 'pending'
756 DO NOTHING",
757 )
758 .bind(Uuid::now_v7())
759 .bind(kb_id)
760 .bind(left_id)
761 .bind(right_id)
762 .bind(score)
763 .bind(reason)
764 .execute(pool)
765 .await?;
766 Ok(())
767}
768
769#[derive(Debug, sqlx::FromRow)]
770struct ReviewRow {
771 id: Uuid,
772 left_id: Uuid,
773 right_id: Uuid,
774 score: f32,
775 reason: Option<String>,
776 stage: String,
777 created_at: DateTime<Utc>,
778}
779
780async fn review_side(pool: &PgPool, kb_id: Uuid, entity_id: Uuid) -> AppResult<ReviewSide> {
781 #[derive(sqlx::FromRow)]
782 struct SideRow {
783 id: Uuid,
784 name: String,
785 type_label: Option<String>,
786 color: String,
787 disambiguator: Option<String>,
788 degree: i64,
789 }
790 let row: SideRow = sqlx::query_as(
791 "SELECT e.id, e.canonical_name AS name, t.label AS type_label,
792 coalesce(t.color, '#94a3b8') AS color, e.disambiguator,
793 (SELECT count(*) FROM facts f
794 WHERE (f.subject_id = e.id OR f.object_id = e.id)
795 AND f.invalidated_at IS NULL) AS degree
796 -- LEFT JOIN:没判出类型的实体照样要能进审核(0009)。
797 -- 内连接会让它整条审核项取不出来,而漂移审核恰恰最常发生在它们身上
798 FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id
799 WHERE e.kb_id = $1 AND e.id = $2",
800 )
801 .bind(kb_id)
802 .bind(entity_id)
803 .fetch_optional(pool)
804 .await?
805 .ok_or(AppError::NotFound)?;
806
807 Ok(ReviewSide {
808 id: row.id,
809 name: row.name,
810 type_label: row.type_label,
811 color: row.color,
812 disambiguator: row.disambiguator,
813 degree: row.degree,
814 top_facts: entity_fact_lines(pool, kb_id, entity_id, 4).await?,
815 })
816}
817
818/// 实体的事实摘要行:"works at → 星云科技 (2023-01 → now)",裁决 prompt 与审核 UI 共用。
819pub async fn entity_fact_lines(
820 pool: &PgPool,
821 kb_id: Uuid,
822 entity_id: Uuid,
823 limit: i64,
824) -> AppResult<Vec<String>> {
825 #[derive(sqlx::FromRow)]
826 struct Line {
827 direction: String,
828 predicate_label: String,
829 other_name: Option<String>,
830 valid_from: Option<DateTime<Utc>>,
831 valid_to: Option<DateTime<Utc>>,
832 }
833 let rows: Vec<Line> = sqlx::query_as(
834 "SELECT CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,
835 COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,
836 o.canonical_name AS other_name,
837 f.valid_from, f.valid_to
838 FROM facts f
839 LEFT JOIN relation_types r ON r.id = f.predicate_id
840 LEFT JOIN entities o
841 ON o.id = CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END
842 WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
843 AND (f.subject_id = $2 OR f.object_id = $2)
844 AND COALESCE(r.label, fact_surface_predicate(f.id)) IS NOT NULL
845 ORDER BY f.confidence DESC, f.recorded_at DESC
846 LIMIT $3",
847 )
848 .bind(kb_id)
849 .bind(entity_id)
850 .bind(limit)
851 .fetch_all(pool)
852 .await?;
853
854 Ok(rows
855 .into_iter()
856 .map(|l| {
857 let other = l.other_name.unwrap_or_else(|| "?".into());
858 let core = if l.direction == "out" {
859 format!("{} → {}", l.predicate_label, other)
860 } else {
861 format!("{} ← {}", l.predicate_label, other)
862 };
863 match (l.valid_from, l.valid_to) {
864 (Some(f), Some(t)) => {
865 format!("{core} ({} → {})", f.format("%Y-%m"), t.format("%Y-%m"))
866 }
867 (Some(f), None) => format!("{core} ({} → now)", f.format("%Y-%m")),
868 _ => core,
869 }
870 })
871 .collect())
872}
873
874async fn assemble_reviews(
875 pool: &PgPool,
876 kb_id: Uuid,
877 rows: Vec<ReviewRow>,
878) -> AppResult<Vec<ReviewItem>> {
879 let mut items = Vec::with_capacity(rows.len());
880 for r in rows {
881 items.push(ReviewItem {
882 id: r.id,
883 score: r.score,
884 reason: r.reason,
885 stage: r.stage,
886 created_at: r.created_at,
887 left: review_side(pool, kb_id, r.left_id).await?,
888 right: review_side(pool, kb_id, r.right_id).await?,
889 });
890 }
891 Ok(items)
892}
893
894/// 全部待处理审核项(LLM 裁决中 + 等人工的都展示,人工可随时抢先定夺)。
895pub async fn list_reviews(
896 pool: &PgPool,
897 kb_id: Uuid,
898 limit: i64,
899 offset: i64,
900) -> AppResult<Vec<ReviewItem>> {
901 let rows: Vec<ReviewRow> = sqlx::query_as(
902 "SELECT id, left_id, right_id, score, reason, stage, created_at
903 FROM resolution_reviews
904 WHERE kb_id = $1 AND status = 'pending'
905 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
906 )
907 .bind(kb_id)
908 .bind(limit)
909 .bind(offset)
910 .fetch_all(pool)
911 .await?;
912 assemble_reviews(pool, kb_id, rows).await
913}
914
915/// 等待 LLM 裁决的审核项(后台裁决任务消费)。
916pub async fn pending_adjudications(
917 pool: &PgPool,
918 kb_id: Uuid,
919 limit: i64,
920) -> AppResult<Vec<ReviewItem>> {
921 let rows: Vec<ReviewRow> = sqlx::query_as(
922 "SELECT id, left_id, right_id, score, reason, stage, created_at
923 FROM resolution_reviews
924 WHERE kb_id = $1 AND status = 'pending' AND stage = 'adjudicating'
925 ORDER BY created_at LIMIT $2",
926 )
927 .bind(kb_id)
928 .bind(limit)
929 .fetch_all(pool)
930 .await?;
931 assemble_reviews(pool, kb_id, rows).await
932}
933
934/// LLM 不确定 / 未配模型 → 转人工。
935/// `reason` 存的是 **code**,可选地跟 `|detail`——不是给人看的句子。
936///
937/// 界面语言在客户端(见 docs/decisions/0004),服务端没有 locale 可用来措辞;
938/// 写进这一列的英文散文会永久留在中文界面上。措辞归 i18n,这里只留稳定的 code。
939pub async fn escalate_review(pool: &PgPool, review_id: Uuid, reason: &str) -> AppResult<()> {
940 sqlx::query(
941 "UPDATE resolution_reviews SET stage = 'human', reason = $2
942 WHERE id = $1 AND status = 'pending'",
943 )
944 .bind(review_id)
945 .bind(reason)
946 .execute(pool)
947 .await?;
948 Ok(())
949}
950
951/// 自动定夺(LLM 高置信):merged / kept。合并动作本身由调用方先执行。
952pub async fn close_review_auto(
953 pool: &PgPool,
954 review_id: Uuid,
955 status: &str,
956 reason: &str,
957) -> AppResult<()> {
958 sqlx::query(
959 "UPDATE resolution_reviews SET status = $2, reason = $3, decided_at = now()
960 WHERE id = $1 AND status = 'pending'",
961 )
962 .bind(review_id)
963 .bind(status)
964 .bind(reason)
965 .execute(pool)
966 .await?;
967 Ok(())
968}
969
970/// 人工定夺。merge 方向:度数高(事实多)的一方作为存活目标,平局取更早创建的。
971pub async fn decide_review(
972 pool: &PgPool,
973 kb_id: Uuid,
974 review_id: Uuid,
975 action: &str,
976 user_id: Uuid,
977) -> AppResult<()> {
978 let row: Option<ReviewRow> = sqlx::query_as(
979 "SELECT id, left_id, right_id, score, reason, stage, created_at
980 FROM resolution_reviews WHERE id = $1 AND kb_id = $2 AND status = 'pending'",
981 )
982 .bind(review_id)
983 .bind(kb_id)
984 .fetch_optional(pool)
985 .await?;
986 let row = row.ok_or(AppError::NotFound)?;
987
988 match action {
989 "merge" => {
990 let (target, source) = merge_direction(pool, row.left_id, row.right_id).await?;
991 merge_entities(
992 pool,
993 kb_id,
994 source,
995 target,
996 Some(user_id),
997 "review decision",
998 )
999 .await?;
1000 sqlx::query(
1001 "UPDATE resolution_reviews SET status = 'merged', decided_at = now(), decided_by = $2
1002 WHERE id = $1",
1003 )
1004 .bind(review_id)
1005 .bind(user_id)
1006 .execute(pool)
1007 .await?;
1008 }
1009 "keep" => {
1010 sqlx::query(
1011 "UPDATE resolution_reviews SET status = 'kept', decided_at = now(), decided_by = $2
1012 WHERE id = $1",
1013 )
1014 .bind(review_id)
1015 .bind(user_id)
1016 .execute(pool)
1017 .await?;
1018 }
1019 _ => return Err(AppError::Validation("action must be merge or keep".into())),
1020 }
1021 Ok(())
1022}
1023
1024/// 合并方向:返回 (target 存活, source 被并)。
1025pub async fn merge_direction(pool: &PgPool, a: Uuid, b: Uuid) -> AppResult<(Uuid, Uuid)> {
1026 let (deg_a,): (i64,) = sqlx::query_as(
1027 "SELECT count(*) FROM facts WHERE (subject_id = $1 OR object_id = $1) AND invalidated_at IS NULL",
1028 )
1029 .bind(a)
1030 .fetch_one(pool)
1031 .await?;
1032 let (deg_b,): (i64,) = sqlx::query_as(
1033 "SELECT count(*) FROM facts WHERE (subject_id = $1 OR object_id = $1) AND invalidated_at IS NULL",
1034 )
1035 .bind(b)
1036 .fetch_one(pool)
1037 .await?;
1038 // uuidv7 时间有序:度数平局时更早创建的一方存活
1039 Ok(if deg_a > deg_b || (deg_a == deg_b && a < b) {
1040 (a, b)
1041 } else {
1042 (b, a)
1043 })
1044}
1045
1046// ---------------------------------------------------------------------------
1047// 合并 / 回滚
1048// ---------------------------------------------------------------------------
1049
1050#[derive(Debug, sqlx::FromRow)]
1051struct EntityFull {
1052 // None = 还没判出来(0009)
1053 type_id: Option<Uuid>,
1054 canonical_name: String,
1055 aliases: Vec<String>,
1056 profile_embedding: Option<Vector>,
1057 profile_n: i32,
1058 merged_into: Option<Uuid>,
1059}
1060
1061async fn entity_full(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<EntityFull> {
1062 sqlx::query_as(
1063 "SELECT type_id, canonical_name, aliases, profile_embedding, profile_n, merged_into
1064 FROM entities WHERE kb_id = $1 AND id = $2",
1065 )
1066 .bind(kb_id)
1067 .bind(id)
1068 .fetch_optional(pool)
1069 .await?
1070 .ok_or(AppError::NotFound)
1071}
1072
1073/// 合并 source → target:事实改挂 target、互指事实与合并后的重复事实作废、
1074/// source 名并入 target 别名、画像加权合并、source 标记 merged_into。全程记日志可回滚。
1075pub async fn merge_entities(
1076 pool: &PgPool,
1077 kb_id: Uuid,
1078 source_id: Uuid,
1079 target_id: Uuid,
1080 merged_by: Option<Uuid>,
1081 reason: &str,
1082) -> AppResult<Uuid> {
1083 if source_id == target_id {
1084 return Err(AppError::invalid(
1085 "self_merge",
1086 "Cannot merge an entity into itself",
1087 ));
1088 }
1089 let source = entity_full(pool, kb_id, source_id).await?;
1090 let target = entity_full(pool, kb_id, target_id).await?;
1091 if source.merged_into.is_some() || target.merged_into.is_some() {
1092 return Err(AppError::Conflict("Entity already merged".into()));
1093 }
1094
1095 let mut tx = pool.begin().await?;
1096
1097 // 互指事实(合并后变自环)→ 作废
1098 let cross: Vec<(Uuid,)> = sqlx::query_as(
1099 "UPDATE facts SET invalidated_at = now()
1100 WHERE kb_id = $1 AND invalidated_at IS NULL
1101 AND ((subject_id = $2 AND object_id = $3) OR (subject_id = $3 AND object_id = $2))
1102 RETURNING id",
1103 )
1104 .bind(kb_id)
1105 .bind(source_id)
1106 .bind(target_id)
1107 .fetch_all(&mut *tx)
1108 .await?;
1109 let mut invalidated: Vec<Uuid> = cross.into_iter().map(|(id,)| id).collect();
1110
1111 let moved_subject: Vec<Uuid> = sqlx::query_as::<_, (Uuid,)>(
1112 "UPDATE facts SET subject_id = $2 WHERE kb_id = $3 AND subject_id = $1 RETURNING id",
1113 )
1114 .bind(source_id)
1115 .bind(target_id)
1116 .bind(kb_id)
1117 .fetch_all(&mut *tx)
1118 .await?
1119 .into_iter()
1120 .map(|(id,)| id)
1121 .collect();
1122 let moved_object: Vec<Uuid> = sqlx::query_as::<_, (Uuid,)>(
1123 "UPDATE facts SET object_id = $2 WHERE kb_id = $3 AND object_id = $1 RETURNING id",
1124 )
1125 .bind(source_id)
1126 .bind(target_id)
1127 .bind(kb_id)
1128 .fetch_all(&mut *tx)
1129 .await?
1130 .into_iter()
1131 .map(|(id,)| id)
1132 .collect();
1133
1134 // 合并后 SPO+valid_from 重复的 live 事实:留最早 recorded_at 的一条,其余作废。
1135 //
1136 // **宾语两侧都要分组。** 字面值事实的 object_id 全是 NULL,只按它分组就等于
1137 // 把同主同谓下的**所有值**当成同一条断言:一次合并之后,
1138 // (公司, 成立年份, 2015) 与 (公司, 注册资本, …) 之外,同谓词的多个值只活得下来
1139 // 最早记的那一个,其余无声消失,且没有 supersedes 可查。
1140 let dups: Vec<(Vec<Uuid>,)> = sqlx::query_as(
1141 "SELECT (array_agg(id ORDER BY recorded_at))[2:] FROM facts
1142 WHERE kb_id = $1 AND invalidated_at IS NULL
1143 AND (subject_id = $2 OR object_id = $2)
1144 GROUP BY subject_id, predicate_id, object_id, object_value, valid_from
1145 HAVING count(*) > 1",
1146 )
1147 .bind(kb_id)
1148 .bind(target_id)
1149 .fetch_all(&mut *tx)
1150 .await?;
1151 let dup_ids: Vec<Uuid> = dups.into_iter().flat_map(|(ids,)| ids).collect();
1152 if !dup_ids.is_empty() {
1153 sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = ANY($1)")
1154 .bind(&dup_ids)
1155 .execute(&mut *tx)
1156 .await?;
1157 invalidated.extend(dup_ids);
1158 }
1159
1160 // source 名与别名并入 target 别名(去重、排除 target 本名)
1161 let mut aliases = target.aliases.clone();
1162 let taken: std::collections::HashSet<String> = std::iter::once(&target.canonical_name)
1163 .chain(aliases.iter())
1164 .map(|s| s.to_lowercase())
1165 .collect();
1166 for a in std::iter::once(&source.canonical_name).chain(source.aliases.iter()) {
1167 if !taken.contains(&a.to_lowercase()) && !aliases.iter().any(|x| x.eq_ignore_ascii_case(a))
1168 {
1169 aliases.push(a.clone());
1170 }
1171 }
1172
1173 // 画像加权合并
1174 let (profile, profile_n) = match (&target.profile_embedding, &source.profile_embedding) {
1175 (Some(t), Some(s)) if t.as_slice().len() == s.as_slice().len() => {
1176 let (nt, ns) = (
1177 target.profile_n.max(1) as f32,
1178 source.profile_n.max(1) as f32,
1179 );
1180 let merged: Vec<f32> = t
1181 .as_slice()
1182 .iter()
1183 .zip(s.as_slice())
1184 .map(|(a, b)| (a * nt + b * ns) / (nt + ns))
1185 .collect();
1186 (
1187 Some(Vector::from(merged)),
1188 target.profile_n + source.profile_n,
1189 )
1190 }
1191 (Some(t), _) => (Some(t.clone()), target.profile_n),
1192 (None, Some(s)) => (Some(s.clone()), source.profile_n),
1193 (None, None) => (None, 0),
1194 };
1195
1196 // 类型调和:**没有类型的一侧让位**。存活方还没判出来而被并方判出来了,
1197 // 就把那个类型带过来;否则保留存活方的。
1198 //
1199 // 从前这里要先查库找出 concept 那行的 id 再跟两侧比对。「还没判出来」
1200 // 现在是 `None`(0009),一个 `or` 就说完了,那次查询也省了
1201 let new_type_id = target.type_id.or(source.type_id);
1202
1203 sqlx::query(
1204 "UPDATE entities SET aliases = $2, profile_embedding = $3, profile_n = $4,
1205 type_id = $5, updated_at = now() WHERE id = $1",
1206 )
1207 .bind(target_id)
1208 .bind(&aliases)
1209 .bind(&profile)
1210 .bind(profile_n)
1211 .bind(new_type_id)
1212 .execute(&mut *tx)
1213 .await?;
1214 sqlx::query("UPDATE entities SET merged_into = $2, updated_at = now() WHERE id = $1")
1215 .bind(source_id)
1216 .bind(target_id)
1217 .execute(&mut *tx)
1218 .await?;
1219
1220 // 其余涉及 source 的 pending 审核项:**改指到合并目标,不是关掉**。
1221 //
1222 // 这里原本一律关掉,理由写的是"疑点若仍在会由后续 mention 重新提起"。
1223 // **那句是错的**:包含关系召回只在**新建实体时**跑一次,而这些实体早就存在了,
1224 // 不会再被新建,也就没有"后续 mention"来重提。关掉就是永远关掉。
1225 //
1226 // 实测:`Mr. Holmes` 跟 `Holmes` 配对入队(0.70),随后 `Holmes` 并入
1227 // `Sherlock Holmes`,这一对被关成 superseded by merge——而
1228 // `Mr. Holmes` vs `Sherlock Holmes` 这个仍然成立的问题,再没人问过。
1229 //
1230 // 先关掉两类真正过时的:重定向后会变成自环的,和目标对已经在队列里的。
1231 sqlx::query(
1232 "UPDATE resolution_reviews AS r
1233 SET status = 'kept', reason = 'superseded by merge', decided_at = now()
1234 WHERE r.kb_id = $1 AND r.status = 'pending'
1235 AND (r.left_id = $2 OR r.right_id = $2)
1236 AND NOT (least(r.left_id, r.right_id) = least($2, $3)
1237 AND greatest(r.left_id, r.right_id) = greatest($2, $3))
1238 AND (
1239 (CASE WHEN r.left_id = $2 THEN r.right_id ELSE r.left_id END) = $3
1240 OR EXISTS (
1241 SELECT 1 FROM resolution_reviews d
1242 WHERE d.kb_id = $1 AND d.status = 'pending' AND d.id <> r.id
1243 AND least(d.left_id, d.right_id)
1244 = least($3, CASE WHEN r.left_id = $2 THEN r.right_id ELSE r.left_id END)
1245 AND greatest(d.left_id, d.right_id)
1246 = greatest($3, CASE WHEN r.left_id = $2 THEN r.right_id ELSE r.left_id END))
1247 )",
1248 )
1249 .bind(kb_id)
1250 .bind(source_id)
1251 .bind(target_id)
1252 .execute(&mut *tx)
1253 .await?;
1254 // 剩下的改指到目标,问题继续挂在队列上等裁决。
1255 // (source, target) 这一对本身除外——它正是本次合并的裁决对象,由调用方标记 merged,
1256 // 在这里动它会让它在历史里错误地显示为"保持分开"
1257 sqlx::query(
1258 "UPDATE resolution_reviews
1259 SET left_id = CASE WHEN left_id = $2 THEN $3 ELSE left_id END,
1260 right_id = CASE WHEN right_id = $2 THEN $3 ELSE right_id END,
1261 reason = reason || '|redirected'
1262 WHERE kb_id = $1 AND status = 'pending' AND (left_id = $2 OR right_id = $2)
1263 AND NOT (least(left_id, right_id) = least($2, $3)
1264 AND greatest(left_id, right_id) = greatest($2, $3))",
1265 )
1266 .bind(kb_id)
1267 .bind(source_id)
1268 .bind(target_id)
1269 .execute(&mut *tx)
1270 .await?;
1271
1272 let merge_id = Uuid::now_v7();
1273 sqlx::query(
1274 "INSERT INTO entity_merges (id, kb_id, source_id, target_id,
1275 moved_subject_facts, moved_object_facts, invalidated_facts,
1276 target_profile_before, target_profile_n_before, target_type_before,
1277 merged_by, reason)
1278 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
1279 )
1280 .bind(merge_id)
1281 .bind(kb_id)
1282 .bind(source_id)
1283 .bind(target_id)
1284 .bind(&moved_subject)
1285 .bind(&moved_object)
1286 .bind(&invalidated)
1287 .bind(&target.profile_embedding)
1288 .bind(target.profile_n)
1289 .bind(target.type_id)
1290 .bind(merged_by)
1291 .bind(reason)
1292 .execute(&mut *tx)
1293 .await?;
1294
1295 tx.commit().await?;
1296
1297 // 搬移后的时态对账:换了主/宾的事实等价于新观察落库——两个对象折成一个后,
1298 // 唯一性不变量才第一次看得到旧开放区间与继任者相撞(如"星尘"并入"星尘项目",
1299 // 旧负责人的 leads 应在新任起点闭合)。
1300 // 修正行 id 记入合并账本:这些修正的唯一成因是本次合并,回滚时必须随之撤销。
1301 // 注:本步在事务外,失败有自愈性——残留的旧开放行会在下一条相关新事实落库时
1302 // 被常规插入对账撞到并闭合。
1303 let moved_all: Vec<Uuid> = moved_subject
1304 .iter()
1305 .chain(moved_object.iter())
1306 .copied()
1307 .collect();
1308 let report = crate::temporal::reconcile_moved_facts(pool, kb_id, &moved_all).await?;
1309 if !report.corrected.is_empty() {
1310 sqlx::query("UPDATE entity_merges SET temporal_corrections = $2 WHERE id = $1")
1311 .bind(merge_id)
1312 .bind(&report.corrected)
1313 .execute(pool)
1314 .await?;
1315 }
1316
1317 refresh_disambiguators(pool, kb_id, &source.canonical_name).await?;
1318 if !source
1319 .canonical_name
1320 .eq_ignore_ascii_case(&target.canonical_name)
1321 {
1322 refresh_disambiguators(pool, kb_id, &target.canonical_name).await?;
1323 }
1324 Ok(merge_id)
1325}
1326
1327#[derive(Debug, sqlx::FromRow)]
1328struct MergeRow {
1329 source_id: Uuid,
1330 target_id: Uuid,
1331 moved_subject_facts: Vec<Uuid>,
1332 moved_object_facts: Vec<Uuid>,
1333 invalidated_facts: Vec<Uuid>,
1334 temporal_corrections: Vec<Uuid>,
1335 target_profile_before: Option<Vector>,
1336 target_profile_n_before: i32,
1337 target_type_before: Option<Uuid>,
1338 reverted_at: Option<DateTime<Utc>>,
1339}
1340
1341/// 精确回滚一次合并:事实原路搬回、作废撤销、target 画像与类型恢复快照、source 复活。
1342pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResult<()> {
1343 let m: MergeRow = sqlx::query_as(
1344 "SELECT source_id, target_id, moved_subject_facts, moved_object_facts,
1345 invalidated_facts, temporal_corrections, target_profile_before,
1346 target_profile_n_before, target_type_before, reverted_at
1347 FROM entity_merges WHERE id = $1 AND kb_id = $2",
1348 )
1349 .bind(merge_id)
1350 .bind(kb_id)
1351 .fetch_optional(pool)
1352 .await?
1353 .ok_or(AppError::NotFound)?;
1354 if m.reverted_at.is_some() {
1355 return Err(AppError::Conflict("Merge already reverted".into()));
1356 }
1357
1358 let mut tx = pool.begin().await?;
1359 sqlx::query("UPDATE facts SET subject_id = $1 WHERE id = ANY($2)")
1360 .bind(m.source_id)
1361 .bind(&m.moved_subject_facts)
1362 .execute(&mut *tx)
1363 .await?;
1364 sqlx::query("UPDATE facts SET object_id = $1 WHERE id = ANY($2)")
1365 .bind(m.source_id)
1366 .bind(&m.moved_object_facts)
1367 .execute(&mut *tx)
1368 .await?;
1369 sqlx::query("UPDATE facts SET invalidated_at = NULL WHERE id = ANY($1)")
1370 .bind(&m.invalidated_facts)
1371 .execute(&mut *tx)
1372 .await?;
1373
1374 // 合并引发的时态修正随之撤销:这些修正的唯一成因是本次合并(两实体折一后
1375 // 不变量才看到的相撞),成因既撤、修正随撤——先恢复被取代的原行,再作废修正行。
1376 // 只撤仍存活的修正:之后被真实新观察再度改写过的链保持不动(那部分有独立依据)。
1377 sqlx::query(
1378 "UPDATE facts SET invalidated_at = NULL WHERE id IN (
1379 SELECT supersedes FROM facts
1380 WHERE id = ANY($1) AND invalidated_at IS NULL AND supersedes IS NOT NULL)",
1381 )
1382 .bind(&m.temporal_corrections)
1383 .execute(&mut *tx)
1384 .await?;
1385 sqlx::query(
1386 "UPDATE facts SET invalidated_at = now()
1387 WHERE id = ANY($1) AND invalidated_at IS NULL",
1388 )
1389 .bind(&m.temporal_corrections)
1390 .execute(&mut *tx)
1391 .await?;
1392
1393 let source = entity_full(pool, kb_id, m.source_id).await?;
1394 // target 别名回退:剔除来自 source 的名字
1395 sqlx::query(
1396 "UPDATE entities SET
1397 aliases = (SELECT coalesce(array_agg(a), '{}') FROM unnest(aliases) a
1398 WHERE lower(a) <> ALL($2)),
1399 profile_embedding = $3, profile_n = $4,
1400 type_id = coalesce($5, type_id), updated_at = now()
1401 WHERE id = $1",
1402 )
1403 .bind(m.target_id)
1404 .bind(
1405 std::iter::once(&source.canonical_name)
1406 .chain(source.aliases.iter())
1407 .map(|s| s.to_lowercase())
1408 .collect::<Vec<_>>(),
1409 )
1410 .bind(&m.target_profile_before)
1411 .bind(m.target_profile_n_before)
1412 .bind(m.target_type_before)
1413 .execute(&mut *tx)
1414 .await?;
1415 sqlx::query("UPDATE entities SET merged_into = NULL, updated_at = now() WHERE id = $1")
1416 .bind(m.source_id)
1417 .execute(&mut *tx)
1418 .await?;
1419 sqlx::query("UPDATE entity_merges SET reverted_at = now() WHERE id = $1")
1420 .bind(merge_id)
1421 .execute(&mut *tx)
1422 .await?;
1423 tx.commit().await?;
1424
1425 refresh_disambiguators(pool, kb_id, &source.canonical_name).await?;
1426 Ok(())
1427}
1428
1429/// 合并日志(审核页历史区)。
1430pub async fn list_merges(
1431 pool: &PgPool,
1432 kb_id: Uuid,
1433 limit: i64,
1434 offset: i64,
1435) -> AppResult<Vec<MergeLogView>> {
1436 let rows: Vec<MergeLogView> = sqlx::query_as(
1437 "SELECT m.id, s.canonical_name AS source_name, t.canonical_name AS target_name,
1438 u.display_name AS merged_by_name, m.reason, m.created_at, m.reverted_at
1439 FROM entity_merges m
1440 JOIN entities s ON s.id = m.source_id
1441 JOIN entities t ON t.id = m.target_id
1442 LEFT JOIN users u ON u.id = m.merged_by
1443 WHERE m.kb_id = $1
1444 ORDER BY m.created_at DESC LIMIT $2 OFFSET $3",
1445 )
1446 .bind(kb_id)
1447 .bind(limit)
1448 .bind(offset)
1449 .fetch_all(pool)
1450 .await?;
1451 Ok(rows)
1452}
1453
1454// ---------------------------------------------------------------------------
1455// LLM 裁决缓存
1456// ---------------------------------------------------------------------------
1457
1458pub async fn get_verdict(
1459 pool: &PgPool,
1460 kb_id: Uuid,
1461 pair_key: &str,
1462) -> AppResult<Option<(Option<bool>, f32)>> {
1463 let row: Option<(Option<bool>, f32)> = sqlx::query_as(
1464 "SELECT same, confidence FROM resolution_verdicts WHERE kb_id = $1 AND pair_key = $2",
1465 )
1466 .bind(kb_id)
1467 .bind(pair_key)
1468 .fetch_optional(pool)
1469 .await?;
1470 Ok(row)
1471}
1472
1473pub async fn put_verdict(
1474 pool: &PgPool,
1475 kb_id: Uuid,
1476 pair_key: &str,
1477 same: Option<bool>,
1478 confidence: f32,
1479 model: &str,
1480) -> AppResult<()> {
1481 sqlx::query(
1482 "INSERT INTO resolution_verdicts (kb_id, pair_key, same, confidence, model)
1483 VALUES ($1, $2, $3, $4, $5)
1484 ON CONFLICT (kb_id, pair_key)
1485 DO UPDATE SET same = $3, confidence = $4, model = $5, created_at = now()",
1486 )
1487 .bind(kb_id)
1488 .bind(pair_key)
1489 .bind(same)
1490 .bind(confidence)
1491 .bind(model)
1492 .execute(pool)
1493 .await?;
1494 Ok(())
1495}
1496
1497/// 记下模型提议、但本体装不下的类型。
1498///
1499/// **只写第一次**:同一实体会被多篇文档提到,第一次的提议就算它的提议;
1500/// 后来的覆盖会让"哪些实体在等 model 类"随最后一篇文档抖动。
1501/// 采纳了对应的类之后由改写流程清空——那时它已经不是"提议"而是既成事实。
1502pub async fn set_proposed_type(pool: &PgPool, entity_id: Uuid, proposed: &str) -> AppResult<()> {
1503 sqlx::query(
1504 "UPDATE entities SET proposed_type = left($2, 60)
1505 WHERE id = $1 AND proposed_type IS NULL",
1506 )
1507 .bind(entity_id)
1508 .bind(proposed)
1509 .execute(pool)
1510 .await?;
1511 Ok(())
1512}
1513
1514/// 待认领的实体类型:模型提议过、本体没有、实体因此降级成了 concept。
1515///
1516/// 与谓词那边的 `graph::proposed_predicates` 对称——连着具体实体,所以采纳时
1517/// 能说清"将重新归类 43 个"并真的去改,而不是只建一个空类。
1518pub async fn proposed_types(
1519 pool: &PgPool,
1520 kb_id: Uuid,
1521) -> AppResult<Vec<utopia_core::models::ProposedType>> {
1522 Ok(sqlx::query_as(
1523 "SELECT e.proposed_type AS form,
1524 count(*) AS entity_count,
1525 (array_agg(e.canonical_name ORDER BY e.created_at))[1] AS example
1526 FROM entities e
1527 WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.proposed_type IS NOT NULL
1528 -- 用户拒绝过的类型不再出现在候选里
1529 AND NOT EXISTS (SELECT 1 FROM ontology_misses m
1530 WHERE m.kb_id = $1 AND m.kind = 'entity_type'
1531 AND m.key = e.proposed_type AND m.dismissed_at IS NOT NULL)
1532 GROUP BY e.proposed_type
1533 ORDER BY entity_count DESC, form",
1534 )
1535 .bind(kb_id)
1536 .fetch_all(pool)
1537 .await?)
1538}
1539
1540/// 把提议过 `forms` 里那些类型的实体改到 `type_id` 上。返回 (批次 id, 改动数)。
1541///
1542/// 与谓词那边的 `graph::adopt_proposed_predicates` 对称:**只建类型不动实体,
1543/// 本体长大了、图没变好**——提议过 model 的实体会继续挂在 concept 下。
1544///
1545/// 实体是可变行(P0 的 PATCH 就直接改),所以这里就是 UPDATE,撤销靠账本
1546/// 记下改之前的类型,而不是靠 supersedes 链。
1547pub async fn adopt_proposed_types(
1548 pool: &PgPool,
1549 kb_id: Uuid,
1550 type_id: Uuid,
1551 forms: &[String],
1552 // None = 引擎自动(本体长出新类之后的收尾认领没有人在按)
1553 actor: Option<Uuid>,
1554) -> AppResult<(Uuid, u32)> {
1555 let batch_id = Uuid::now_v7();
1556 if forms.is_empty() {
1557 return Ok((batch_id, 0));
1558 }
1559 // 已经在目标类上的不算改动,也不进账本——撤销时不该把它们推回去。
1560 //
1561 // **`IS DISTINCT FROM` 而不是 `<>`**:0009 之后 type_id 可能是 NULL,而
1562 // `NULL <> uuid` 求值为 NULL 不是 true,那一行会被悄悄滤掉——偏偏带着
1563 // proposed_type 的几乎全是还没判出类型的实体,整个认领功能会一声不响地空转
1564 let targets: Vec<(Uuid, Option<Uuid>, String)> = sqlx::query_as(
1565 "SELECT id, type_id, canonical_name FROM entities
1566 WHERE kb_id = $1 AND merged_into IS NULL
1567 -- 人拍过板的不认领。**这一行顺带让 unadopt 天然正确**:human 行
1568 -- 永远不进采纳批次,撤销时也就不会遇到它们,不必额外还原 type_source
1569 AND type_source <> 'human'
1570 AND proposed_type = ANY($2) AND type_id IS DISTINCT FROM $3",
1571 )
1572 .bind(kb_id)
1573 .bind(forms)
1574 .bind(type_id)
1575 .fetch_all(pool)
1576 .await?;
1577
1578 let mut names: HashSet<String> = HashSet::new();
1579 let mut moved = 0u32;
1580 for (entity_id, from_type, name) in targets {
1581 let mut tx = pool.begin().await?;
1582 sqlx::query(
1583 // actor 有值 = 人在界面上点的批准,他背书了这个类型 → 受保护。
1584 // 无值 = 本体长出新类之后的收尾认领,没人在按
1585 "UPDATE entities
1586 SET type_id = $2, proposed_type = NULL, updated_at = now(),
1587 type_source = CASE WHEN $3::uuid IS NULL THEN 'inferred' ELSE 'human' END
1588 WHERE id = $1",
1589 )
1590 .bind(entity_id)
1591 .bind(type_id)
1592 .bind(actor)
1593 .execute(&mut *tx)
1594 .await?;
1595 sqlx::query(
1596 "INSERT INTO entity_retypes
1597 (batch_id, kb_id, entity_id, from_type_id, to_type_id, actor_id)
1598 VALUES ($1, $2, $3, $4, $5, $6)",
1599 )
1600 .bind(batch_id)
1601 .bind(kb_id)
1602 .bind(entity_id)
1603 .bind(from_type)
1604 .bind(type_id)
1605 .bind(actor)
1606 .execute(&mut *tx)
1607 .await?;
1608 tx.commit().await?;
1609 names.insert(name);
1610 moved += 1;
1611 }
1612 // 消歧后缀的兜底值就是类型标签,改了类就得重算(同 P0 的实体改类)
1613 for n in &names {
1614 refresh_disambiguators(pool, kb_id, n).await?;
1615 }
1616 Ok((batch_id, moved))
1617}
1618
1619/// 撤销一次实体改类:把它们放回原来的类型。
1620///
1621/// 类型本身不删——与谓词那边同一条理由:有实体指向过它,而"它存在过"是历史。
1622/// `proposed_type` 也一并恢复,否则撤销之后那些实体就再也认领不回来了。
1623pub async fn unadopt_types(pool: &PgPool, kb_id: Uuid, batch_id: Uuid) -> AppResult<u32> {
1624 // from_type_id 可能是 NULL:0009 之后最常见的一次改类正是"从没有类到有类",
1625 // 撤销就是把它推回没有类。解成 Uuid 会在这里当场崩
1626 let rows: Vec<(Uuid, Option<Uuid>, String)> = sqlx::query_as(
1627 "SELECT r.entity_id, r.from_type_id, t.key
1628 FROM entity_retypes r JOIN entity_types t ON t.id = r.to_type_id
1629 WHERE r.batch_id = $1 AND r.kb_id = $2 AND r.reverted_at IS NULL",
1630 )
1631 .bind(batch_id)
1632 .bind(kb_id)
1633 .fetch_all(pool)
1634 .await?;
1635 if rows.is_empty() {
1636 return Err(AppError::NotFound);
1637 }
1638 let mut names: Vec<String> = Vec::new();
1639 let mut tx = pool.begin().await?;
1640 let mut reverted = 0u32;
1641 for (entity_id, from_type, adopted_key) in &rows {
1642 let row: Option<(String,)> = sqlx::query_as(
1643 "UPDATE entities SET type_id = $2, proposed_type = $3, updated_at = now()
1644 WHERE id = $1 RETURNING canonical_name",
1645 )
1646 .bind(entity_id)
1647 .bind(from_type)
1648 .bind(adopted_key)
1649 .fetch_optional(&mut *tx)
1650 .await?;
1651 if let Some((name,)) = row {
1652 names.push(name);
1653 }
1654 reverted += 1;
1655 }
1656 sqlx::query(
1657 "UPDATE entity_retypes SET reverted_at = now()
1658 WHERE batch_id = $1 AND kb_id = $2 AND reverted_at IS NULL",
1659 )
1660 .bind(batch_id)
1661 .bind(kb_id)
1662 .execute(&mut *tx)
1663 .await?;
1664 tx.commit().await?;
1665 for n in &names {
1666 refresh_disambiguators(pool, kb_id, n).await?;
1667 }
1668 Ok(reverted)
1669}
1670
1671/// 把提议的类型规整成 key 的形状:小写、非字母数字换下划线、压缩重复。
1672/// "AI Model" → "ai_model",与 validate_key 允许的字符集对齐。
1673fn normalize_type_key(s: &str) -> String {
1674 let mut out = String::with_capacity(s.len());
1675 let mut last_us = true; // 前导下划线也算重复
1676 for c in s.trim().chars() {
1677 if c.is_ascii_alphanumeric() {
1678 out.push(c.to_ascii_lowercase());
1679 last_us = false;
1680 } else if !last_us {
1681 out.push('_');
1682 last_us = true;
1683 }
1684 }
1685 while out.ends_with('_') {
1686 out.pop();
1687 }
1688 out.chars().take(40).collect()
1689}
1690
1691/// 认领那些"类型已经在本体里、实体却还挂在 concept 下"的实体。
1692///
1693/// `adopt_proposed_types` 只在**建类的那一刻**被调用,于是类先建好、实体后被
1694/// 抽出来的情形就永远等不到搬运——而这恰恰是常态:本体第一轮建好,后续文档
1695/// 继续产出提议。这个扫描把它们收尾。
1696///
1697/// 只做**规整后精确同名**的匹配,不做近似——猜错就是把实体放进错的类,
1698/// 而"再等一轮"的代价接近零。
1699pub async fn sweep_proposed_types(
1700 pool: &PgPool,
1701 kb_id: Uuid,
1702 actor: Option<Uuid>,
1703) -> AppResult<Vec<(Uuid, u32)>> {
1704 let pending = proposed_types(pool, kb_id).await?;
1705 let existing: Vec<(Uuid, String)> =
1706 sqlx::query_as("SELECT id, key FROM entity_types WHERE kb_id = $1")
1707 .bind(kb_id)
1708 .fetch_all(pool)
1709 .await?;
1710 let mut out = Vec::new();
1711 for p in &pending {
1712 let norm = normalize_type_key(&p.form);
1713 let Some((type_id, _)) = existing.iter().find(|(_, k)| *k == norm) else {
1714 continue;
1715 };
1716 let (batch, n) =
1717 adopt_proposed_types(pool, kb_id, *type_id, std::slice::from_ref(&p.form), actor)
1718 .await?;
1719 if n > 0 {
1720 out.push((batch, n));
1721 }
1722 }
1723 Ok(out)
1724}
1725#[cfg(test)]
1726mod tests {
1727 use super::*;
1728
1729 #[test]
1730 fn normalize_fullwidth_and_whitespace() {
1731 assert_eq!(normalize_name(" ACME Corp "), "ACME Corp");
1732 assert_eq!(normalize_name("张三"), "张三");
1733 assert_eq!(normalize_name("张 三"), "张 三");
1734 }
1735
1736 #[test]
1737 fn stem_generic_suffixes() {
1738 assert_eq!(name_stem("星尘项目").as_deref(), Some("星尘"));
1739 assert_eq!(name_stem("星辰科技公司").as_deref(), Some("星辰科技"));
1740 assert_eq!(name_stem("Phoenix Project").as_deref(), Some("phoenix"));
1741 assert_eq!(name_stem("Project Phoenix").as_deref(), Some("phoenix"));
1742 assert_eq!(name_stem("Acme Inc.").as_deref(), Some("acme"));
1743 assert_eq!(name_stem("星尘"), None);
1744 assert_eq!(name_stem("项目"), None); // 剥空不算词干
1745 assert_eq!(name_stem("项目团队"), None); // 词干本身是泛用词
1746 assert_eq!(name_stem("Team Project"), None);
1747 }
1748
1749 #[test]
1750 fn recall_keys_bidirectional() {
1751 // 无后缀 mention 能召回带后缀实体(增广),反之靠词干
1752 let k = recall_keys("星尘");
1753 assert!(k.contains(&"星尘".to_string()));
1754 assert!(k.contains(&"星尘项目".to_string()));
1755 let k = recall_keys("星尘项目");
1756 assert!(k.contains(&"星尘项目".to_string()));
1757 assert!(k.contains(&"星尘".to_string()));
1758 let k = recall_keys("Phoenix");
1759 assert!(k.contains(&"phoenix project".to_string()));
1760 assert!(k.contains(&"project phoenix".to_string()));
1761 let k = recall_keys("Project Phoenix");
1762 assert!(k.contains(&"phoenix".to_string()));
1763 assert!(recall_keys("张三").len() <= 10);
1764 }
1765
1766 #[test]
1767 fn type_drift_classes() {
1768 // 还没判出类型的那一侧 → 召回候选。0009 之前这一档比的是 `concept`
1769 // 这个 key,现在比的是"有没有类"本身
1770 assert_eq!(
1771 classify_type_drift(None, Some("organization")),
1772 TypeDrift::Recall
1773 );
1774 assert_eq!(
1775 classify_type_drift(Some("project"), None),
1776 TypeDrift::Recall
1777 );
1778 // 两边都还没判出来:也归召回,由画像相似度说话
1779 assert_eq!(classify_type_drift(None, None), TypeDrift::Recall);
1780 // 易混具体类型两两 → 审核对
1781 assert_eq!(
1782 classify_type_drift(Some("organization"), Some("project")),
1783 TypeDrift::Review
1784 );
1785 assert_eq!(
1786 classify_type_drift(Some("project"), Some("product")),
1787 TypeDrift::Review
1788 );
1789 assert_eq!(
1790 classify_type_drift(Some("product"), Some("organization")),
1791 TypeDrift::Review
1792 );
1793 // 硬互斥与未知自定义类型 → 完全分开
1794 assert_eq!(
1795 classify_type_drift(Some("person"), Some("organization")),
1796 TypeDrift::Disjoint
1797 );
1798 assert_eq!(
1799 classify_type_drift(Some("person"), Some("project")),
1800 TypeDrift::Disjoint
1801 );
1802 assert_eq!(
1803 classify_type_drift(Some("event"), Some("location")),
1804 TypeDrift::Disjoint
1805 );
1806 assert_eq!(
1807 classify_type_drift(Some("team"), Some("organization")),
1808 TypeDrift::Disjoint
1809 );
1810 }
1811
1812 #[test]
1813 fn cosine_basics() {
1814 assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]).unwrap() - 1.0).abs() < 1e-6);
1815 assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).unwrap().abs() < 1e-6);
1816 assert!(cosine(&[1.0], &[1.0, 2.0]).is_none());
1817 assert!(cosine(&[0.0, 0.0], &[1.0, 1.0]).is_none());
1818 }
1819}
1820
1821/// 一个等着精化类型的实体,连同用来判断它是什么的全部材料。
1822#[derive(Debug, Clone, sqlx::FromRow)]
1823pub struct TypeCandidateSubject {
1824 pub id: Uuid,
1825 pub canonical_name: String,
1826 pub aliases: Vec<String>,
1827 /// 现在挂着的类,**可能没有**(0009:没判出来就是 NULL)。名字里的"粗"
1828 /// 是历史——抽取现在也可能直接给一个细类,而且可能给错(实测
1829 /// `绍兴 → address`),所以这里也可能是要被**纠正**的那个
1830 pub coarse_key: Option<String>,
1831 pub coarse_id: Option<Uuid>,
1832 /// 现类的描述。裁决要判"现在这个类对不对",光看 key 不够——
1833 /// 导入本体的 key 常常自解释不了(`entry_point` 是什么?)
1834 pub coarse_description: Option<String>,
1835 /// 抽取时模型自己报的类型名,**词表里没有**才会留在这儿
1836 pub proposed_type: Option<String>,
1837 /// 模型对它自己的说法,每个实体都有。
1838 ///
1839 /// 这是最强的信号,因为它把任务从"读懂这是什么"换回"本体里哪个类叫这个"
1840 /// ——短名字对短标签。实测的失败正出在另一头:拿一段中文画像去匹配
1841 /// schema.org 的 "A software application.",两边形状根本不对等
1842 pub specific_type: Option<String>,
1843 /// 它参与的谓词,连着对方的名字(`produces 深蓝`、`leads by 张伟`)。
1844 /// **跨文档累积**,这正是抽取当场没有的东西
1845 pub roles: Vec<String>,
1846 /// 证据引文,最多几句。抽取看的是同一批句子,但那一次要同时做实体识别、
1847 /// 关系判断、时态解析、JSON 格式化,还要跟几十个别的实体抢注意力
1848 /// 证据引文,**只取它当主语的那些**。宾语位的引文讲的是主语:
1849 /// 「上海浦东新区」是 located_in 的宾语,引文却是"星云科技(上海)
1850 /// 有限公司是一家注册于上海浦东新区的股份有限公司",整句重心在
1851 /// "股份有限公司"上——实测那一版检索给出的候选全是 corporation 一类
1852 pub quotes: Vec<String>,
1853 pub fact_count: i64,
1854}
1855
1856/// 值得送去精化类型的实体:**还没有类的**,或者模型报过一个词表外类型的。
1857///
1858/// 类型化得已经很具体的实体不动——重判一次只有下降风险,没有上升空间。
1859pub async fn entities_for_type_resolution(
1860 pool: &PgPool,
1861 kb_id: Uuid,
1862 limit: i64,
1863) -> AppResult<Vec<TypeCandidateSubject>> {
1864 Ok(sqlx::query_as(
1865 "SELECT e.id, e.canonical_name, e.aliases, t.key AS coarse_key, t.id AS coarse_id,
1866 t.description AS coarse_description,
1867 e.proposed_type, e.specific_type,
1868 -- 对方写**名字**,不写它的类型 key。
1869 -- 写 key 是自毁:查询里出现 organization / product / event 这些词,
1870 -- 而检索的目标正是这些类自己,于是候选就是画像里那几个词。
1871 -- 实测「张伟」的画像是 leads→organization … works_at→organization,
1872 -- 回来的候选是 corporation、organization、business_entity_type——
1873 -- 检索到的是画像自己,不是这个人是什么
1874 ARRAY(
1875 SELECT DISTINCT COALESCE(rt.key, fact_surface_predicate(f.id))
1876 || CASE WHEN f.subject_id = e.id THEN ' ' ELSE ' by ' END
1877 || coalesce(oe.canonical_name, 'a value')
1878 FROM facts f
1879 LEFT JOIN relation_types rt ON rt.id = f.predicate_id
1880 LEFT JOIN entities oe ON oe.id = CASE WHEN f.subject_id = e.id
1881 THEN f.object_id ELSE f.subject_id END
1882 WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
1883 AND (f.subject_id = e.id OR f.object_id = e.id)
1884 AND COALESCE(rt.key, fact_surface_predicate(f.id)) IS NOT NULL
1885 LIMIT 12
1886 ) AS roles,
1887 ARRAY(
1888 SELECT DISTINCT ev.quote FROM fact_evidence ev
1889 JOIN facts f2 ON f2.id = ev.fact_id
1890 WHERE f2.kb_id = $1 AND f2.invalidated_at IS NULL
1891 AND f2.subject_id = e.id
1892 AND ev.quote IS NOT NULL
1893 LIMIT 3
1894 ) AS quotes,
1895 (SELECT count(*) FROM facts f3
1896 WHERE f3.kb_id = $1 AND f3.invalidated_at IS NULL
1897 AND (f3.subject_id = e.id OR f3.object_id = e.id)) AS fact_count
1898 FROM entities e
1899 LEFT JOIN entity_types t ON t.id = e.type_id
1900 WHERE e.kb_id = $1 AND e.merged_into IS NULL
1901 -- **人拍过板的不再重判。**
1902 --
1903 -- 少了这一行,下面第三种条件会把它们全都捞回来:一个人工定成
1904 -- organization 的实体,只要 organization 有子类就够格,于是引擎
1905 -- 每一轮都去重新裁决一遍人已经决定过的事,而账本事后才看得出是谁改的。
1906 --
1907 -- 「不落库」不等于「不许说话」:引擎若认为人定错了,该走 Review 队列,
1908 -- 而不是直接改掉。憋着不说和直接改掉都是失真,只是方向相反
1909 AND e.type_source <> 'human'
1910 -- 值得看的三种:**还没有类的**、模型报过词表外类型的、
1911 -- **以及现类本身还有子类的**。第三种是主力:抽取只认基类之后,
1912 -- organization 下面挂着一大批更具体的类,那才是导进来的本体
1913 -- 唯一的用武之地。只看前两种就把它整个漏掉了
1914 AND (e.type_id IS NULL OR e.proposed_type IS NOT NULL OR e.specific_type IS NOT NULL
1915 OR EXISTS (SELECT 1 FROM entity_type_parents p WHERE p.parent_id = t.id))
1916 ORDER BY fact_count DESC, e.created_at
1917 LIMIT $2",
1918 )
1919 .bind(kb_id)
1920 .bind(limit)
1921 .fetch_all(pool)
1922 .await?)
1923}
1924
1925/// 某个类的全部后代(含自身)。精化只能往粗类的后代走。
1926///
1927/// **递归而不是一层**:本体是 DAG,`software_application ⊂ creative_work ⊂ thing`,
1928/// 只查一层就把绝大多数正确答案挡在门外了。
1929pub async fn descendants_of(pool: &PgPool, kb_id: Uuid, root: Uuid) -> AppResult<Vec<Uuid>> {
1930 let rows: Vec<(Uuid,)> = sqlx::query_as(
1931 "WITH RECURSIVE d(id) AS (
1932 SELECT $2::uuid
1933 UNION
1934 SELECT p.child_id FROM entity_type_parents p JOIN d ON d.id = p.parent_id
1935 )
1936 SELECT d.id FROM d JOIN entity_types t ON t.id = d.id WHERE t.kb_id = $1",
1937 )
1938 .bind(kb_id)
1939 .bind(root)
1940 .fetch_all(pool)
1941 .await?;
1942 Ok(rows.into_iter().map(|(id,)| id).collect())
1943}
1944
1945/// 记下模型对这个实体自己的说法。
1946///
1947/// **后写者不覆盖先写者**(`IS NULL` 才写),与 `set_proposed_type` 同一条:
1948/// 同一个实体会被多个分块提到,第一次的说法通常出自最完整的那句话,
1949/// 后面的分块往往只是顺带一提。
1950pub async fn set_specific_type(pool: &PgPool, entity_id: Uuid, value: &str) -> AppResult<()> {
1951 sqlx::query(
1952 "UPDATE entities SET specific_type = left($2, 80)
1953 WHERE id = $1 AND specific_type IS NULL",
1954 )
1955 .bind(entity_id)
1956 .bind(value)
1957 .execute(pool)
1958 .await?;
1959 Ok(())
1960}
1961
1962/// 跟这个实体最像的**已定类**实体,连同它们的类。
1963///
1964/// 类型消解的第二个候选来源。第一个是拿画像去搜类的描述,它的软肋实测很清楚:
1965/// 中文画像对 schema.org 的 "A software application.",两边形状根本不对等。
1966/// 这一条绕开了那道坎——**名字对名字、同语言**,而且库越大越准:
1967/// 「深蓝向量数据库」像「Milvus」,而 Milvus 已经标成 software_application。
1968///
1969/// 比的是双方的 `profile_embedding`(出现语境的滑动平均),**同一种向量对同一种
1970/// 向量**,不是拿文本画像去比语境向量。代价是零——这个向量实体消解本来就在维护。
1971///
1972/// 已知弱点:只出现在一篇文档里的实体,语境向量就是那一块的向量,同文档的实体
1973/// 会互相成为近邻。调用方要看得到 `same_document`,别把它当成类型证据。
1974pub async fn nearest_typed_entities(
1975 pool: &PgPool,
1976 kb_id: Uuid,
1977 entity_id: Uuid,
1978 limit: i64,
1979) -> AppResult<Vec<(String, Uuid, String, f64, bool)>> {
1980 Ok(sqlx::query_as(
1981 "WITH me AS (
1982 SELECT profile_embedding AS v FROM entities WHERE id = $2 AND kb_id = $1
1983 ),
1984 my_docs AS (
1985 SELECT DISTINCT ev.document_id FROM fact_evidence ev
1986 JOIN facts f ON f.id = ev.fact_id
1987 WHERE f.kb_id = $1 AND (f.subject_id = $2 OR f.object_id = $2)
1988 )
1989 SELECT e.canonical_name, t.id, t.key,
1990 (e.profile_embedding <=> (SELECT v FROM me))::float8 AS distance,
1991 EXISTS (SELECT 1 FROM fact_evidence ev2
1992 JOIN facts f2 ON f2.id = ev2.fact_id
1993 WHERE f2.kb_id = $1 AND (f2.subject_id = e.id OR f2.object_id = e.id)
1994 AND ev2.document_id IN (SELECT document_id FROM my_docs))
1995 AS same_document
1996 -- 内连接就是那道门:没判出类型的实体(type_id IS NULL)不是答案,
1997 -- 拿它当邻居的证据只会把「没判出来」传染开
1998 FROM entities e
1999 JOIN entity_types t ON t.id = e.type_id
2000 WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2
2001 AND e.profile_embedding IS NOT NULL
2002 AND (SELECT v FROM me) IS NOT NULL
2003 ORDER BY e.profile_embedding <=> (SELECT v FROM me)
2004 LIMIT $3",
2005 )
2006 .bind(kb_id)
2007 .bind(entity_id)
2008 .bind(limit)
2009 .fetch_all(pool)
2010 .await?)
2011}
2012
2013/// 按实体逐个改类,写进同一本账。返回 (批次 id, 改动数)。
2014///
2015/// 与 [`adopt_proposed_types`] 的区别只在挑选方式:那个按 `proposed_type` 这个
2016/// **说法**认领一批,这个由调用方点名——类型消解裁决出来的是"这个实体是那个类",
2017/// 不是"叫这个说法的都是那个类"。
2018///
2019/// 账本格式一字不差,所以 [`unadopt_types`] 原样能撤。
2020pub async fn retype_entities(
2021 pool: &PgPool,
2022 kb_id: Uuid,
2023 picks: &[(Uuid, Uuid)],
2024 // None = 引擎自动裁决。跟 entity_merges.merged_by 一个约定,
2025 // 实体历史据此区分"某某某改的"与"高置信自动改的"
2026 actor: Option<Uuid>,
2027) -> AppResult<(Uuid, u32)> {
2028 let batch_id = Uuid::now_v7();
2029 let mut moved = 0u32;
2030 let mut names: std::collections::HashSet<String> = std::collections::HashSet::new();
2031 // 一个实体在一批里只改一次。账本主键是 (batch_id, entity_id),同一个 id
2032 // 来两次会撞——而调用方拿到的是 500,整批一个都没落。这里挡住比在那边
2033 // 追每一条产生 picks 的路子可靠:重复的第二条本来也没有意义
2034 let mut seen: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
2035 for (entity_id, type_id) in picks {
2036 if !seen.insert(*entity_id) {
2037 continue;
2038 }
2039 let mut tx = pool.begin().await?;
2040 // 已经在目标类上的不算改动,也不进账本——撤销时不该把它们推回去。
2041 //
2042 // **旧类型要从 CTE 里读**:`UPDATE … RETURNING` 给的是新值,而账本要记的
2043 // 是改之前那个。直接 RETURNING type_id 拿到的就是刚写进去的那一个,
2044 // 撤销时等于把实体"放回"它现在的位置——账本看着满满当当,实际什么都撤不了。
2045 // 条件也一并放进 CTE:这一行还在、没被合并、且确实要变
2046 //
2047 // **`IS DISTINCT FROM` 而不是 `<>`**:0009 之后起点常常是 NULL,而
2048 // `NULL <> uuid` 是 NULL 不是 true——CTE 会空掉,UPDATE 一行不动,
2049 // 于是"给没有类的实体定类"这个最主要的场景整个变成空操作
2050 let row: Option<(Option<Uuid>, String)> = sqlx::query_as(
2051 "WITH before AS (
2052 SELECT id, type_id, canonical_name FROM entities
2053 WHERE id = $1 AND kb_id = $3 AND merged_into IS NULL
2054 AND type_id IS DISTINCT FROM $2
2055 )
2056 UPDATE entities e SET type_id = $2, updated_at = now(),
2057 type_source = CASE WHEN $4::uuid IS NULL THEN 'inferred' ELSE 'human' END
2058 FROM before
2059 WHERE e.id = before.id
2060 RETURNING before.type_id, before.canonical_name",
2061 )
2062 .bind(entity_id)
2063 .bind(type_id)
2064 .bind(kb_id)
2065 .bind(actor)
2066 .fetch_optional(&mut *tx)
2067 .await?;
2068 let Some((from_type, name)) = row else {
2069 tx.rollback().await?;
2070 continue;
2071 };
2072 sqlx::query(
2073 "INSERT INTO entity_retypes
2074 (batch_id, kb_id, entity_id, from_type_id, to_type_id, actor_id)
2075 VALUES ($1, $2, $3, $4, $5, $6)",
2076 )
2077 .bind(batch_id)
2078 .bind(kb_id)
2079 .bind(entity_id)
2080 .bind(from_type)
2081 .bind(type_id)
2082 .bind(actor)
2083 .execute(&mut *tx)
2084 .await?;
2085 tx.commit().await?;
2086 names.insert(name);
2087 moved += 1;
2088 }
2089 // 消歧后缀的兜底值就是类型标签,改了类就得重算
2090 for n in &names {
2091 refresh_disambiguators(pool, kb_id, n).await?;
2092 }
2093 Ok((batch_id, moved))
2094}
2095
2096/// 人认可过的"粗类 → 细类"配对。
2097///
2098/// 待人工那一档由"跨没跨分类轴"触发,而那条判据测的常常是**种子类跟导入词汇表
2099/// 连没连上**,不是风险:schema.org 的 Place 另起 key,内置 location 零子类,
2100/// 于是每个城市都要问一遍。配对是类与类之间的事,实体只是碰巧撞上它——
2101/// 认可一次就该一直算数。
2102pub async fn approved_refinements(
2103 pool: &PgPool,
2104 kb_id: Uuid,
2105) -> AppResult<std::collections::HashSet<(Uuid, Uuid)>> {
2106 let rows: Vec<(Uuid, Uuid)> = sqlx::query_as(
2107 "SELECT from_type_id, to_type_id FROM type_refinement_pairs WHERE kb_id = $1",
2108 )
2109 .bind(kb_id)
2110 .fetch_all(pool)
2111 .await?;
2112 Ok(rows.into_iter().collect())
2113}
2114
2115/// 记下一个被认可的配对。重复认可是幂等的。
2116pub async fn approve_refinement(
2117 pool: &PgPool,
2118 kb_id: Uuid,
2119 from_type_id: Uuid,
2120 to_type_id: Uuid,
2121 by: Uuid,
2122) -> AppResult<()> {
2123 sqlx::query(
2124 "INSERT INTO type_refinement_pairs (kb_id, from_type_id, to_type_id, approved_by)
2125 VALUES ($1, $2, $3, $4)
2126 ON CONFLICT (kb_id, from_type_id, to_type_id) DO NOTHING",
2127 )
2128 .bind(kb_id)
2129 .bind(from_type_id)
2130 .bind(to_type_id)
2131 .bind(by)
2132 .execute(pool)
2133 .await?;
2134 Ok(())
2135}
2136
2137#[cfg(test)]
2138mod same_type_tests {
2139 use super::{classify_type_drift, TypeDrift};
2140
2141 /// **相同类型是最常见的情形,而它曾经落在 Disjoint 上。**
2142 ///
2143 /// 这个函数生来服务"类型漂移"(同名被抽成两种类型),那里两边相同不会发生;
2144 /// 后来被 `containment_reviews` 借去当相容性判据,那里两边相同是常态。
2145 /// 结果是 `Sherlock Holmes` 与 `Holmes` 一对都进不了审阅队列。
2146 #[test]
2147 fn the_same_type_is_a_recall_candidate() {
2148 for k in ["person", "location", "organization", "product", "event"] {
2149 assert_eq!(
2150 classify_type_drift(Some(k), Some(k)),
2151 TypeDrift::Recall,
2152 "{k} 对 {k} 必须可召回"
2153 );
2154 }
2155 // 自定义类型同样——这里判的是"两边是不是同一种东西",不是"它在不在白名单里"
2156 assert_eq!(
2157 classify_type_drift(Some("drug"), Some("drug")),
2158 TypeDrift::Recall
2159 );
2160 // 跨类型的老结论一条都不变
2161 assert_eq!(
2162 classify_type_drift(Some("person"), Some("organization")),
2163 TypeDrift::Disjoint
2164 );
2165 }
2166}