From d8e3cf87172bf985f7421a277e22dced4c0bee41 Mon Sep 17 00:00:00 2001 From: Virtue039 Date: Sat, 10 Oct 2026 21:45:35 +0800 Subject: [PATCH 1/4] Keep ambiguous namesake mentions apart until source facts identify a candidate. Signed-off-by: Virtue039 --- crates/utopia-store/src/resolution.rs | 81 ++++++++- ...sake_tie_goes_to_review_not_a_coin_flip.rs | 169 ++++++++++++++++++ 2 files changed, 244 insertions(+), 6 deletions(-) diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 9af51e4db..2c54e7bf7 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -194,6 +194,8 @@ struct Candidate { profile_embedding: Option, profile_n: i32, degree: i64, + exact_name: bool, + same_type: bool, } /// 消解结果:mention 落到了哪个实体;附带需要入队的疑似重复审核对 @@ -355,8 +357,8 @@ async fn type_label(pool: &PgPool, type_id: Uuid) -> AppResult> { } /// 通道 1:名字字面相等的候选,按画像分层归并或新建(原 `resolve_mention` 的全部)。 -/// `context` 为 mention 所在分块的向量(无 embedding 模型时为 None,退化为 v1 行为: -/// 同名归并到事实最多的候选)。 +/// `context` 为 mention 所在分块的向量。多个候选使用这次的同一个名字时, +/// 画像与事实数量不能证明是谁;先问原文旁证,分不开就交给人。 #[allow(clippy::too_many_arguments)] async fn resolve_by_name( pool: &PgPool, @@ -382,31 +384,98 @@ async fn resolve_by_name( "SELECT e.id, e.canonical_name, e.profile_embedding, e.profile_n, (SELECT count(*) FROM facts f WHERE f.kb_id = e.kb_id AND (f.subject_id = e.id OR f.object_id = e.id) - AND f.invalidated_at IS NULL AND {not_name}) AS degree + AND f.invalidated_at IS NULL AND {not_name}) AS degree, + (lower(e.canonical_name) = ANY($4) OR {exact_named}) AS exact_name, + e.type_id IS NOT DISTINCT FROM $2 AS same_type FROM entities e -- IS NOT DISTINCT FROM 而不是 =(0009 的那个陷阱):开放图谱里的实体都没有类 -- (类由对齐来定),`type_id = NULL` 永远不成立,同名的它就永远撞不上—— -- 实测一个库里 Securities and Exchange Commission 与它的全大写写法成了两个实体 - WHERE e.kb_id = $1 AND e.type_id IS NOT DISTINCT FROM $2 AND e.merged_into IS NULL + WHERE e.kb_id = $1 AND e.merged_into IS NULL + AND (e.type_id IS NOT DISTINCT FROM $2 + OR ($2::uuid IS NULL AND (lower(e.canonical_name) = ANY($4) OR {exact_named}))) -- 被描述的东西没有名字(0044):它的 canonical_name 只是显示用的描述, -- 不是召回的桥——两篇文档里描述得一样的两个东西不能因此接到一起 AND e.description IS NULL AND (lower(e.canonical_name) = ANY($3) OR {named})", not_name = crate::names::not_a_name("f"), named = crate::names::has_name_in("e", 1, 3), + exact_named = crate::names::has_name_in("e", 1, 4), )) .bind(kb_id) .bind(type_id) .bind(&keys) + .bind(vec![name.to_lowercase()]) .fetch_all(pool) .await? .into_iter() .filter(|candidate: &Candidate| !exclude.contains(&candidate.id)) .collect(); + // #1136: 两个同名人的话题可以一样,也可以拉开。分差大于 0.02 不代表 + // 名字突然有了身份信息,无画像或没配 embedding 也不能按事实数量猜。 + // 只拦本次名字真的被多人使用的情形,泛用后缀扩召回不是同名的证据。 + // 名字事实也算:两个不同 canonical_name 都可能被原文叫作「张伟」。 + // 未绑定的类别词不能过滤已分类的同名人;否则一个尚未分类的工程师会 + // 成为唯一候选,原文中的财务总监连旁证这一关都进不来。 + let namesakes: Vec<_> = candidates.iter().filter(|c| c.exact_name).collect(); + if namesakes.len() > 1 { + if let Some(t) = text { + if let Some(c) = corroborating_candidate(pool, kb_id, &namesakes, t).await? { + if let Some(ctx) = context { + update_profile(pool, c.id, c.profile_n, ctx).await?; + } else { + touch_entity(pool, c.id).await?; + } + return Ok(Resolution { + entity_id: c.id, + created: false, + reviews: Vec::new(), + }); + } + } + // 锁内同名回捞也得排除这些候选,否则刚决定不猜,又在建实体时猜回去。 + let weighed: Vec<_> = exclude + .iter() + .copied() + .chain(candidates.iter().map(|c| c.id)) + .collect(); + let (id, created) = create_entity(pool, kb_id, type_id, &name, context, &weighed).await?; + if created { + refresh_disambiguators(pool, kb_id, &name).await?; + } + let reviews = if created { + namesakes + .into_iter() + .map(|c| { + let score = context + .and_then(|ctx| { + c.profile_embedding + .as_ref() + .and_then(|p| cosine(p.as_slice(), ctx)) + }) + .unwrap_or(1.0); + ReviewRequest { + other_id: c.id, + score, + reason: format!("namesake_tie|{score:.2}"), + stage: ReviewStage::Human, + } + }) + .collect() + } else { + Vec::new() + }; + return Ok(Resolution { + entity_id: id, + created, + reviews, + }); + } + + // 额外召回的已分类同名实体只参与上述歧义检查;没有歧义时保持类型漂移的处置。 + let candidates: Vec<_> = candidates.into_iter().filter(|c| c.same_type).collect(); if candidates.is_empty() { - // 同类型无候选 ≠ 新名字:类型标签会漂(同一团队被抽成 organization/project/ - // concept),先查其它类型下的同名实体,按类型对的互斥强度分流。 return resolve_type_drift(pool, kb_id, type_id, &name, &keys, context, exclude).await; } diff --git a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs index 60b6f33f9..0f8c0e06b 100644 --- a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs +++ b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs @@ -204,3 +204,172 @@ async fn a_namesake_tie_creates_an_entity_and_two_reviews() -> anyhow::Result<() .await?; run } + +// #1136: topic scores, missing profiles and fact counts cannot choose between known namesakes. +#[tokio::test] +async fn namesakes_without_a_clue_are_reviewed_outside_the_tie_margin() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let mut outcomes = Vec::new(); + for case in [ + "unequal_scores", + "unprofiled", + "no_context", + "shared_alias", + "unbound_typed", + "unbound_mixed", + ] { + let f = seed(&pool).await?; + let run = async { + sqlx::query("UPDATE entities SET profile_embedding = $2::vector WHERE id = $1") + .bind(f.zhang_b) + .bind(if case == "unprofiled" { + None + } else { + Some("[0.8,0.6,0]") + }) + .execute(&pool) + .await?; + if case == "shared_alias" { + for (id, name) in [ + (f.zhang_a, "Engineering Zhang Wei"), + (f.zhang_b, "Finance Zhang Wei"), + ] { + sqlx::query( + "UPDATE entities SET canonical_name = $2, type_id = NULL WHERE id = $1", + ) + .bind(id) + .bind(name) + .execute(&pool) + .await?; + utopia_store::names::record(&pool, f.kb, id, "Zhang Wei", None, None).await?; + } + } + if case == "unbound_mixed" { + sqlx::query("UPDATE entities SET type_id = NULL WHERE id = $1") + .bind(f.zhang_b) + .execute(&pool) + .await?; + } + let ctx = if case == "unprofiled" { + [0.0, 0.0, 1.0] + } else { + [1.0, 0.0, 0.0] + }; + let r = utopia_store::resolution::resolve_mention( + &pool, + f.kb, + (!matches!(case, "shared_alias" | "unbound_typed" | "unbound_mixed")) + .then_some(f.person), + "Zhang Wei", + (case != "no_context").then_some(ctx.as_slice()), + None, + Some("Zhang Wei received an award."), + &[], + ) + .await?; + let mut others: Vec<_> = r.reviews.iter().map(|v| v.other_id).collect(); + others.sort(); + let mut expected = vec![f.zhang_a, f.zhang_b]; + expected.sort(); + outcomes.push(( + case, + r.created + && !expected.contains(&r.entity_id) + && others == expected + && r.reviews.iter().all(|v| v.stage == ReviewStage::Human), + )); + Ok::<_, anyhow::Error>(()) + } + .await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run?; + } + assert!( + outcomes.iter().all(|(_, safe)| *safe), + "silent namesake attachment: {outcomes:?}" + ); + Ok(()) +} + +#[tokio::test] +async fn a_single_namesake_still_resolves_without_a_clue() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let f = seed(&pool).await?; + let run = async { + sqlx::query("DELETE FROM entities WHERE id = $1") + .bind(f.zhang_b) + .execute(&pool) + .await?; + for ctx in [None, Some([1.0, 0.0, 0.0])] { + let r = utopia_store::resolution::resolve_mention( + &pool, + f.kb, + Some(f.person), + "Zhang Wei", + ctx.as_ref().map(|v| v.as_slice()), + None, + Some("Zhang Wei received an award."), + &[], + ) + .await?; + assert_eq!(r.entity_id, f.zhang_a); + assert!(!r.created && r.reviews.is_empty()); + } + Ok::<_, anyhow::Error>(()) + } + .await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run +} + +#[tokio::test] +async fn a_namesakes_fact_outweighs_a_higher_topic_score() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let f = seed(&pool).await?; + let run = async { + sqlx::query("UPDATE entities SET profile_embedding = '[0.8,0.6,0]'::vector WHERE id = $1") + .bind(f.zhang_b) + .execute(&pool) + .await?; + for type_id in [Some(f.person), None] { + let r = utopia_store::resolution::resolve_mention( + &pool, + f.kb, + type_id, + "Zhang Wei", + Some(&[1.0, 0.0, 0.0]), + None, + Some("Zhang Wei of Finance signed the report."), + &[], + ) + .await?; + assert_eq!( + r.entity_id, f.zhang_b, + "Finance belongs to the lower-scoring namesake" + ); + assert!(!r.created && r.reviews.is_empty()); + } + Ok::<_, anyhow::Error>(()) + } + .await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run +} From 893ec7541fce9764ea67dee500b7c8d36e7c3166 Mon Sep 17 00:00:00 2001 From: Virtue039 Date: Sun, 11 Oct 2026 11:27:11 +0800 Subject: [PATCH 2/4] Reuse unresolved namesakes so recurring mentions do not multiply reviews Signed-off-by: Virtue039 --- crates/utopia-store/src/resolution.rs | 211 ++++++++++++------ ...sake_tie_goes_to_review_not_a_coin_flip.rs | 85 +++++++ 2 files changed, 225 insertions(+), 71 deletions(-) diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 2c54e7bf7..b0a145f2f 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -196,6 +196,7 @@ struct Candidate { degree: i64, exact_name: bool, same_type: bool, + unresolved: bool, } /// 消解结果:mention 落到了哪个实体;附带需要入队的疑似重复审核对 @@ -386,7 +387,11 @@ async fn resolve_by_name( WHERE f.kb_id = e.kb_id AND (f.subject_id = e.id OR f.object_id = e.id) AND f.invalidated_at IS NULL AND {not_name}) AS degree, (lower(e.canonical_name) = ANY($4) OR {exact_named}) AS exact_name, - e.type_id IS NOT DISTINCT FROM $2 AS same_type + e.type_id IS NOT DISTINCT FROM $2 AS same_type, + EXISTS (SELECT 1 FROM resolution_reviews rv + WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id + AND rv.status = 'pending' AND rv.stage = 'human' + AND rv.reason LIKE 'namesake_tie|%') AS unresolved FROM entities e -- IS NOT DISTINCT FROM 而不是 =(0009 的那个陷阱):开放图谱里的实体都没有类 -- (类由对齐来定),`type_id = NULL` 永远不成立,同名的它就永远撞不上—— @@ -418,7 +423,11 @@ async fn resolve_by_name( // 名字事实也算:两个不同 canonical_name 都可能被原文叫作「张伟」。 // 未绑定的类别词不能过滤已分类的同名人;否则一个尚未分类的工程师会 // 成为唯一候选,原文中的财务总监连旁证这一关都进不来。 - let namesakes: Vec<_> = candidates.iter().filter(|c| c.exact_name).collect(); + // 待人分配的提及不是第三个已知同名者;它积累的事实也不能拿来猜身份。 + let namesakes: Vec<_> = candidates + .iter() + .filter(|c| c.exact_name && !c.unresolved) + .collect(); if namesakes.len() > 1 { if let Some(t) = text { if let Some(c) = corroborating_candidate(pool, kb_id, &namesakes, t).await? { @@ -434,38 +443,43 @@ async fn resolve_by_name( }); } } - // 锁内同名回捞也得排除这些候选,否则刚决定不猜,又在建实体时猜回去。 + let reviews: Vec<_> = namesakes + .into_iter() + .map(|c| { + let score = context + .and_then(|ctx| { + c.profile_embedding + .as_ref() + .and_then(|p| cosine(p.as_slice(), ctx)) + }) + .unwrap_or(1.0); + ReviewRequest { + other_id: c.id, + score, + reason: format!("namesake_tie|{score:.2}"), + stage: ReviewStage::Human, + } + }) + .collect(); + // 排除已知候选,复用同名未决项;否则每篇文档再生一个未决者,审核对平方增长。 let weighed: Vec<_> = exclude .iter() .copied() - .chain(candidates.iter().map(|c| c.id)) + .chain(candidates.iter().filter(|c| !c.unresolved).map(|c| c.id)) .collect(); - let (id, created) = create_entity(pool, kb_id, type_id, &name, context, &weighed).await?; + let (id, created) = create_entity( + pool, + kb_id, + type_id, + &name, + context, + &weighed, + Some(&reviews), + ) + .await?; if created { refresh_disambiguators(pool, kb_id, &name).await?; } - let reviews = if created { - namesakes - .into_iter() - .map(|c| { - let score = context - .and_then(|ctx| { - c.profile_embedding - .as_ref() - .and_then(|p| cosine(p.as_slice(), ctx)) - }) - .unwrap_or(1.0); - ReviewRequest { - other_id: c.id, - score, - reason: format!("namesake_tie|{score:.2}"), - stage: ReviewStage::Human, - } - }) - .collect() - } else { - Vec::new() - }; return Ok(Resolution { entity_id: id, created, @@ -558,7 +572,7 @@ async fn resolve_by_name( } } let (id, created) = - create_entity(pool, kb_id, type_id, &name, context, &weighed).await?; + create_entity(pool, kb_id, type_id, &name, context, &weighed, None).await?; if !created { // 并行的另一份文档刚建好它:用它的,审核对也是它排的 return Ok(Resolution { @@ -622,7 +636,7 @@ async fn resolve_by_name( }); } } - let (id, created) = create_entity(pool, kb_id, type_id, &name, context, &weighed).await?; + let (id, created) = create_entity(pool, kb_id, type_id, &name, context, &weighed, None).await?; if !created { // 并行的另一份文档刚建好它:用它的,审核对也是它排的 return Ok(Resolution { @@ -1124,7 +1138,7 @@ async fn resolve_type_drift( .copied() .chain(cross.iter().map(|c| c.id)) .collect(); - let (id, created) = create_entity(pool, kb_id, type_id, name, context, &weighed).await?; + let (id, created) = create_entity(pool, kb_id, type_id, name, context, &weighed, None).await?; if !created { // 并行的另一份文档刚建好它:用它的,审核对也是它排的 return Ok(Resolution { @@ -1188,60 +1202,115 @@ async fn create_entity( // 替人把 mention 归到其中一个身上。同名并列那条路上这正是 #270 禁的事: // 分不开就别硬分,谁也不归,两个都送审。 weighed: &[Uuid], + unresolved_reviews: Option<&[ReviewRequest]>, ) -> AppResult<(Uuid, bool)> { // 名字属性在锁外取:它自己有一次插入,放进锁里会让所有建实体的人排同一把队 let known_as = crate::names::ensure_known_as(pool, kb_id).await?; let mut tx = pool.begin().await?; sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))") .bind(kb_id.to_string()) - .bind(name) + .bind(if unresolved_reviews.is_some() { + name.to_lowercase() + } else { + name.to_string() + }) .execute(&mut *tx) .await?; - let existing: Option<(Uuid,)> = sqlx::query_as( - // 被描述的东西不算「同名的它」(0044):它的 canonical_name 只是显示用的描述 - "SELECT id FROM entities + let existing: Option<(Uuid,)> = if unresolved_reviews.is_some() { + // pending 的人工 namesake 对标识未决项。合并后或人已裁完的实体不再是桶。 + sqlx::query_as( + "SELECT e.id FROM entities e + WHERE e.kb_id = $1 AND lower(e.canonical_name) = lower($2) + AND (e.type_id IS NOT DISTINCT FROM $3 OR e.type_id IS NULL OR $3::uuid IS NULL) + AND e.merged_into IS NULL AND e.description IS NULL AND e.id <> ALL($4) + AND EXISTS (SELECT 1 FROM resolution_reviews rv + WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id + AND rv.status = 'pending' AND rv.stage = 'human' + AND rv.reason LIKE 'namesake_tie|%') + ORDER BY e.id LIMIT 1", + ) + .bind(kb_id) + .bind(name) + .bind(type_id) + .bind(weighed) + .fetch_optional(&mut *tx) + .await? + } else { + sqlx::query_as( + // 被描述的东西不算「同名的它」(0044):它的 canonical_name 只是显示用的描述 + "SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = $2 AND type_id IS NOT DISTINCT FROM $3 AND merged_into IS NULL AND description IS NULL AND id <> ALL($4) ORDER BY id LIMIT 1", - ) - .bind(kb_id) - .bind(name) - .bind(type_id) - .bind(weighed) - .fetch_optional(&mut *tx) - .await?; - if let Some((id,)) = existing { - tx.commit().await?; - return Ok((id, false)); - } - let id = Uuid::now_v7(); - sqlx::query( - "INSERT INTO entities (id, kb_id, type_id, canonical_name, profile_embedding, profile_n) - VALUES ($1, $2, $3, $4, $5, $6)", - ) - .bind(id) - .bind(kb_id) - .bind(type_id) - .bind(name) - .bind(context.map(|c| Vector::from(c.to_vec()))) - .bind(i32::from(context.is_some())) - .execute(&mut *tx) - .await?; - // 与实体同一个事务:召回按名字事实找它,建出来却查不到名字的那一瞬间不能有。 - // 出处(哪一块、哪句话)由抽取随后给这条事实补证据 - sqlx::query( - "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value) + ) + .bind(kb_id) + .bind(name) + .bind(type_id) + .bind(weighed) + .fetch_optional(&mut *tx) + .await? + }; + let created = existing.is_none(); + let id = if let Some((id,)) = existing { + id + } else { + let id = Uuid::now_v7(); + sqlx::query( + "INSERT INTO entities (id, kb_id, type_id, canonical_name, profile_embedding, profile_n) + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(id) + .bind(kb_id) + .bind(type_id) + .bind(name) + .bind(context.map(|c| Vector::from(c.to_vec()))) + .bind(i32::from(context.is_some())) + .execute(&mut *tx) + .await?; + // 与实体同一个事务:召回按名字事实找它,建出来却查不到名字的那一瞬间不能有。 + // 出处(哪一块、哪句话)由抽取随后给这条事实补证据 + sqlx::query( + "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value) VALUES ($1, $2, $3, $4, jsonb_build_object('value', $5::text))", - ) - .bind(Uuid::now_v7()) - .bind(kb_id) - .bind(id) - .bind(known_as) - .bind(name) - .execute(&mut *tx) - .await?; + ) + .bind(Uuid::now_v7()) + .bind(kb_id) + .bind(id) + .bind(known_as) + .bind(name) + .execute(&mut *tx) + .await?; + id + }; + if let Some(reviews) = unresolved_reviews { + // 标记与实体同事务:并行文档不能看见「新建但还没入审核」的桶再生一个。 + // 返回给调用方的审核请求仍保留,原有 pending 唯一索引使再入队幂等。 + for rv in reviews { + sqlx::query( + "INSERT INTO resolution_reviews AS existing + (id, kb_id, left_id, right_id, score, reason, stage) + SELECT $1, $2, $3, $4, $5, $6, 'human' + WHERE NOT EXISTS (SELECT 1 FROM resolution_reviews kept + WHERE kept.kb_id = $2 AND kept.status = 'kept' + AND least(kept.left_id, kept.right_id) = least($3, $4) + AND greatest(kept.left_id, kept.right_id) = greatest($3, $4)) + ON CONFLICT (kb_id, least(left_id, right_id), greatest(left_id, right_id)) + WHERE status = 'pending' + DO UPDATE SET stage = 'human', reason = EXCLUDED.reason + WHERE existing.stage = 'adjudicating'", + ) + .bind(Uuid::now_v7()) + .bind(kb_id) + .bind(id) + .bind(rv.other_id) + .bind(rv.score) + .bind(&rv.reason) + .execute(&mut *tx) + .await?; + } + } tx.commit().await?; - Ok((id, true)) + Ok((id, created)) } /// 一个被描述、没有名字的东西(0044 第一刀,#729):"the buyer's parent company"、 diff --git a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs index 0f8c0e06b..373cafd0a 100644 --- a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs +++ b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs @@ -373,3 +373,88 @@ async fn a_namesakes_fact_outweighs_a_higher_topic_score() -> anyhow::Result<()> .await?; run } + +// Every call can be a new document: an unresolved mention is not a third known namesake. +#[tokio::test] +async fn recurring_ambiguous_mentions_share_one_unresolved_entity() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let f = seed(&pool).await?; + let run = async { + sqlx::query("UPDATE entities SET profile_embedding = '[0.8,0.6,0]'::vector WHERE id = $1") + .bind(f.zhang_b) + .execute(&pool) + .await?; + let mut ids = Vec::new(); + for _ in 0..20 { + let r = utopia_store::resolution::resolve_mention( + &pool, f.kb, Some(f.person), "Zhang Wei", Some(&[1.0, 0.0, 0.0]), + None, Some("Zhang Wei received an award."), &[], + ).await?; + for rv in &r.reviews { + utopia_store::resolution::create_review( + &pool, f.kb, r.entity_id, rv.other_id, rv.score, &rv.reason, rv.stage, + ).await?; + } + ids.push(r.entity_id); + } + let entities: i64 = sqlx::query_scalar( + "SELECT count(*) FROM entities WHERE kb_id = $1 AND lower(canonical_name) = 'zhang wei' AND merged_into IS NULL", + ).bind(f.kb).fetch_one(&pool).await?; + let reviews: i64 = sqlx::query_scalar( + "SELECT count(*) FROM resolution_reviews WHERE kb_id = $1 AND status = 'pending' AND stage = 'human'", + ).bind(f.kb).fetch_one(&pool).await?; + assert_eq!((entities, reviews), (3, 2), "20 mentions must add one unresolved entity and two reviews"); + assert!(ids.iter().all(|id| *id == ids[0])); + assert!(![f.zhang_a, f.zhang_b].contains(&ids[0])); + Ok::<_, anyhow::Error>(()) + }.await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run +} + +#[tokio::test] +async fn parallel_mentions_do_not_create_two_unresolved_entities() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let f = seed(&pool).await?; + let run = async { + let resolve = |type_id, name| utopia_store::resolution::resolve_mention( + &pool, f.kb, type_id, name, Some(&[1.0, 0.0, 0.0]), None, + Some("Zhang Wei received an award."), &[], + ); + let (a, b) = tokio::join!(resolve(Some(f.person), "Zhang Wei"), resolve(None, "zhang wei")); + let (a, b) = (a?, b?); + assert_eq!(a.entity_id, b.entity_id); + assert_ne!(a.created, b.created); + // No caller has persisted returned reviews yet: the unresolved marker must be atomic. + let reviews: i64 = sqlx::query_scalar( + "SELECT count(*) FROM resolution_reviews WHERE kb_id = $1 AND status = 'pending' AND stage = 'human'", + ).bind(f.kb).fetch_one(&pool).await?; + assert_eq!(reviews, 2); + // Facts of an unresolved mention are not evidence that it is the finance namesake. + sqlx::query( + "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id) + SELECT $1, kb_id, $2, predicate_id, object_id FROM facts WHERE subject_id = $3", + ).bind(Uuid::now_v7()).bind(a.entity_id).bind(f.zhang_b).execute(&pool).await?; + let placed = utopia_store::resolution::resolve_mention( + &pool, f.kb, None, "Zhang Wei", Some(&[1.0, 0.0, 0.0]), None, + Some("Zhang Wei of Finance signed the report."), &[], + ).await?; + assert_eq!(placed.entity_id, f.zhang_b); + assert!(!placed.created && placed.reviews.is_empty()); + Ok::<_, anyhow::Error>(()) + }.await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run +} From 69c3978f7d4bff13c36ae1ad585499c54edb2ab5 Mon Sep 17 00:00:00 2001 From: Virtue039 Date: Sun, 11 Oct 2026 11:59:09 +0800 Subject: [PATCH 3/4] Keep merged namesake survivors out of the unresolved bucket lookup Signed-off-by: Virtue039 --- crates/utopia-store/src/resolution.rs | 15 +++++-- ...sake_tie_goes_to_review_not_a_coin_flip.rs | 43 +++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index b0a145f2f..792933c0a 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -391,7 +391,11 @@ async fn resolve_by_name( EXISTS (SELECT 1 FROM resolution_reviews rv WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id AND rv.status = 'pending' AND rv.stage = 'human' - AND rv.reason LIKE 'namesake_tie|%') AS unresolved + AND rv.reason LIKE 'namesake_tie|%' + AND rv.reason NOT LIKE '%|redirected%' + AND NOT EXISTS (SELECT 1 FROM entity_merges m + WHERE m.kb_id = e.kb_id AND m.target_id = e.id + AND m.reverted_at IS NULL)) AS unresolved FROM entities e -- IS NOT DISTINCT FROM 而不是 =(0009 的那个陷阱):开放图谱里的实体都没有类 -- (类由对齐来定),`type_id = NULL` 永远不成立,同名的它就永远撞不上—— @@ -1217,7 +1221,8 @@ async fn create_entity( .execute(&mut *tx) .await?; let existing: Option<(Uuid,)> = if unresolved_reviews.is_some() { - // pending 的人工 namesake 对标识未决项。合并后或人已裁完的实体不再是桶。 + // pending 的人工 namesake 对标识未决项。合并后或人已裁完的实体不再是桶; + // 合并会把其它 pending 对转给存活者,不能因此把已确认的人误认成未决项。 sqlx::query_as( "SELECT e.id FROM entities e WHERE e.kb_id = $1 AND lower(e.canonical_name) = lower($2) @@ -1226,7 +1231,11 @@ async fn create_entity( AND EXISTS (SELECT 1 FROM resolution_reviews rv WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id AND rv.status = 'pending' AND rv.stage = 'human' - AND rv.reason LIKE 'namesake_tie|%') + AND rv.reason LIKE 'namesake_tie|%' + AND rv.reason NOT LIKE '%|redirected%' + AND NOT EXISTS (SELECT 1 FROM entity_merges m + WHERE m.kb_id = e.kb_id AND m.target_id = e.id + AND m.reverted_at IS NULL)) ORDER BY e.id LIMIT 1", ) .bind(kb_id) diff --git a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs index 373cafd0a..790522957 100644 --- a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs +++ b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs @@ -458,3 +458,46 @@ async fn parallel_mentions_do_not_create_two_unresolved_entities() -> anyhow::Re .await?; run } + +#[tokio::test] +async fn a_merged_namesake_is_no_longer_unresolved() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + for bucket_survives in [false, true] { + let f = seed(&pool).await?; + let run = async { + let r = utopia_store::resolution::resolve_mention( + &pool, f.kb, Some(f.person), "Zhang Wei", None, None, + Some("Zhang Wei received an award."), &[], + ).await?; + let review: Uuid = sqlx::query_scalar( + "SELECT id FROM resolution_reviews WHERE kb_id = $1 AND left_id = $2 AND right_id = $3 AND status = 'pending'", + ).bind(f.kb).bind(r.entity_id).bind(f.zhang_a).fetch_one(&pool).await?; + let (source, target) = if bucket_survives { (f.zhang_a, r.entity_id) } else { (r.entity_id, f.zhang_a) }; + utopia_store::resolution::merge_entities(&pool, f.kb, source, target, None, "review fixture").await?; + utopia_store::resolution::close_review_auto(&pool, review, "merged", "review fixture").await?; + // One namesake review remains (redirected if the bucket was the source). + // It must not hide the now-identified survivor from the ambiguity guard. + let next = utopia_store::resolution::resolve_mention( + &pool, f.kb, Some(f.person), "Zhang Wei", None, None, + Some("Zhang Wei received an award."), &[], + ).await?; + assert!(next.created, "merged survivor is known, not an unresolved bucket"); + assert!(![target, f.zhang_b].contains(&next.entity_id)); + let placed = utopia_store::resolution::resolve_mention( + &pool, f.kb, Some(f.person), "Zhang Wei", None, None, + Some("Zhang Wei of Platform Engineering received an award."), &[], + ).await?; + assert_eq!(placed.entity_id, target); + Ok::<_, anyhow::Error>(()) + }.await; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(f.org) + .execute(&pool) + .await?; + run?; + } + Ok(()) +} From 945425e8c0ca24aeb1d43da31282be5679902d02 Mon Sep 17 00:00:00 2001 From: Virtue039 Date: Sun, 11 Oct 2026 13:09:42 +0800 Subject: [PATCH 4/4] Keep automatically separated namesakes in one unresolved entity without reopening reviews Signed-off-by: Virtue039 --- crates/utopia-store/src/resolution.rs | 26 ++++++++++--- ...sake_tie_goes_to_review_not_a_coin_flip.rs | 37 +++++++++++++++++++ 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 792933c0a..f7c47d50e 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -390,8 +390,10 @@ async fn resolve_by_name( e.type_id IS NOT DISTINCT FROM $2 AS same_type, EXISTS (SELECT 1 FROM resolution_reviews rv WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id - AND rv.status = 'pending' AND rv.stage = 'human' - AND rv.reason LIKE 'namesake_tie|%' + AND rv.stage = 'human' + AND ((rv.status = 'pending' AND rv.reason LIKE 'namesake_tie|%') + OR (rv.status = 'kept' AND rv.decided_by IS NULL AND starts_with(rv.reason, + 'kept_apart|no_checkable_identity_evidence|unresolved_namesake_left|namesake_tie|'))) AND rv.reason NOT LIKE '%|redirected%' AND NOT EXISTS (SELECT 1 FROM entity_merges m WHERE m.kb_id = e.kb_id AND m.target_id = e.id @@ -1221,7 +1223,8 @@ async fn create_entity( .execute(&mut *tx) .await?; let existing: Option<(Uuid,)> = if unresolved_reviews.is_some() { - // pending 的人工 namesake 对标识未决项。合并后或人已裁完的实体不再是桶; + // pending 的人工 namesake 对,或机器因无身份证据而 kept 的左角色,仍是未决项。 + // 人已裁完的实体不再是桶; // 合并会把其它 pending 对转给存活者,不能因此把已确认的人误认成未决项。 sqlx::query_as( "SELECT e.id FROM entities e @@ -1230,8 +1233,10 @@ async fn create_entity( AND e.merged_into IS NULL AND e.description IS NULL AND e.id <> ALL($4) AND EXISTS (SELECT 1 FROM resolution_reviews rv WHERE rv.kb_id = e.kb_id AND rv.left_id = e.id - AND rv.status = 'pending' AND rv.stage = 'human' - AND rv.reason LIKE 'namesake_tie|%' + AND rv.stage = 'human' + AND ((rv.status = 'pending' AND rv.reason LIKE 'namesake_tie|%') + OR (rv.status = 'kept' AND rv.decided_by IS NULL AND starts_with(rv.reason, + 'kept_apart|no_checkable_identity_evidence|unresolved_namesake_left|namesake_tie|'))) AND rv.reason NOT LIKE '%|redirected%' AND NOT EXISTS (SELECT 1 FROM entity_merges m WHERE m.kb_id = e.kb_id AND m.target_id = e.id @@ -1537,6 +1542,8 @@ pub async fn refresh_disambiguators(pool: &PgPool, kb_id: Uuid, name: &str) -> A // --------------------------------------------------------------------------- /// 灰区疑似重复对入队(同一 pending 对幂等)。 +/// An evidence-gated keep closes work, not the unresolved left identity. Repeated +/// ambiguity must not reopen it; a later adjudicating proposal may bring new evidence. pub async fn create_review( pool: &PgPool, kb_id: Uuid, @@ -1549,7 +1556,14 @@ pub async fn create_review( sqlx::query( "INSERT INTO resolution_reviews AS existing (id, kb_id, left_id, right_id, score, reason, stage) - VALUES ($1, $2, $3, $4, $5, $6, $7) + SELECT $1, $2, $3, $4, $5, $6, $7 + WHERE NOT EXISTS (SELECT 1 FROM resolution_reviews kept + WHERE $7 = 'human' AND starts_with($6, 'namesake_tie|') + AND kept.kb_id = $2 AND kept.left_id = $3 AND kept.right_id = $4 + AND kept.status = 'kept' AND kept.stage = 'human' AND kept.decided_by IS NULL + AND starts_with(kept.reason, + 'kept_apart|no_checkable_identity_evidence|unresolved_namesake_left|namesake_tie|') + AND kept.reason NOT LIKE '%|redirected%') ON CONFLICT (kb_id, least(left_id, right_id), greatest(left_id, right_id)) WHERE status = 'pending' DO UPDATE SET stage = 'human', reason = EXCLUDED.reason diff --git a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs index 790522957..73eb73095 100644 --- a/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs +++ b/crates/utopia-store/tests/store/a_namesake_tie_goes_to_review_not_a_coin_flip.rs @@ -375,6 +375,43 @@ async fn a_namesakes_fact_outweighs_a_higher_topic_score() -> anyhow::Result<()> } // Every call can be a new document: an unresolved mention is not a third known namesake. +#[tokio::test] +async fn a_governance_kept_ambiguity_still_reuses_the_unresolved_namesake() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let f = seed(&pool).await?; + let result = async { + sqlx::query("UPDATE entities SET canonical_name='Zhang Wei' WHERE id IN ($1,$2)").bind(f.zhang_a).bind(f.zhang_b).execute(&pool).await?; + let first = utopia_store::resolution::resolve_mention(&pool, f.kb, Some(f.person), "Zhang Wei", None, None, Some("Zhang Wei received an award."), &[]).await?; + let reviews: Vec<(Uuid,String)> = sqlx::query_as("SELECT id,reason FROM resolution_reviews WHERE kb_id=$1 AND stage='human' AND status='pending'").bind(f.kb).fetch_all(&pool).await?; + assert_eq!(reviews.len(), 2); + for (id, original) in reviews { + // Governance preserves which side was unresolved when it closes review work. + let reason = format!("kept_apart|no_checkable_identity_evidence|unresolved_namesake_left|{original}"); + utopia_store::resolution::close_review_auto(&pool, id, "kept", &reason).await?; + } + for _ in 0..20 { + let next = utopia_store::resolution::resolve_mention(&pool, f.kb, Some(f.person), "Zhang Wei", None, None, Some("Zhang Wei received another award."), &[]).await?; + assert_eq!(next.entity_id, first.entity_id, "keeping apart cannot make an unresolved mention into an identified person"); + for rv in &next.reviews { + // Exercise the real caller too, not just create_entity's atomic insertion. + utopia_store::resolution::create_review(&pool, f.kb, next.entity_id, rv.other_id, rv.score, &rv.reason, rv.stage).await?; + } + } + let entities: i64 = sqlx::query_scalar("SELECT count(*) FROM entities WHERE kb_id=$1 AND merged_into IS NULL AND lower(canonical_name)='zhang wei'").bind(f.kb).fetch_one(&pool).await?; + let human: i64 = sqlx::query_scalar("SELECT count(*) FROM resolution_reviews WHERE kb_id=$1 AND stage='human' AND status='pending'").bind(f.kb).fetch_one(&pool).await?; + assert_eq!((entities,human),(3,0)); + Ok(()) + }.await; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(f.org) + .execute(&pool) + .await?; + result +} + #[tokio::test] async fn recurring_ambiguous_mentions_share_one_unresolved_entity() -> anyhow::Result<()> { let Some(url) = utopia_store::test_db::url() else {