Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/utopia-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = 113;
const CURRENT_SCHEMA_VERSION: u32 = 114;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
Expand Down
3 changes: 1 addition & 2 deletions crates/utopia-server/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,8 @@ 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,
Expand Down
44 changes: 44 additions & 0 deletions crates/utopia-server/src/pipeline_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1486,3 +1486,47 @@ async fn a_memory_that_cannot_be_embedded_does_not_hold_back_the_others() -> any
assert_eq!(embedded, vec![true, false, true, true, true]);
f.cleanup().await
}

/// #1514:同一个提议人的两条记忆只排一份抽取;换了提议人,审核记到谁头上不能变,各排各的
#[tokio::test]
async fn a_memory_extraction_folds_only_for_the_same_proposer() -> anyhow::Result<()> {
let Some(f) = fixture(FakeEmbed::new(Duration::ZERO)).await? else {
return Ok(());
};
utopia_store::settings::upsert(
&f.pool,
f.ws,
Some("http://chat.invalid"),
None,
Some("fake-chat"),
None,
None,
None,
None,
)
.await?;
let doc = f.document_with_chunks(1).await?;
let (alice, bob) = (Uuid::now_v7(), Uuid::now_v7());
for user_id in [alice, alice, bob] {
let proposer = Proposer {
user_id: Some(user_id),
token_id: None,
};
super::memory_ingest(&f.state, doc, proposer).await?;
}
let proposers: Vec<String> = sqlx::query_scalar(
"SELECT payload->>'proposed_by' FROM jobs
WHERE kind = 'extract_document' AND payload->>'document_id' = $1 ORDER BY id",
)
.bind(doc.to_string())
.fetch_all(&f.pool)
.await?;
sqlx::query(
"DELETE FROM jobs WHERE kind = 'extract_document' AND payload->>'document_id' = $1",
)
.bind(doc.to_string())
.execute(&f.pool)
.await?;
assert_eq!(proposers, vec![alice.to_string(), bob.to_string()]);
f.cleanup().await
}
4 changes: 1 addition & 3 deletions crates/utopia-store/src/documents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1095,11 +1095,9 @@ 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,
)
.await?;
}
Expand Down
47 changes: 45 additions & 2 deletions crates/utopia-store/src/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,36 @@ pub async fn enqueue_with_max_attempts_tx(
Ok(id)
}

/// 排一份 `extract_document`,同一篇文档、同一个提议人已经有一份没动过的排着就不再排,
/// 返回 None = 并进了那一份。唯一索引 `jobs_one_queued_extraction_per_proposal` 挡着,
/// 两处同时排也不会各插一份。
pub async fn enqueue_extraction(
pool: &PgPool,
payload: serde_json::Value,
) -> AppResult<Option<i64>> {
let mut tx = pool.begin().await?;
let id = enqueue_extraction_tx(&mut tx, payload).await?;
tx.commit().await?;
Ok(id)
}

pub async fn enqueue_extraction_tx(
tx: &mut Transaction<'_, Postgres>,
payload: serde_json::Value,
) -> AppResult<Option<i64>> {
let row: Option<(i64,)> = sqlx::query_as(
"INSERT INTO jobs (kind, payload) VALUES ('extract_document', $1)
ON CONFLICT DO NOTHING RETURNING id",
)
.bind(payload)
.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(
Expand Down Expand Up @@ -302,6 +332,17 @@ const KB_SCOPE: &str = "(
SELECT 1 FROM sources s
WHERE s.id::text = j.payload->>'source_id' AND s.kb_id = $KB)))";

/// 失败的抽取排回去会撞 `jobs_one_queued_extraction_per_proposal`:同一篇文档、同一个提议人
/// 已经排着一份没动过的,或者还有更早失败的一份会先排回去。这样的不动,留在 failed——
/// 排着的那份读的是同样的块,留着也不丢活
const EXTRACTION_ALREADY_COVERED: &str = "j.kind = 'extract_document' AND EXISTS (
SELECT 1 FROM jobs o
WHERE o.kind = 'extract_document'
AND o.payload->>'document_id' = j.payload->>'document_id'
AND coalesce(o.payload->>'proposed_by', '') = coalesce(j.payload->>'proposed_by', '')
AND coalesce(o.payload->>'proposed_token', '') = coalesce(j.payload->>'proposed_token', '')
AND ((o.status = 'queued' AND o.attempts = 0) OR (o.status = 'failed' AND o.id < j.id)))";

/// 把范围内的 failed 任务放回队列:`attempts` 归零、立即到期。
///
/// RSS hydration is excluded: its source admission policy owns retries.
Expand All @@ -315,8 +356,10 @@ pub async fn requeue_failed(pool: &PgPool, scope: RequeueScope<'_>) -> AppResult
WHERE j.status = 'failed' AND j.kind <> 'hydrate_rss_entry'
AND ($1::text IS NULL OR j.kind = $1)
AND ($2::timestamptz IS NULL OR j.updated_at >= $2)
AND ($3::uuid IS NULL OR {})",
KB_SCOPE.replace("$KB", "$3")
AND ($3::uuid IS NULL OR {})
AND NOT ({})",
KB_SCOPE.replace("$KB", "$3"),
EXTRACTION_ALREADY_COVERED
);
let res = sqlx::query(&sql)
.bind(scope.kind)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! #1514: 迁移 0127 删掉同一篇文档、同一个提议人排着的重复抽取,留最早那份。
//!
//! 这条 DELETE 不按 kb 过滤、看全库排着的抽取,所以自成一个二进制(为什么见 `store/main.rs`)。

use sqlx::PgPool;
use uuid::Uuid;

const MIGRATION: &str =
include_str!("../../../migrations/0127_a_document_waits_for_one_queued_extraction.sql");

async fn queue(
pool: &PgPool,
document: Uuid,
proposer: Option<Uuid>,
status: &str,
attempts: i32,
) -> anyhow::Result<i64> {
Ok(sqlx::query_scalar(
"INSERT INTO jobs (kind, payload, status, attempts)
VALUES ('extract_document', $1, $2, $3) RETURNING id",
)
.bind(serde_json::json!({ "document_id": document, "proposed_by": proposer }))
.bind(status)
.bind(attempts)
.fetch_one(pool)
.await?)
}

#[tokio::test]
async fn the_repeats_queued_for_one_proposal_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 (document, alice, bob) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
sqlx::query("DROP INDEX IF EXISTS jobs_one_queued_extraction_per_proposal")
.execute(&pool)
.await?;
let oldest = queue(&pool, document, Some(alice), "queued", 0).await?;
let failed_before = queue(&pool, document, Some(alice), "queued", 1).await?;
let running = queue(&pool, document, Some(alice), "running", 0).await?;
queue(&pool, document, Some(alice), "queued", 0).await?;
queue(&pool, document, Some(alice), "queued", 0).await?;
let by_bob = queue(&pool, document, Some(bob), "queued", 0).await?;
let by_nobody = queue(&pool, document, None, "queued", 0).await?;

sqlx::raw_sql(MIGRATION).execute(&pool).await?;
sqlx::raw_sql(MIGRATION).execute(&pool).await?;
let kept: Vec<i64> = sqlx::query_scalar(
"SELECT id FROM jobs
WHERE kind = 'extract_document' AND payload->>'document_id' = $1 ORDER BY id",
)
.bind(document.to_string())
.fetch_all(&pool)
.await?;

sqlx::query(
"DELETE FROM jobs WHERE kind = 'extract_document' AND payload->>'document_id' = $1",
)
.bind(document.to_string())
.execute(&pool)
.await?;
pool.close().await;
assert_eq!(
kept,
vec![oldest, failed_before, running, by_bob, by_nobody]
);
Ok(())
}
54 changes: 54 additions & 0 deletions crates/utopia-store/tests/store/a_failed_job_finds_its_way_back.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,57 @@ async fn a_failed_job_finds_its_way_back() -> anyhow::Result<()> {
.await;
run
}

/// #1514:排着一份没动过的抽取时,同一篇文档、同一个提议人失败的抽取不再排回去,
/// 一起失败的重复也只回来一份;否则唯一索引撞上,整批重排回滚
#[tokio::test]
async fn failed_extractions_requeue_one_per_proposal() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let f = seed(&pool).await?;
let (alice, bob) = (Uuid::now_v7(), Uuid::now_v7());
let by = |user: Uuid| serde_json::json!({ "document_id": f.doc1, "proposed_by": user });
let m = Duration::minutes(1);

let run = async {
jobs::enqueue_extraction(&pool, by(alice)).await?;
let waits = job(&pool, "extract_document", by(alice), "failed", m).await?;
let first = job(&pool, "extract_document", by(bob), "failed", m).await?;
let repeat = job(&pool, "extract_document", by(bob), "failed", m).await?;

let n = jobs::requeue_failed(
&pool,
RequeueScope {
kb_id: Some(f.kb1),
kind: Some("extract_document"),
failed_since: None,
},
)
.await?;
assert_eq!(n, 1);
assert_eq!(
(
state(&pool, waits).await?.0,
state(&pool, first).await?,
state(&pool, repeat).await?.0
),
("failed".into(), ("queued".into(), 0), "failed".into())
);
Ok::<_, anyhow::Error>(())
}
.await;

let _ = sqlx::query(
"DELETE FROM jobs WHERE kind = 'extract_document' AND payload->>'document_id' = $1",
)
.bind(f.doc1.to_string())
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
.bind(f.org)
.execute(&pool)
.await;
run
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! #1514: 一篇文档排着一份抽取时,同一个提议人再变一次不再多排一份。
//!
//! 抽取跑的时候才读文档当下的块,所以排着的第二份读到的和第一份一样。跑过一次失败、带着
//! 退避和用掉的重试次数回到队里的那份不算:新版本不该继承它的处境。

use sqlx::PgPool;
use utopia_store::jobs;
use uuid::Uuid;

async fn extractions_of(pool: &PgPool, document: Uuid) -> anyhow::Result<Vec<i32>> {
Ok(sqlx::query_scalar(
"SELECT attempts 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_push_while_its_extraction_waits_folds_into_it() -> 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 })).await?;
let second = jobs::enqueue_extraction(
&pool,
serde_json::json!({ "document_id": document, "proposed_by": null, "proposed_token": null }),
)
.await?;
let attempts = extractions_of(&pool, document).await?;

clean(&pool, document).await?;
pool.close().await;
assert!(first.is_some());
assert_eq!((second, attempts), (None, vec![0]));
Ok(())
}

#[tokio::test]
async fn a_push_while_its_extraction_has_failed_once_queues_a_fresh_one() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let document = Uuid::now_v7();
sqlx::query("INSERT INTO jobs (kind, payload, attempts) VALUES ('extract_document', $1, 1)")
.bind(serde_json::json!({ "document_id": document }))
.execute(&pool)
.await?;

let fresh =
jobs::enqueue_extraction(&pool, serde_json::json!({ "document_id": document })).await?;
let attempts = extractions_of(&pool, document).await?;

clean(&pool, document).await?;
pool.close().await;
assert!(fresh.is_some());
assert_eq!(attempts, vec![1, 0]);
Ok(())
}

#[tokio::test]
async fn a_push_by_another_proposer_queues_its_own_extraction() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let (document, alice, bob) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
let push = |user: Uuid| {
serde_json::json!({
"document_id": document, "proposed_by": user, "proposed_token": null,
})
};

let by_alice = jobs::enqueue_extraction(&pool, push(alice)).await?;
let by_bob = jobs::enqueue_extraction(&pool, push(bob)).await?;
let again_by_bob = jobs::enqueue_extraction(&pool, push(bob)).await?;
let attempts = extractions_of(&pool, document).await?;

clean(&pool, document).await?;
pool.close().await;
assert_eq!(
(by_alice.is_some(), by_bob.is_some(), again_by_bob, attempts),
(true, true, None, vec![0, 0])
);
Ok(())
}
3 changes: 3 additions & 0 deletions crates/utopia-store/tests/store/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
//! 过滤——修正行、重复行都按全库找,会改到别的测试正在物化、改写的行。
//! - `a_row_a_rule_implied_follows_its_statements`:把迁移 0101 原样跑一遍,同样不按 kb
//! 过滤——它按来源重算全库类型化行的见证,会改到别的测试正在物化的行。
//! - `a_document_waits_for_one_queued_extraction`:把迁移 0127 原样跑一遍,它删全库排着的重复抽取,
//! 不按 kb 过滤,会删掉别的测试正排着的抽取;还要先拆掉它建的唯一索引才排得出重复。
//! - `a_due_base_is_queued_once`:`queue_due_inferences` 扫全库到期的库。0050 起新建的库开着
//! 推理又从没推过,别的测试刚建的库全算到期,会被它排上推理任务——数自己库任务的测试
//! (比如 lib 单元测试里的 `phrase_bindings_delivery_tests`)就会多数出一个。
Expand Down Expand Up @@ -123,6 +125,7 @@ mod an_event_holds_at_the_moment_it_names;
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;
Expand Down
Loading
Loading