Skip to content

World's first open-source enterprise world model.

A deleted document's date no longer attests: each piece of evidence records when its passage speaks, and attestation is rebuilt from what remains (#1059)

WaylandYang741ca15dc9e3
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 28ac45de..58515eb0 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 = 94;
+const CURRENT_SCHEMA_VERSION: u32 = 95;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-server/src/time_attestation_tests.rs b/crates/utopia-server/src/time_attestation_tests.rs
index 81d9bd8f..de4de89f 100644
--- a/crates/utopia-server/src/time_attestation_tests.rs
+++ b/crates/utopia-server/src/time_attestation_tests.rs
@@ -201,6 +201,68 @@ async fn section_dates_reconcile_values_materialized_before_attestation() -> any
run
}
+/// 每条证据记下它那一节的日期和名字,没说日期的那一节记成空;文档再解析时一条日期都没说,
+/// 上一遍记下的清掉。删文档之后按还在的证据重算见证(`documents::reattest_tx`)读的就是这两列
+#[tokio::test]
+async fn each_piece_of_evidence_records_the_date_its_section_speaks_from() -> anyhow::Result<()> {
+ let Some(fixture) = fixture().await? else {
+ return Ok(());
+ };
+ let pool = &fixture.state.pool;
+ let run = async {
+ let (earlier, _) = chapter(&fixture, 0, "Earlier", "desk", None).await?;
+ let (later, _) = chapter(&fixture, 1, "Later", "shelf", None).await?;
+ let (appendix, _) = chapter(&fixture, 2, "Appendix", "floor", None).await?;
+ let context: DocumentDating = serde_json::from_value(json!({"entries": [
+ {"kind":"now","name":"Report date","words":"2015-01-01",
+ "from":{"year":2015,"month":1,"day":1},"scope":["Earlier"]},
+ {"kind":"now","name":"","words":"2026-01-01",
+ "from":{"year":2026,"month":1,"day":1},"scope":["Later"]}
+ ]}))?;
+ let doc = utopia_store::documents::get(pool, fixture.doc).await?;
+ attest_statements(&fixture.state, &doc, &context).await?;
+ type Witness = (Option<DateTime<Utc>>, Option<String>);
+ let witness = |statement: Uuid| async move {
+ sqlx::query_as::<_, Witness>(
+ "SELECT attested_at, attested_by FROM fact_evidence WHERE fact_id=$1",
+ )
+ .bind(statement)
+ .fetch_one(pool)
+ .await
+ };
+ assert_eq!(
+ witness(earlier).await?,
+ (Some(day(2015)), Some("Report date 2015-01-01".into()))
+ );
+ assert_eq!(
+ witness(later).await?,
+ (Some(day(2026)), Some("2026-01-01".into()))
+ );
+ assert_eq!(
+ witness(appendix).await?,
+ (None, None),
+ "no date governs this section"
+ );
+
+ let silent: DocumentDating = serde_json::from_value(json!({"entries": []}))?;
+ attest_statements(&fixture.state, &doc, &silent).await?;
+ for statement in [earlier, later, appendix] {
+ assert_eq!(
+ witness(statement).await?,
+ (None, None),
+ "the document now states no date"
+ );
+ }
+ anyhow::Ok(())
+ }
+ .await;
+ sqlx::query("DELETE FROM organizations WHERE id=$1")
+ .bind(fixture.org)
+ .execute(pool)
+ .await?;
+ run
+}
+
#[tokio::test]
async fn current_context_does_not_reattest_superseded_chunks() -> anyhow::Result<()> {
let Some(fixture) = fixture().await? else {
diff --git a/crates/utopia-server/src/time_resolution.rs b/crates/utopia-server/src/time_resolution.rs
index fb6a6317..ece296b1 100644
--- a/crates/utopia-server/src/time_resolution.rs
+++ b/crates/utopia-server/src/time_resolution.rs
@@ -652,12 +652,20 @@ async fn attest_statements(
doc: &utopia_core::models::Document,
context: &DocumentDating,
) -> anyhow::Result<()> {
+ let pool = &state.pool;
if !context.entries.iter().any(|e| e.kind == "now") {
+ // 这一遍文档一条日期都没说:上一遍记在证据上的也不算数了
+ sqlx::query(
+ "UPDATE fact_evidence SET attested_at = NULL, attested_by = NULL
+ WHERE document_id = $1 AND attested_at IS NOT NULL",
+ )
+ .bind(doc.id)
+ .execute(pool)
+ .await?;
return Ok(());
}
- let pool = &state.pool;
- let rows: Vec<(Uuid, String, Option<i32>)> = sqlx::query_as(
- "SELECT fe.fact_id, c.text, fe.quote_start
+ let rows: Vec<(Uuid, Uuid, String, Option<i32>)> = sqlx::query_as(
+ "SELECT fe.fact_id, fe.chunk_id, c.text, fe.quote_start
FROM fact_evidence fe
JOIN facts f ON f.id = fe.fact_id
JOIN chunks c ON c.id = fe.chunk_id
@@ -668,25 +676,35 @@ async fn attest_statements(
.fetch_all(pool)
.await?;
let mut moved = 0usize;
- for (fact_id, text, start) in rows {
+ for (fact_id, chunk_id, text, start) in rows {
let path = headings_at(&text, usize::try_from(start.unwrap_or(0)).unwrap_or(0));
- let Some(now) = now_in_force(&context.entries, &path) else {
- continue;
- };
- let Some((at, _)) = parts_to_time(&now.from) else {
+ let witness = now_in_force(&context.entries, &path).and_then(|now| {
+ let (at, _) = parts_to_time(&now.from)?;
+ let by = if now.name.is_empty() {
+ now.words.clone()
+ } else {
+ format!("{} {}", now.name, now.words)
+ };
+ Some((at, by))
+ });
+ // 每条证据记下自己这一节的日期(没说的记成空):事实上只留最早的那一个,证据所在
+ // 的文档删了之后要照还在的证据重算,得知道每一条各是哪天
+ utopia_store::graph::witness_evidence(
+ pool,
+ fact_id,
+ chunk_id,
+ witness.as_ref().map(|(at, by)| (*at, by.as_str())),
+ )
+ .await?;
+ let Some((at, by)) = witness else {
continue;
};
- let by = if now.name.is_empty() {
- now.words.clone()
- } else {
- format!("{} {}", now.name, now.words)
- };
if utopia_store::graph::attest_statement(pool, fact_id, at, &by).await? {
moved += 1;
}
}
// 已经物化出来的、规则算出来的类型化行跟着它们的陈述走
- let typed = utopia_store::materialize::sync_typed_attestation(pool, doc.kb_id).await?;
+ let typed = utopia_store::materialize::sync_typed_attestation(pool, doc.kb_id, None).await?;
// 见证动了的行换了它在唯一性时间线上的位置:只把这些行所在的时间线重算一遍,不是整个库
// ——每篇文档都把全库的时间线各开一个事务重算一遍,库一大就是每篇几千个事务。
// 先提交同步,再拿时间线锁,不在持有 UPDATE 行锁时等咨询锁(与物化提交后对账的顺序一致)
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
index c2567557..e28c91a1 100644
--- a/crates/utopia-store/src/documents.rs
+++ b/crates/utopia-store/src/documents.rs
@@ -1003,7 +1003,7 @@ pub async fn delete(
.await?;
let chunk_ids: Vec<Uuid> = chunks.into_iter().map(|(c,)| c).collect();
let fact_ids: Vec<Uuid> = facts.into_iter().map(|(f,)| f).collect();
- reattest_tx(&mut tx, &cited).await?;
+ reattest_tx(&mut tx, kb_id, &cited).await?;
crate::temporal::tidy_timelines_tx(&mut tx, kb_id, &timelines).await?;
let deletion_id = Uuid::now_v7();
sqlx::query(
@@ -1029,16 +1029,52 @@ pub async fn delete(
})
}
-/// 证据文档变了(删了一篇、撤销了删除),把这些事实的「最早证据日期」按还在的文档重算。
+/// 证据文档变了(删了一篇、撤销了删除),把这些事实的见证按还在的证据重算。
///
-/// 读路径拿它当没起点的事实从哪天起成立(`facts_holds_from`),引擎排时间线用的是同一个
-/// 日期(`temporal::DATED_AT`)。删掉最早那份文档之后引擎的锚点挪到了第二份,这里不跟着
-/// 挪的话,前任读到新锚点为止、它却还从旧日期读起,两段叠了一年(#679 第四轮评审)。
-/// 一份带日期的文档都不剩的,保留原值——那是别的来源(人写的)给的日期
-async fn reattest_tx(tx: &mut Transaction<'_, Postgres>, fact_ids: &[Uuid]) -> AppResult<()> {
+/// 读路径拿见证当没起点的事实从哪天起成立(`facts_holds_from`),引擎排时间线用的是同一个
+/// 日期(`temporal::DATED_AT`)。删掉最早那份文档之后,见证不跟着挪到还在的证据上的话,
+/// 前任读到新锚点为止、它却还从旧日期读起,两段叠了一年(#679 第四轮评审)。
+///
+/// 三种行,三个来处(0064 决定 3、5;0022 修订 2026-10-03):
+///
+/// - **开放陈述**:还在的证据里最早的那一条,连同那条日期的名字。每条证据记着它那段原文
+/// 说话的那一刻(`fact_evidence.attested_at`,时间解析写下的章节日期);没记的(这一列
+/// 之前写下的、那篇文档还没再解析过的)按文档自己的日期读,口径同从前的 `DATED_AT`。
+/// 还在的证据一条带日期的都没有,见证就是空——删掉的那篇文档的日期不再给它作证;
+/// - **跟着陈述走的类型化行**(物化出来的、规则算出来的):来源陈述里最早的那个见证,
+/// 和物化时同一句(`materialize::sync_typed_attestation`)。它们抄了陈述的证据,所以也在
+/// 这批里,时间线已经由调用方锁上;
+/// - **其余**(人写的、这套分层之前写下的):还在的文档里最早的文档日期;一份带日期的
+/// 文档都不剩的保留原值——那是别的来源(人写的)给的日期
+async fn reattest_tx(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ fact_ids: &[Uuid],
+) -> AppResult<()> {
if fact_ids.is_empty() {
return Ok(());
}
+ sqlx::query(
+ "UPDATE facts f SET attested_from = w.at, attested_by = w.by
+ FROM (SELECT DISTINCT ON (fe.fact_id) fe.fact_id,
+ COALESCE(fe.attested_at, own.at) AS at,
+ CASE WHEN fe.attested_at IS NOT NULL THEN fe.attested_by END AS by
+ FROM fact_evidence fe
+ JOIN documents d ON d.id = fe.document_id
+ LEFT JOIN document_versions v ON v.document_id = fe.document_id
+ AND v.version = fe.doc_version
+ CROSS JOIN LATERAL (
+ SELECT CASE WHEN d.doc_time_source IN ('content', 'source')
+ THEN COALESCE(v.doc_time, d.doc_time) END AS at) own
+ WHERE fe.fact_id = ANY($1) AND d.deleted_at IS NULL
+ ORDER BY fe.fact_id, COALESCE(fe.attested_at, own.at) NULLS LAST, fe.chunk_id) w
+ WHERE f.id = w.fact_id AND f.layer = 'open' AND f.invalidated_at IS NULL
+ AND (f.attested_from IS DISTINCT FROM w.at OR f.attested_by IS DISTINCT FROM w.by)",
+ )
+ .bind(fact_ids)
+ .execute(&mut **tx)
+ .await?;
+ crate::materialize::sync_typed_attestation(&mut **tx, kb_id, Some(fact_ids)).await?;
sqlx::query(
"UPDATE facts f SET attested_from = e.first
FROM (SELECT fe.fact_id, min(d.doc_time) AS first
@@ -1047,7 +1083,9 @@ async fn reattest_tx(tx: &mut Transaction<'_, Postgres>, fact_ids: &[Uuid]) -> A
JOIN documents d ON d.id = c.document_id
WHERE fe.fact_id = ANY($1) AND d.deleted_at IS NULL AND d.doc_time IS NOT NULL
GROUP BY fe.fact_id) e
- WHERE f.id = e.fact_id AND f.invalidated_at IS NULL
+ WHERE f.id = e.fact_id AND f.invalidated_at IS NULL AND f.layer <> 'open'
+ AND NOT (f.implied
+ OR EXISTS (SELECT 1 FROM typed_fact_sources ts WHERE ts.fact_id = f.id))
AND f.attested_from IS DISTINCT FROM e.first",
)
.bind(fact_ids)
@@ -1194,7 +1232,7 @@ async fn restore_tx(
.execute(&mut **tx)
.await?;
let touched: Vec<Uuid> = cited.iter().chain(&restored).copied().collect();
- reattest_tx(tx, &touched).await?;
+ reattest_tx(tx, kb_id, &touched).await?;
crate::temporal::tidy_timelines_tx(tx, kb_id, &timelines).await?;
sqlx::query("UPDATE document_deletions SET reverted_at = now() WHERE id = $1")
.bind(deletion_id)
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 5183313b..ec77e855 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -973,6 +973,32 @@ pub async fn attest_statement(
Ok(moved.rows_affected() > 0)
}
+/// 一条证据记下它那段原文说话的那一刻,连同那条日期的名字;那一节没说日期的记成空。
+///
+/// [`attest_statement`] 只把事实的见证往早挪,哪份证据给的、别的证据各是哪天都不留。证据
+/// 所在的文档删了、删除撤销了,事实的见证要照还在的证据重算(`documents::reattest_tx`),
+/// 靠的就是这里记下的每一条
+pub async fn witness_evidence(
+ pool: &PgPool,
+ fact_id: Uuid,
+ chunk_id: Uuid,
+ witness: Option<(chrono::DateTime<chrono::Utc>, &str)>,
+) -> AppResult<()> {
+ let (at, by) = witness.unzip();
+ sqlx::query(
+ "UPDATE fact_evidence SET attested_at = $3, attested_by = $4
+ WHERE fact_id = $1 AND chunk_id = $2
+ AND (attested_at IS DISTINCT FROM $3 OR attested_by IS DISTINCT FROM $4)",
+ )
+ .bind(fact_id)
+ .bind(chunk_id)
+ .bind(at)
+ .bind(by)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
/// 字面值宾语的事实(object_value 通道,问数映射首个消费者)。
/// 去重:同 (S,P) 且 object_value 完全相等的 live 事实只存一条。
#[allow(clippy::too_many_arguments)]
diff --git a/crates/utopia-store/src/materialize.rs b/crates/utopia-store/src/materialize.rs
index 57d7ebb7..d6d3af49 100644
--- a/crates/utopia-store/src/materialize.rs
+++ b/crates/utopia-store/src/materialize.rs
@@ -420,7 +420,7 @@ async fn materialize_in_tx(
// 用的写入口在陈述没有见证时填的是此刻(那是给人写的事实用的缺省),这里改回陈述的。
// 排在 3a 之后:规则算出的行也是这样写下的
// 见证动了的已有行和新写下的行一起,提交后对账:见证是时间线排序用的时刻
- written.extend(sync_typed_attestation(&mut **tx, kb_id).await?);
+ written.extend(sync_typed_attestation(&mut **tx, kb_id, None).await?);
Ok((
Outcome {
retired,
@@ -445,9 +445,14 @@ async fn materialize_in_tx(
/// 回见证动了的那些行。见证是唯一性时间线给没起点的行排序用的时刻(`temporal::DATED_AT`),
/// 所以调用方提交之后要拿这些行去对账(`temporal::reconcile_moved_facts`)——只对这些行
/// 所在的时间线,不是整个库
+///
+/// 作废了的来源陈述不作证:物化自己会先把它们从来源里清掉,删文档那条路
+/// (`documents::reattest_tx`)却是在物化之前跑的,陈述刚随文档作废、来源表还没动。
+/// `only`:只动这些行(删文档时只动引用了那篇文档的,它们的时间线已经锁上);`None` 是整个库
pub async fn sync_typed_attestation<'e>(
ex: impl sqlx::Executor<'e, Database = sqlx::Postgres>,
kb_id: Uuid,
+ only: Option<&[Uuid]>,
) -> AppResult<Vec<Uuid>> {
let moved = sqlx::query_scalar(
"UPDATE facts t
@@ -463,10 +468,11 @@ pub async fn sync_typed_attestation<'e>(
SELECT i.fact_id, i.statement_id
FROM implied_fact_sources i
JOIN implication_rules r ON r.id = i.rule_id AND r.kb_id = $1) u
- LEFT JOIN facts s ON s.id = u.statement_id
+ LEFT JOIN facts s ON s.id = u.statement_id AND s.invalidated_at IS NULL
GROUP BY u.fact_id) src
WHERE t.id = src.fact_id AND t.kb_id = $1 AND t.layer = 'typed'
AND t.invalidated_at IS NULL
+ AND ($2::uuid[] IS NULL OR t.id = ANY($2))
AND (t.implied
OR EXISTS (SELECT 1 FROM typed_fact_sources ts WHERE ts.fact_id = t.id))
AND (t.attested_from IS DISTINCT FROM src.at
@@ -474,6 +480,7 @@ pub async fn sync_typed_attestation<'e>(
RETURNING t.id",
)
.bind(kb_id)
+ .bind(only)
.fetch_all(ex)
.await?;
Ok(moved)
diff --git a/crates/utopia-store/tests/store/a_deleted_document_no_longer_attests.rs b/crates/utopia-store/tests/store/a_deleted_document_no_longer_attests.rs
new file mode 100644
index 00000000..c9aff48b
--- /dev/null
+++ b/crates/utopia-store/tests/store/a_deleted_document_no_longer_attests.rs
@@ -0,0 +1,295 @@
+//! 证据所在的文档删了、删除撤销了,事实的见证照还在的证据重算(0064 决定 3、5;0022 修订
+//! 2026-10-03 留下的口子)。
+//!
+//! - 每条证据记着它那段原文说话的那一刻;删掉最早那篇,陈述的见证挪到还在的证据里最早的
+//! 那一节的日期上,连同名字——不是那篇文档的日期;
+//! - 还在的证据一条日期都没说,见证就是空:删掉的文档的日期不再给它作证;
+//! - 撤销删除,见证原样回来;
+//! - 没记章节日期的证据(这一列之前写下的)按文档自己的日期读,和从前一样;
+//! - 跟着陈述走的类型化行一起挪,随文档作废的来源陈述不再给它作证。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use chrono::{DateTime, TimeZone, Utc};
+use sqlx::PgPool;
+use utopia_store::graph::{self, FactObject};
+use uuid::Uuid;
+
+const ORG: &str = "deleted-document-no-longer-attests-test";
+
+fn day(y: i32, m: u32, d: u32) -> DateTime<Utc> {
+ Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).unwrap()
+}
+
+type Anchor = (Option<DateTime<Utc>>, Option<String>);
+/// 一条证据所在那一节的日期和它的名字;那一节没说日期就是 `None`
+type Witness<'a> = Option<(DateTime<Utc>, &'a str)>;
+
+async fn anchor(pool: &PgPool, fact: Uuid) -> anyhow::Result<Anchor> {
+ Ok(
+ sqlx::query_as("SELECT attested_from, attested_by FROM facts WHERE id = $1")
+ .bind(fact)
+ .fetch_one(pool)
+ .await?,
+ )
+}
+
+/// 一篇文档和它的一块正文。`own` 是文档自己的日期(正文说的),没有就是没说
+async fn document(
+ pool: &PgPool,
+ kb: Uuid,
+ own: Option<DateTime<Utc>>,
+) -> anyhow::Result<(Uuid, Uuid)> {
+ let (doc, chunk) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, filename, sha256, doc_time, doc_time_source)
+ VALUES ($1, $2, $3, $3, $4, $5)",
+ )
+ .bind(doc)
+ .bind(kb)
+ .bind(format!("doc-{doc}.md"))
+ .bind(own)
+ .bind(if own.is_some() { "content" } else { "none" })
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text) VALUES ($1, $2, $3, 0, $4)",
+ )
+ .bind(chunk)
+ .bind(kb)
+ .bind(doc)
+ .bind("# 年报\n码表所属市场为全球。")
+ .execute(pool)
+ .await?;
+ Ok((doc, chunk))
+}
+
+/// 一条开放陈述,证据在这几块里;`Some` 的那几条证据记着章节日期,陈述按最早的作证
+async fn statement(
+ pool: &PgPool,
+ kb: Uuid,
+ subject: Uuid,
+ object: Uuid,
+ phrase: &str,
+ evidence: &[(Uuid, Witness<'_>)],
+) -> anyhow::Result<Uuid> {
+ let (id, _) = graph::insert_open_statement(
+ pool,
+ kb,
+ subject,
+ phrase,
+ FactObject::Entity(object),
+ None,
+ 0.9,
+ )
+ .await?;
+ for (chunk, witness) in evidence {
+ graph::add_evidence(pool, id, *chunk, Some("码表所属市场为全球"), None).await?;
+ graph::witness_evidence(pool, id, *chunk, *witness).await?;
+ if let Some((at, by)) = witness {
+ graph::attest_statement(pool, id, *at, by).await?;
+ }
+ }
+ Ok(id)
+}
+
+/// 从这些陈述物化出来的一行类型化事实:记着来源,抄了它们的证据
+async fn typed(
+ pool: &PgPool,
+ kb: Uuid,
+ subject: Uuid,
+ object: Uuid,
+ predicate: Uuid,
+ sources: &[Uuid],
+) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, object_id, predicate_id, layer, from_statement_id)
+ VALUES ($1, $2, $3, $4, $5, 'typed', $6)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(subject)
+ .bind(object)
+ .bind(predicate)
+ .bind(sources[0])
+ .execute(pool)
+ .await?;
+ for source in sources {
+ sqlx::query("INSERT INTO typed_fact_sources (fact_id, statement_id) VALUES ($1, $2)")
+ .bind(id)
+ .bind(source)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version,
+ proposed_predicate, quote_start, quote_end)
+ SELECT $1, chunk_id, quote, document_id, doc_version, proposed_predicate,
+ quote_start, quote_end
+ FROM fact_evidence WHERE fact_id = $2
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(id)
+ .bind(source)
+ .execute(pool)
+ .await?;
+ }
+ utopia_store::materialize::sync_typed_attestation(pool, kb, None).await?;
+ Ok(id)
+}
+
+#[tokio::test]
+async fn attestation_follows_the_evidence_that_remains() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ sqlx::query("DELETE FROM organizations WHERE name = $1")
+ .bind(ORG)
+ .execute(&pool)
+ .await?;
+ let (org, ws, kb, watch, market, region, sold_in) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::raw_sql(&format!(
+ "INSERT INTO organizations(id,name) VALUES ('{org}','{ORG}');
+ INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','{ORG}');
+ INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','{ORG}');
+ INSERT INTO entities(id,kb_id,canonical_name) VALUES
+ ('{watch}','{kb}','码表'), ('{market}','{kb}','全球'), ('{region}','{kb}','欧洲');
+ INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description) VALUES
+ ('{sold_in}','{kb}','sold_in','sold in','relation','state','');"
+ ))
+ .execute(&pool)
+ .await?;
+
+ let run = async {
+ let (chapter_2015, chapter_2020) = (day(2015, 6, 1), day(2020, 6, 1));
+ let (by_2015, by_2020) = ("2015 年年报", "2020 年年报");
+ let late_own_date = day(2026, 3, 1);
+ // 早的那篇自己的日期是 2026 年 1 月,章节说的是 2015;晚的那篇 2026 年 3 月,章节说 2020;
+ // 第三篇什么日期都没说
+ let (early, early_chunk) = document(&pool, kb, Some(day(2026, 1, 10))).await?;
+ let (_late, late_chunk) = document(&pool, kb, Some(late_own_date)).await?;
+ let (_bare, bare_chunk) = document(&pool, kb, None).await?;
+ let from_2015 = Some((chapter_2015, by_2015));
+ let from_2020 = Some((chapter_2020, by_2020));
+
+ // 两篇都说过:最早的章节作证
+ let both = statement(
+ &pool,
+ kb,
+ watch,
+ market,
+ "所属市场为",
+ &[(early_chunk, from_2015), (late_chunk, from_2020)],
+ )
+ .await?;
+ // 另一处出处一个日期都没说
+ let beside_undated = statement(
+ &pool,
+ kb,
+ watch,
+ market,
+ "销往",
+ &[(early_chunk, from_2015), (bare_chunk, None)],
+ )
+ .await?;
+ // 只在早的那篇里:随它一起作废
+ let only_early = statement(
+ &pool,
+ kb,
+ watch,
+ region,
+ "所属市场为",
+ &[(early_chunk, from_2015)],
+ )
+ .await?;
+ // 这一列之前写下的证据:没记章节日期,见证是当时按文档日期给的
+ let legacy = statement(
+ &pool,
+ kb,
+ watch,
+ region,
+ "销往",
+ &[(early_chunk, None), (late_chunk, None)],
+ )
+ .await?;
+ sqlx::query("UPDATE facts SET attested_from = $2 WHERE id = $1")
+ .bind(legacy)
+ .bind(day(2026, 1, 10))
+ .execute(&pool)
+ .await?;
+ // 类型化的行:一行跟着两篇都说过的那条;一行的两个来源里有一个只在早的那篇里
+ let follows_both = typed(&pool, kb, watch, market, sold_in, &[both]).await?;
+ let late_only = statement(
+ &pool,
+ kb,
+ watch,
+ region,
+ "在售于",
+ &[(late_chunk, from_2020)],
+ )
+ .await?;
+ let mixed_sources = typed(&pool, kb, watch, region, sold_in, &[only_early, late_only]).await?;
+
+ let earliest: Anchor = (Some(chapter_2015), Some(by_2015.to_string()));
+ for fact in [both, beside_undated, follows_both, mixed_sources] {
+ assert_eq!(anchor(&pool, fact).await?, earliest, "before the deletion");
+ }
+
+ utopia_store::documents::delete(&pool, kb, early, None).await?;
+
+ let remaining: Anchor = (Some(chapter_2020), Some(by_2020.to_string()));
+ assert_eq!(
+ anchor(&pool, both).await?,
+ remaining,
+ "the chapter date of the evidence that remains, with its name, not that document's own date"
+ );
+ assert_eq!(
+ anchor(&pool, beside_undated).await?,
+ (None, None),
+ "what remains states no date: the deleted document's date no longer attests"
+ );
+ assert_eq!(
+ anchor(&pool, legacy).await?,
+ (Some(late_own_date), None),
+ "evidence with no recorded chapter date reads the document's own date, as before"
+ );
+ assert_eq!(anchor(&pool, follows_both).await?, remaining, "a typed row follows its statement");
+ let gone: Option<DateTime<Utc>> =
+ sqlx::query_scalar("SELECT invalidated_at FROM facts WHERE id = $1")
+ .bind(only_early)
+ .fetch_one(&pool)
+ .await?;
+ assert!(gone.is_some(), "a statement whose only source is deleted is invalidated");
+ assert_eq!(
+ anchor(&pool, mixed_sources).await?,
+ remaining,
+ "a source statement invalidated with the document no longer attests the typed row"
+ );
+
+ utopia_store::documents::restore(&pool, kb, early).await?;
+ for fact in [both, beside_undated, follows_both, mixed_sources] {
+ assert_eq!(anchor(&pool, fact).await?, earliest, "after the restore");
+ }
+ assert_eq!(
+ anchor(&pool, legacy).await?,
+ (Some(day(2026, 1, 10)), None),
+ "legacy evidence reads the earliest own date again"
+ );
+ anyhow::Ok(())
+ }
+ .await;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/store/a_statement_is_attested_by_what_its_document_says.rs b/crates/utopia-store/tests/store/a_statement_is_attested_by_what_its_document_says.rs
index fb413db6..b54cadd4 100644
--- a/crates/utopia-store/tests/store/a_statement_is_attested_by_what_its_document_says.rs
+++ b/crates/utopia-store/tests/store/a_statement_is_attested_by_what_its_document_says.rs
@@ -140,7 +140,7 @@ async fn an_unattested_statement_holds_at_every_moment_and_an_attested_one_from_
.execute(&pool)
.await?;
}
- utopia_store::materialize::sync_typed_attestation(&pool, kb).await?;
+ utopia_store::materialize::sync_typed_attestation(&pool, kb, None).await?;
assert_eq!(
anchor(&pool, typed).await?,
(Some(earlier_report), Some("提报日期 2026年8月28日".to_string()))
@@ -256,7 +256,7 @@ async fn a_row_a_rule_implies_follows_the_statement_it_read() -> anyhow::Result<
// 陈述后来由它所在那一节的日期作证,时间解析那条路:先给陈述作证,再同步类型化的行。
// 规则算出的行跟到那天,连同那条日期的名字;类别词那行没有陈述,照旧没有
assert!(graph::attest_statement(&pool, signed, signed_day, "签约日 2026年9月4日").await?);
- utopia_store::materialize::sync_typed_attestation(&pool, kb).await?;
+ utopia_store::materialize::sync_typed_attestation(&pool, kb, None).await?;
let followed = (Some(signed_day), Some("签约日 2026年9月4日".to_string()));
assert_eq!(anchor(&pool, by_rule).await?, followed);
assert!(!holds_at(&pool, by_rule, long_ago).await?);
diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs
index 7ae56bb4..565ef2f3 100644
--- a/crates/utopia-store/tests/store/main.rs
+++ b/crates/utopia-store/tests/store/main.rs
@@ -39,6 +39,7 @@ mod a_declaration_arrives_late;
mod a_declared_disjointness_keeps_names_apart;
mod a_deferred_job_does_not_spend_its_budget;
mod a_definition_can_be_written_by_hand;
+mod a_deleted_document_no_longer_attests;
mod a_deletion_is_an_event;
mod a_derivation_follows_the_second_clock;
mod a_described_thing_is_an_entity_without_a_name;
diff --git a/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md b/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
index 59b70bb1..ccedd0a4 100644
--- a/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
+++ b/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
@@ -90,7 +90,7 @@ Why not the document's date in `valid_from` / `valid_to` with a marker precision
>
> The ordering date is `min(doc_time)` over the row's evidence, counting only documents whose own date is known (`doc_time_source` of `content` or `source`). It is not `attested_from`, for the reason section 3 gives in reverse. An undated document anchors `attested_from` at the moment of recording, and ordering by that would read every start-less row as holding now, turning an ordinary "X, then Y from 2021" into a conflict. A row with no dated evidence has no place in the timeline; when it and another value are both open, the pair goes to a person, whichever arrived first. A start-less row whose text says it has ended is not placed by its evidence either: that date shows it ended by then, not that it held then. Evidence from a deleted document no longer places a row. The concern above about copied evidence does not bite here: a superseding row's evidence is the same documents, and the earliest of them is still the earliest date the row is known to hold.
>
-> > **Revised 2026-10-03 (#1054, after [0064](0064-extraction-reads-time-as-it-goes.md) cut 3): the ordering date is the row's attestation.** The reason given above no longer holds. Since migration 0100 an undated document leaves `attested_from` null instead of the moment of recording, and a statement is attested by the date its own section speaks from. Ordering by `min(doc_time)` then disagreed with the reads: two start-less statements under the 2015 and the 2026 chapters of one document shared the document's date, were read as simultaneous, and both stayed open, while the reads placed them eleven years apart. The engine now orders a start-less row by `attested_from`, the same anchor the reads use, and anchors the ended-unknown predecessor there. What stays: a row with no attestation has no place in the timeline and its pair goes to a person; an as-of is never written as a start; a row whose text says it has ended is not placed by its attestation. A typed row follows the attestation of its statements, and a row whose attestation moves has its timeline recomputed. An end the old engine drew from a document date the row no longer has a basis for is reopened through the supersedes ledger; stated ends are not touched. Not changed, and weaker than the rule above: when a document is deleted or restored, attestation is rebuilt from the dates of the documents that remain (`documents::reattest_tx`), not from chapter dates, and a row left with no dated document keeps the attestation it had, so there a deleted document's date can still place a row.
+> > **Revised 2026-10-03 (#1054, after [0064](0064-extraction-reads-time-as-it-goes.md) cut 3): the ordering date is the row's attestation.** The reason given above no longer holds. Since migration 0100 an undated document leaves `attested_from` null instead of the moment of recording, and a statement is attested by the date its own section speaks from. Ordering by `min(doc_time)` then disagreed with the reads: two start-less statements under the 2015 and the 2026 chapters of one document shared the document's date, were read as simultaneous, and both stayed open, while the reads placed them eleven years apart. The engine now orders a start-less row by `attested_from`, the same anchor the reads use, and anchors the ended-unknown predecessor there. What stays: a row with no attestation has no place in the timeline and its pair goes to a person; an as-of is never written as a start; a row whose text says it has ended is not placed by its attestation. A typed row follows the attestation of its statements, and a row whose attestation moves has its timeline recomputed. An end the old engine drew from a document date the row no longer has a basis for is reopened through the supersedes ledger; stated ends are not touched. When a document is deleted or restored, attestation is rebuilt from the evidence that remains (`documents::reattest_tx`, migration 0104): each piece of evidence records the date its own passage speaks from, a statement takes the earliest of those with its name, a typed row follows its statements, and a statement whose remaining evidence states no date has no attestation, so a deleted document's date no longer places a row. Evidence written before 0104 that has not been resolved again reads its document's own date, as the rule above had it.
>
> A value the text gives only relative to an event, such as a deadline of "45 days after the Trigger Date", has no calendar date. The extractor marks it `relative` (the model decides; the server matches no wording), and the server stores it as written. It is still the current value, so it closes the dated value before it in the same way, anchored at its own document. It is never compared or sorted as a date. An unflagged value that is not a date is still dropped as `attr_datatype`.
diff --git a/docs/design/time.md b/docs/design/time.md
index 04260713..0369d15a 100644
--- a/docs/design/time.md
+++ b/docs/design/time.md
@@ -26,7 +26,9 @@ bound is `valid_from` or else `attested_from`, the date the text of the row's ow
from, and null when the document states none [0064].
An ending with no date is not "still holds": `valid_to_precision = 'unknown'` with `attested_to`,
the date of the document that said it was over. An open end still reads as holds until told
-otherwise [0022]. Anchors are copied by every superseding writer and moved only earlier.
+otherwise [0022]. Anchors are copied by every superseding writer and moved only earlier, except
+when a document is deleted or restored: each piece of evidence records the date its passage speaks
+from, and attestation is rebuilt from the evidence that remains [0022 revised 2026-10-03].
**The temporal engine** (`temporal.rs`) works only on `state` relations declared functional or
inverse-functional. A new value closes the open one before it; an undated or dated ending closes
diff --git a/migrations/0104_an_evidence_row_says_when_its_passage_speaks.sql b/migrations/0104_an_evidence_row_says_when_its_passage_speaks.sql
new file mode 100644
index 00000000..3cf5b7cb
--- /dev/null
+++ b/migrations/0104_an_evidence_row_says_when_its_passage_speaks.sql
@@ -0,0 +1,27 @@
+-- 一条证据记下它那段原文说话的那一刻(0064 决定 3;0022 修订 2026-10-03 留下的口子)。
+--
+-- 陈述的见证是它所在那一节里文本说话的那一刻,一条陈述几份文档都说过时取最早的。这个
+-- 「最早」从前只记在事实上:哪份证据给的、别的证据各是哪天,都没留下。于是删掉一篇文档、
+-- 撤销一次删除时没法照章节重算,`documents::reattest_tx` 只能退回文档的日期,一份带日期的
+-- 文档都不剩时干脆留着原值——删掉的文档的日期还在给这条陈述排时间线。
+--
+-- 现在每条证据自己记着:时间解析给陈述作证时顺手写下这一节的日期和那条日期的名字。
+-- 证据所在的文档变了,事实的见证就是还在的证据里最早的那个,一条带日期的都不剩就是空。
+-- 只有开放陈述的证据有这两列的值;类型化的行跟着它的来源陈述走,抄过去的证据不带。
+ALTER TABLE fact_evidence ADD COLUMN attested_at TIMESTAMPTZ;
+ALTER TABLE fact_evidence ADD COLUMN attested_by TEXT;
+
+-- 已有的证据:事实的见证带着日期的名字时,名字出自哪篇文档的时间语境,那篇里的证据就是
+-- 给出这个见证的那一条。别的证据各是哪天这里算不出来(要读标题),留空——留空的按文档
+-- 自己的日期读,和这一列之前一样;那篇文档下次解析时间时补上。
+UPDATE fact_evidence fe
+ SET attested_at = f.attested_from, attested_by = f.attested_by
+ FROM facts f, documents d
+ WHERE f.id = fe.fact_id AND d.id = fe.document_id
+ AND f.layer = 'open' AND f.attested_from IS NOT NULL AND f.attested_by IS NOT NULL
+ AND jsonb_typeof(d.time_context -> 'entries') = 'array'
+ AND EXISTS (
+ SELECT 1 FROM jsonb_array_elements(d.time_context -> 'entries') e
+ WHERE e ->> 'kind' = 'now'
+ AND f.attested_by = CASE WHEN COALESCE(e ->> 'name', '') = '' THEN e ->> 'words'
+ ELSE (e ->> 'name') || ' ' || (e ->> 'words') END);