From 7651a5cd9596b1373118baa6384435b7a2222cc0 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 24 Nov 2026 16:35:47 +0100 Subject: [PATCH] A pushed item remembers the fact of each statement and the entity of each name, so a re-push can reuse what it did not change Signed-off-by: Bogdan Szabo --- crates/utopia-cli/src/main.rs | 2 +- crates/utopia-extract/src/open.rs | 23 ++++-- .../src/api/sources_repush_tests.rs | 76 +++++++++++++++++++ crates/utopia-server/src/extraction_open.rs | 37 +++++++++ crates/utopia-store/src/lib.rs | 1 + crates/utopia-store/src/pushed_memo.rs | 46 +++++++++++ ..._a_pushed_statement_remembers_its_fact.sql | 20 +++++ 7 files changed, 199 insertions(+), 6 deletions(-) create mode 100644 crates/utopia-store/src/pushed_memo.rs create mode 100644 migrations/9012_a_pushed_statement_remembers_its_fact.sql diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index 63adfc732..37af7e281 100644 --- a/crates/utopia-cli/src/main.rs +++ b/crates/utopia-cli/src/main.rs @@ -82,7 +82,7 @@ struct ManifestDataDir { /// not a side effect of a code change. // 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current` // 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71 -const CURRENT_SCHEMA_VERSION: u32 = 125; +const CURRENT_SCHEMA_VERSION: u32 = 126; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/crates/utopia-extract/src/open.rs b/crates/utopia-extract/src/open.rs index 3888a2412..708f38dd4 100644 --- a/crates/utopia-extract/src/open.rs +++ b/crates/utopia-extract/src/open.rs @@ -56,6 +56,8 @@ pub struct OpenEntity { pub kind: String, /// 原文点了名(true)还是只描述了(false) pub named: bool, + /// where it stood in the reply's `e` array; a malformed or repeated neighbour is dropped + pub raw_index: usize, } #[derive(Debug, Clone)] @@ -78,6 +80,9 @@ pub struct OpenStatement { pub ended: Option, /// the sentence of the passage that states it, verbatim pub quote: Option, + /// where it stood in the reply's `s` array; a malformed neighbour is dropped, so this is not + /// its position in `OpenExtraction::statements` + pub raw_index: usize, } #[derive(Debug, Clone)] @@ -546,7 +551,12 @@ fn parse_entity(arr: &[Value]) -> Option { Some(Value::Number(n)) => n.as_f64() != Some(0.0), _ => true, }; - Some(OpenEntity { name, kind, named }) + Some(OpenEntity { + name, + kind, + named, + raw_index: 0, + }) } /// `[quote, subject, phrase, object, value, qualifiers, when, ended]`。八格都得在:短了的 @@ -567,6 +577,7 @@ fn parse_statement(arr: &[Value]) -> Option { when: opt_text(&arr[6]), ended: opt_text(&arr[7]), quote: opt_text(&arr[0]), + raw_index: 0, }) } @@ -611,15 +622,17 @@ pub fn parse_open_response(raw: &str) -> anyhow::Result { ..Default::default() }; let mut seen = HashSet::new(); - for item in items(&value, "e") { + for (raw_index, item) in items(&value, "e").iter().enumerate() { match item.as_array().and_then(|a| parse_entity(a)) { - Some(e) if seen.insert(name_key(&e.name)) => out.entities.push(e), + Some(e) if seen.insert(name_key(&e.name)) => { + out.entities.push(OpenEntity { raw_index, ..e }) + } _ => out.skipped += 1, } } - for item in items(&value, "s") { + for (raw_index, item) in items(&value, "s").iter().enumerate() { match item.as_array().and_then(|a| parse_statement(a)) { - Some(s) => out.statements.push(s), + Some(s) => out.statements.push(OpenStatement { raw_index, ..s }), None => out.skipped += 1, } } diff --git a/crates/utopia-server/src/api/sources_repush_tests.rs b/crates/utopia-server/src/api/sources_repush_tests.rs index fe4cdf2dd..96fa8ddbb 100644 --- a/crates/utopia-server/src/api/sources_repush_tests.rs +++ b/crates/utopia-server/src/api/sources_repush_tests.rs @@ -112,3 +112,79 @@ async fn a_repush_keeps_a_statement_another_item_still_states() -> anyhow::Resul ); f.cleanup().await } + +#[tokio::test] +async fn an_extracted_item_remembers_the_fact_of_each_statement() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let body = item( + "obs-1", + &[("is based in", "Port Ellen"), ("visited", "Oslo")], + ); + let doc = push_and_extract(&f, &body, "created").await?; + + let rows: Vec<(i32, String, String)> = sqlx::query_as( + "SELECT w.ord, w.key, f.phrase + FROM pushed_statement_writes w + JOIN chunks c ON c.id = w.chunk_id + JOIN facts f ON f.id = w.fact_id + WHERE c.document_id = $1 AND c.superseded_at IS NULL AND f.invalidated_at IS NULL + ORDER BY w.ord", + ) + .bind(doc) + .fetch_all(&f.pool) + .await?; + + let expected: Vec<(i32, String, String)> = body["s"] + .as_array() + .unwrap() + .iter() + .enumerate() + .map(|(ord, statement)| { + ( + ord as i32, + serde_json::to_string(statement).unwrap(), + statement[2].as_str().unwrap().to_string(), + ) + }) + .collect(); + assert_eq!(rows, expected); + f.cleanup().await +} + +#[tokio::test] +async fn an_extracted_item_remembers_the_entity_of_each_name() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let body = item("obs-1", &[("is based in", "Port Ellen")]); + let doc = push_and_extract(&f, &body, "created").await?; + + let mut rows: Vec<(String, String)> = sqlx::query_as( + "SELECT h.key, e.canonical_name + FROM pushed_entity_handles h + JOIN chunks c ON c.id = h.chunk_id + JOIN entities e ON e.id = h.entity_id + WHERE c.document_id = $1 AND c.superseded_at IS NULL", + ) + .bind(doc) + .fetch_all(&f.pool) + .await?; + rows.sort(); + + let mut expected: Vec<(String, String)> = body["e"] + .as_array() + .unwrap() + .iter() + .map(|entity| { + ( + serde_json::to_string(entity).unwrap(), + entity[0].as_str().unwrap().to_string(), + ) + }) + .collect(); + expected.sort(); + assert_eq!(rows, expected); + f.cleanup().await +} diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs index 6e19d948a..2f85e57cb 100644 --- a/crates/utopia-server/src/extraction_open.rs +++ b/crates/utopia-server/src/extraction_open.rs @@ -267,6 +267,28 @@ async fn call_and_parse_one_chunk( })) } +/// 推送块里 `e` / `s` 两个数组的规范键,按原始位置排列(9012 的记忆键) +struct PushedRaw { + entities: Vec, + statements: Vec, +} + +impl PushedRaw { + fn parse(chunk_text: &str) -> Self { + let payload: serde_json::Value = serde_json::from_str(chunk_text).unwrap_or_default(); + let keys = |field: &str| -> Vec { + payload[field] + .as_array() + .map(|items| items.iter().map(|item| item.to_string()).collect()) + .unwrap_or_default() + }; + Self { + entities: keys("e"), + statements: keys("s"), + } + } +} + /// 一个分块的后半步:把解析出来的回复写成陈述、名字和证据(#588 cut 1)。 /// /// **要按分块顺序跑**:前面的块认下的实体(`doc_entities`、`known_by_name`)、描述出来的 @@ -309,6 +331,7 @@ async fn apply_open_extraction( let mut local: HashMap = HashMap::new(); // 被描述的东西:先记下名字和类别词,等陈述指到它再建(见 `place`) let mut deferred: HashMap = HashMap::new(); + let pushed_raw = pushed.then(|| PushedRaw::parse(&chunk.text)); for e in &extraction.entities { let name = e.name.trim(); if name.is_empty() { @@ -360,6 +383,12 @@ async fn apply_open_extraction( ) .await; } + if let Some(key) = pushed_raw + .as_ref() + .and_then(|raw| raw.entities.get(e.raw_index)) + { + 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())); @@ -374,6 +403,7 @@ async fn apply_open_extraction( } // ---- 陈述 ---- + // 推送来的陈述按原始位置记下它写出的事实:再推时没变的陈述可以直接沿用旧事实 for s in &extraction.statements { let phrase = s.phrase.trim(); if phrase.is_empty() { @@ -651,6 +681,13 @@ async fn apply_open_extraction( confidence, ) .await?; + if let Some(key) = pushed_raw + .as_ref() + .and_then(|raw| raw.statements.get(s.raw_index)) + { + utopia_store::pushed_memo::remember(pool, chunk.id, s.raw_index as i32, key, fact_id) + .await?; + } // 表层谓词也写短语:今天的读路径都从 `fact_surface_predicate` 取名字 utopia_store::graph::add_evidence_located( pool, diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs index 8616cfbe8..fd5c208f4 100644 --- a/crates/utopia-store/src/lib.rs +++ b/crates/utopia-store/src/lib.rs @@ -37,6 +37,7 @@ pub mod palette; pub mod paths; pub mod pending; pub mod phrase_bindings; +pub mod pushed_memo; pub mod reasoning; pub mod record_axis; pub mod resolution; diff --git a/crates/utopia-store/src/pushed_memo.rs b/crates/utopia-store/src/pushed_memo.rs new file mode 100644 index 000000000..29f8bd86f --- /dev/null +++ b/crates/utopia-store/src/pushed_memo.rs @@ -0,0 +1,46 @@ +//! 推送来的陈述记住它写下的事实:块内位置 + 陈述的规范键 → 事实(9012)。 + +use sqlx::PgPool; +use uuid::Uuid; + +use utopia_core::AppResult; + +/// 记下块内第 `ord` 条陈述(规范键 `key`)写出的事实。 +pub async fn remember( + pool: &PgPool, + chunk_id: Uuid, + ord: i32, + key: &str, + fact_id: Uuid, +) -> AppResult<()> { + 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(ord) + .bind(key) + .bind(fact_id) + .execute(pool) + .await?; + Ok(()) +} + +/// 记下规范键 `key` 的具名实体对应的 entity_id。 +pub async fn remember_entity( + pool: &PgPool, + chunk_id: Uuid, + key: &str, + entity_id: Uuid, +) -> AppResult<()> { + sqlx::query( + "INSERT INTO pushed_entity_handles (chunk_id, key, entity_id) + VALUES ($1, $2, $3) ON CONFLICT (chunk_id, key) DO NOTHING", + ) + .bind(chunk_id) + .bind(key) + .bind(entity_id) + .execute(pool) + .await?; + Ok(()) +} diff --git a/migrations/9012_a_pushed_statement_remembers_its_fact.sql b/migrations/9012_a_pushed_statement_remembers_its_fact.sql new file mode 100644 index 000000000..249719805 --- /dev/null +++ b/migrations/9012_a_pushed_statement_remembers_its_fact.sql @@ -0,0 +1,20 @@ +-- A pushed statement remembers the fact it wrote: one row per (chunk, statement position), holding +-- the statement's canonical key and the fact it became, so a re-push can reuse the facts of the +-- statements it did not change, and, per named entity, the entity its entry resolved to. Running this again changes nothing. + +CREATE TABLE IF NOT EXISTS pushed_statement_writes ( + chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + ord INT NOT NULL, + key TEXT NOT NULL, + fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE, + PRIMARY KEY (chunk_id, ord) +); + +CREATE INDEX IF NOT EXISTS pushed_statement_writes_fact ON pushed_statement_writes (fact_id); + +CREATE TABLE IF NOT EXISTS pushed_entity_handles ( + chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, + key TEXT NOT NULL, + entity_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE, + PRIMARY KEY (chunk_id, key) +);