From 9dd3a70e8e94b1bd258b9c204160aae6c25c2b09 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 10 Nov 2026 11:26:54 +0100 Subject: [PATCH 1/3] A fact is not stale while a new version of its document is still on its way to extraction, so a re-push no longer flags facts it has not yet had a chance to restate Signed-off-by: Bogdan Szabo --- crates/utopia-store/src/graph.rs | 8 +- crates/utopia-store/src/review.rs | 26 ++- ...fact_waits_for_its_new_version_to_speak.rs | 187 ++++++++++++++++++ crates/utopia-store/tests/store/main.rs | 1 + 4 files changed, 218 insertions(+), 4 deletions(-) create mode 100644 crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 23de9f06c..58ae63f4f 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -1812,6 +1812,7 @@ pub async fn entity_detail( AND NOT EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.id = fe.chunk_id WHERE fe.fact_id = f.id AND {chunk_live}) + AND NOT {awaits} ) AS stale, (f.supersedes IS NOT NULL) AS corrected, f.end_derived, f.end_after_period, {corrected_ends} AS corrected_ends, @@ -1868,6 +1869,7 @@ pub async fn entity_detail( holds_to = crate::world_axis::facts_holds_to("f"), subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false), object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true), + awaits = crate::review::AWAITS_A_NEW_VERSION, chunk_live = crate::record_axis::chunk_live_at("c", as_of.map(|_| 3)), violation_open = crate::record_axis::violation_open_at("v", as_of.map(|_| 3)), conflict_open = crate::record_axis::conflict_open_at("c", as_of.map(|_| 3)), @@ -2076,7 +2078,7 @@ pub async fn stale_facts( limit: i64, offset: i64, ) -> AppResult> { - let rows: Vec = sqlx::query_as( + let rows: Vec = sqlx::query_as(&format!( "SELECT f.id, s.canonical_name AS subject_name, COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label, COALESCE(o.canonical_name, f.object_value->>'summary') AS object_name, f.valid_from, f.valid_to, f.confidence, @@ -2093,9 +2095,11 @@ pub async fn stale_facts( AND NOT EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.id = fe.chunk_id WHERE fe.fact_id = f.id AND c.superseded_at IS NULL) + AND NOT {awaits} ORDER BY f.recorded_at DESC, f.id DESC LIMIT $2 OFFSET $3", - ) + awaits = crate::review::AWAITS_A_NEW_VERSION, + )) .bind(kb_id) .bind(limit) .bind(offset) diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs index 49f7808a8..78483c739 100644 --- a/crates/utopia-store/src/review.rs +++ b/crates/utopia-store/src/review.rs @@ -19,18 +19,40 @@ use uuid::Uuid; /// 迟早分叉成「徽标说 12 条,点进去 9 条」。 pub const LOW_CONFIDENCE_BELOW: f32 = 0.75; +macro_rules! awaits_a_new_version { + () => { + "EXISTS (SELECT 1 FROM fact_evidence fe + JOIN chunks c ON c.document_id = fe.document_id + JOIN documents d ON d.id = fe.document_id + WHERE fe.fact_id = f.id AND c.superseded_at IS NULL AND c.extracted_at IS NULL + AND (d.graph_status IN ('queued', 'extracting') + OR d.status IN ('pending', 'parsing', 'indexing', 'embedding')))" + }; +} + /// 「待确认」的判据,写成 SQL 片段,`counts` 与总览(`review_summary`)共用: /// 有证据、但证据所在的分块全被新版本取代了,**而且这条事实至今仍成立**。别名固定用 `f`。 /// /// 上界那一句是「闭合」这个出路的前提:闭合是作废+改写,修正行把证据一起复制下来 /// (`temporal::close_superseded`),少了它,刚闭合的行照样满足判据——队列永远清不掉, /// 再点一次只会撞上「区间已闭合」。判据与 0022 说同一句话:「结束不知哪天」不是开放。 -pub const UNCONFIRMED_FACT: &str = "f.valid_to IS NULL AND f.valid_to_precision IS NULL +/// +/// 最后一句:新版本写下了、还没被读,就不算待确认(见 [`AWAITS_A_NEW_VERSION`])。 +pub const UNCONFIRMED_FACT: &str = concat!( + "f.valid_to IS NULL AND f.valid_to_precision IS NULL AND EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id) AND NOT EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.id = fe.chunk_id WHERE fe.fact_id = f.id - AND c.superseded_at IS NULL)"; + AND c.superseded_at IS NULL) + AND NOT ", + awaits_a_new_version!(), +); + +/// 事实引用的某个文档有一块现行分块还没人读:新版本写下了、还没抽取。它开口之前, +/// 它可能没再提的东西还谈不上「没了」。只等还会被读的版本:还在摄入,或排着队、正在抽取。 +/// 抽取关着、跳过或失败的版本没人会读,等它就是永远等。 +pub const AWAITS_A_NEW_VERSION: &str = awaits_a_new_version!(); pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult { let sql = format!( diff --git a/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs new file mode 100644 index 000000000..159b63ec0 --- /dev/null +++ b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs @@ -0,0 +1,187 @@ +//! 新版本写下了、还没被读:它引用的事实不算过期,也不进审核队列。 +//! 新版本被读过而没再提这条事实,才算它不再被陈述。 +//! 没人会去读的新版本(抽取关着、跳过或失败)不让事实等:等下去就是永远。 + +use chrono::{DateTime, Utc}; +use sqlx::PgPool; +use utopia_store::{graph, review}; +use uuid::Uuid; + +struct Seeded { + kb: Uuid, + org: Uuid, + ada: Uuid, + fresh: Uuid, + said: Uuid, +} + +async fn seed(pool: &PgPool, status: &str, graph_status: &str) -> anyhow::Result { + let [org, ws, kb, class, ada, port, based_in, binding] = + std::array::from_fn(|_| Uuid::now_v7()); + let [source, doc, old, fresh, said] = std::array::from_fn(|_| Uuid::now_v7()); + sqlx::raw_sql(&format!( + "INSERT INTO organizations(id,name) VALUES ('{org}','fact-waits'); + INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','fact-waits'); + INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','fact-waits'); + INSERT INTO entity_types(id,kb_id,key,label) VALUES ('{class}','{kb}','thing','Thing'); + INSERT INTO entities(id,kb_id,type_id,canonical_name) VALUES + ('{ada}','{kb}','{class}','Ada'), ('{port}','{kb}','{class}','Port Ellen'); + INSERT INTO relation_types (id,kb_id,key,label,temporal) + VALUES ('{based_in}','{kb}','based_in','based in','state'); + INSERT INTO phrase_bindings + (id,kb_id,phrase,subject_type_id,object_type_id,object_is_value, + relation_type_id,direction,status) + VALUES ('{binding}','{kb}','is based in','{class}','{class}',false, + '{based_in}','forward','bound'); + INSERT INTO sources(id,kb_id,kind,name) VALUES ('{source}','{kb}','statements','mirror'); + INSERT INTO documents(id,kb_id,filename,sha256,source_id,status,graph_status) + VALUES ('{doc}','{kb}','a.md','sha-a','{source}','{status}','{graph_status}'); + INSERT INTO chunks(id,kb_id,document_id,seq,text,doc_version,superseded_at,extracted_at) VALUES + ('{old}','{kb}','{doc}',0,'v1','1','2025-06-01T12:34:56Z','2025-06-01T12:00:00Z'), + ('{fresh}','{kb}','{doc}',1,'v2','2',NULL,NULL); + INSERT INTO facts (id,kb_id,subject_id,object_id,layer,phrase,confidence, + valid_from,valid_from_precision) + VALUES ('{said}','{kb}','{ada}','{port}','open','is based in',0.9,'2020-01-01','day'); + INSERT INTO fact_evidence (fact_id,chunk_id,document_id,quote) + VALUES ('{said}','{old}','{doc}','q');" + )) + .execute(pool) + .await?; + Ok(Seeded { + kb, + org, + ada, + fresh, + said, + }) +} + +async fn is_stale(pool: &PgPool, seeded: &Seeded) -> anyhow::Result { + let (_, facts) = graph::entity_detail(pool, seeded.kb, seeded.ada, None, None).await?; + let fact = facts + .iter() + .find(|fact| fact.id == seeded.said) + .expect("the fact is on Ada"); + Ok(fact.stale) +} + +async fn is_listed_stale(pool: &PgPool, seeded: &Seeded) -> anyhow::Result { + let listed = graph::stale_facts(pool, seeded.kb, 100, 0).await?; + Ok(listed.iter().any(|item| item.id == seeded.said)) +} + +async fn is_counted_unconfirmed(pool: &PgPool, seeded: &Seeded) -> anyhow::Result { + Ok(review::counts(pool, seeded.kb).await?.unconfirmed == 1) +} + +async fn drop_seeded(pool: &PgPool, seeded: &Seeded) -> anyhow::Result<()> { + let Seeded { kb, org, .. } = seeded; + sqlx::raw_sql(&format!( + "DELETE FROM jobs WHERE payload->>'kb_id' = '{kb}'; + DELETE FROM knowledge_bases WHERE id = '{kb}'; + DELETE FROM organizations WHERE id = '{org}';" + )) + .execute(pool) + .await?; + Ok(()) +} + +#[tokio::test] +async fn a_fact_is_not_stale_until_the_new_version_has_been_read() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let seeded = seed(&pool, "ready", "queued").await?; + let run = async { + assert!( + !is_stale(&pool, &seeded).await?, + "a new version was written and not yet read: nothing has been dropped yet" + ); + assert!( + !is_listed_stale(&pool, &seeded).await?, + "the review queue must not list a fact whose new version is unread" + ); + assert!( + !is_counted_unconfirmed(&pool, &seeded).await?, + "the review badge must not count a fact whose new version is unread" + ); + + let read_at: DateTime = Utc::now(); + sqlx::query("UPDATE chunks SET extracted_at = $2 WHERE id = $1") + .bind(seeded.fresh) + .bind(read_at) + .execute(&pool) + .await?; + assert!( + is_stale(&pool, &seeded).await?, + "the new version spoke and did not restate the fact" + ); + assert!( + is_listed_stale(&pool, &seeded).await?, + "the review queue lists it once the version has spoken" + ); + assert!( + is_counted_unconfirmed(&pool, &seeded).await?, + "the review badge counts it once the version has spoken" + ); + anyhow::Ok(()) + } + .await; + drop_seeded(&pool, &seeded).await?; + run +} + +#[tokio::test] +async fn a_fact_does_not_wait_for_a_version_nobody_will_read() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + for (status, graph_status) in [ + ("ready", "none"), + ("ready", "skipped"), + ("ready", "failed"), + ("failed", "none"), + ] { + let seeded = seed(&pool, status, graph_status).await?; + let run = async { + assert!( + is_stale(&pool, &seeded).await?, + "{status}/{graph_status}: no extraction is coming, so the unread version holds nothing back" + ); + assert!( + is_listed_stale(&pool, &seeded).await?, + "{status}/{graph_status}: the review queue lists it" + ); + anyhow::Ok(()) + } + .await; + drop_seeded(&pool, &seeded).await?; + run?; + } + Ok(()) +} + +#[tokio::test] +async fn a_fact_waits_while_its_new_version_is_still_being_ingested() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let seeded = seed(&pool, "pending", "none").await?; + let run = async { + assert!( + !is_stale(&pool, &seeded).await?, + "a re-push resets graph_status to none until ingest queues the extraction" + ); + assert!( + !is_listed_stale(&pool, &seeded).await?, + "the review queue lists nothing before the version is queued" + ); + anyhow::Ok(()) + } + .await; + drop_seeded(&pool, &seeded).await?; + run +} diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs index be6e452af..b09a5afe4 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -53,6 +53,7 @@ mod a_disambiguator_follows_the_ontology; mod a_document_opening_is_its_first_live_chunk; mod a_fact_awaits_a_nod; mod a_fact_says_where_its_dates_came_from; +mod a_fact_waits_for_its_new_version_to_speak; mod a_failed_job_finds_its_way_back; mod a_forward_reference_is_judged_at_commit; mod a_governor_reads_the_ledger; From a3006e69815e8fc9b32bc7aec25c3225f23b379b Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 10 Nov 2026 12:02:05 +0100 Subject: [PATCH 2/3] A replay reads the wait for a new version at its own moment, so a fact whose new version was unread then is not stale then Signed-off-by: Bogdan Szabo --- crates/utopia-store/src/graph.rs | 2 +- crates/utopia-store/src/review.rs | 36 +++++++++- ...fact_waits_for_its_new_version_to_speak.rs | 66 ++++++++++++++++--- 3 files changed, 90 insertions(+), 14 deletions(-) diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 58ae63f4f..17189c7e0 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -1869,7 +1869,7 @@ pub async fn entity_detail( holds_to = crate::world_axis::facts_holds_to("f"), subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false), object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true), - awaits = crate::review::AWAITS_A_NEW_VERSION, + awaits = crate::review::awaits_a_new_version_at(as_of.map(|_| 3)), chunk_live = crate::record_axis::chunk_live_at("c", as_of.map(|_| 3)), violation_open = crate::record_axis::violation_open_at("v", as_of.map(|_| 3)), conflict_open = crate::record_axis::conflict_open_at("c", as_of.map(|_| 3)), diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs index 78483c739..eea43587b 100644 --- a/crates/utopia-store/src/review.rs +++ b/crates/utopia-store/src/review.rs @@ -19,14 +19,25 @@ use uuid::Uuid; /// 迟早分叉成「徽标说 12 条,点进去 9 条」。 pub const LOW_CONFIDENCE_BELOW: f32 = 0.75; +/// 文档 `d` 的新版本还会被读:还在摄入,或排着队、正在抽取 +macro_rules! will_still_be_read { + () => { + "(d.graph_status IN ('queued', 'extracting') + OR d.status IN ('pending', 'parsing', 'indexing', 'embedding'))" + }; +} + macro_rules! awaits_a_new_version { () => { - "EXISTS (SELECT 1 FROM fact_evidence fe + concat!( + "EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.document_id = fe.document_id JOIN documents d ON d.id = fe.document_id WHERE fe.fact_id = f.id AND c.superseded_at IS NULL AND c.extracted_at IS NULL - AND (d.graph_status IN ('queued', 'extracting') - OR d.status IN ('pending', 'parsing', 'indexing', 'embedding')))" + AND ", + will_still_be_read!(), + ")" + ) }; } @@ -54,6 +65,25 @@ pub const UNCONFIRMED_FACT: &str = concat!( /// 抽取关着、跳过或失败的版本没人会读,等它就是永远等。 pub const AWAITS_A_NEW_VERSION: &str = awaits_a_new_version!(); +/// [`AWAITS_A_NEW_VERSION`] 按记录轴(0019)读:T 时刻现行、而那时还没被读的分块。 +/// 后来读过的(`extracted_at` 晚于 T),那时确实在等;至今没读的照现在的状态看, +/// 文档的状态没有历史。`as_of` 是时刻参数的位置,`None` 即当下 +pub fn awaits_a_new_version_at(as_of: Option) -> String { + let Some(param) = as_of else { + return AWAITS_A_NEW_VERSION.into(); + }; + format!( + "EXISTS (SELECT 1 FROM fact_evidence fe + JOIN chunks c ON c.document_id = fe.document_id + JOIN documents d ON d.id = fe.document_id + WHERE fe.fact_id = f.id AND {live} + AND (c.extracted_at > coalesce(${param}, now()) + OR (c.extracted_at IS NULL AND {coming})))", + live = crate::record_axis::chunk_live_at("c", as_of), + coming = will_still_be_read!(), + ) +} + pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult { let sql = format!( "SELECT diff --git a/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs index 159b63ec0..debc4167c 100644 --- a/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs +++ b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs @@ -7,6 +7,9 @@ use sqlx::PgPool; use utopia_store::{graph, review}; use uuid::Uuid; +/// 新版本写下的那一刻:旧分块在这时被取代 +const REPUSHED: &str = "2025-06-01T12:34:56Z"; + struct Seeded { kb: Uuid, org: Uuid, @@ -24,8 +27,9 @@ async fn seed(pool: &PgPool, status: &str, graph_status: &str) -> anyhow::Result INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','fact-waits'); INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','fact-waits'); INSERT INTO entity_types(id,kb_id,key,label) VALUES ('{class}','{kb}','thing','Thing'); - INSERT INTO entities(id,kb_id,type_id,canonical_name) VALUES - ('{ada}','{kb}','{class}','Ada'), ('{port}','{kb}','{class}','Port Ellen'); + INSERT INTO entities(id,kb_id,type_id,canonical_name,created_at) VALUES + ('{ada}','{kb}','{class}','Ada','2025-01-01'), + ('{port}','{kb}','{class}','Port Ellen','2025-01-01'); INSERT INTO relation_types (id,kb_id,key,label,temporal) VALUES ('{based_in}','{kb}','based_in','based in','state'); INSERT INTO phrase_bindings @@ -34,14 +38,15 @@ async fn seed(pool: &PgPool, status: &str, graph_status: &str) -> anyhow::Result VALUES ('{binding}','{kb}','is based in','{class}','{class}',false, '{based_in}','forward','bound'); INSERT INTO sources(id,kb_id,kind,name) VALUES ('{source}','{kb}','statements','mirror'); - INSERT INTO documents(id,kb_id,filename,sha256,source_id,status,graph_status) - VALUES ('{doc}','{kb}','a.md','sha-a','{source}','{status}','{graph_status}'); - INSERT INTO chunks(id,kb_id,document_id,seq,text,doc_version,superseded_at,extracted_at) VALUES - ('{old}','{kb}','{doc}',0,'v1','1','2025-06-01T12:34:56Z','2025-06-01T12:00:00Z'), - ('{fresh}','{kb}','{doc}',1,'v2','2',NULL,NULL); + INSERT INTO documents(id,kb_id,filename,sha256,source_id,status,graph_status,created_at) + VALUES ('{doc}','{kb}','a.md','sha-a','{source}','{status}','{graph_status}','2025-01-01'); + INSERT INTO chunks(id,kb_id,document_id,seq,text,doc_version,created_at,superseded_at,extracted_at) VALUES + ('{old}','{kb}','{doc}',0,'v1','1','2025-01-01','{REPUSHED}','2025-01-02'), + ('{fresh}','{kb}','{doc}',1,'v2','2','{REPUSHED}',NULL,NULL); INSERT INTO facts (id,kb_id,subject_id,object_id,layer,phrase,confidence, - valid_from,valid_from_precision) - VALUES ('{said}','{kb}','{ada}','{port}','open','is based in',0.9,'2020-01-01','day'); + valid_from,valid_from_precision,recorded_at) + VALUES ('{said}','{kb}','{ada}','{port}','open','is based in',0.9,'2020-01-01','day', + '2025-01-02'); INSERT INTO fact_evidence (fact_id,chunk_id,document_id,quote) VALUES ('{said}','{old}','{doc}','q');" )) @@ -57,7 +62,15 @@ async fn seed(pool: &PgPool, status: &str, graph_status: &str) -> anyhow::Result } async fn is_stale(pool: &PgPool, seeded: &Seeded) -> anyhow::Result { - let (_, facts) = graph::entity_detail(pool, seeded.kb, seeded.ada, None, None).await?; + is_stale_as_of(pool, seeded, None).await +} + +async fn is_stale_as_of( + pool: &PgPool, + seeded: &Seeded, + as_of: Option>, +) -> anyhow::Result { + let (_, facts) = graph::entity_detail(pool, seeded.kb, seeded.ada, None, as_of).await?; let fact = facts .iter() .find(|fact| fact.id == seeded.said) @@ -185,3 +198,36 @@ async fn a_fact_waits_while_its_new_version_is_still_being_ingested() -> anyhow: drop_seeded(&pool, &seeded).await?; run } + +#[tokio::test] +async fn a_replay_to_the_day_before_the_new_version_was_read_shows_the_fact_still_waiting( +) -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let seeded = seed(&pool, "ready", "done").await?; + let run = async { + sqlx::query("UPDATE chunks SET extracted_at = '2025-06-03T00:00:00Z' WHERE id = $1") + .bind(seeded.fresh) + .execute(&pool) + .await?; + let stale_on = |day: &'static str| { + let (pool, seeded) = (&pool, &seeded); + async move { is_stale_as_of(pool, seeded, Some(day.parse()?)).await } + }; + assert_eq!( + ( + stale_on("2025-05-31T00:00:00Z").await?, + stale_on("2025-06-02T00:00:00Z").await?, + stale_on("2025-06-04T00:00:00Z").await?, + ), + (false, false, true), + "before the re-push, between the re-push and its reading, after the reading" + ); + anyhow::Ok(()) + } + .await; + drop_seeded(&pool, &seeded).await?; + run +} From 8203faabae798c2adf156625030ccbc4aeb34cc4 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 10 Nov 2026 22:01:33 +0100 Subject: [PATCH 3/3] The wait for a new version is read only in the present and found through the cited chunk, so a forced re-extract cannot change what a replay shows and evidence without a document id still waits Signed-off-by: Bogdan Szabo --- crates/utopia-store/src/graph.rs | 9 ++- crates/utopia-store/src/review.rs | 73 ++++++------------- crates/utopia-store/src/review_summary.rs | 6 +- ...fact_waits_for_its_new_version_to_speak.rs | 60 +++++++++++++-- docs/design/governance.md | 2 +- 5 files changed, 87 insertions(+), 63 deletions(-) diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 17189c7e0..eb1c81cc7 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -1869,7 +1869,10 @@ pub async fn entity_detail( holds_to = crate::world_axis::facts_holds_to("f"), subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false), object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true), - awaits = crate::review::awaits_a_new_version_at(as_of.map(|_| 3)), + awaits = match as_of { + Some(_) => "false", + None => crate::review::awaits_a_new_version(), + }, chunk_live = crate::record_axis::chunk_live_at("c", as_of.map(|_| 3)), violation_open = crate::record_axis::violation_open_at("v", as_of.map(|_| 3)), conflict_open = crate::record_axis::conflict_open_at("c", as_of.map(|_| 3)), @@ -2071,7 +2074,7 @@ pub async fn low_confidence_facts( /// /// **「现行」这一条不能少。** 闭合是作废+改写,修正行带着原证据(`temporal::close_superseded`), /// 只看证据存活性的话,刚闭合的行立刻回到这一档——那个出路等于不存在。 -/// WHERE 与 `review::UNCONFIRMED_FACT` 同一套(0022:「结束不知哪天」不是开放)。 +/// WHERE 与 `review::unconfirmed_fact` 同一套(0022:「结束不知哪天」不是开放)。 pub async fn stale_facts( pool: &PgPool, kb_id: Uuid, @@ -2098,7 +2101,7 @@ pub async fn stale_facts( AND NOT {awaits} ORDER BY f.recorded_at DESC, f.id DESC LIMIT $2 OFFSET $3", - awaits = crate::review::AWAITS_A_NEW_VERSION, + awaits = crate::review::awaits_a_new_version(), )) .bind(kb_id) .bind(limit) diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs index eea43587b..647cf34ba 100644 --- a/crates/utopia-store/src/review.rs +++ b/crates/utopia-store/src/review.rs @@ -19,26 +19,23 @@ use uuid::Uuid; /// 迟早分叉成「徽标说 12 条,点进去 9 条」。 pub const LOW_CONFIDENCE_BELOW: f32 = 0.75; -/// 文档 `d` 的新版本还会被读:还在摄入,或排着队、正在抽取 -macro_rules! will_still_be_read { - () => { - "(d.graph_status IN ('queued', 'extracting') - OR d.status IN ('pending', 'parsing', 'indexing', 'embedding'))" - }; -} - -macro_rules! awaits_a_new_version { - () => { - concat!( - "EXISTS (SELECT 1 FROM fact_evidence fe - JOIN chunks c ON c.document_id = fe.document_id - JOIN documents d ON d.id = fe.document_id - WHERE fe.fact_id = f.id AND c.superseded_at IS NULL AND c.extracted_at IS NULL - AND ", - will_still_be_read!(), - ")" - ) - }; +/// 事实引用的某个文档有一块现行分块还没人读:新版本写下了、还没抽取。它开口之前, +/// 它可能没再提的东西还谈不上「没了」。只等还会被读的版本:还在摄入,或排着队、正在抽取。 +/// 抽取关着、跳过或失败的版本没人会读,等它就是永远等。别名固定用 `f`。 +/// +/// 文档从证据的分块找(`fe.chunk_id`),不从 `fe.document_id`:后者可以为空。 +/// +/// **只说当下。** `extracted_at` 没有历史:强制重抽把它清空再写成现在,一个分块 +/// 「T 时刻读过没有」事后无从得知。所以回放(0019)不问这一句,只看证据分块那时 +/// 是否已被取代,那是重抽动不了的。 +pub fn awaits_a_new_version() -> &'static str { + "EXISTS (SELECT 1 FROM fact_evidence fe + JOIN chunks cited ON cited.id = fe.chunk_id + JOIN documents d ON d.id = cited.document_id + JOIN chunks c ON c.document_id = d.id + WHERE fe.fact_id = f.id AND c.superseded_at IS NULL AND c.extracted_at IS NULL + AND (d.graph_status IN ('queued', 'extracting') + OR d.status IN ('pending', 'parsing', 'indexing', 'embedding')))" } /// 「待确认」的判据,写成 SQL 片段,`counts` 与总览(`review_summary`)共用: @@ -48,39 +45,17 @@ macro_rules! awaits_a_new_version { /// (`temporal::close_superseded`),少了它,刚闭合的行照样满足判据——队列永远清不掉, /// 再点一次只会撞上「区间已闭合」。判据与 0022 说同一句话:「结束不知哪天」不是开放。 /// -/// 最后一句:新版本写下了、还没被读,就不算待确认(见 [`AWAITS_A_NEW_VERSION`])。 -pub const UNCONFIRMED_FACT: &str = concat!( - "f.valid_to IS NULL AND f.valid_to_precision IS NULL +/// 最后一句:新版本写下了、还没被读,就不算待确认(见 [`awaits_a_new_version`])。 +pub fn unconfirmed_fact() -> String { + format!( + "f.valid_to IS NULL AND f.valid_to_precision IS NULL AND EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id) AND NOT EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.id = fe.chunk_id WHERE fe.fact_id = f.id AND c.superseded_at IS NULL) - AND NOT ", - awaits_a_new_version!(), -); - -/// 事实引用的某个文档有一块现行分块还没人读:新版本写下了、还没抽取。它开口之前, -/// 它可能没再提的东西还谈不上「没了」。只等还会被读的版本:还在摄入,或排着队、正在抽取。 -/// 抽取关着、跳过或失败的版本没人会读,等它就是永远等。 -pub const AWAITS_A_NEW_VERSION: &str = awaits_a_new_version!(); - -/// [`AWAITS_A_NEW_VERSION`] 按记录轴(0019)读:T 时刻现行、而那时还没被读的分块。 -/// 后来读过的(`extracted_at` 晚于 T),那时确实在等;至今没读的照现在的状态看, -/// 文档的状态没有历史。`as_of` 是时刻参数的位置,`None` 即当下 -pub fn awaits_a_new_version_at(as_of: Option) -> String { - let Some(param) = as_of else { - return AWAITS_A_NEW_VERSION.into(); - }; - format!( - "EXISTS (SELECT 1 FROM fact_evidence fe - JOIN chunks c ON c.document_id = fe.document_id - JOIN documents d ON d.id = fe.document_id - WHERE fe.fact_id = f.id AND {live} - AND (c.extracted_at > coalesce(${param}, now()) - OR (c.extracted_at IS NULL AND {coming})))", - live = crate::record_axis::chunk_live_at("c", as_of), - coming = will_still_be_read!(), + AND NOT {awaits}", + awaits = awaits_a_new_version(), ) } @@ -123,7 +98,7 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult { (SELECT count(*) FROM (SELECT 1 FROM phrase_bindings b WHERE b.kb_id = $1 AND {waiting_phrase} UNION ALL SELECT 1 FROM type_bindings WHERE kb_id = $1 AND status = 'undecided') a) AS alignment, (SELECT count(*) FROM errata_actions WHERE kb_id = $1 AND status = 'held') AS errata", - unconfirmed = UNCONFIRMED_FACT, + unconfirmed = unconfirmed_fact(), waiting_phrase = crate::alignment_queue::WAITING_PHRASE, same = crate::resolution::TypeFilter::Same.clause(), conflict = crate::resolution::TypeFilter::Conflict.clause(), diff --git a/crates/utopia-store/src/review_summary.rs b/crates/utopia-store/src/review_summary.rs index dabebe8f7..95e1f4fb3 100644 --- a/crates/utopia-store/src/review_summary.rs +++ b/crates/utopia-store/src/review_summary.rs @@ -19,7 +19,7 @@ use utopia_core::models::{ use utopia_core::AppResult; use uuid::Uuid; -use crate::review::{LOW_CONFIDENCE_BELOW, UNCONFIRMED_FACT}; +use crate::review::{unconfirmed_fact, LOW_CONFIDENCE_BELOW}; /// 「办过的」按天看多少天 pub const DAILY_DAYS: i64 = 14; @@ -107,7 +107,7 @@ async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult { UNION ALL SELECT decided_at FROM type_bindings WHERE kb_id = $1 AND status = 'undecided') a) AS alignment_oldest, (SELECT count(*) FROM errata_actions WHERE kb_id = $1 AND status = 'held') AS errata, (SELECT min(created_at) FROM errata_actions WHERE kb_id = $1 AND status = 'held') AS errata_oldest", - unconfirmed = UNCONFIRMED_FACT, + unconfirmed = unconfirmed_fact(), waiting_phrase = crate::alignment_queue::WAITING_PHRASE, ); let r: WaitingRow = sqlx::query_as(&sql) @@ -333,7 +333,7 @@ async fn health(pool: &PgPool, kb_id: Uuid) -> AppResult { WHERE kb_id = $1 AND status = 'open' ) c ON c.fact_id = f.id WHERE f.kb_id = $1 AND f.invalidated_at IS NULL", - unconfirmed = UNCONFIRMED_FACT, + unconfirmed = unconfirmed_fact(), ); let r: HealthRow = sqlx::query_as(&sql) .bind(kb_id) diff --git a/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs index debc4167c..483bc1be2 100644 --- a/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs +++ b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs @@ -1,10 +1,11 @@ //! 新版本写下了、还没被读:它引用的事实不算过期,也不进审核队列。 //! 新版本被读过而没再提这条事实,才算它不再被陈述。 //! 没人会去读的新版本(抽取关着、跳过或失败)不让事实等:等下去就是永远。 +//! 回放不问这一句:分块哪天被读没有历史,重抽会把它挪走。 use chrono::{DateTime, Utc}; use sqlx::PgPool; -use utopia_store::{graph, review}; +use utopia_store::{documents, graph, review}; use uuid::Uuid; /// 新版本写下的那一刻:旧分块在这时被取代 @@ -14,6 +15,7 @@ struct Seeded { kb: Uuid, org: Uuid, ada: Uuid, + doc: Uuid, fresh: Uuid, said: Uuid, } @@ -56,6 +58,7 @@ async fn seed(pool: &PgPool, status: &str, graph_status: &str) -> anyhow::Result kb, org, ada, + doc, fresh, said, }) @@ -200,7 +203,36 @@ async fn a_fact_waits_while_its_new_version_is_still_being_ingested() -> anyhow: } #[tokio::test] -async fn a_replay_to_the_day_before_the_new_version_was_read_shows_the_fact_still_waiting( +async fn a_fact_whose_evidence_names_no_document_still_waits_for_the_new_version( +) -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let seeded = seed(&pool, "ready", "queued").await?; + let run = async { + sqlx::query("UPDATE fact_evidence SET document_id = NULL WHERE fact_id = $1") + .bind(seeded.said) + .execute(&pool) + .await?; + assert_eq!( + ( + is_stale(&pool, &seeded).await?, + is_listed_stale(&pool, &seeded).await?, + is_counted_unconfirmed(&pool, &seeded).await?, + ), + (false, false, false), + "the document is found through the cited chunk" + ); + anyhow::Ok(()) + } + .await; + drop_seeded(&pool, &seeded).await?; + run +} + +#[tokio::test] +async fn a_replay_to_june_15_shows_the_fact_stale_after_a_later_forced_re_extract( ) -> anyhow::Result<()> { let Some(url) = utopia_store::test_db::url() else { return Ok(()); @@ -208,7 +240,7 @@ async fn a_replay_to_the_day_before_the_new_version_was_read_shows_the_fact_stil let pool = PgPool::connect(&url).await?; let seeded = seed(&pool, "ready", "done").await?; let run = async { - sqlx::query("UPDATE chunks SET extracted_at = '2025-06-03T00:00:00Z' WHERE id = $1") + sqlx::query("UPDATE chunks SET extracted_at = '2025-06-02T00:00:00Z' WHERE id = $1") .bind(seeded.fresh) .execute(&pool) .await?; @@ -216,14 +248,28 @@ async fn a_replay_to_the_day_before_the_new_version_was_read_shows_the_fact_stil let (pool, seeded) = (&pool, &seeded); async move { is_stale_as_of(pool, seeded, Some(day.parse()?)).await } }; + let replayed = ( + stale_on("2025-05-31T00:00:00Z").await?, + stale_on("2025-06-15T00:00:00Z").await?, + ); + assert_eq!( + replayed, + (false, true), + "before the re-push, and after the new version was read without the fact" + ); + + documents::queue_extraction_one(&pool, seeded.doc).await?; assert_eq!( ( stale_on("2025-05-31T00:00:00Z").await?, - stale_on("2025-06-02T00:00:00Z").await?, - stale_on("2025-06-04T00:00:00Z").await?, + stale_on("2025-06-15T00:00:00Z").await?, ), - (false, false, true), - "before the re-push, between the re-push and its reading, after the reading" + replayed, + "a re-extract moves extracted_at, and the replay reads the same as before it" + ); + assert!( + !is_stale(&pool, &seeded).await?, + "today the version is being read again, so the fact waits for it" ); anyhow::Ok(()) } diff --git a/docs/design/governance.md b/docs/design/governance.md index dc1af298f..0c188580f 100644 --- a/docs/design/governance.md +++ b/docs/design/governance.md @@ -9,7 +9,7 @@ Records: [0025] (the governor), [0026] (why), [0027] (the impact gate), [0028] ( **Queues, grouped by where an item came from.** Review holds nods (`pending_facts`, placed first), duplicates (`resolution_reviews`), conflicts (`fact_conflicts`), unconfirmed (every evidence chunk -superseded), low-confidence (`confidence < 0.75`), violations (`axiom_violations`), defects +superseded, and no cited document has a live chunk still waiting to be read, #1477), low-confidence (`confidence < 0.75`), violations (`axiom_violations`), defects (`ontology_defects`) and alignment (a phrase signature or a kind word the aligner's two votes split on, `phrase_bindings` and `type_bindings` in `undecided`; a person binds it to a property with a direction or to a class, or says none fits, and the typed graph recomputes at once; the