From f6cc30531efd0c1f31ee4b5788d50484872c29c4 Mon Sep 17 00:00:00 2001 From: Royce Lam Date: Fri, 23 Oct 2026 22:56:48 +0800 Subject: [PATCH 1/4] Charge only changed items against the custom sync budget (#1212, ADR 0072) Signed-off-by: Royce Lam --- crates/utopia-server/src/ingest_sources.rs | 72 +++++++++- .../src/source_checkpoint_tests.rs | 132 ++++++++++++++++++ 2 files changed, 203 insertions(+), 1 deletion(-) diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs index 97cab507b..d862d9eac 100644 --- a/crates/utopia-server/src/ingest_sources.rs +++ b/crates/utopia-server/src/ingest_sources.rs @@ -43,6 +43,13 @@ pub struct SyncStats { pub discovered: usize, pub queued_for_content: usize, pub content_terminal: usize, + /// 这一轮因为触顶而没走完,`since` 不能前进(#1212 / ADR 0072 的 Custom) + /// + /// 上一条成功那一轮的 `started_at` 是下一次的下界;本轮要是记 `ok`,下界就跨过了 + /// 这批还没读到的条目,之后每一轮都够不着它们。这里标出来,`sync_source` 据此把 + /// 游标留在原处,本轮的 created / updated 照旧记进审计。 + pub incomplete: bool, + /// 这一轮读到的位置(GitHub / Jira 的更新时刻,ADR 0072) pub checkpoint: Option>, } @@ -73,6 +80,9 @@ impl SyncStats { pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<()> { let source = utopia_store::sources::get(&state.pool, source_id).await?; let kind = SourceKind::parse(&source.kind); + // #1212 / ADR 0072:下界取自**上一条完整读完的那一轮**的开始。`last_successful_sync_start` + // 只认 `status = 'ok'`,而触顶那一轮我们写成 `failed`,所以游标自然留在触顶之前 + // 那一轮,下一轮用同一条 since 重发。 let since = match kind { Some(SourceKind::Custom) => { utopia_store::sources::last_successful_sync_start(&state.pool, source_id).await? @@ -112,6 +122,44 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() None => Err(anyhow::anyhow!("unknown source kind `{}`", source.kind)), }; + // 没走完这一轮:游标留在原处,但这一轮已经做成的部分照旧记进审计 + // (ADR 0072 的「Keep the committed counts visible for incomplete runs」)。 + // run 写 `failed` 而不是 `ok`:游标只在这一轮整条响应都走完时才前进, + // 所以这一轮没走完,下一轮就从原处接着读。 + if let Ok(stats) = &outcome { + if stats.incomplete { + let err = format!( + "changed {MAX_NEW_PER_SYNC} items and stopped with more behind; \ + the checkpoint stays where it was, so the next sync resumes here" + ); + utopia_store::sources::finish_run( + &state.pool, + run_id, + source_id, + Some(&err), + stats.created as i32, + stats.updated as i32, + ) + .await?; + utopia_store::sources::finish_sync_quiet( + &state.pool, + source_id, + &err, + stats.total() as i32, + ) + .await?; + state.emit_source(source.kb_id); + tracing::warn!( + %source_id, + kind = %source.kind, + created = stats.created, + updated = stats.updated, + discovered = stats.discovered, + "来源同步未读完,游标不前进" + ); + return Ok(()); + } + } let outcome = match outcome { Ok(stats) if matches!( @@ -1346,8 +1394,26 @@ async fn sync_custom( .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?; let mut stats = SyncStats::default(); + stats.discovered = items.len(); let mut seen_keys: Vec = Vec::new(); - for item in items.iter().take(MAX_NEW_PER_SYNC) { + // **走完整个响应,只把有变的条目记在预算上**(ADR 0072 的 Custom 一节)。 + // `take(MAX_NEW_PER_SYNC)` 是 ADR 明写在 Rejected 里的那条:它取走的永远是同样的 + // 前 200 条,重试一万次也够不到第 201 条。这里每条都先问 `ingest_item`,只有 + // `Created` / `Updated` 才计入 `changed`;`Unchanged` / `Moved` / `Duplicate` + // 让预算不被消耗,于是重试能把没变的前缀让过去、走到剩下的那几条。 + let mut changed = 0usize; + for item in items.iter() { + // 预算满了就不再往下走——剩下的留在下一轮,且本轮 `incomplete` 让游标留在原处 + if changed >= MAX_NEW_PER_SYNC { + stats.incomplete = true; + tracing::warn!( + source_id = %source.id, + imported = changed, + remaining = items.len().saturating_sub(seen_keys.len()), + "custom 本轮用满 {MAX_NEW_PER_SYNC} 条预算,还有条目没读到;游标不前进,下一轮接着走" + ); + break; + } let Some(id) = item["id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else { tracing::warn!(source_id = %source.id, "custom item 缺少 id,跳过"); continue; @@ -1379,6 +1445,10 @@ async fn sync_custom( doc_time, ) .await?; + match action { + IngestAction::Created | IngestAction::Updated => changed += 1, + _ => {} + } stats.absorb(action); seen_keys.push(key); } diff --git a/crates/utopia-server/src/source_checkpoint_tests.rs b/crates/utopia-server/src/source_checkpoint_tests.rs index 805e12115..1f69cfbcd 100644 --- a/crates/utopia-server/src/source_checkpoint_tests.rs +++ b/crates/utopia-server/src/source_checkpoint_tests.rs @@ -135,3 +135,135 @@ async fn retry_keeps_updates_from_the_previous_successful_run_window() -> anyhow async fn updates_during_a_successful_sync_remain_in_the_next_window() -> anyhow::Result<()> { retry_reads_the_uncovered_window(true, false).await } + +/// #1212 / ADR 0072(Custom 一节):201 条全都变了,第一轮装下 200 条就停, +/// 第二轮把没变的前缀让过去、走到第 201 条。 +/// +/// 关键的两条性质都在这里: +/// +/// 1. 触顶那一轮 `incomplete` → run 写 `failed` → 下界不前进 → 第二轮拿到的还是同一条 +/// since,因此前 200 条原样回来、但它们现在都是 `Unchanged` 不占预算,第 201 条 +/// 这次够得着了。ADR 把「取走同样的前 200 条」列在 Rejected 里说的就是这条。 +/// 2. `stats.discovered` 记的是响应里的条数(201),不是跑进来的条数(200)—— +/// 否则日志与那条警告会读成 `(0 > 200)`。 +#[tokio::test] +async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + let (org, ws, kb, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations(id,name) VALUES($1,'truncation-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'truncation-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'truncation-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + + // **来源先插,`start_run` 后跑**:source_sync_runs.source_id 上有外键, + // 反过来插会以 `source_sync_runs_source_id_fkey` 失败。 + let server = MockServer::start().await; + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,config) VALUES($1,$2,'custom','fixture',$3)", + ) + .bind(source) + .bind(kb) + .bind(serde_json::json!({ "endpoint": server.uri() })) + .execute(&pool) + .await?; + + // 201 条,全部是新的:每一轮都会重新拿到它们 + let all: Vec = (0..201u32) + .map(|i| { + serde_json::json!({ + "id": format!("item-{i}"), + "title": format!("Item {i}"), + "content": format!("Body {i}"), + }) + }) + .collect(); + let served = all.clone(); + Mock::given(method("GET")) + .respond_with(move |_req: &Request| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": served })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-truncation-{source}")); + let cfg = utopia_core::config::AppConfig { + data_dir: dir.to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open(&dir.join("search"))?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + + let result = async { + // 第一轮:201 > 200,触顶 + sync_source(&state, source).await?; + let first = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + first.last_sync_status, "failed", + "触顶的那一轮不能记为 'ok',否则下界会越过还没读到的条目" + ); + assert!( + first + .last_sync_error + .unwrap_or_default() + .contains("stopped with more"), + "错误要说明为什么停:{:?}", + first.last_sync_error + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 200, "第一轮装得下 200 条,第 201 条得等下一轮"); + + // 第二轮:同一批原样回来,前 200 条是 Unchanged 不占预算,第 201 条这次够得着 + sync_source(&state, source).await?; + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 201, "第二轮之后 201 条都在库里了"); + let last = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + last.last_sync_status, "ok", + "这一轮走完了,可以记 ok 让游标前进" + ); + Ok::<_, anyhow::Error>(()) + } + .await; + + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(org) + .execute(&pool) + .await?; + drop(state); + let _ = std::fs::remove_dir_all(dir); + result +} From da0e600604efaff6cd337a6b6dc930dfc921d478 Mon Sep 17 00:00:00 2001 From: Royce Lam Date: Fri, 23 Oct 2026 23:34:52 +0800 Subject: [PATCH 2/4] Satisfy clippy on the custom sync budget change Signed-off-by: Royce Lam --- crates/utopia-server/src/ingest_sources.rs | 7 +++++-- crates/utopia-server/src/source_checkpoint_tests.rs | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs index d862d9eac..2acac7939 100644 --- a/crates/utopia-server/src/ingest_sources.rs +++ b/crates/utopia-server/src/ingest_sources.rs @@ -1393,8 +1393,11 @@ async fn sync_custom( .as_array() .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?; - let mut stats = SyncStats::default(); - stats.discovered = items.len(); + // `discovered` 记响应里的条数,不是跑进来的条数——否则日志与警告会读成 `(0 > 200)` + let mut stats = SyncStats { + discovered: items.len(), + ..Default::default() + }; let mut seen_keys: Vec = Vec::new(); // **走完整个响应,只把有变的条目记在预算上**(ADR 0072 的 Custom 一节)。 // `take(MAX_NEW_PER_SYNC)` 是 ADR 明写在 Rejected 里的那条:它取走的永远是同样的 diff --git a/crates/utopia-server/src/source_checkpoint_tests.rs b/crates/utopia-server/src/source_checkpoint_tests.rs index 1f69cfbcd..55d4ddc97 100644 --- a/crates/utopia-server/src/source_checkpoint_tests.rs +++ b/crates/utopia-server/src/source_checkpoint_tests.rs @@ -224,6 +224,7 @@ async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<() assert!( first .last_sync_error + .as_deref() .unwrap_or_default() .contains("stopped with more"), "错误要说明为什么停:{:?}", From 657d80944349e3378434e27bea2cfb54a87039ce Mon Sep 17 00:00:00 2001 From: Royce Lam Date: Tue, 10 Nov 2026 22:45:18 +0800 Subject: [PATCH 3/4] Custom's bound is the source's own checkpoint, so it can be cleared once, and a capped round is failed without an alert (#1212, ADR 0072) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The custom bound used to be derived from the audit history — the last `ok` run's `started_at`. That says when the previous round began, not how far it read: a capped round recorded `ok` too, so the lower bound could step over items that were never read, and the bound could not be cleared without rewriting the rows the same paragraph says to preserve. The bound becomes a value on the source, `sources.sync_checkpoint` — the column migration 0119 already added. NULL means "no bound", which is where every existing source starts, so the upgrade *is* the reset (ADR 0072's Recovery section): the first round re-reads the whole window, and unchanged content dedups into no new version and no new job. Custom's checkpoint advances to the start of the round that read the whole response rather than to now, so changes that arrive during a round stay in the next round's window. A capped round is recorded as failed, but it does not raise a source.sync_failed alert: it did not break, it stopped, and the next round resumes from the same place. `finish_sync` couples the status write to the alert, so the store grows `finish_sync_quiet` for this case. The run error says "changed 200 items" rather than "read", because the budget is charged against changed items. `sync_source` now returns its stats, so a test can assert that the whole response was read instead of only the slice the budget allowed. The 450-item case covers the three rounds it takes to read one window whole, and it reads the alerts table to show that the capped rounds raised no sync-failed alert. Signed-off-by: Royce Lam --- .../src/api/google_drive_routes_tests.rs | 2 + crates/utopia-server/src/ingest_sources.rs | 49 ++++- crates/utopia-server/src/main.rs | 2 +- .../src/source_checkpoint_tests.rs | 197 +++++++++++++++++- crates/utopia-store/src/sources.rs | 49 +++-- ...t-source-says-where-its-reading-stopped.md | 9 + docs/design/sources.md | 9 +- 7 files changed, 285 insertions(+), 32 deletions(-) diff --git a/crates/utopia-server/src/api/google_drive_routes_tests.rs b/crates/utopia-server/src/api/google_drive_routes_tests.rs index 504fc8378..73ff520fd 100644 --- a/crates/utopia-server/src/api/google_drive_routes_tests.rs +++ b/crates/utopia-server/src/api/google_drive_routes_tests.rs @@ -402,10 +402,12 @@ async fn a_sync_stops_once_the_connected_person_is_no_longer_an_editor() -> anyh let reason = |e: anyhow::Error| format!("{e:#}"); let while_editor = crate::ingest_sources::sync_source(&fx.state, fx.source) .await + .map(|_| ()) .map_err(reason); fx.demote_connector().await?; let after = crate::ingest_sources::sync_source(&fx.state, fx.source) .await + .map(|_| ()) .map_err(reason); let says_reconnect = |r: &Result<(), String>| { r.as_ref() diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs index 2acac7939..bb3b84e36 100644 --- a/crates/utopia-server/src/ingest_sources.rs +++ b/crates/utopia-server/src/ingest_sources.rs @@ -77,21 +77,31 @@ impl SyncStats { } } -pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<()> { +pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result { let source = utopia_store::sources::get(&state.pool, source_id).await?; let kind = SourceKind::parse(&source.kind); - // #1212 / ADR 0072:下界取自**上一条完整读完的那一轮**的开始。`last_successful_sync_start` - // 只认 `status = 'ok'`,而触顶那一轮我们写成 `failed`,所以游标自然留在触顶之前 - // 那一轮,下一轮用同一条 since 重发。 + // #1212 / ADR 0072:下界取自**这个来源自己的游标**。 + // + // - 工单来源(GitHub / Jira):游标是消费到的更新时刻,且那一刻的整组都读完了。 + // - custom:游标是**这一轮整条响应走完时**推进到的时刻(见下面 `round_started_at`)。 + // + // **游标是源自己的一列,不是从跑次推出来的。** 早先的下界取自「上一条 `ok` 跑次的 + // `started_at`」——那说的是「上一轮什么时候开始」,不是「上一轮读到哪」;一轮没读完 + // 的时候,两者不是一回事,而下界一旦越过没读到的条目,之后每一轮都够不着它们。 + // + // 游标存在源上,于是它能被**一次性清空**(ADR 0072 的 Recovery 一节):老来源的 + // 游标是 NULL,它们从头再来一遍,靠文档、版本与处理任务的去重,未变的内容不会 + // 变成新版本。 let since = match kind { - Some(SourceKind::Custom) => { - utopia_store::sources::last_successful_sync_start(&state.pool, source_id).await? - } - Some(SourceKind::GithubIssues | SourceKind::JiraIssues) => { + Some(SourceKind::Custom | SourceKind::GithubIssues | SourceKind::JiraIssues) => { utopia_store::sources::sync_checkpoint(&state.pool, source_id).await? } _ => None, }; + // **这一轮开始的时刻。** custom 的游标推进到这里,而不是推进到「现在」: + // 运行期间到达的改动必须留在下一轮的窗口里(ADR 0072 的 Custom 一节 + // 「preserving the existing protection for changes during the run」)。 + let round_started_at = Utc::now(); utopia_store::sources::mark_running(&state.pool, source_id).await?; let run_id = utopia_store::sources::start_run(&state.pool, source_id).await?; state.emit_source(source.kb_id); @@ -157,10 +167,27 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() discovered = stats.discovered, "来源同步未读完,游标不前进" ); - return Ok(()); + return Ok(*stats); } } let outcome = match outcome { + // custom:这一轮把**整条响应**都走完了,游标推进到**这一轮开始的时刻**。 + // 不是推进到现在——运行期间到达的改动还在下一轮的窗口里,它们还没被走过。 + // 触顶那一轮(`incomplete`)走不到这里:游标留在原处,下一轮从那儿接着读。 + Ok(stats) if matches!(kind, Some(SourceKind::Custom)) => { + utopia_store::sources::finish_timestamp_sync( + &state.pool, + run_id, + source_id, + since, + Some(round_started_at), + stats.created as i32, + stats.updated as i32, + ) + .await + .map(|()| stats) + .map_err(anyhow::Error::from) + } Ok(stats) if matches!( kind, @@ -186,7 +213,7 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() Ok(stats) => { if !matches!( kind, - Some(SourceKind::GithubIssues | SourceKind::JiraIssues) + Some(SourceKind::GithubIssues | SourceKind::JiraIssues | SourceKind::Custom) ) { utopia_store::sources::finish_run( &state.pool, @@ -216,7 +243,7 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() content_terminal = stats.content_terminal, "来源同步完成" ); - Ok(()) + Ok(stats) } Err(e) => { utopia_store::sources::finish_run( diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs index 8b1339e8f..07a259a84 100644 --- a/crates/utopia-server/src/main.rs +++ b/crates/utopia-server/src/main.rs @@ -626,7 +626,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow .and_then(|v| v.as_str()) .and_then(|s| s.parse().ok()) .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?; - ingest_sources::sync_source(st, source_id).await + ingest_sources::sync_source(st, source_id).await.map(|_| ()) } "hydrate_rss_entry" => { let source_id: Uuid = job diff --git a/crates/utopia-server/src/source_checkpoint_tests.rs b/crates/utopia-server/src/source_checkpoint_tests.rs index 55d4ddc97..dd8de7a28 100644 --- a/crates/utopia-server/src/source_checkpoint_tests.rs +++ b/crates/utopia-server/src/source_checkpoint_tests.rs @@ -54,6 +54,16 @@ async fn retry_reads_the_uncovered_window( .bind(started + chrono::Duration::hours(1)) .execute(&pool) .await?; + // **源自己的游标落在那一刻**(ADR 0072)。 + // + // 从前下界是从跑次推出来的——上一条 `ok` 的 `started_at`。那有两个问题: + // 它证不了那个窗口被读完(触顶那一轮也记过 `ok`),而且它没法清空,所以 + // 老来源没法一次性从头再来一遍(0072 的 Recovery 一节)。 + sqlx::query("UPDATE sources SET sync_checkpoint=$2 WHERE id=$1") + .bind(source) + .bind(started) + .execute(&pool) + .await?; utopia_store::sources::touch_sync_time(&pool, source, started + chrono::Duration::hours(1)) .await?; } @@ -100,7 +110,7 @@ async fn retry_reads_the_uncovered_window( let last = last.expect("没有带下界:增量拉取整个没了"); assert!( (last - started).num_seconds().abs() <= 1, - "下界应当是上一次成功那轮的开始 {started},实得 {last}" + "下界应当是源自己的游标(上一轮成功那轮的开始){started},实得 {last}" ); assert!(last < changed, "下界晚于那次改动,漏掉的窗口又被跳过了"); } else { @@ -215,7 +225,11 @@ async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<() let result = async { // 第一轮:201 > 200,触顶 - sync_source(&state, source).await?; + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 201, + "整条响应都读了,不是只读到预算那一段" + ); let first = utopia_store::sources::get(&pool, source).await?; assert_eq!( first.last_sync_status, "failed", @@ -239,7 +253,11 @@ async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<() assert_eq!(imported, 200, "第一轮装得下 200 条,第 201 条得等下一轮"); // 第二轮:同一批原样回来,前 200 条是 Unchanged 不占预算,第 201 条这次够得着 - sync_source(&state, source).await?; + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 201, + "整条响应都读了,不是只读到预算那一段" + ); let imported: i64 = sqlx::query_scalar( "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", ) @@ -268,3 +286,176 @@ async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<() let _ = std::fs::remove_dir_all(dir); result } + +/// **450 条分三轮读完**(0072 的验收项)。 +/// +/// 预算 200,而没变的条目不占预算:所以第二轮能把前 200 条当没变的前缀让过去, +/// 第三轮把剩下的 50 条收掉。每一轮都读了整条响应——`discovered` 一直是 450, +/// 不是预算那一段。 +#[tokio::test] +async fn a_capped_custom_batch_is_read_whole_over_three_rounds() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + let (org, ws, kb, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations(id,name) VALUES($1,'three-round-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'three-round-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'three-round-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + + // **来源先插,`start_run` 后跑**:source_sync_runs.source_id 上有外键, + // 反过来插会以 `source_sync_runs_source_id_fkey` 失败。 + let server = MockServer::start().await; + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,config) VALUES($1,$2,'custom','fixture',$3)", + ) + .bind(source) + .bind(kb) + .bind(serde_json::json!({ "endpoint": server.uri() })) + .execute(&pool) + .await?; + + // 450 条,全部是新的:每一轮都会重新拿到它们 + let all: Vec = (0..450u32) + .map(|i| { + serde_json::json!({ + "id": format!("item-{i}"), + "title": format!("Item {i}"), + "content": format!("Body {i}"), + }) + }) + .collect(); + let served = all.clone(); + Mock::given(method("GET")) + .respond_with(move |_req: &Request| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": served })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-three-round-{source}")); + let cfg = utopia_core::config::AppConfig { + data_dir: dir.to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open(&dir.join("search"))?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + + let result = async { + // 第一轮:装下 200 条,触顶,游标留在原处 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 200, "第一轮装得下 200 条,剩下的留给下一轮"); + let first = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + first.last_sync_status, "failed", + "触顶的那一轮不能记为 'ok',否则游标会越过还没读到的条目" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_none(), + "触顶那一轮游标留在原处,下一轮从那儿接着读" + ); + // 触顶不是连接坏了:这一轮记成 `failed`,但**不发** source.sync_failed 告警 + // (同一件事天天报,#1212)。 + let alerts: i64 = sqlx::query_scalar( + "SELECT count(*) FROM alerts WHERE subject_id=$1 AND kind='source.sync_failed'", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(alerts, 0, "触顶的那一轮不该发同步失败告警"); + + // 第二轮:前 200 条原样回来(Unchanged,不占预算),再装下 200 条,又触顶 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 400, "第二轮之后 400 条都在库里了"); + let second = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + second.last_sync_status, "failed", + "第二轮又触顶,游标仍然不前进" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_none(), + "触顶那一轮游标留在原处,下一轮从那儿接着读" + ); + + // 第三轮:前 400 条原样回来,把剩下的 50 条收掉,这一轮走完了 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 450, "第三轮之后 450 条都在库里了"); + let third = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + third.last_sync_status, "ok", + "这一轮走完了,可以记 ok 让游标前进" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_some(), + "走完的那一轮把游标推进了" + ); + Ok::<_, anyhow::Error>(()) + } + .await; + + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(org) + .execute(&pool) + .await?; + drop(state); + let _ = std::fs::remove_dir_all(dir); + result +} diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs index 1c3dce25e..f98eb5c81 100644 --- a/crates/utopia-store/src/sources.rs +++ b/crates/utopia-store/src/sources.rs @@ -548,7 +548,40 @@ pub async fn sync_checkpoint(pool: &PgPool, source_id: Uuid) -> AppResult