From 6e29f79c8bd0bcd2aeaf31ade817ab09f75ac4fb Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Tue, 17 Nov 2026 14:29:26 +0100 Subject: [PATCH] A document waits for one queued extraction, and the repeats already queued are removed Signed-off-by: Bogdan Szabo --- crates/utopia-cli/src/main.rs | 2 +- crates/utopia-server/src/pipeline.rs | 4 +- crates/utopia-store/src/documents.rs | 3 +- crates/utopia-store/src/jobs.rs | 40 +++++++++ .../a_document_waits_for_one_extraction.rs | 68 ++++++++++++++++ ..._extraction_is_queued_once_per_document.rs | 81 +++++++++++++++++++ crates/utopia-store/tests/store/main.rs | 3 + ...009-a-document-waits-for-one-extraction.md | 27 +++++++ ...11_a_document_waits_for_one_extraction.sql | 14 ++++ 9 files changed, 237 insertions(+), 5 deletions(-) create mode 100644 crates/utopia-store/tests/a_document_waits_for_one_extraction.rs create mode 100644 crates/utopia-store/tests/store/an_extraction_is_queued_once_per_document.rs create mode 100644 docs/decisions/re-cinq/RC-009-a-document-waits-for-one-extraction.md create mode 100644 migrations/9011_a_document_waits_for_one_extraction.sql diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index cab11f942..63adfc732 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 = 124; +const CURRENT_SCHEMA_VERSION: u32 = 125; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/crates/utopia-server/src/pipeline.rs b/crates/utopia-server/src/pipeline.rs index 2db5f5472..74032fcb8 100644 --- a/crates/utopia-server/src/pipeline.rs +++ b/crates/utopia-server/src/pipeline.rs @@ -311,14 +311,14 @@ pub async fn memory_ingest( if settings.as_ref().is_some_and(|s| s.chat_ready()) { utopia_store::documents::set_graph_status(&state.pool, document_id, "queued").await?; - utopia_store::jobs::enqueue( + utopia_store::jobs::enqueue_extraction( &state.pool, - "extract_document", serde_json::json!({ "document_id": document_id, "proposed_by": proposer.user_id, "proposed_token": proposer.token_id, }), + 3, ) .await?; } diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs index 1dd499cc9..90e8cd4d3 100644 --- a/crates/utopia-store/src/documents.rs +++ b/crates/utopia-store/src/documents.rs @@ -1095,9 +1095,8 @@ pub async fn finish_processing_if_current( .execute(&mut *tx) .await?; if graph_status == Some("queued") { - crate::jobs::enqueue_with_max_attempts_tx( + crate::jobs::enqueue_extraction_tx( &mut tx, - "extract_document", serde_json::json!({ "document_id": input.document.id }), 3, ) diff --git a/crates/utopia-store/src/jobs.rs b/crates/utopia-store/src/jobs.rs index fbfe48aeb..8ca4cf8d0 100644 --- a/crates/utopia-store/src/jobs.rs +++ b/crates/utopia-store/src/jobs.rs @@ -187,6 +187,46 @@ pub async fn enqueue_with_max_attempts_tx( Ok(id) } +/// 排一份 `extract_document`,除非同一篇文档已经有一份排着(RC-009)。 +/// +/// 抽取只带文档 id、跑的时候读当下的块,所以排着的第二份读到的和第一份一样;按 +/// `document_id` 比而不按整份载荷,两处入队的载荷不同。在跑的那份不算:它可能在新版本 +/// 写入之前就读完了。返回 `None` = 并进了排着的那份。 +pub async fn enqueue_extraction( + pool: &PgPool, + payload: serde_json::Value, + max_attempts: i32, +) -> AppResult> { + let mut tx = pool.begin().await?; + let id = enqueue_extraction_tx(&mut tx, payload, max_attempts).await?; + tx.commit().await?; + Ok(id) +} + +/// 同 [`enqueue_extraction`],排在调用方的事务里。 +pub async fn enqueue_extraction_tx( + tx: &mut Transaction<'_, Postgres>, + payload: serde_json::Value, + max_attempts: i32, +) -> AppResult> { + let row: Option<(i64,)> = sqlx::query_as( + "INSERT INTO jobs (kind, payload, max_attempts) + SELECT 'extract_document', $1, $2 + WHERE NOT EXISTS (SELECT 1 FROM jobs + WHERE kind = 'extract_document' AND status = 'queued' + AND payload->>'document_id' = $1->>'document_id') + RETURNING id", + ) + .bind(payload) + .bind(max_attempts) + .fetch_optional(&mut **tx) + .await?; + if row.is_some() { + notify_worker_tx(tx).await?; + } + Ok(row.map(|(id,)| id)) +} + /// 同 [`enqueue_with_max_attempts_tx`],但 `after` 之后才到期。从插入这一刻 /// (`clock_timestamp()`)算起:`now()` 是事务开始的时刻,事务长了,提交时延迟已经用掉 pub async fn enqueue_with_max_attempts_after_tx( diff --git a/crates/utopia-store/tests/a_document_waits_for_one_extraction.rs b/crates/utopia-store/tests/a_document_waits_for_one_extraction.rs new file mode 100644 index 000000000..0fcb323ca --- /dev/null +++ b/crates/utopia-store/tests/a_document_waits_for_one_extraction.rs @@ -0,0 +1,68 @@ +//! RC-009:迁移 9011 删掉同一篇文档排着的重复抽取,留最早那份,在跑的不动,别的文档不动。 +//! +//! 这条 DELETE 不按 kb 过滤、看全库排着的抽取,所以自成一个二进制(为什么见 `store/main.rs`)。 + +use sqlx::PgPool; +use uuid::Uuid; + +const MIGRATION: &str = + include_str!("../../../migrations/9011_a_document_waits_for_one_extraction.sql"); + +async fn queue(pool: &PgPool, document: Uuid, status: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "INSERT INTO jobs (kind, payload, status) VALUES ('extract_document', $1, $2) RETURNING id", + ) + .bind(serde_json::json!({ "document_id": document })) + .bind(status) + .fetch_one(pool) + .await?) +} + +async fn jobs_of(pool: &PgPool, document: Uuid) -> anyhow::Result> { + Ok(sqlx::query_as( + "SELECT id, status FROM jobs + WHERE kind = 'extract_document' AND payload->>'document_id' = $1 ORDER BY id", + ) + .bind(document.to_string()) + .fetch_all(pool) + .await?) +} + +#[tokio::test] +async fn the_repeats_queued_for_one_document_are_removed_keeping_the_oldest() -> anyhow::Result<()> +{ + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let (busy, alone) = (Uuid::now_v7(), Uuid::now_v7()); + let running = queue(&pool, busy, "running").await?; + let oldest = queue(&pool, busy, "queued").await?; + queue(&pool, busy, "queued").await?; + queue(&pool, busy, "queued").await?; + let single = queue(&pool, alone, "queued").await?; + + sqlx::raw_sql(MIGRATION).execute(&pool).await?; + sqlx::raw_sql(MIGRATION).execute(&pool).await?; + let kept = (jobs_of(&pool, busy).await?, jobs_of(&pool, alone).await?); + + sqlx::query( + "DELETE FROM jobs WHERE kind = 'extract_document' AND payload->>'document_id' IN ($1, $2)", + ) + .bind(busy.to_string()) + .bind(alone.to_string()) + .execute(&pool) + .await?; + pool.close().await; + assert_eq!( + kept, + ( + vec![ + (running, "running".to_string()), + (oldest, "queued".to_string()) + ], + vec![(single, "queued".to_string())], + ) + ); + Ok(()) +} diff --git a/crates/utopia-store/tests/store/an_extraction_is_queued_once_per_document.rs b/crates/utopia-store/tests/store/an_extraction_is_queued_once_per_document.rs new file mode 100644 index 000000000..178b20a8d --- /dev/null +++ b/crates/utopia-store/tests/store/an_extraction_is_queued_once_per_document.rs @@ -0,0 +1,81 @@ +//! RC-009:一篇文档排着一份抽取时,再变一次不再多排一份。 +//! +//! `extract_document` 只带文档 id,跑的时候读文档当下的块,所以同一篇排着的第二份读到的和 +//! 第一份一模一样。两处入队的载荷不同(一处多带提议人),按 `document_id` 比,不按整份载荷。 +//! 在跑的那份不算:它可能在新版本到之前就读完了,新版本得有自己的一次。 + +use sqlx::PgPool; +use utopia_store::jobs; +use uuid::Uuid; + +async fn queued_for(pool: &PgPool, document: Uuid) -> anyhow::Result> { + Ok(sqlx::query_scalar( + "SELECT status FROM jobs + WHERE kind = 'extract_document' AND payload->>'document_id' = $1 ORDER BY id", + ) + .bind(document.to_string()) + .fetch_all(pool) + .await?) +} + +async fn clean(pool: &PgPool, document: Uuid) -> anyhow::Result<()> { + sqlx::query( + "DELETE FROM jobs WHERE kind = 'extract_document' AND payload->>'document_id' = $1", + ) + .bind(document.to_string()) + .execute(pool) + .await?; + Ok(()) +} + +#[tokio::test] +async fn a_second_change_while_its_extraction_waits_queues_nothing() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let document = Uuid::now_v7(); + + let first = + jobs::enqueue_extraction(&pool, serde_json::json!({ "document_id": document }), 3).await?; + let second = jobs::enqueue_extraction( + &pool, + serde_json::json!({ "document_id": document, "proposed_by": null, "proposed_token": null }), + 3, + ) + .await?; + let statuses = queued_for(&pool, document).await?; + + clean(&pool, document).await?; + pool.close().await; + assert!(first.is_some()); + assert_eq!((second, statuses), (None, vec!["queued".to_string()])); + Ok(()) +} + +#[tokio::test] +async fn a_change_while_its_extraction_runs_queues_one_more() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + let document = Uuid::now_v7(); + let payload = serde_json::json!({ "document_id": document }); + + jobs::enqueue_extraction(&pool, payload.clone(), 3).await?; + sqlx::query( + "UPDATE jobs SET status = 'running', locked_at = now() + WHERE kind = 'extract_document' AND payload->>'document_id' = $1", + ) + .bind(document.to_string()) + .execute(&pool) + .await?; + let again = jobs::enqueue_extraction(&pool, payload, 3).await?; + let statuses = queued_for(&pool, document).await?; + + clean(&pool, document).await?; + pool.close().await; + assert!(again.is_some()); + assert_eq!(statuses, vec!["running".to_string(), "queued".to_string()]); + Ok(()) +} diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs index f4c6c12cb..91c765828 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -22,6 +22,8 @@ //! 过滤——修正行、重复行都按全库找,会改到别的测试正在物化、改写的行。 //! - `a_row_a_rule_implied_follows_its_statements`:把迁移 0101 原样跑一遍,同样不按 kb //! 过滤——它按来源重算全库类型化行的见证,会改到别的测试正在物化的行。 +//! - `a_document_waits_for_one_extraction`:把迁移 9011 原样跑一遍,它删全库排着的重复抽取, +//! 不按 kb 过滤,会删掉别的测试正排着的抽取。 //! - `a_due_base_is_queued_once`:`queue_due_inferences` 扫全库到期的库。0050 起新建的库开着 //! 推理又从没推过,别的测试刚建的库全算到期,会被它排上推理任务——数自己库任务的测试 //! (比如 lib 单元测试里的 `phrase_bindings_delivery_tests`)就会多数出一个。 @@ -135,6 +137,7 @@ mod an_evicted_document_is_remembered_until_it_is_restored; mod an_exact_name_search_returns_only_that_entity; mod an_exploration_says_what_it_covered; mod an_export_carries_the_whole_ledger; +mod an_extraction_is_queued_once_per_document; mod an_identity_name_attaches_by_its_exact_name; mod an_instance_list_names_what_a_type_lacks; mod an_old_version_keeps_no_vector; diff --git a/docs/decisions/re-cinq/RC-009-a-document-waits-for-one-extraction.md b/docs/decisions/re-cinq/RC-009-a-document-waits-for-one-extraction.md new file mode 100644 index 000000000..6516c1f03 --- /dev/null +++ b/docs/decisions/re-cinq/RC-009-a-document-waits-for-one-extraction.md @@ -0,0 +1,27 @@ +# RC-009 · A document waits for one extraction + +> re:cinq fork only. Status: accepted 2026-11-17. Upstream: proposed in [deeplethe/utopia#1514](https://github.com/deeplethe/utopia/issues/1514). + +## Context + +`extract_document` carries a document id and nothing that says which version to read: the extraction reads the document's current chunks when it runs. Nothing checked for a job already waiting when one was enqueued, so a document that changed three times while the queue was behind got three jobs, and the second and third read exactly what the first read. + +On our instance on 2026-11-17, 29,493 `extract_document` jobs were queued for 12,986 documents. A mirror re-pushes its statements items after every merge, and each extraction there costs about 75 s of entity matching, so the repeats held new uploads about two days behind. + +Two places enqueue the job, `documents::finish_processing_if_current` with `{document_id}` and the memory re-embed in `pipeline.rs` with `{document_id, proposed_by, proposed_token}`. `enqueue_unless_queued` compares the whole payload, so it would not see one as a repeat of the other. + +## Decision + +**A document has at most one queued `extract_document` job.** `jobs::enqueue_extraction` (and `_tx`) inserts the job only when no job of that kind with the same `payload->>'document_id'` is `queued`, and both sites use it. A `running` job does not count: it may have read the chunks before the new version was written, so a change while it runs still queues one more. + +**The first queued job keeps its payload.** A later push folded into it does not replace the proposer it names. Every push to one base comes through one source token on both sites today, so no attribution is lost there. + +**The check has an index.** Migration `9011` adds `jobs_queued_extraction_document`, a partial index on `(payload->>'document_id') WHERE kind = 'extract_document' AND status = 'queued'`, so the check reads one entry however long the queue is. + +**The repeats already queued are removed once.** The same migration deletes every queued `extract_document` job that has an older queued job for the same document, keeping the oldest, so each document keeps its place in the queue. Running it again deletes nothing. + +## Consequences + +- A busy queue does each document's extraction once for the version current when it runs, instead of once per change. +- A job can no longer be queued for a document "on top" of a waiting one to force a second read. Re-reading the same chunks would change nothing, so nothing needs that. +- Other job kinds keep their own enqueue rules; this record covers `extract_document` only. diff --git a/migrations/9011_a_document_waits_for_one_extraction.sql b/migrations/9011_a_document_waits_for_one_extraction.sql new file mode 100644 index 000000000..cfd575eda --- /dev/null +++ b/migrations/9011_a_document_waits_for_one_extraction.sql @@ -0,0 +1,14 @@ +-- RC-009: a document has at most one queued extract_document job. The index keeps the check +-- in jobs::enqueue_extraction cheap; the delete removes the repeats queued before it, keeping +-- each document's oldest job so it keeps its place. Running this again changes nothing. + +CREATE INDEX IF NOT EXISTS jobs_queued_extraction_document + ON jobs ((payload->>'document_id')) + WHERE kind = 'extract_document' AND status = 'queued'; + +DELETE FROM jobs later + USING jobs earlier + WHERE later.kind = 'extract_document' AND later.status = 'queued' + AND earlier.kind = 'extract_document' AND earlier.status = 'queued' + AND earlier.payload->>'document_id' = later.payload->>'document_id' + AND earlier.id < later.id;