From 345553a33030646ed0e208b466e87d4e1945b395 Mon Sep 17 00:00:00 2001 From: Wayland Yang Date: Tue, 1 Dec 2026 19:49:01 +0800 Subject: [PATCH] Re-extracting a document takes back the described things it made, so an unchanged document adds no second copy of them or their statements One run already reuses one entity per description across a document's chunks. A re-extraction started that map empty, so every round of an unchanged document made a new described entity for each description and a new statement pointing at it (#1534: 12 -> 53 described entities over six rounds). The map now starts from the described things this document's live facts sit on, followed through merges, keyed by their exact description. They stay out of the prompt's known list and out of name recall, so a description still never crosses documents. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Wayland Yang --- crates/utopia-server/src/extraction_open.rs | 8 +- .../src/extraction_open_known_flow_tests.rs | 98 +++++++++++++++++++ crates/utopia-store/src/resolution.rs | 50 +++++++++- docs/design/extraction.md | 5 +- 4 files changed, 157 insertions(+), 4 deletions(-) diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs index bfb5831b7..f9f47a288 100644 --- a/crates/utopia-server/src/extraction_open.rs +++ b/crates/utopia-server/src/extraction_open.rs @@ -1069,8 +1069,14 @@ pub(crate) async fn run_open( .collect(); // 类别词已经绑到类的(0044 对齐第一片):提及带着类去消解,同名不同类才分得开 let bound_types = utopia_store::type_bindings::bound_map(pool, kb_id).await?; - // 被描述的东西按描述文字在本文档内复用:同一块里「the northern wing」说了三次是一个东西 + // 被描述的东西按描述文字在本文档内复用:同一块里「the northern wing」说了三次是一个东西。 + // 重抽也一样(#1534):上一次在这篇里建下的同一段描述认回它,不进提示词清单 let mut described: HashMap = HashMap::new(); + for (text, id) in + utopia_store::resolution::described_entities_of_document(pool, kb_id, document_id).await? + { + described.entry(name_key(&text)).or_insert(id); + } let mut handled_by_name: HashMap> = HashMap::new(); let mut ambiguous_bare_cache: HashMap = HashMap::new(); let mut touched_names: HashSet = HashSet::new(); diff --git a/crates/utopia-server/src/extraction_open_known_flow_tests.rs b/crates/utopia-server/src/extraction_open_known_flow_tests.rs index 66975caeb..031d8e7db 100644 --- a/crates/utopia-server/src/extraction_open_known_flow_tests.rs +++ b/crates/utopia-server/src/extraction_open_known_flow_tests.rs @@ -507,6 +507,104 @@ async fn reextracting_an_unchanged_document_reuses_the_entities_it_named() -> an run } +/// 两次抽取都在第一块列出同一个被描述的东西、说同一句话(#1534) +fn replies_that_describe_the_harbour_office_twice() -> Vec { + let first = json!({ + "e": [["Acme", "organization", 1], ["the harbour office", "office", 0]], + "s": [["Acme is based in London.", "Acme", "based in", "the harbour office", null, null, null, null]], + "n": [] + }) + .to_string(); + let second = json!({"e": [], "s": [], "n": []}).to_string(); + vec![first.clone(), second.clone(), first, second] +} + +/// 重抽一篇没改过的文档,被描述的东西按描述原文认回上一次建的那个:不多一个实体, +/// 挂在它上面的陈述也不多一条;它照旧不进提示词清单 +#[tokio::test] +async fn reextracting_an_unchanged_document_reuses_what_it_described() -> anyhow::Result<()> { + let Some(f) = Fx::new(replies_that_describe_the_harbour_office_twice(), true, None).await? + else { + return Ok(()); + }; + let run = async { + let count_offices = || async { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM entities + WHERE kb_id=$1 AND description='the harbour office' AND merged_into IS NULL", + ) + .bind(f.kb) + .fetch_one(&f.pool) + .await + }; + let count_facts = || async { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM facts WHERE kb_id=$1 AND invalidated_at IS NULL", + ) + .bind(f.kb) + .fetch_one(&f.pool) + .await + }; + crate::extraction::extract_document(&f.state, f.doc, Proposer::default()).await?; + let (offices, facts) = (count_offices().await?, count_facts().await?); + anyhow::ensure!( + offices == 1, + "the first run describes one office: {offices}" + ); + utopia_store::documents::queue_extraction_one(&f.pool, f.doc).await?; + crate::extraction::extract_document(&f.state, f.doc, Proposer::default()).await?; + let offices_after = count_offices().await?; + anyhow::ensure!( + offices_after == 1, + "re-extract made another harbour office: {offices_after}" + ); + let facts_after = count_facts().await?; + anyhow::ensure!( + facts_after == facts, + "re-extract added statements: {facts} -> {facts_after}" + ); + let requests = f.model.requests.lock().unwrap(); + let rerun_first = requests[2]["messages"][1]["content"].as_str().unwrap_or(""); + anyhow::ensure!( + !rerun_first.contains("harbour office"), + "a described thing stays out of the known list: {rerun_first}" + ); + Ok(()) + } + .await; + f.cleanup().await?; + run +} + +/// 同一段描述只在本文档内认回:另一篇文档说同一句描述,建它自己的 +#[tokio::test] +async fn the_described_seed_is_this_documents_own() -> anyhow::Result<()> { + let Some(f) = Fx::new(replies_that_describe_the_harbour_office_twice(), true, None).await? + else { + return Ok(()); + }; + let run = async { + crate::extraction::extract_document(&f.state, f.doc, Proposer::default()).await?; + let office = utopia_store::resolution::create_described( + &f.pool, + f.kb, + "the harbour office", + Some("office"), + ) + .await?; + let seed = + utopia_store::resolution::described_entities_of_document(&f.pool, f.kb, f.doc).await?; + anyhow::ensure!( + seed.len() == 1 && seed[0].0 == "the harbour office" && seed[0].1 != office, + "only this document's office is seeded: {seed:?}" + ); + Ok(()) + } + .await; + f.cleanup().await?; + run +} + /// 起步清单跟着合并走:上一次认下的实体后来被并进别人,重抽认的是存活者 #[tokio::test] async fn the_rerun_seed_follows_a_merge_to_the_survivor() -> anyhow::Result<()> { diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index c080a3627..ab215ae0e 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -1534,8 +1534,9 @@ pub async fn existing_by_name( /// 同类的实体和一批审核对。 /// /// 认的是还活着的事实的证据落在这篇文档的分块上(含旧版本被取代的分块)的主语和宾语, -/// 名字事实也算;并掉的跟着 `merged_into` 走到存活者。被描述的东西不进来:「一家医院」 -/// 在这篇里指的是哪一家,下一次抽要重新看上下文 +/// 名字事实也算;并掉的跟着 `merged_into` 走到存活者。被描述的东西不进这份清单:清单会 +/// 送进提示词、按名字认,「一家医院」不该当名字用;它们按描述原文在本文档内认回,见 +/// [`described_entities_of_document`] pub async fn named_entities_of_document( pool: &PgPool, kb_id: Uuid, @@ -1576,6 +1577,51 @@ pub async fn named_entities_of_document( .collect()) } +/// 这篇文档上一次抽取建下的**被描述的**东西:`(描述原文, 存活者 id)`,同一段描述取最早 +/// 建的那个(#1534)。 +/// +/// 同一次抽取里,同一段描述在整篇文档内只建一个实体(`extraction_open` 的 `described`); +/// 重抽也按这条走,否则一篇没改过的文档每重抽一次,每个被描述的东西就多一份、挂着它的 +/// 陈述也多一份。它们只用来按描述原文认回,不进提示词清单,也不参与名字召回:描述照旧 +/// 不跨文档。 +/// +/// 认的范围和 [`named_entities_of_document`] 一样:活着的事实的证据落在这篇文档的分块上, +/// 主语或宾语是被描述的东西;并掉的跟着 `merged_into` 走到存活者 +pub async fn described_entities_of_document( + pool: &PgPool, + kb_id: Uuid, + document_id: Uuid, +) -> AppResult> { + let rows: Vec<(String, Uuid)> = sqlx::query_as( + "WITH RECURSIVE touched AS ( + SELECT DISTINCT t.id AS entity_id + FROM fact_evidence fe + JOIN facts f ON f.id = fe.fact_id + CROSS JOIN LATERAL (VALUES (f.subject_id), (f.object_id)) AS t(id) + WHERE fe.document_id = $2 AND f.kb_id = $1 + AND f.invalidated_at IS NULL AND t.id IS NOT NULL + ), up(start, id, depth) AS ( + SELECT entity_id, entity_id, 0 FROM touched + UNION ALL + SELECT up.start, e.merged_into, up.depth + 1 + FROM up JOIN entities e ON e.id = up.id + WHERE e.merged_into IS NOT NULL AND up.depth < 16 + ) + SELECT DISTINCT ON (o.description) o.description, s.id + FROM up + JOIN entities o ON o.id = up.start + JOIN entities s ON s.id = up.id + WHERE o.kb_id = $1 AND o.description IS NOT NULL + AND s.kb_id = $1 AND s.merged_into IS NULL + ORDER BY o.description, o.id", + ) + .bind(kb_id) + .bind(document_id) + .fetch_all(pool) + .await?; + Ok(rows) +} + pub async fn refresh_disambiguators(pool: &PgPool, kb_id: Uuid, name: &str) -> AppResult<()> { let group: Vec<(Uuid,)> = sqlx::query_as( "SELECT id FROM entities diff --git a/docs/design/extraction.md b/docs/design/extraction.md index 602214709..94ba2e92b 100644 --- a/docs/design/extraction.md +++ b/docs/design/extraction.md @@ -148,7 +148,10 @@ re-extraction does not start from an empty known list: the named entities that l document's chunks (any version) already sit on, followed through merges and without described things, are known from the first chunk, and a listed name that matches exactly one of them is taken back without resolving again, so re-extracting an unchanged document reuses its entities instead of -splitting them in the grey zone (#1513); a chunk of origin `described` keeps its confidence ceiling +splitting them in the grey zone (#1513). The described things it made are taken back the same way by +their exact description, as one run already does across its chunks, but never listed in the prompt +nor recalled by name, so a re-extraction adds no second copy of them or of their statements (#1534); +a chunk of origin `described` keeps its confidence ceiling [0040]. Until alignment, a base holds open statements and no typed facts, so timelines, conflicts and signature queues stay empty.