From 315c7f8c9545bd3d17cdbc3727ba578f3c62e30e Mon Sep 17 00:00:00 2001 From: Maya Kid Date: Wed, 18 Nov 2026 20:01:32 +1100 Subject: [PATCH 1/3] Look up fact successors within their knowledge base (#1512) Signed-off-by: Maya Kid --- crates/utopia-store/src/graph.rs | 18 ++++++++++-------- crates/utopia-store/src/resolution.rs | 15 +++++++++------ 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 214645ed3..6893cbc44 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -1261,19 +1261,21 @@ pub async fn add_evidence_located( let mut tx = pool.begin().await?; let mut target = fact_id; loop { - let live: Option = - sqlx::query_scalar("SELECT invalidated_at IS NULL FROM facts WHERE id = $1 FOR SHARE") - .bind(target) - .fetch_optional(&mut *tx) - .await?; - if live != Some(false) { + let Some((kb_id, false)) = sqlx::query_as::<_, (Uuid, bool)>( + "SELECT kb_id, invalidated_at IS NULL FROM facts WHERE id = $1 FOR SHARE", + ) + .bind(target) + .fetch_optional(&mut *tx) + .await? + else { break; - } + }; let next: Option = sqlx::query_scalar( - "SELECT id FROM facts WHERE supersedes = $1 + "SELECT id FROM facts WHERE supersedes = $1 AND kb_id = $2 ORDER BY invalidated_at IS NULL DESC, recorded_at DESC LIMIT 1", ) .bind(target) + .bind(kb_id) .fetch_optional(&mut *tx) .await?; match next { diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 4cefc3b83..9918dffe9 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -2467,17 +2467,19 @@ struct MergeRow { /// 搬过的事实,连同从它们改写出来的每一行(顺着 supersedes 往下走到底,作废的也算) async fn with_rewrites( tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + kb_id: Uuid, roots: &[Uuid], ) -> AppResult> { Ok(sqlx::query_scalar( "WITH RECURSIVE chain(id) AS ( SELECT unnest($1::uuid[]) UNION - SELECT f.id FROM facts f JOIN chain c ON f.supersedes = c.id + SELECT f.id FROM facts f JOIN chain c ON f.supersedes = c.id AND f.kb_id = $2 ) SELECT id FROM chain", ) .bind(roots) + .bind(kb_id) .fetch_all(&mut **tx) .await?) } @@ -2525,10 +2527,10 @@ pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResu .bind(m.target_id) .fetch_all(&mut *tx) .await?; - let touched: Vec = with_rewrites(&mut tx, &m.moved_subject_facts) + let touched: Vec = with_rewrites(&mut tx, kb_id, &m.moved_subject_facts) .await? .into_iter() - .chain(with_rewrites(&mut tx, &m.moved_object_facts).await?) + .chain(with_rewrites(&mut tx, kb_id, &m.moved_object_facts).await?) .chain(m.invalidated_facts.iter().copied()) .collect(); let timelines = @@ -2536,8 +2538,8 @@ pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResu .await?; crate::temporal::lock_timelines(&mut tx, kb_id, &timelines).await?; // 锁上之后再走一遍:等锁的时候,引擎可能刚从它们改写出新的一行 - let subject_rows = with_rewrites(&mut tx, &m.moved_subject_facts).await?; - let object_rows = with_rewrites(&mut tx, &m.moved_object_facts).await?; + let subject_rows = with_rewrites(&mut tx, kb_id, &m.moved_subject_facts).await?; + let object_rows = with_rewrites(&mut tx, kb_id, &m.moved_object_facts).await?; sqlx::query("UPDATE facts SET subject_id = $1 WHERE id = ANY($2) AND subject_id = ANY($3)") .bind(m.source_id) @@ -2582,13 +2584,14 @@ pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResu "WITH RECURSIVE chain(fact_id, chunk_id) AS ( SELECT * FROM unnest($1::uuid[], $2::uuid[]) UNION - SELECT f.id, c.chunk_id FROM facts f JOIN chain c ON f.supersedes = c.fact_id + SELECT f.id, c.chunk_id FROM facts f JOIN chain c ON f.supersedes = c.fact_id AND f.kb_id = $3 ) DELETE FROM fact_evidence fe USING chain c WHERE fe.fact_id = c.fact_id AND fe.chunk_id = c.chunk_id", ) .bind(&m.copied_evidence_facts) .bind(&m.copied_evidence_chunks) + .bind(kb_id) .execute(&mut *tx) .await?; sqlx::query("UPDATE facts SET invalidated_at = NULL WHERE id = ANY($1)") From ccd4203fd2fcabcd283ba91da28b5cc491ca63d2 Mon Sep 17 00:00:00 2001 From: Maya Kid Date: Wed, 18 Nov 2026 20:11:13 +1100 Subject: [PATCH 2/3] ADR 0067: each task chooses its model (#1239) * ADR 0067: each task chooses its model Signed-off-by: dada-yan * ADR 0067 is accepted, with the answers to its three open questions folded into the decisions Profiles stay per workspace, implication::read_phrases goes under alignment, a base's unset tasks follow the task defaults; decision 4 names the connection test as its one exception and decision 5 says where chat_reasoning_effort and embed_dim go (0035), as asked in the 2026-10-19 review. Co-Authored-By: Claude Opus 5.5 --------- Signed-off-by: dada-yan Co-authored-by: Wayland Yang Co-authored-by: Claude Opus 5.5 Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- .../0067-each-task-chooses-its-model.md | 36 +++++++++++++++++++ docs/decisions/README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 docs/decisions/0067-each-task-chooses-its-model.md diff --git a/docs/decisions/0067-each-task-chooses-its-model.md b/docs/decisions/0067-each-task-chooses-its-model.md new file mode 100644 index 000000000..7e44619d7 --- /dev/null +++ b/docs/decisions/0067-each-task-chooses-its-model.md @@ -0,0 +1,36 @@ +# 0067 · Each task chooses its model + +- **Status**: Accepted · 2026-10-19 · #470 · open: cuts 1–4 +- **Written**: 2026-10-15 (conventions in the [README](README.md)) +- **Related**: [#470](https://github.com/deeplethe/utopia/issues/470) (the proposal, its cuts and the six tasks); [0042](0042-the-chat-loop-is-a-runner-with-hooks.md) (a per-task model is not wired); [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) (a model trained for these steps is the planned route); [0065](0065-readers-choose-their-provider.md) (readers keep their own provider); [#1066](https://github.com/deeplethe/utopia/pull/1066) (one reasoning effort for every call); [#996](https://github.com/deeplethe/utopia/pull/996) (call labels in the usage log) + +## Problem + +A workspace has one `llm_settings` row, so every call goes to one chat endpoint and one embedding endpoint, and since #1066 with one reasoning effort. The calls have opposite economics. Extraction reads every chunk of every document and should be cheap and fast; adjudication and Chat should be careful. Alignment is about six tenths of a document's tokens, and the model 0044 plans to train for extraction and alignment has nowhere to plug in. Concurrency limits are already keyed by base URL and model (#48), so only the choosing is missing. + +## Decisions + +1. **A profile is a named endpoint**: a name, a kind (`chat` or `embedding`), a base URL, a key and a model, plus a reasoning effort on chat profiles. The key is sealed at rest like every model key. A profile is ready when it has an address and a model. "Extraction without thinking, alignment with" is two profiles of one model. **Profiles live per workspace**, like today's row: keys and admins are per workspace, and a deployment-level profile would let one workspace's data go to another workspace's endpoint. +2. **Six tasks, grouped by what the calls are for.** #996's call labels stay as they are: a task chooses the endpoint, a label names the call in the usage log. + + | Task | The calls | + |---|---| + | `extraction` | reading a passage (`extraction_open::run_open`), time interpretation (`time_resolution::resolve_document`) | + | `alignment` | kind-word and phrase votes (`type_alignment`, `phrase_alignment`), rule proposals (`implication::propose_rules`), the readings for those rules (`implication::read_phrases`) | + | `governance` | type resolution (`type_resolution`), entity adjudication (`adjudication` and the governance queue, `governance::govern`), errata (`errata`), the ontology agent (`ontology_agent`) | + | `chat` | a conversation turn | + | `mappings` | mapping exploration (`mappings::explore`, `mappings::describe_data`) | + | `embedding` | every vector: chunks, names, the ontology, signatures, mappings and queries | + +3. **The chain.** `model_for(kb, task)` takes the first link that is set: the base's override for the task (cut 2), the default for the task, then, for every task except `embedding`, the default for `chat`. A task with no default of its own follows `chat`, which is today's behaviour. `embedding` never falls back to a chat profile: with no embedding profile there are no vectors, as with no embedding model today. A link that is set but not ready ends the search, and the task counts as not configured, so its data never goes to an endpoint nobody chose for it. A base's unset tasks follow the task defaults: a base's own `chat` override covers only `chat`, so a base that has to stay on a local endpoint overrides every task it uses. +4. **`model_for` is the only way to a model.** No call site reads the settings or builds a client. `model_for` returns the client together with the base URL and model that the concurrency gate is keyed by, so per-model limits stay as they are. The one exception is the connection test, which builds a client from the profile being edited, since that profile may not be any task's link yet. +5. **The migration** turns each `llm_settings` row into at most two profiles, `chat` and `embedding`, and sets only those two defaults, so a migrated deployment makes the same calls. `chat_reasoning_effort` moves onto the migrated chat profile, and `embed_dim` onto the migrated embedding profile: an embedding profile carries its dimension, because the vector indexes are built per dimension (0035). The chat and embedding columns then leave `llm_settings`; OCR and transcription stay there (0065). +6. **Cuts**, as #470 lays them out: (1) profiles, task defaults, the migration and `model_for` at every call site, with no endpoints and no UI, so until cut 3 a task gets a profile of its own only in the database; (2) a base's overrides; (3) Administration → Models as a table of profiles, plus the task defaults; (4) changing a base's embedding profile, which re-embeds that base. + +## Not chosen + +- **The issue's five tasks.** Alignment would hide inside another task, and it is the one with the volume and the planned model. +- **#996's call kinds as tasks.** Too fine, and they change with the prompts. +- **Profiles at the deployment level**, as #470 first wrote it. Keys and admins are per workspace, so a shared profile would carry one workspace's data to another's endpoint. +- **A base's `chat` override covering its other unset tasks.** It would make a base's override reach tasks nobody set for that base. +- **OCR and transcription as profiles.** A base URL, key and model cannot say which protocol a reader speaks (0065). diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 10a3051e0..4f973013f 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -154,6 +154,7 @@ By domain; the domains are the files of [../design/](../design/README.md). **Sta | 0046 | [The app surface is MCP](0046-the-app-surface-is-mcp.md) | Accepted | | | 0063 | [Stopping a chat ends the generation](0063-stopping-a-chat-ends-the-generation.md) | Implemented | | | 0064 | [Extraction reads time as it goes](0064-extraction-reads-time-as-it-goes.md) | In progress | | +| 0067 | [Each task chooses its model](0067-each-task-chooses-its-model.md) | Accepted | | ### process From 3d307f6236904a12ae50e2f31f0d1d1f02f3bc25 Mon Sep 17 00:00:00 2001 From: Royce Date: Wed, 18 Nov 2026 17:17:34 +0800 Subject: [PATCH 3/3] Charge only changed items against the custom sync budget (#1212, ADR 0072) (#1397) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Charge only changed items against the custom sync budget (#1212, ADR 0072) Signed-off-by: Royce Lam * Satisfy clippy on the custom sync budget change Signed-off-by: Royce Lam * 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) 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 * A custom item changed while a round is running is still read by the next one, so 0072's status line can be closed (#1212, ADR 0072) Signed-off-by: Royce Lam --------- Signed-off-by: Royce Lam Co-authored-by: Wayland Yang Co-authored-by: Claude Opus 5.5 Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- .../src/api/google_drive_routes_tests.rs | 2 + crates/utopia-server/src/ingest_sources.rs | 118 ++++- crates/utopia-server/src/main.rs | 2 +- .../src/source_checkpoint_tests.rs | 473 +++++++++++++++++- crates/utopia-store/src/sources.rs | 49 +- ...checkpoint-ends-at-a-timestamp-boundary.md | 26 +- ...t-source-says-where-its-reading-stopped.md | 9 + docs/decisions/README.md | 2 +- docs/design/sources.md | 9 +- 9 files changed, 656 insertions(+), 34 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 17b97891c..a9cf842f7 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>, } @@ -79,18 +86,31 @@ fn reads_by_timestamp(kind: SourceKind) -> bool { ) } -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:下界取自**这个来源自己的游标**。 + // + // - 工单来源(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(kind) if reads_by_timestamp(kind) => { + Some(kind) if kind == SourceKind::Custom || reads_by_timestamp(kind) => { 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); @@ -122,7 +142,62 @@ 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(*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 kind.is_some_and(reads_by_timestamp) => { utopia_store::sources::finish_timestamp_sync( &state.pool, @@ -141,7 +216,7 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() }; match outcome { Ok(stats) => { - if !kind.is_some_and(reads_by_timestamp) { + if !kind.is_some_and(|k| k == SourceKind::Custom || reads_by_timestamp(k)) { utopia_store::sources::finish_run( &state.pool, run_id, @@ -170,7 +245,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( @@ -1453,9 +1528,30 @@ async fn sync_custom( .as_array() .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?; - let mut stats = SyncStats::default(); + // `discovered` 记响应里的条数,不是跑进来的条数——否则日志与警告会读成 `(0 > 200)` + let mut stats = SyncStats { + discovered: items.len(), + ..Default::default() + }; 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; @@ -1487,6 +1583,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/main.rs b/crates/utopia-server/src/main.rs index f916f4507..0fc82fb08 100644 --- a/crates/utopia-server/src/main.rs +++ b/crates/utopia-server/src/main.rs @@ -679,7 +679,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 805e12115..7155c37ea 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 { @@ -135,3 +145,464 @@ 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,触顶 + 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", + "触顶的那一轮不能记为 'ok',否则下界会越过还没读到的条目" + ); + assert!( + first + .last_sync_error + .as_deref() + .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 条这次够得着 + 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", + ) + .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 +} + +/// **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 +} + +/// **端点自己记的账**:每条工单的 id、正文、它是什么时候改的。协议里没有这个 +/// 字段——这是端点自己的账,用来决定回哪几条。 +type Feed = Arc)>>>; + +/// **运行期间到达的改动,下一轮还够得着**(ADR 0072 的 Custom 一节: +/// "preserving the existing protection for changes during the run")。 +/// +/// 游标推进到**这一轮开始的时刻**,不是推进到现在:端点在第一轮被问的时候改了 +/// 一条工单(更新时刻在那一轮开始之后),第二轮的下界必须还在那条改动之前, +/// 否则它就永远读不到了。 +/// +/// 这条断言有牙:把游标改成「推进到现在」,端点就会因为下界太晚而什么都不给, +/// 这条工单也就永远进不来。 +#[tokio::test] +async fn an_item_changed_during_a_round_is_still_read_by_the_next_one() -> 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,'concurrent-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'concurrent-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'concurrent-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + 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?; + + // **端点自己记着每条工单是什么时候改的**(协议里没有这个字段,是端点自己的账)。 + // 第一次被问的时候,它顺手把一条改了、又添了一条——改动时刻落在这一轮开始之后。 + let feed: Feed = Arc::new(std::sync::Mutex::new(vec![( + "item-0".to_string(), + "Body 0".to_string(), + chrono::Utc::now() - chrono::Duration::hours(1), + )])); + let served = feed.clone(); + let asked = Arc::new(std::sync::Mutex::new(Vec::< + Option>, + >::new())); + let seen = asked.clone(); + Mock::given(method("GET")) + .respond_with(move |req: &Request| { + let since = req + .url + .query_pairs() + .find(|(k, _)| k == "since") + .map(|(_, v)| { + chrono::DateTime::parse_from_rfc3339(&v) + .unwrap() + .with_timezone(&chrono::Utc) + }); + seen.lock().unwrap().push(since); + let mut feed = served.lock().unwrap(); + // 端点只给「下界之后改过的」那些(custom 协议:下界由端点自己解释) + let items: Vec = feed + .iter() + .filter(|(_, _, changed_at)| since.is_none_or(|s| *changed_at > s)) + .map(|(id, content, changed_at)| { + serde_json::json!({ + "id": id, + "title": format!("Item {id}"), + "content": content, + "doc_time": changed_at.to_rfc3339(), + }) + }) + .collect(); + // 答完这一轮顺手改一条、添一条——改动时刻落在这一轮开始之后, + // 所以**下一轮**才看得到(这一轮答的是改动之前的样子) + if feed.len() == 1 { + let now = chrono::Utc::now(); + feed[0].1 = "Body 0, changed".to_string(); + feed[0].2 = now; + feed.push(("item-1".to_string(), "Body 1".to_string(), now)); + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": items })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-concurrent-{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 { + // 第一轮:只有 item-0,读完就走完了 + let first = sync_source(&state, source).await?; + assert_eq!(first.created, 1, "第一轮只有 item-0"); + let checkpoint = utopia_store::sources::sync_checkpoint(&pool, source).await?; + assert!(checkpoint.is_some(), "这一轮走完了,游标该落下来"); + + // 第二轮:端点现在有两条改过的,下界必须还在它们的改动之前 + let second = 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, 2, + "运行期间改的那一条、添的那一条,下一轮都得进来(游标要停在那一轮**开始**的时刻,不是结束的时刻)" + ); + assert_eq!(second.updated, 1, "item-0 是改过的,item-1 是新的"); + 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 265277e71..a73fb3df2 100644 --- a/crates/utopia-store/src/sources.rs +++ b/crates/utopia-store/src/sources.rs @@ -571,7 +571,40 @@ pub async fn sync_checkpoint(pool: &PgPool, source_id: Uuid) -> AppResult