From 1f409bf2c55a368ce25778a0279a8b8f49bd84d8 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 24 Nov 2026 16:57:03 +0100 Subject: [PATCH] A re-pushed item carries over the statements and names it did not change instead of extracting them again Signed-off-by: Bogdan Szabo --- .../src/api/sources_repush_tests.rs | 163 +++++++++++++++++ crates/utopia-server/src/extraction_open.rs | 169 ++++++++++++------ crates/utopia-store/src/pushed_memo.rs | 124 +++++++++++++ 3 files changed, 402 insertions(+), 54 deletions(-) diff --git a/crates/utopia-server/src/api/sources_repush_tests.rs b/crates/utopia-server/src/api/sources_repush_tests.rs index 96fa8ddbb..8237051e1 100644 --- a/crates/utopia-server/src/api/sources_repush_tests.rs +++ b/crates/utopia-server/src/api/sources_repush_tests.rs @@ -48,6 +48,32 @@ async fn standing( .await?) } +/// The fact the live version of `doc` remembers for the statement with this memo key +async fn remembered_fact(f: &Fixture, doc: Uuid, key: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "SELECT w.fact_id FROM pushed_statement_writes w + JOIN chunks c ON c.id = w.chunk_id + WHERE c.document_id = $1 AND c.superseded_at IS NULL AND w.key = $2", + ) + .bind(doc) + .bind(key) + .fetch_one(&f.pool) + .await?) +} + +/// The entity the live version of `doc` remembers for the name with this memo key +async fn remembered_entity(f: &Fixture, doc: Uuid, key: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "SELECT h.entity_id FROM pushed_entity_handles h + JOIN chunks c ON c.id = h.chunk_id + WHERE c.document_id = $1 AND c.superseded_at IS NULL AND h.key = $2", + ) + .bind(doc) + .bind(key) + .fetch_one(&f.pool) + .await?) +} + #[tokio::test] async fn a_repush_closes_the_statement_its_new_version_dropped() -> anyhow::Result<()> { let Some(f) = Fixture::new().await? else { @@ -188,3 +214,140 @@ async fn an_extracted_item_remembers_the_entity_of_each_name() -> anyhow::Result assert_eq!(rows, expected); f.cleanup().await } + +/// `item` with one unnamed (described) place the statements can point at +fn item_with_harbour(external_id: &str, statements: &[(&str, &str)]) -> Value { + let mut body = item(external_id, statements); + body["e"] + .as_array_mut() + .unwrap() + .push(json!(["a small harbour town", "town", false])); + body +} + +#[tokio::test] +async fn a_repush_keeps_the_fact_of_a_statement_it_did_not_change() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let unchanged = ("grew up in", "a small harbour town"); + let v1 = item_with_harbour("obs-1", &[unchanged, ("visited", "Oslo")]); + let doc = push_and_extract(&f, &v1, "created").await?; + let key = serde_json::to_string(&v1["s"][0]).unwrap(); + + let first_fact = remembered_fact(&f, doc, &key).await?; + + let v2 = item_with_harbour("obs-1", &[unchanged, ("is based in", "Port Ellen")]); + push_and_extract(&f, &v2, "updated").await?; + + let second_fact = remembered_fact(&f, doc, &key).await?; + let (is_live, evidence_on_new_chunk): (bool, i64) = sqlx::query_as( + "SELECT f.invalidated_at IS NULL, + (SELECT count(*) FROM fact_evidence ev + JOIN chunks c ON c.id = ev.chunk_id + WHERE ev.fact_id = f.id AND c.document_id = $2 AND c.superseded_at IS NULL) + FROM facts f WHERE f.id = $1", + ) + .bind(second_fact) + .bind(doc) + .fetch_one(&f.pool) + .await?; + + assert_eq!( + (second_fact, is_live, evidence_on_new_chunk), + (first_fact, true, 1) + ); + f.cleanup().await +} + +#[tokio::test] +async fn a_repush_keeps_the_time_of_a_statement_it_did_not_change() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let with_time = |extra: (&str, &str)| { + let mut body = item("obs-1", &[extra]); + body["s"].as_array_mut().unwrap().insert( + 0, + json!([ + null, + "Ada", + "lived in", + "Oslo", + null, + {}, + "2019-05-01", + null + ]), + ); + body + }; + let doc = push_and_extract(&f, &with_time(("visited", "Oslo")), "created").await?; + crate::time_resolution::resolve_document(&f.state, doc).await?; + push_and_extract(&f, &with_time(("is based in", "Port Ellen")), "updated").await?; + crate::time_resolution::resolve_document(&f.state, doc).await?; + + let (valid_from, mentions_on_live_chunk): (Option>, i64) = + sqlx::query_as( + "SELECT f.valid_from, + (SELECT count(*) FROM time_mentions m JOIN chunks c ON c.id = m.chunk_id + WHERE m.fact_id = f.id AND c.document_id = $2 AND c.superseded_at IS NULL) + FROM facts f WHERE f.kb_id = $1 AND f.layer = 'open' AND f.phrase = 'lived in' + AND f.invalidated_at IS NULL", + ) + .bind(f.kb) + .bind(doc) + .fetch_one(&f.pool) + .await?; + + assert_eq!( + ( + valid_from.map(|at| at.date_naive().to_string()), + mentions_on_live_chunk + ), + (Some("2019-05-01".to_string()), 1) + ); + f.cleanup().await +} + +#[tokio::test] +async fn a_repush_keeps_the_entity_of_a_name_it_did_not_change() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + sqlx::query("UPDATE sources SET config = '{\"names\": \"identity\"}'::jsonb WHERE id = $1") + .bind(f.source) + .execute(&f.pool) + .await?; + let doc = push_and_extract(&f, &item("obs-1", &[("visited", "Oslo")]), "created").await?; + let ada_key = serde_json::to_string(&json!(["Ada", "person", true]))?; + let first_ada = remembered_entity(&f, doc, &ada_key).await?; + + let namesake = Uuid::now_v7(); + sqlx::query("INSERT INTO entities(id, kb_id, canonical_name) VALUES ($1, $2, 'Ada')") + .bind(namesake) + .bind(f.kb) + .execute(&f.pool) + .await?; + for phrase in ["wrote", "built", "taught"] { + sqlx::query( + "INSERT INTO facts(id, kb_id, subject_id, object_value, layer, phrase, confidence) + VALUES ($1, $2, $3, to_jsonb('x'::text), 'open', $4, 1.0)", + ) + .bind(Uuid::now_v7()) + .bind(f.kb) + .bind(namesake) + .bind(phrase) + .execute(&f.pool) + .await?; + } + push_and_extract( + &f, + &item("obs-1", &[("is based in", "Port Ellen")]), + "updated", + ) + .await?; + + assert_eq!(remembered_entity(&f, doc, &ada_key).await?, first_ada); + f.cleanup().await +} diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs index 2f85e57cb..42a0c0282 100644 --- a/crates/utopia-server/src/extraction_open.rs +++ b/crates/utopia-server/src/extraction_open.rs @@ -289,6 +289,14 @@ impl PushedRaw { } } +/// 再推时从上一版沿用下来的东西:没变的陈述(块内原始位置 → 事实)和没变的具名实体 +/// (规范键 → 实体)。沿用的直接用旧结果,不再走消解和落事实 +#[derive(Default)] +struct Carried { + statements: HashMap, + entities: HashMap, +} + /// 一个分块的后半步:把解析出来的回复写成陈述、名字和证据(#588 cut 1)。 /// /// **要按分块顺序跑**:前面的块认下的实体(`doc_entities`、`known_by_name`)、描述出来的 @@ -310,6 +318,7 @@ async fn apply_open_extraction( pushed: bool, identity: bool, await_nod: bool, + carried: &Carried, proposer: Proposer, pending_count: &mut usize, statement_count: &mut usize, @@ -342,31 +351,42 @@ async fn apply_open_extraction( if local.contains_key(&key) { continue; } + let carried = pushed_raw + .as_ref() + .and_then(|raw| raw.entities.get(e.raw_index)) + .and_then(|key| carried.entities.get(key).copied()); let id = if e.named { - let bound = bound_types - .get(&utopia_store::type_bindings::normalize(kind)) - .copied(); - let id = resolve_handle( - pool, - kb_id, - bound, - name, - ctx, - name_vecs.get(&key).map(Vec::as_slice), - evidence.get(&key).map(String::as_str), - identity, - &mut response_claims, - handled_by_name, - ambiguous_bare_cache, - needs_adjudication, - human_reviews_found, - ) - .await?; - // 模型说它是什么(「a British film」里的 film):存成它自己的说法, - // 类的绑定等对齐来做 - if !kind.is_empty() { - let _ = utopia_store::resolution::set_specific_type(pool, id, kind).await; - } + let id = match carried { + Some(id) => id, + None => { + let bound = bound_types + .get(&utopia_store::type_bindings::normalize(kind)) + .copied(); + let id = resolve_handle( + pool, + kb_id, + bound, + name, + ctx, + name_vecs.get(&key).map(Vec::as_slice), + evidence.get(&key).map(String::as_str), + identity, + &mut response_claims, + handled_by_name, + ambiguous_bare_cache, + needs_adjudication, + human_reviews_found, + ) + .await?; + // 模型说它是什么(「a British film」里的 film):存成它自己的说法, + // 类的绑定等对齐来做 + if !kind.is_empty() { + let _ = utopia_store::resolution::set_specific_type(pool, id, kind).await; + } + touched_names.insert(name_key(name)); + id + } + }; // 名字就在这一块原文里时,给名字事实补出处(0041)。记忆日志里的不补: // 那一句算不算出处,要等人点头(0018) if !await_nod && span_in_quote(name, &chunk.text) { @@ -389,7 +409,6 @@ async fn apply_open_extraction( { utopia_store::pushed_memo::remember_entity(pool, chunk.id, key, id).await?; } - touched_names.insert(name_key(name)); if !doc_entities.iter().any(|(x, _, _)| *x == id) { doc_entities.push((id, kind.to_string(), name.to_string())); known_by_name.entry(key.clone()).or_insert(id); @@ -405,6 +424,17 @@ async fn apply_open_extraction( // ---- 陈述 ---- // 推送来的陈述按原始位置记下它写出的事实:再推时没变的陈述可以直接沿用旧事实 for s in &extraction.statements { + if let Some(&fact_id) = carried.statements.get(&s.raw_index) { + let time_words = + locate_time_words(state, kb_id, document_id, chunk, None, pushed, s).await; + for (words, start, role) in &time_words { + utopia_store::time_mentions::record( + pool, kb_id, fact_id, chunk.id, words, *start, role, + ) + .await?; + } + continue; + } let phrase = s.phrase.trim(); if phrase.is_empty() { continue; @@ -588,35 +618,8 @@ async fn apply_open_extraction( None => qualifiers.push((role, Some(serde_json::json!(text)), None)), } } - // 时间词:起与止各是一条提及,必须原样在这条陈述的引文里 - let mut time_words: Vec<(&str, i32, &str)> = Vec::new(); - for (role, words) in [("when", s.when.as_deref()), ("ended", s.ended.as_deref())] - .into_iter() - .filter_map(|(role, words)| Some((role, words?.trim()))) - .filter(|(_, w)| !w.is_empty()) - { - // 推送来的陈述没有引文:条目自己就是证据(0054 决定 4),这一块就是这一份 - // 载荷,时间词在块里找。走 `locate_time` 会在 `quote?` 上退出,起止就都丢了 - let located = if pushed { - locate(&chunk.text, words).map(|(start, _)| start) - } else { - locate_time(&chunk.text, quote, words) - }; - match located { - Some(start) => time_words.push((words, start, role)), - None => { - drop_signal( - state, - kb_id, - document_id, - reason::TIME_NOT_IN_QUOTE, - "a time mention's words are not in the statement's own sentence", - Some(words), - ) - .await; - } - } - } + let time_words = + locate_time_words(state, kb_id, document_id, chunk, quote, pushed, s).await; if await_nod { // 记忆日志:一切原样进待确认表(0015),人点头时 `pending::confirm` 才把它 // 落成开放陈述——同样的短语、限定、时间词、引文偏移 @@ -813,6 +816,47 @@ pub(crate) fn dated_at(doc: &Document) -> Option> } } +/// 一条陈述的时间词:起与止各是一条提及,必须原样在这条陈述的引文里 +async fn locate_time_words<'a>( + state: &AppState, + kb_id: Uuid, + document_id: Uuid, + chunk: &ChunkForExtract, + quote: Option<(&str, Option<(i32, i32)>)>, + pushed: bool, + s: &'a utopia_extract::open::OpenStatement, +) -> Vec<(&'a str, i32, &'static str)> { + let mut time_words = Vec::new(); + for (role, words) in [("when", s.when.as_deref()), ("ended", s.ended.as_deref())] + .into_iter() + .filter_map(|(role, words)| Some((role, words?.trim()))) + .filter(|(_, w)| !w.is_empty()) + { + // 推送来的陈述没有引文:条目自己就是证据(0054 决定 4),这一块就是这一份 + // 载荷,时间词在块里找。走 `locate_time` 会在 `quote?` 上退出,起止就都丢了 + let located = if pushed { + locate(&chunk.text, words).map(|(start, _)| start) + } else { + locate_time(&chunk.text, quote, words) + }; + match located { + Some(start) => time_words.push((words, start, role)), + None => { + drop_signal( + state, + kb_id, + document_id, + reason::TIME_NOT_IN_QUOTE, + "a time mention's words are not in the statement's own sentence", + Some(words), + ) + .await; + } + } + } + time_words +} + /// 一段字在块里的**字符**偏移(起、止)。字符不是字节:界面和 SQL 的 `substr` 都按字符数, /// 中文一个字三个字节,按字节存的偏移到界面上就错位。找不到的就 `None`—— /// 偏移只能由服务端从原文算出来,模型报的数字不算数。 @@ -1204,6 +1248,22 @@ pub(crate) async fn run_open( ..entry.clone() }); } + // 再推时没变的陈述和名字沿用上一版(只在推送路径、且不等人点头时) + let carried = if pushed && !await_nod { + Carried { + statements: utopia_store::pushed_memo::carry_over( + pool, + document_id, + chunk.id, + &PushedRaw::parse(&chunk.text).statements, + ) + .await?, + entities: utopia_store::pushed_memo::carried_entities(pool, document_id, chunk.id) + .await?, + } + } else { + Carried::default() + }; apply_open_extraction( state, pool, @@ -1218,6 +1278,7 @@ pub(crate) async fn run_open( pushed, identity, await_nod, + &carried, proposer, &mut pending_count, &mut statement_count, diff --git a/crates/utopia-store/src/pushed_memo.rs b/crates/utopia-store/src/pushed_memo.rs index 29f8bd86f..2e28abedc 100644 --- a/crates/utopia-store/src/pushed_memo.rs +++ b/crates/utopia-store/src/pushed_memo.rs @@ -1,5 +1,7 @@ //! 推送来的陈述记住它写下的事实:块内位置 + 陈述的规范键 → 事实(9012)。 +use std::collections::{HashMap, VecDeque}; + use sqlx::PgPool; use uuid::Uuid; @@ -44,3 +46,125 @@ pub async fn remember_entity( .await?; Ok(()) } + +/// 同一文档里最近一块被取代、抽过、记过陈述的块:沿用的上一版 +async fn previous_chunk( + pool: &PgPool, + document_id: Uuid, + chunk_id: Uuid, +) -> AppResult> { + Ok(sqlx::query_scalar::<_, Uuid>( + "SELECT c.id FROM chunks c + WHERE c.document_id = $1 AND c.id <> $2 + AND c.superseded_at IS NOT NULL AND c.extracted_at IS NOT NULL + AND EXISTS (SELECT 1 FROM pushed_statement_writes w WHERE w.chunk_id = c.id) + ORDER BY c.superseded_at DESC LIMIT 1", + ) + .bind(document_id) + .bind(chunk_id) + .fetch_optional(pool) + .await?) +} + +/// 上一版记下的具名实体:规范键 → 仍然活着(没被并走)的 entity_id;没有上一版就是空表 +pub async fn carried_entities( + pool: &PgPool, + document_id: Uuid, + chunk_id: Uuid, +) -> AppResult> { + let Some(previous) = previous_chunk(pool, document_id, chunk_id).await? else { + return Ok(HashMap::new()); + }; + let remembered: Vec<(String, Uuid)> = sqlx::query_as( + "SELECT h.key, h.entity_id FROM pushed_entity_handles h + JOIN entities e ON e.id = h.entity_id + WHERE h.chunk_id = $1 AND e.merged_into IS NULL", + ) + .bind(previous) + .fetch_all(pool) + .await?; + Ok(remembered.into_iter().collect()) +} + +/// 沿用上一版的事实:同一文档里最近一块被取代、抽过、记过陈述的块,按规范键配对(相同的键按 +/// 原有顺序一一配),配上且事实还活着的陈述把事实、证据和角色词搬到新块上,并给新块记下 +/// 同一条事实。返回被沿用的陈述在块里的原始位置和它们的事实;没有上一版就是空表 +pub async fn carry_over( + pool: &PgPool, + document_id: Uuid, + chunk_id: Uuid, + keys: &[String], +) -> AppResult> { + let Some(previous) = previous_chunk(pool, document_id, chunk_id).await? else { + return Ok(HashMap::new()); + }; + let remembered: Vec<(String, Uuid)> = sqlx::query_as( + "SELECT w.key, w.fact_id FROM pushed_statement_writes w + JOIN facts f ON f.id = w.fact_id + WHERE w.chunk_id = $1 AND f.invalidated_at IS NULL + ORDER BY w.ord", + ) + .bind(previous) + .fetch_all(pool) + .await?; + let mut available: HashMap<&str, VecDeque> = HashMap::new(); + for (key, fact_id) in &remembered { + available.entry(key).or_default().push_back(*fact_id); + } + let mut reused: Vec<(usize, &str, Uuid)> = Vec::new(); + for (raw_index, key) in keys.iter().enumerate() { + if let Some(fact_id) = available + .get_mut(key.as_str()) + .and_then(VecDeque::pop_front) + { + reused.push((raw_index, key, fact_id)); + } + } + if reused.is_empty() { + return Ok(HashMap::new()); + } + let fact_ids: Vec = reused.iter().map(|(_, _, fact_id)| *fact_id).collect(); + let mut tx = pool.begin().await?; + sqlx::query( + "INSERT INTO fact_evidence (fact_id, chunk_id, quote, proposed_predicate, document_id, + doc_version, quote_start, quote_end) + SELECT fe.fact_id, $1, fe.quote, fe.proposed_predicate, c.document_id, c.doc_version, + fe.quote_start, fe.quote_end + FROM fact_evidence fe JOIN chunks c ON c.id = $1 + WHERE fe.chunk_id = $2 AND fe.fact_id = ANY($3) + ON CONFLICT (fact_id, chunk_id) DO NOTHING", + ) + .bind(chunk_id) + .bind(previous) + .bind(&fact_ids) + .execute(&mut *tx) + .await?; + sqlx::query( + "INSERT INTO statement_qualifiers (fact_id, role, value, entity_id, chunk_id) + SELECT fact_id, role, value, entity_id, $1 + FROM statement_qualifiers WHERE chunk_id = $2 AND fact_id = ANY($3) + ON CONFLICT (fact_id, role, chunk_id) DO NOTHING", + ) + .bind(chunk_id) + .bind(previous) + .bind(&fact_ids) + .execute(&mut *tx) + .await?; + for (raw_index, key, fact_id) in &reused { + sqlx::query( + "INSERT INTO pushed_statement_writes (chunk_id, ord, key, fact_id) + VALUES ($1, $2, $3, $4) ON CONFLICT (chunk_id, ord) DO NOTHING", + ) + .bind(chunk_id) + .bind(*raw_index as i32) + .bind(*key) + .bind(fact_id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(reused + .iter() + .map(|(raw_index, _, fact_id)| (*raw_index, *fact_id)) + .collect()) +}