diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs index a5036d33d..fc2bf6834 100644 --- a/crates/utopia-core/src/models.rs +++ b/crates/utopia-core/src/models.rs @@ -676,6 +676,8 @@ pub struct StatementQualifier { pub value: Option, pub entity_id: Option, pub entity_name: Option, + /// 说这个值的那几块(0070):两块活着的块说法不同,各自一条 + pub chunk_ids: Vec, } /// 一次 OWL 导入的记录。原文按内容寻址存在 blob 里,这行只是账。 diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rs index d92916da3..08ef1921b 100644 --- a/crates/utopia-server/src/api/mcp_tests.rs +++ b/crates/utopia-server/src/api/mcp_tests.rs @@ -1028,7 +1028,8 @@ async fn entity_facts_reads_back_a_statements_role_words() -> anyhow::Result<()> .unwrap(); assert_eq!( fact["statement_qualifiers"], - json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null}]) + json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null, + "chunk_ids":[f.chunk]}]) ); f.clean().await } diff --git a/crates/utopia-server/src/api/sources_statements_tests.rs b/crates/utopia-server/src/api/sources_statements_tests.rs index ce1085d7f..44daaf5f7 100644 --- a/crates/utopia-server/src/api/sources_statements_tests.rs +++ b/crates/utopia-server/src/api/sources_statements_tests.rs @@ -437,6 +437,42 @@ async fn a_second_push_under_the_same_identity_updates_in_place() -> anyhow::Res f.cleanup().await } +/// 0070 的例子:再推一次把 `lines` 从 40-52 改成 58-70,读回来只有新的范围 +#[tokio::test] +async fn a_re_push_that_moves_lines_to_58_70_reads_back_only_58_70() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + for lines in ["40-52", "58-70"] { + let mut body = observation("08:14:03", "kitchen table"); + body["s"][0][5] = json!({ "lines": lines }); + let (status, body) = f.push(f.source, &f.token, &body).await?; + assert_eq!(status, StatusCode::OK, "{body}"); + let doc = documents::find_by_external_key(&f.pool, f.source, "statements:obs-000412") + .await? + .expect("the push has a document"); + crate::pipeline::process_document(&f.state, doc.id).await?; + let proposer = Proposer { + user_id: None, + token_id: None, + }; + crate::extraction::extract_document(&f.state, doc.id, proposer).await?; + } + let (cup,): (Uuid,) = + sqlx::query_as("SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = 'cup-7'") + .bind(f.kb) + .fetch_one(&f.pool) + .await?; + let (_, facts) = utopia_store::graph::entity_detail(&f.pool, f.kb, cup, None, None).await?; + let said: Vec<_> = facts + .iter() + .flat_map(|x| &x.statement_qualifiers) + .map(|q| (q.role.as_str(), q.value.clone())) + .collect(); + assert_eq!(said, vec![("lines", Some(json!("58-70")))]); + f.cleanup().await +} + /// 门口的拒绝走到 HTTP 是 422(`AppError::Validation`,与 `api` 推送被拒时同一个码), /// 并且这次推送留在 run 历史里;`api` 来源不认这条路由(404),钥匙不对是 401 #[tokio::test] diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 02632074f..23de9f06c 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -237,10 +237,11 @@ pub async fn add_statement_qualifier( } /// 一批开放陈述各自的角色词属性,按事实 id 取回;实体那一格连上显示名。 -/// 同一个值记在几块上只返回一次 +/// 只取 `as_of` 时刻说话的行(0070 决定 2、3);同一个值记在几块上返回一次,带上那几块 pub async fn statement_qualifiers_for( pool: &PgPool, fact_ids: &[Uuid], + as_of: Option>, ) -> AppResult>> { let mut out: HashMap> = HashMap::new(); if fact_ids.is_empty() { @@ -253,23 +254,37 @@ pub async fn statement_qualifiers_for( value: Option, entity_id: Option, entity_name: Option, + chunk_ids: Vec, } - let rows: Vec = sqlx::query_as( - "SELECT DISTINCT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name + let as_of_param = as_of.map(|_| 2); + let sql = format!( + "WITH rw_f AS (SELECT rw_ee.fact_id, {ends} FROM {evidence} + WHERE rw_ee.fact_id = ANY($1) GROUP BY rw_ee.fact_id) + SELECT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name, + array_agg(q.chunk_id ORDER BY q.chunk_id) AS chunk_ids FROM statement_qualifiers q + LEFT JOIN rw_f ON rw_f.fact_id = q.fact_id + JOIN chunks rw_c ON rw_c.id = q.chunk_id + JOIN documents rw_d ON rw_d.id = rw_c.document_id LEFT JOIN entities e ON e.id = q.entity_id - WHERE q.fact_id = ANY($1) - ORDER BY q.fact_id, q.role", - ) - .bind(fact_ids) - .fetch_all(pool) - .await?; - for r in rows { + WHERE q.fact_id = ANY($1) AND {speaks} + GROUP BY q.fact_id, q.role, q.value, q.entity_id, e.canonical_name + ORDER BY q.fact_id, q.role, chunk_ids", + ends = crate::record_axis::role_word_fact_ends(as_of_param), + evidence = crate::record_axis::ROLE_WORD_EVIDENCE, + speaks = crate::record_axis::role_word_speaks_given("rw_c", "rw_d", "rw_f", as_of_param), + ); + let mut query = sqlx::query_as::<_, Row>(&sql).bind(fact_ids); + if let Some(at) = as_of { + query = query.bind(at); + } + for r in query.fetch_all(pool).await? { out.entry(r.fact_id).or_default().push(StatementQualifier { role: r.role, value: r.value, entity_id: r.entity_id, entity_name: r.entity_name, + chunk_ids: r.chunk_ids, }); } Ok(out) @@ -1519,7 +1534,7 @@ async fn edges_among( let ids: Vec = edges.iter().map(|x| x.id).collect(); let (mut typed, mut worded) = tokio::try_join!( fact_qualifiers_for(pool, &ids), - statement_qualifiers_for(pool, &ids) + statement_qualifiers_for(pool, &ids, as_of) )?; for x in edges.iter_mut() { x.qualifiers = typed.remove(&x.id).unwrap_or_default(); @@ -1868,7 +1883,7 @@ pub async fn entity_detail( let ids: Vec = facts.iter().map(|x| x.id).collect(); let (mut typed, mut worded) = tokio::try_join!( fact_qualifiers_for(pool, &ids), - statement_qualifiers_for(pool, &ids) + statement_qualifiers_for(pool, &ids, as_of) )?; for x in facts.iter_mut() { x.qualifiers = typed.remove(&x.id).unwrap_or_default(); diff --git a/crates/utopia-store/src/materialize.rs b/crates/utopia-store/src/materialize.rs index 855f1da6a..f00036102 100644 --- a/crates/utopia-store/src/materialize.rs +++ b/crates/utopia-store/src/materialize.rs @@ -208,8 +208,8 @@ async fn materialize_in_tx( AND b.relation_type_id = t.predicate_id AND ((b.direction = 'forward' AND t.subject_id = s.subject_id) OR (b.direction = 'reverse' AND t.subject_id = s.object_id)) - AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q - WHERE q.fact_id = s.id AND q.role = 'mood'))" + AND {NO_MOOD})", + NO_MOOD = no_mood_spoken(), )) .persistent(false) .bind(kb_id) @@ -274,8 +274,7 @@ async fn materialize_in_tx( WHERE s.kb_id = $1 AND s.layer = 'open' AND s.invalidated_at IS NULL AND b.status = 'bound' AND (b.direction = 'forward' OR s.object_id IS NOT NULL) - AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q - WHERE q.fact_id = s.id AND q.role = 'mood') + AND {NO_MOOD} -- 勘误撤过的(陈述, 属性)不再算(0044 决定 7):撤销要站得住 AND NOT EXISTS (SELECT 1 FROM errata_actions ea WHERE ea.statement_id = s.id AND ea.predicate_id = b.relation_type_id @@ -283,7 +282,8 @@ async fn materialize_in_tx( AND NOT EXISTS (SELECT 1 FROM typed_fact_sources src JOIN facts t ON t.id = src.fact_id WHERE src.statement_id = s.id AND t.invalidated_at IS NULL AND t.predicate_id = b.relation_type_id) - ORDER BY s.id" + ORDER BY s.id", + NO_MOOD = no_mood_spoken(), )) .persistent(false) .bind(kb_id) @@ -562,7 +562,7 @@ async fn imply_in_tx( AND pr.reading = r.reading AND pr.phrase = {TEXT} WHERE r.kb_id = $1 AND r.status = 'approved' AND r.trigger = 'phrase' AND {RULE_MATCH} - AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.fact_id = s.id AND q.role = 'mood') + AND {NO_MOOD} AND (r.reading IS NULL OR pr.entity_id IS NOT NULL OR pr.value IS NOT NULL) AND NOT EXISTS (SELECT 1 FROM errata_actions ea WHERE ea.statement_id = s.id AND ea.predicate_id = r.conclude_property_id @@ -572,6 +572,7 @@ async fn imply_in_tx( ORDER BY s.id", TEXT = crate::implication_rules::object_text_sql(), RULE_MATCH = crate::implication_rules::RULE_MATCH, + NO_MOOD = no_mood_spoken(), )) .persistent(false) .bind(kb_id) @@ -835,6 +836,14 @@ fn attribute_value(raw: &Value, datatype: Option<&str>, unit: Option<&str>) -> O Some(out) } +/// 陈述 `s` 没有一个说着话的 `mood`(0070 决定 2):重推丢掉了 mood,旧块上的 mood 就不再拦着 +fn no_mood_spoken() -> String { + format!( + "NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.fact_id = s.id AND q.role = 'mood' AND {})", + crate::record_axis::role_word_speaks_now("q") + ) +} + /// 类别词的归一(同 type_bindings):这里要在 SQL 里对上实体的 specific_type fn kind_word_sql(col: &str) -> String { format!("lower(btrim(regexp_replace({col}, '\\s+', ' ', 'g')))") diff --git a/crates/utopia-store/src/record_axis.rs b/crates/utopia-store/src/record_axis.rs index 01387f075..51576b8ff 100644 --- a/crates/utopia-store/src/record_axis.rs +++ b/crates/utopia-store/src/record_axis.rs @@ -102,6 +102,61 @@ pub fn chunk_live_at(alias: &str, as_of: Option) -> String { } } +/// 一条事实的证据,选成 `rw_ee`(证据)、`rw_ec`(块)、`rw_ed`(文档),供 [`role_word_fact_ends`] 聚合 +pub const ROLE_WORD_EVIDENCE: &str = "fact_evidence rw_ee + JOIN chunks rw_ec ON rw_ec.id = rw_ee.chunk_id + JOIN documents rw_ed ON rw_ed.id = rw_ec.document_id"; + +/// 按事实聚合 [`ROLE_WORD_EVIDENCE`]:T 时刻有没有活块(`any_live`),T 时刻已有的块里 +/// 最晚的终点(`last_end`)。块的终点是 `superseded_at` 与文档 `deleted_at` 里早的那个 +pub fn role_word_fact_ends(as_of: Option) -> String { + format!( + "bool_or({} AND {}) AS any_live, + max(least(rw_ec.superseded_at, rw_ed.deleted_at)) FILTER (WHERE {}) AS last_end", + chunk_live_at("rw_ec", as_of), + document_live_at("rw_ed", as_of), + chunk_existed_at("rw_ec", as_of), + ) +} + +fn chunk_existed_at(alias: &str, as_of: Option) -> String { + match as_of { + None => "true".into(), + Some(param) => format!("{alias}.created_at <= coalesce(${param}, now())"), + } +} + +/// 角色词在 T 时刻替它的事实说话吗(0070 决定 2、3),给定它那块 `c`、那块的文档 `d` +/// 和它事实的 [`role_word_fact_ends`] 一行 `f`。 +/// +/// 它那块与那块的文档在 T 时刻都还活着,就说话;活着的几块值不同,都说话。 +/// 事实在 T 时刻一块活证据都没有时,最后到头的那几块说话(同一时刻到头的都算), +/// 只看 T 时刻已有的块。每条事实的证据只聚合一次:重推几百次的陈述不按行重扫 +pub fn role_word_speaks_given(c: &str, d: &str, f: &str, as_of: Option) -> String { + format!( + "(({c_live} AND {d_live}) + OR (NOT {f}.any_live AND {existed} + AND least({c}.superseded_at, {d}.deleted_at) = {f}.last_end))", + c_live = chunk_live_at(c, as_of), + d_live = document_live_at(d, as_of), + existed = chunk_existed_at(c, as_of), + ) +} + +/// `statement_qualifiers`:这一行 `q` 此刻说话吗,[`role_word_speaks_given`] 的单行形状。 +/// 只在写入口用,所以不带 T;别名都带 `rw_` 前缀,不和调用方的撞 +pub fn role_word_speaks_now(q: &str) -> String { + format!( + "EXISTS (SELECT 1 FROM chunks rw_c JOIN documents rw_d ON rw_d.id = rw_c.document_id + CROSS JOIN LATERAL (SELECT {ends} FROM {evidence} + WHERE rw_ee.fact_id = {q}.fact_id) rw_f + WHERE rw_c.id = {q}.chunk_id AND {speaks})", + ends = role_word_fact_ends(None), + evidence = ROLE_WORD_EVIDENCE, + speaks = role_word_speaks_given("rw_c", "rw_d", "rw_f", None), + ) +} + /// `entity_merges`:这次合并在 T 时刻**生效着**吗(0019 第二刀 / #336)。 /// /// 实体身上没有记录轴——`merged_into` 只说合并发生过,不说何时。时刻在这张表上, diff --git a/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs b/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs index 401688e46..cb26cc6dd 100644 --- a/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs +++ b/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs @@ -5,7 +5,8 @@ //! place) 绑到 headquartered_in:算出一条类型化行,谓词是它,证据与限定抄过来, //! `from_statement_id` 指回陈述;再跑一遍什么都不动;带 mood 的陈述不算;另一份文档 //! 的同一句并进同一行(两条来源、两条证据),它说的另一个 since 不跟进来,行只读建行那条的,它说的 until 行还没有、跟进来;作废其中一条陈述,行还在、来源少一条; -//! 绑定翻成 reverse,旧行作废、新行主宾对调;绑定改成 none,行作废、不再补。 +//! 绑定翻成 reverse,旧行作废、新行主宾对调;绑定改成 none,行作废、不再补; +//! 带 mood 的陈述重推、新块不再说 mood,就成一行。 //! //! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 @@ -287,6 +288,15 @@ async fn a_bound_statement_becomes_a_typed_fact() -> anyhow::Result<()> { .await?; assert_eq!(materialize(&pool, kb).await?, Outcome { retired: 1, added: 0, merged: 0, implied: 0, corrected: 0, conflicts: 0 }); assert_eq!(utopia_store::materialize::count(&pool, kb).await?, 0); + + // 带 mood 的那条重推、新块不再说 mood:旧块上的 mood 不再拦着,它成一行(0070 决定 2) + sqlx::query("UPDATE chunks SET superseded_at = now() WHERE id = $1") + .bind(planned_chunk) + .execute(&pool) + .await?; + evidence_of(planned, "bakery-plan-2.txt").await?; + assert_eq!(materialize(&pool, kb).await?.added, 1); + assert_eq!(utopia_store::materialize::count(&pool, kb).await?, 1); anyhow::Ok(()) } .await; diff --git a/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs b/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs index ce8188f40..3360cd3a8 100644 --- a/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs +++ b/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs @@ -208,10 +208,11 @@ async fn role_words_move_onto_every_evidence_chunk_and_leave_a_purged_fact() -> expected, "每块证据一行,没有证据的已失效事实一行不留" ); - let read = utopia_store::graph::statement_qualifiers_for(&pool, &[stated]).await?; + let read = utopia_store::graph::statement_qualifiers_for(&pool, &[stated], None).await?; assert_eq!( serde_json::to_value(&read[&stated])?, - serde_json::json!([{ "role": "lines", "value": "40-52", "entity_id": null, "entity_name": null }]) + serde_json::json!([{ "role": "lines", "value": "40-52", "entity_id": null, + "entity_name": null, "chunk_ids": [ledger.live_chunk] }]) ); pool.close().await; drop_scratch(&name).await; diff --git a/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs b/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs index 46983265b..34b292cf5 100644 --- a/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs +++ b/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs @@ -4,6 +4,7 @@ //! 空谓词的读路径(图、实体面板、邻域、路径、导出)要按短语显示它;同一句话再听到 //! 一次是同一行、证据累积;它的短语永远不出现在等着被采纳的说法里;角色词属性与 //! 时间词各自取得回来;证据带着引文在块里的偏移;库拒绝没有短语的开放行。 +//! 角色词只在它那块活着时说话,没有活块时最后被取代的那块说话(0070)。 //! //! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 @@ -24,7 +25,7 @@ struct Fixture { chunk_b: Uuid, } -async fn seed(pool: &PgPool) -> anyhow::Result { +async fn seed(pool: &PgPool, org_name: &str) -> anyhow::Result { let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7()); let etype = Uuid::now_v7(); let (acme, beta) = (Uuid::now_v7(), Uuid::now_v7()); @@ -36,19 +37,19 @@ async fn seed(pool: &PgPool) -> anyhow::Result { ); sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, $2)") .bind(org) - .bind(ORG) + .bind(org_name) .execute(pool) .await?; sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3)") .bind(ws) .bind(org) - .bind(ORG) + .bind(org_name) .execute(pool) .await?; sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)") .bind(kb) .bind(ws) - .bind(ORG) + .bind(org_name) .execute(pool) .await?; sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'org', '组织')") @@ -119,7 +120,7 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow .bind(ORG) .execute(&pool) .await?; - let f = seed(&pool).await?; + let f = seed(&pool, ORG).await?; let run = async { // 1. 落一条开放陈述:Acme —acquired→ Beta,短语照写、谓词为空、没有 valid_* @@ -199,7 +200,8 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow let amount = |q: &[utopia_core::models::StatementQualifier]| { serde_json::to_value(q).unwrap() == serde_json::json!([{ "role": "amount", - "value": { "value": "$1.2 billion" }, "entity_id": null, "entity_name": null }]) + "value": { "value": "$1.2 billion" }, "entity_id": null, "entity_name": null, + "chunk_ids": [f.chunk_a] }]) }; assert!( amount(&e.statement_qualifiers), @@ -310,7 +312,7 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow assert!(created && other != fact); // 4. 角色词属性与时间词各自取得回来 - let qualifiers = graph::statement_qualifiers_for(&pool, &[fact]).await?; + let qualifiers = graph::statement_qualifiers_for(&pool, &[fact], None).await?; let q = &qualifiers[&fact]; assert_eq!(q.len(), 1); assert_eq!(q[0].role, "amount"); @@ -352,7 +354,7 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow .is_err() ); graph::add_statement_qualifier(&pool, fact, f.chunk_a, "buyer", None, Some(f.acme)).await?; - let q = &graph::statement_qualifiers_for(&pool, &[fact]).await?[&fact]; + let q = &graph::statement_qualifiers_for(&pool, &[fact], None).await?[&fact]; let buyer = q.iter().find(|x| x.role == "buyer").unwrap(); assert_eq!(buyer.entity_id, Some(f.acme)); assert_eq!(buyer.entity_name.as_deref(), Some("Acme")); @@ -417,3 +419,308 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow .await?; run } + +/// 一条陈述,两块都是它的证据;每块记下自己说的角色词 +async fn stated(pool: &PgPool, f: &Fixture, words: &[(Uuid, &str, &str)]) -> anyhow::Result { + let (fact, _) = graph::insert_open_statement( + pool, + f.kb, + f.acme, + "covers", + FactObject::Entity(f.beta), + None, + 0.9, + ) + .await?; + for chunk in [f.chunk_a, f.chunk_b] { + graph::add_evidence(pool, fact, chunk, None, None).await?; + } + for (chunk, role, value) in words { + graph::add_statement_qualifier( + pool, + fact, + *chunk, + role, + Some(&serde_json::json!(value)), + None, + ) + .await?; + } + Ok(fact) +} + +async fn supersede(pool: &PgPool, chunk: Uuid, at: &str) -> anyhow::Result<()> { + sqlx::query("UPDATE chunks SET superseded_at = $2::timestamptz WHERE id = $1") + .bind(chunk) + .bind(at) + .execute(pool) + .await?; + Ok(()) +} + +/// 现在说话的角色词:(角色, 值, 说它的块) +async fn speaking( + pool: &PgPool, + fact: Uuid, +) -> anyhow::Result)>> { + let read = graph::statement_qualifiers_for(pool, &[fact], None).await?; + Ok(read + .get(&fact) + .into_iter() + .flatten() + .map(|q| { + ( + q.role.clone(), + q.value.clone().unwrap_or_default(), + q.chunk_ids.clone(), + ) + }) + .collect()) +} + +/// 每个测试自己的组织:建库、跑完、拆掉 +async fn with_fixture(org_name: &str, run: F) -> anyhow::Result<()> +where + F: FnOnce(PgPool, Fixture) -> Fut, + Fut: std::future::Future>, +{ + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let clean = |pool: PgPool| async move { + sqlx::query("DELETE FROM organizations WHERE name = $1") + .bind(org_name) + .execute(&pool) + .await + }; + clean(pool.clone()).await?; + let f = seed(&pool, org_name).await?; + let outcome = run(pool.clone(), f).await; + clean(pool).await?; + outcome +} + +fn lines(value: &str, chunk: Uuid) -> (String, serde_json::Value, Vec) { + ("lines".into(), serde_json::json!(value), vec![chunk]) +} + +#[tokio::test] +async fn a_superseded_chunk_stops_speaking_once_a_live_chunk_says_58_70() -> anyhow::Result<()> { + with_fixture("role-word-superseded-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + supersede(&pool, f.chunk_a, "2026-03-01").await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn two_live_chunks_that_disagree_both_speak_with_their_chunk() -> anyhow::Result<()> { + with_fixture("role-word-disagree-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("40-52", f.chunk_a), lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_status_the_live_chunk_does_not_repeat_is_gone() -> anyhow::Result<()> { + with_fixture("role-word-dropped-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[ + (f.chunk_a, "lines", "40-52"), + (f.chunk_a, "status", "failing"), + (f.chunk_b, "lines", "58-70"), + ], + ) + .await?; + supersede(&pool, f.chunk_a, "2026-03-01").await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_stale_statement_shows_58_70_from_its_last_superseded_chunk() -> anyhow::Result<()> { + with_fixture("role-word-stale-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + supersede(&pool, f.chunk_a, "2026-03-01").await?; + supersede(&pool, f.chunk_b, "2026-04-01").await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_deleted_documents_chunk_is_dated_by_its_deleted_at() -> anyhow::Result<()> { + with_fixture("role-word-deleted-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + supersede(&pool, f.chunk_a, "2026-03-01").await?; + sqlx::query("UPDATE documents SET deleted_at = now() WHERE kb_id = $1") + .bind(f.kb) + .execute(&pool) + .await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_restored_document_lets_its_live_chunk_speak_58_70_alone_again() -> anyhow::Result<()> { + with_fixture("role-word-restored-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + supersede(&pool, f.chunk_a, "2026-03-01").await?; + let deleted_at = |at: Option<&'static str>| { + sqlx::query("UPDATE documents SET deleted_at = $2::timestamptz WHERE kb_id = $1") + .bind(f.kb) + .bind(at) + .execute(&pool) + }; + // 删在取代之前:两块同一刻到头,都说话 + deleted_at(Some("2026-02-01")).await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("40-52", f.chunk_a), lines("58-70", f.chunk_b)] + ); + deleted_at(None).await?; + assert_eq!( + speaking(&pool, fact).await?, + vec![lines("58-70", f.chunk_b)] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_stale_read_as_of_february_shows_40_52_before_the_latest_chunk_existed( +) -> anyhow::Result<()> { + with_fixture("role-word-stale-as-of-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + sqlx::raw_sql(&format!( + "UPDATE documents SET created_at = '2026-01-01' WHERE kb_id = '{kb}'; + UPDATE chunks SET created_at = '2026-01-01', superseded_at = '2026-02-01' + WHERE id = '{a}'; + UPDATE chunks SET created_at = '2026-03-01', superseded_at = '2026-04-01' + WHERE id = '{b}';", + kb = f.kb, + a = f.chunk_a, + b = f.chunk_b, + )) + .execute(&pool) + .await?; + let as_of = "2026-02-15T00:00:00Z".parse::>()?; + let read = graph::statement_qualifiers_for(&pool, &[fact], Some(as_of)).await?; + assert_eq!( + read[&fact] + .iter() + .map(|q| q.value.clone()) + .collect::>(), + vec![Some(serde_json::json!("40-52"))] + ); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_read_as_of_february_shows_40_52_said_before_the_march_push() -> anyhow::Result<()> { + with_fixture("role-word-as-of-test", |pool, f| async move { + let fact = stated( + &pool, + &f, + &[(f.chunk_a, "lines", "40-52"), (f.chunk_b, "lines", "58-70")], + ) + .await?; + sqlx::raw_sql(&format!( + "UPDATE entities SET created_at = '2026-01-01' WHERE kb_id = '{kb}'; + UPDATE documents SET created_at = '2026-01-01' WHERE kb_id = '{kb}'; + UPDATE facts SET recorded_at = '2026-01-01' WHERE id = '{fact}'; + UPDATE chunks SET created_at = '2026-01-01', superseded_at = '2026-03-01' + WHERE id = '{a}'; + UPDATE chunks SET created_at = '2026-03-01' WHERE id = '{b}';", + kb = f.kb, + a = f.chunk_a, + b = f.chunk_b, + )) + .execute(&pool) + .await?; + let read_at = |as_of: Option<&str>| { + let pool = pool.clone(); + let as_of = as_of.map(|t| t.parse::>().unwrap()); + async move { + let (_, facts) = graph::entity_detail(&pool, f.kb, f.acme, None, as_of).await?; + let row = facts + .into_iter() + .find(|x| x.id == fact) + .expect("the statement"); + anyhow::Ok( + row.statement_qualifiers + .into_iter() + .map(|q| q.value) + .collect::>(), + ) + } + }; + assert_eq!( + read_at(Some("2026-02-01T00:00:00Z")).await?, + vec![Some(serde_json::json!("40-52"))] + ); + assert_eq!(read_at(None).await?, vec![Some(serde_json::json!("58-70"))]); + Ok(()) + }) + .await +} diff --git a/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md b/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md index 9abc926cd..14f6683b7 100644 --- a/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md +++ b/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md @@ -1,6 +1,6 @@ # 0070 · A role word speaks while its chunk is live -- **Status**: In progress · 2026-10-25 · [#1267](https://github.com/deeplethe/utopia/issues/1267) · decision 1 built (migration 0121) · open: decisions 2 to 4 +- **Status**: In progress · 2026-10-25 · [#1267](https://github.com/deeplethe/utopia/issues/1267) · decision 1 built (migration 0121), decisions 2 and 3 built (`record_axis::role_word_speaks_given`, the three `mood` checks included) · open: decision 4 - **Written**: 2026-10-16 (conventions in the [README](README.md)) - **Related**: [0037](0037-a-relation-carries-its-own-attributes.md) decided that a qualifier is not part of a fact's identity and that the first value stays; [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) owns the open statement and the role words on it; [0054](0054-a-source-may-push-statements-in-the-open-contract.md) decision 7 is the re-push that supersedes a chunk; migration `0061` created `statement_qualifiers`; [0048](0048-provenance-references-stay-inside-the-knowledge-base.md) gets one more edge to keep inside the base; [0019](0019-the-second-clock-can-be-rewound.md) is the record axis `as_of` reads on; [#1267](https://github.com/deeplethe/utopia/issues/1267), [#1272](https://github.com/deeplethe/utopia/issues/1272) diff --git a/docs/design/ledger.md b/docs/design/ledger.md index ab78135d3..35e684a20 100644 --- a/docs/design/ledger.md +++ b/docs/design/ledger.md @@ -36,7 +36,7 @@ declared attribute for typed rows, converted by the attribute's datatype, the un text (`$4 billion` becomes 4000000000 with unit `$`) and the declared unit only when the text carries none; a qualifier is not part of the edge's identity; every superseding writer copies qualifiers with the evidence [0037, #731]. Entity detail, graph edges and the MCP `entity_facts` -tool return both: typed ones in `qualifiers`, role words in `statement_qualifiers` [#1267]. +tool return both: typed ones in `qualifiers`, role words in `statement_qualifiers`, each with the live chunks that say it [#1267, 0070]. `time_mentions (fact, chunk, text, char_start)` hold verbatim time words [#731]. Names are value facts on `known_as` [0041]. `entities.description` marks a described, unnamed thing [#731]. diff --git a/web/src/api.ts b/web/src/api.ts index 65c5d15c0..0d94044a5 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1123,6 +1123,8 @@ export interface StatementQualifier { value: unknown | null; entity_id: string | null; entity_name: string | null; + /** 说这个值的那几块(0070):两块活着的块说法不同,各自一条 */ + chunk_ids: string[]; } export interface EntityFact { diff --git a/web/src/docs/mcp.md b/web/src/docs/mcp.md index 3f2eded6b..e8958e7e1 100644 --- a/web/src/docs/mcp.md +++ b/web/src/docs/mcp.md @@ -143,7 +143,9 @@ unaccepted predicate name; it does **not** mean the fact is derived. `qualifier_type_id`, `key`, `label`, raw `value`, `entity_id`, and `entity_name`. `statement_qualifiers[]` holds the document's own role words for the statement (such as `amount` or `lines`), which are not declared attributes: each has `role`, -raw `value`, `entity_id`, and `entity_name`. +raw `value`, `entity_id`, `entity_name`, and the `chunk_ids` that say it. Only +chunks live at the read's time speak, so a re-pushed value replaces the old one; +two live chunks that disagree give two entries. A `derived_facts[]` entry contains `id`, `subject_id`, `subject`, `predicate_id`, `predicate`, `object_id`, `object`, raw `object_value`, `rule`, `rule_name`,