From aa91d3949a9c6ce9340502a79486a88230b0f41f Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 17 Nov 2026 16:05:05 +0100 Subject: [PATCH] A deletion releases its source before reattesting the facts it touched Signed-off-by: Bogdan Szabo --- crates/utopia-server/src/main.rs | 14 ++ crates/utopia-store/src/documents.rs | 82 +++++++-- .../a_deletion_reattests_after_its_source.rs | 160 ++++++++++++++++++ crates/utopia-store/tests/store/main.rs | 1 + ...-releases-its-source-before-reattesting.md | 23 +++ 5 files changed, 269 insertions(+), 11 deletions(-) create mode 100644 crates/utopia-store/tests/store/a_deletion_reattests_after_its_source.rs create mode 100644 docs/decisions/re-cinq/RC-010-a-deletion-releases-its-source-before-reattesting.md diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs index e0a13c62e..8b14cfdb8 100644 --- a/crates/utopia-server/src/main.rs +++ b/crates/utopia-server/src/main.rs @@ -470,6 +470,20 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow } Ok(()) } + // RC-010:删除、撤销删除留下的见证重算,在来源行之外的事务里做 + "reattest_facts" => { + let kb_id: Uuid = job + .payload + .get("kb_id") + .and_then(|v| v.as_str()) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; + let fact_ids: Vec = + serde_json::from_value(job.payload.get("fact_ids").cloned().unwrap_or_default())?; + utopia_store::documents::reattest_facts(&st.pool, kb_id, &fact_ids).await?; + st.emit_graph(kb_id); + Ok(()) + } "extract_document" => { let id = payload_document_id(&job.payload)?; extraction::extract_document(st, id, payload_proposer(&job.payload)).await diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs index 90e8cd4d3..281eadb9c 100644 --- a/crates/utopia-store/src/documents.rs +++ b/crates/utopia-store/src/documents.rs @@ -56,7 +56,7 @@ pub async fn create_from_upload( .fetch_optional(&mut *tx) .await?; let document = if let Some(id) = deleted { - let document = restore_tx(&mut tx, kb_id, id).await?; + let (document, _) = restore_tx(&mut tx, kb_id, id).await?; crate::jobs::enqueue_with_max_attempts_tx( &mut tx, "process_document", @@ -1155,7 +1155,7 @@ pub async fn delete( // 作废的事实可能是别的值的后任:它走了,关在它开始时的前任要重新接上;没作废、只是 // 少了这份证据的,排序用的日期也可能变。牵连的时间线先按固定顺序锁上,再作废任何一行 // (与撤回合并同一个顺序,见 temporal 模块头) - let (cited, timelines) = lock_cited_timelines(&mut tx, kb_id, id, &[]).await?; + let (cited, _timelines) = lock_cited_timelines(&mut tx, kb_id, id, &[]).await?; // 先打了墓碑再算:这篇文档此刻已经算「已删除」,所以只剩它作出处的事实才落网; // 另一篇活着的文档里也有证据的一条不动——删一份重复上传不该掀掉半张图 let facts: Vec<(Uuid,)> = sqlx::query_as( @@ -1183,8 +1183,7 @@ pub async fn delete( .await?; let chunk_ids: Vec = chunks.into_iter().map(|(c,)| c).collect(); let fact_ids: Vec = facts.into_iter().map(|(f,)| f).collect(); - reattest_tx(&mut tx, kb_id, &cited).await?; - crate::temporal::tidy_timelines_tx(&mut tx, kb_id, &timelines).await?; + let reattest = defer_reattest_tx(&mut tx, kb_id, &cited).await?; let deletion_id = Uuid::now_v7(); sqlx::query( "INSERT INTO document_deletions @@ -1202,6 +1201,7 @@ pub async fn delete( .execute(&mut *tx) .await?; tx.commit().await?; + settle_reattest(pool, reattest).await?; Ok(DeletionReport { deletion_id, invalidated_facts: fact_ids.len(), @@ -1274,6 +1274,65 @@ async fn reattest_tx( Ok(()) } +/// 删除、撤销删除排下的见证重算(RC-010):事实 id 与那份任务。 +#[derive(Debug)] +pub struct DeferredReattest { + kb_id: Uuid, + fact_ids: Vec, + job_id: i64, +} + +/// 见证重算不在删除的事务里做(RC-010):那个事务从锁来源行开始,重算一篇引用上千条事实 +/// 的文档要几十秒,同一来源的每一次推送都排在这把锁后面。这里只排一份 `reattest_facts`, +/// 和作废一起提交——进程在提交之后退出,任务还在 +async fn defer_reattest_tx( + tx: &mut Transaction<'_, Postgres>, + kb_id: Uuid, + fact_ids: &[Uuid], +) -> AppResult> { + if fact_ids.is_empty() { + return Ok(None); + } + let job_id = crate::jobs::enqueue_with_max_attempts_tx( + tx, + "reattest_facts", + serde_json::json!({ "kb_id": kb_id, "fact_ids": fact_ids }), + 3, + ) + .await?; + Ok(Some(DeferredReattest { + kb_id, + fact_ids: fact_ids.to_vec(), + job_id, + })) +} + +/// 提交之后、来源行已经放开,当场把排下的重算做掉,返回时见证与时间线已经跟上,和从前 +/// 同一个承诺;做完撤掉还没被认领的那份任务。被 worker 先认领了也无妨:重算只写不同的值 +async fn settle_reattest(pool: &PgPool, deferred: Option) -> AppResult<()> { + let Some(deferred) = deferred else { + return Ok(()); + }; + reattest_facts(pool, deferred.kb_id, &deferred.fact_ids).await?; + sqlx::query("DELETE FROM jobs WHERE id = $1 AND status = 'queued'") + .bind(deferred.job_id) + .execute(pool) + .await?; + Ok(()) +} + +/// 这些事实的见证按还在的证据重算,它们的时间线随后理顺(`reattest_facts` 任务,RC-010)。 +/// 自己一个事务:先按固定顺序锁时间线(与删除同一个顺序),不碰来源行 +pub async fn reattest_facts(pool: &PgPool, kb_id: Uuid, fact_ids: &[Uuid]) -> AppResult<()> { + let mut tx = pool.begin().await?; + let timelines = crate::temporal::timelines_of(&mut *tx, kb_id, fact_ids, None).await?; + crate::temporal::lock_timelines(&mut tx, kb_id, &timelines).await?; + reattest_tx(&mut tx, kb_id, fact_ids).await?; + crate::temporal::tidy_timelines_tx(&mut tx, kb_id, &timelines).await?; + tx.commit().await?; + Ok(()) +} + /// 引用这篇文档的现存事实,连同它们所在的唯一性时间线,锁上之后返回。 /// /// **锁上之后再读一遍**(#679 第三轮评审):等锁的时候,时间线重算可能把其中一行改写成了 @@ -1325,8 +1384,9 @@ async fn lock_cited_timelines( /// 都不在名单里。三条路都从这里走:人点撤销、同步撞见墓碑、同内容重传 pub async fn restore(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult { let mut tx = pool.begin().await?; - let document = restore_tx(&mut tx, kb_id, id).await?; + let (document, reattest) = restore_tx(&mut tx, kb_id, id).await?; tx.commit().await?; + settle_reattest(pool, reattest).await?; Ok(document) } @@ -1334,7 +1394,7 @@ async fn restore_tx( tx: &mut Transaction<'_, Postgres>, kb_id: Uuid, id: Uuid, -) -> AppResult { +) -> AppResult<(Document, Option)> { lock_document_source_tx(tx, id).await?; // 文档和这次删除作废的事实共用同一个事务时间,清墓碑前先记住它。 let deleted_at = sqlx::query_scalar::<_, Option>>( @@ -1408,7 +1468,7 @@ async fn restore_tx( let restored: Vec = fact_ids.iter().chain(&shared_ids).copied().collect(); // 复活的事实回到各自的时间线上;一直引用着这篇文档的事实,排序用的日期也回来了。 // 先锁、再复活、再重算(同删除);等锁期间若又作废,不覆盖新的决定。 - let (cited, timelines) = lock_cited_timelines(tx, kb_id, id, &restored).await?; + let (cited, _timelines) = lock_cited_timelines(tx, kb_id, id, &restored).await?; sqlx::query( "UPDATE facts SET invalidated_at = NULL WHERE invalidated_at IS NOT NULL @@ -1422,16 +1482,16 @@ async fn restore_tx( .execute(&mut **tx) .await?; let touched: Vec = cited.iter().chain(&restored).copied().collect(); - reattest_tx(tx, kb_id, &touched).await?; - crate::temporal::tidy_timelines_tx(tx, kb_id, &timelines).await?; + let reattest = defer_reattest_tx(tx, kb_id, &touched).await?; sqlx::query("UPDATE document_deletions SET reverted_at = now() WHERE id = $1") .bind(deletion_id) .execute(&mut **tx) .await?; - Ok(sqlx::query_as("SELECT * FROM documents WHERE id = $1") + let document = sqlx::query_as("SELECT * FROM documents WHERE id = $1") .bind(id) .fetch_one(&mut **tx) - .await?) + .await?; + Ok((document, reattest)) } /// 一次真删的产出。`blobs` 是这篇(连同历史版本)独占的原文指纹——别处还引用的 diff --git a/crates/utopia-store/tests/store/a_deletion_reattests_after_its_source.rs b/crates/utopia-store/tests/store/a_deletion_reattests_after_its_source.rs new file mode 100644 index 000000000..a90d067c1 --- /dev/null +++ b/crates/utopia-store/tests/store/a_deletion_reattests_after_its_source.rs @@ -0,0 +1,160 @@ +//! RC-010:删除、撤销删除的见证重算不在锁着来源行的那个事务里做。 +//! +//! - `documents::delete` 返回时见证已经挪到还在的证据上,身后不留 `reattest_facts` 任务; +//! - 上传撞上墓碑、在调用方的事务里复活的文档,排下一份 `reattest_facts`,任务跑完见证才回来。 +//! +//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 + +use chrono::{DateTime, TimeZone, Utc}; +use sqlx::PgPool; +use utopia_store::graph::{self, FactObject}; +use uuid::Uuid; + +const ORG: &str = "deletion-reattests-after-its-source-test"; + +fn day(y: i32, m: u32, d: u32) -> DateTime { + Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).unwrap() +} + +async fn attested(pool: &PgPool, fact: Uuid) -> anyhow::Result>> { + Ok( + sqlx::query_scalar("SELECT attested_from FROM facts WHERE id = $1") + .bind(fact) + .fetch_one(pool) + .await?, + ) +} + +async fn queued_reattests(pool: &PgPool, kb: Uuid) -> anyhow::Result> { + Ok(sqlx::query_scalar( + "SELECT payload FROM jobs + WHERE kind = 'reattest_facts' AND status = 'queued' AND payload->>'kb_id' = $1", + ) + .bind(kb.to_string()) + .fetch_all(pool) + .await?) +} + +/// 一篇自己带日期的文档和它的一块正文;`sha256` 就是文件名,上传同名内容即撞上它 +async fn document(pool: &PgPool, kb: Uuid, own: DateTime) -> 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, 'content')", + ) + .bind(doc) + .bind(kb) + .bind(format!("doc-{doc}.md")) + .bind(own) + .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("码表所属市场为全球。") + .execute(pool) + .await?; + Ok((doc, chunk)) +} + +#[tokio::test] +async fn a_deletion_reattests_before_it_returns_and_an_upload_restore_queues_it( +) -> 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) = ( + 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}','全球');" + )) + .execute(&pool) + .await?; + + let run = async { + let (early, early_chunk) = document(&pool, kb, day(2020, 1, 1)).await?; + let (_late, late_chunk) = document(&pool, kb, day(2021, 1, 1)).await?; + let (fact, _) = graph::insert_open_statement( + &pool, + kb, + watch, + "所属市场为", + FactObject::Entity(market), + None, + 0.9, + ) + .await?; + for chunk in [early_chunk, late_chunk] { + graph::add_evidence(&pool, fact, chunk, Some("码表所属市场为全球"), None).await?; + } + utopia_store::documents::reattest_facts(&pool, kb, &[fact]).await?; + let before = attested(&pool, fact).await?; + + utopia_store::documents::delete(&pool, kb, early, None).await?; + let after_delete = ( + attested(&pool, fact).await?, + queued_reattests(&pool, kb).await?.len(), + ); + + let filename = format!("doc-{early}.md"); + utopia_store::documents::create_from_upload( + &pool, + kb, + &filename, + "text/markdown", + 1, + &filename, + None, + None, + ) + .await?; + let queued = queued_reattests(&pool, kb).await?; + let waiting = attested(&pool, fact).await?; + let fact_ids: Vec = serde_json::from_value(queued[0]["fact_ids"].clone())?; + utopia_store::documents::reattest_facts(&pool, kb, &fact_ids).await?; + let after_job = attested(&pool, fact).await?; + + anyhow::Ok((before, after_delete, queued.len(), waiting, after_job)) + } + .await; + + sqlx::query("DELETE FROM jobs WHERE kind IN ('reattest_facts', 'process_document') AND (payload->>'kb_id' = $1 OR payload->>'document_id' IN (SELECT id::text FROM documents WHERE kb_id = $2))") + .bind(kb.to_string()) + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(org) + .execute(&pool) + .await?; + pool.close().await; + let (before, after_delete, queued, waiting, after_job) = run?; + assert_eq!( + (before, after_delete, queued, waiting, after_job), + ( + Some(day(2020, 1, 1)), + (Some(day(2021, 1, 1)), 0), + 1, + Some(day(2021, 1, 1)), + Some(day(2020, 1, 1)), + ) + ); + Ok(()) +} diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs index 91c765828..a730fc15e 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -49,6 +49,7 @@ 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_deletion_reattests_after_its_source; mod a_derivation_follows_the_second_clock; mod a_described_thing_is_an_entity_without_a_name; mod a_dirty_ledger_stops_the_migration; diff --git a/docs/decisions/re-cinq/RC-010-a-deletion-releases-its-source-before-reattesting.md b/docs/decisions/re-cinq/RC-010-a-deletion-releases-its-source-before-reattesting.md new file mode 100644 index 000000000..431f2f158 --- /dev/null +++ b/docs/decisions/re-cinq/RC-010-a-deletion-releases-its-source-before-reattesting.md @@ -0,0 +1,23 @@ +# RC-010 · A deletion releases its source before reattesting + +> re:cinq fork only. Status: accepted 2026-11-17. Upstream: to be proposed as an issue first. + +## Context + +`documents::delete` and `restore_tx` open with `lock_document_source_tx`, which locks the document's `sources` row (`FOR UPDATE`), the ordering that keeps them from crossing a sync of the same source. In the same transaction they then recompute the attestation of every fact the document cites (`reattest_tx`) and tidy the timelines those facts sit on. For a document that cites many facts, that recompute takes tens of seconds. + +Every push to a statements source writes the same `sources` row (`start_run`, `finish_sync`). On our instance on 2026-11-17, a mirror's `POST …/missing/cleanup` was deleting the items it had tombstoned, one 34-second delete held the row, ten pushes to that source waited behind it, and the mirror's requests timed out. + +## Decision + +**The recompute leaves the transaction that holds the source row.** `delete` and `restore_tx` still invalidate or restore facts and lock the cited timelines as before, but where they recomputed they now enqueue one `reattest_facts` job, `{kb_id, fact_ids}`, committed with the invalidation, so a process that stops right after the commit still leaves the work queued. + +**`documents::reattest_facts` does the work in a transaction of its own.** It finds the facts' timelines, locks them in the usual order, recomputes attestation (`reattest_tx`), tidies the timelines, and commits. It never touches the source row. The tidy moves with the recompute because timelines are ordered by the attested dates. + +**A caller that owns its transaction runs it right after the commit.** `delete` and `restore` call it as soon as the source row is released and then remove the queued job if no worker has claimed it, so when they return, attestation and timelines are as current as they were before this record. A worker that claimed the job first runs it again, which writes nothing new. `restore_tx` inside a caller's transaction (an upload that meets a tombstone, a sync that revives an entry) leaves the job to the worker. + +## Consequences + +- A push no longer waits on a deletion's recompute; it waits only on the short invalidation. +- Between a deletion's commit and its recompute (milliseconds when `delete` runs it, one worker pass otherwise), a fact can still carry the date of the evidence just deleted, and a timeline can still show a predecessor closed by a row now invalidated. +- The job is idempotent: it computes from the evidence as it stands when it runs.