Elffuss BraidHub

kikocis/utopia public

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