diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 2f942e28a..214645ed3 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -1843,6 +1843,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, @@ -1899,6 +1900,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 = 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)), @@ -2100,14 +2105,14 @@ 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, 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, @@ -2124,9 +2129,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..647cf34ba 100644 --- a/crates/utopia-store/src/review.rs +++ b/crates/utopia-store/src/review.rs @@ -19,18 +19,45 @@ use uuid::Uuid; /// 迟早分叉成「徽标说 12 条,点进去 9 条」。 pub const LOW_CONFIDENCE_BELOW: f32 = 0.75; +/// 事实引用的某个文档有一块现行分块还没人读:新版本写下了、还没抽取。它开口之前, +/// 它可能没再提的东西还谈不上「没了」。只等还会被读的版本:还在摄入,或排着队、正在抽取。 +/// 抽取关着、跳过或失败的版本没人会读,等它就是永远等。别名固定用 `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`)共用: /// 有证据、但证据所在的分块全被新版本取代了,**而且这条事实至今仍成立**。别名固定用 `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 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 c.superseded_at IS NULL) + AND NOT {awaits}", + awaits = awaits_a_new_version(), + ) +} pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult { let sql = format!( @@ -71,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 new file mode 100644 index 000000000..483bc1be2 --- /dev/null +++ b/crates/utopia-store/tests/store/a_fact_waits_for_its_new_version_to_speak.rs @@ -0,0 +1,279 @@ +//! 新版本写下了、还没被读:它引用的事实不算过期,也不进审核队列。 +//! 新版本被读过而没再提这条事实,才算它不再被陈述。 +//! 没人会去读的新版本(抽取关着、跳过或失败)不让事实等:等下去就是永远。 +//! 回放不问这一句:分块哪天被读没有历史,重抽会把它挪走。 + +use chrono::{DateTime, Utc}; +use sqlx::PgPool; +use utopia_store::{documents, graph, review}; +use uuid::Uuid; + +/// 新版本写下的那一刻:旧分块在这时被取代 +const REPUSHED: &str = "2025-06-01T12:34:56Z"; + +struct Seeded { + kb: Uuid, + org: Uuid, + ada: Uuid, + doc: 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,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 + (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,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,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');" + )) + .execute(pool) + .await?; + Ok(Seeded { + kb, + org, + ada, + doc, + fresh, + said, + }) +} + +async fn is_stale(pool: &PgPool, seeded: &Seeded) -> anyhow::Result { + 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) + .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 +} + +#[tokio::test] +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(()); + }; + 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-02T00: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 } + }; + 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-15T00:00:00Z").await?, + ), + 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(()) + } + .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 ddf254cb6..3a5aa3392 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; 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