From 4fc7164fb57f5e614771c4fd86ee8c520d3ed1f0 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Wed, 21 Oct 2026 22:37:29 +0200 Subject: [PATCH] A stale document of a decaying source ranks at 0.6 of its score and says it is stale Signed-off-by: Bogdan Szabo --- crates/utopia-server/src/retrieval.rs | 36 ++++++- crates/utopia-server/src/retrieval_tests.rs | 90 +++++++++++++++++ crates/utopia-store/src/decay.rs | 24 +++++ ...ument_is_found_among_a_decaying_sources.rs | 99 +++++++++++++++++++ crates/utopia-store/tests/store/main.rs | 1 + .../re-cinq/RC-003-a-source-may-decay.md | 4 +- docs/design/chat-and-mcp.md | 3 + 7 files changed, 252 insertions(+), 5 deletions(-) create mode 100644 crates/utopia-store/tests/store/a_stale_document_is_found_among_a_decaying_sources.rs diff --git a/crates/utopia-server/src/retrieval.rs b/crates/utopia-server/src/retrieval.rs index eb037404c..fac382749 100644 --- a/crates/utopia-server/src/retrieval.rs +++ b/crates/utopia-server/src/retrieval.rs @@ -40,6 +40,10 @@ pub struct ScoredChunk { #[serde(flatten)] pub chunk: SourcedChunk, pub score: f64, + /// 来自一个会衰减的源、且久没被检索:分已经乘过 [`utopia_store::decay::STALE_SEARCH_WEIGHT`]。 + /// 不衰减的库这一格永远是 false,不进响应 + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub stale: bool, pub bm25_rank: Option, pub vector_rank: Option, } @@ -130,20 +134,31 @@ pub async fn hybrid_scored( let live = utopia_store::documents::chunks_by_ids(&state.pool, kb_id, &ids, opts.as_of).await?; let has_more = live.len() > depth; let mut fused: HashMap = fused.into_iter().collect(); - let results = live + let mut scored: Vec = live .into_iter() - .skip(opts.offset) - .take(opts.top_k) .filter_map(|chunk| { let f = fused.remove(&chunk.chunk.id)?; Some(ScoredChunk { chunk, score: f.score, + stale: false, bm25_rank: position(&f.ranks, 0), vector_rank: position(&f.ranks, 1), }) }) .collect(); + // 陈旧的先降分再翻页:久没人读的文档才可能被挤出这一页,而不是只在页内挪位置 + let document_ids: Vec = scored + .iter() + .map(|hit| hit.chunk.chunk.document_id) + .collect(); + let stale = utopia_store::decay::stale_documents(&state.pool, &document_ids).await?; + demote_stale(&mut scored, &stale); + let results = scored + .into_iter() + .skip(opts.offset) + .take(opts.top_k) + .collect(); Ok(SearchPage { results, has_more, @@ -164,6 +179,21 @@ pub fn record_retrievals(state: &AppState, mut document_ids: Vec) { }); } +/// 陈旧文档的命中乘 [`utopia_store::decay::STALE_SEARCH_WEIGHT`] 后重排。没有陈旧的就不动, +/// 排序稳定,同分仍按原来的先后。 +fn demote_stale(hits: &mut [ScoredChunk], stale: &std::collections::HashSet) { + if stale.is_empty() { + return; + } + for hit in hits.iter_mut() { + if stale.contains(&hit.chunk.chunk.document_id) { + hit.score *= utopia_store::decay::STALE_SEARCH_WEIGHT; + hit.stale = true; + } + } + hits.sort_by(|a, b| b.score.total_cmp(&a.score)); +} + /// 第 `channel` 路里的名次,从 1 数 fn position(ranks: &[Option], channel: usize) -> Option { ranks diff --git a/crates/utopia-server/src/retrieval_tests.rs b/crates/utopia-server/src/retrieval_tests.rs index 7628c1dcf..58bc9dfd7 100644 --- a/crates/utopia-server/src/retrieval_tests.rs +++ b/crates/utopia-server/src/retrieval_tests.rs @@ -122,6 +122,19 @@ impl Fixture { Ok(chunks.into_iter().map(|c| c.id).collect()) } + async fn scored_search(&self) -> anyhow::Result { + let opts = super::SearchOpts { + top_k: 8, + offset: 0, + as_of: None, + documents: None, + }; + Ok( + super::hybrid_scored(&self.state, self.kb, self.ws, "apple harvest", opts, None) + .await?, + ) + } + async fn cleanup(self) -> anyhow::Result<()> { sqlx::query("DELETE FROM organizations WHERE id=$1") .bind(self.org) @@ -264,3 +277,80 @@ async fn historical_search_keeps_live_candidates_before_limiting_results() -> an ); Ok(()) } + +fn hit(document_id: Uuid, score: f64) -> super::ScoredChunk { + super::ScoredChunk { + chunk: utopia_core::models::SourcedChunk { + chunk: utopia_core::models::ChunkView { + id: Uuid::now_v7(), + document_id, + seq: 0, + text: String::new(), + filename: String::new(), + }, + source_id: None, + external_id: None, + }, + score, + stale: false, + bm25_rank: None, + vector_rank: None, + } +} + +#[test] +fn a_stale_hit_loses_forty_percent_and_the_list_is_reordered() { + let (fresh, old) = (Uuid::now_v7(), Uuid::now_v7()); + let mut hits = vec![hit(old, 1.0), hit(fresh, 0.7)]; + super::demote_stale(&mut hits, &[old].into_iter().collect()); + let order: Vec<(Uuid, bool)> = hits + .iter() + .map(|h| (h.chunk.chunk.document_id, h.stale)) + .collect(); + assert_eq!(order, vec![(fresh, false), (old, true)]); + assert!((hits[1].score - 0.6).abs() < 1e-12); +} + +#[test] +fn a_list_with_nothing_stale_keeps_its_order_and_scores() { + let (a, b) = (Uuid::now_v7(), Uuid::now_v7()); + let mut hits = vec![hit(a, 0.2), hit(b, 0.9)]; + super::demote_stale(&mut hits, &std::collections::HashSet::new()); + assert_eq!( + hits.iter().map(|h| h.score).collect::>(), + vec![0.2, 0.9] + ); +} + +#[tokio::test] +async fn a_search_scores_a_stale_document_of_a_decaying_source_at_sixty_percent( +) -> anyhow::Result<()> { + let Some(f) = fixture().await? else { + return Ok(()); + }; + let before = f.scored_search().await?; + assert!(!before.results[0].stale); + + let source = Uuid::now_v7(); + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,decay) VALUES($1,$2,'folder','f','{}'::jsonb)", + ) + .bind(source) + .bind(f.kb) + .execute(&f.pool) + .await?; + sqlx::query( + "UPDATE documents SET source_id = $1, created_at = now() - interval '100 days' WHERE id = $2", + ) + .bind(source) + .bind(f.doc) + .execute(&f.pool) + .await?; + let after = f.scored_search().await?; + let (was, is) = (before.results[0].score, after.results[0].score); + let stale = after.results[0].stale; + f.cleanup().await?; + assert!(stale); + assert!((is - was * 0.6).abs() < 1e-12, "{is} is not 0.6 of {was}"); + Ok(()) +} diff --git a/crates/utopia-store/src/decay.rs b/crates/utopia-store/src/decay.rs index 7908e8b47..d41767e9e 100644 --- a/crates/utopia-store/src/decay.rs +++ b/crates/utopia-store/src/decay.rs @@ -155,6 +155,30 @@ pub fn is_stale(last_touched: DateTime, stale_after_days: u32, now: DateTim now - last_touched > chrono::Duration::days(i64::from(stale_after_days)) } +/// 陈旧文档的检索分乘这个数,和 Lore 对陈旧事实的权重一样。 +pub const STALE_SEARCH_WEIGHT: f64 = 0.6; + +/// 这些文档里,属于打开了衰减的源、并且陈旧的那些([`is_stale`] 的判据,在库里算)。 +pub async fn stale_documents( + pool: &PgPool, + document_ids: &[Uuid], +) -> AppResult> { + let ids: Vec<(Uuid,)> = sqlx::query_as( + "SELECT d.id + FROM documents d + JOIN sources s ON s.id = d.source_id + LEFT JOIN document_salience sal ON sal.document_id = d.id + WHERE d.id = ANY($1) AND s.decay IS NOT NULL + AND COALESCE(sal.last_retrieved_at, d.created_at) + < now() - make_interval(days => COALESCE((s.decay->>'stale_after_days')::int, $2))", + ) + .bind(document_ids) + .bind(i32::try_from(DecaySettings::default().stale_after_days).unwrap_or(30)) + .fetch_all(pool) + .await?; + Ok(ids.into_iter().map(|(id,)| id).collect()) +} + /// 淘汰候选:一个文档和给它打分用的材料。 pub struct Candidate { pub document_id: Uuid, diff --git a/crates/utopia-store/tests/store/a_stale_document_is_found_among_a_decaying_sources.rs b/crates/utopia-store/tests/store/a_stale_document_is_found_among_a_decaying_sources.rs new file mode 100644 index 000000000..52e09cb85 --- /dev/null +++ b/crates/utopia-store/tests/store/a_stale_document_is_found_among_a_decaying_sources.rs @@ -0,0 +1,99 @@ +//! 陈旧的文档(RC-003),打在真库上。 +//! +//! 要钉住的行为:只有打开了衰减的源的文档才可能陈旧;久没被检索(没被检索过就看创建) +//! 超过源里的 `stale_after_days` 才算;检索一次就不陈旧了。 +//! +//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 + +use sqlx::PgPool; +use utopia_store::decay::{record_retrievals, stale_documents}; +use uuid::Uuid; + +#[tokio::test] +async fn a_stale_document_is_found_among_a_decaying_sources() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = PgPool::connect(&url).await?; + utopia_store::db::migrate(&pool).await?; + + let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7()); + let (decaying, plain) = (Uuid::now_v7(), Uuid::now_v7()); + let (old, recent, read, unwatched) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'stale-document-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'stale-document-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'stale-document-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + for (id, decay) in [ + (decaying, Some(r#"{"stale_after_days": 20}"#)), + (plain, None), + ] { + sqlx::query("INSERT INTO sources (id, kb_id, kind, name, decay) VALUES ($1, $2, 'folder', 'f', $3::jsonb)") + .bind(id) + .bind(kb) + .bind(decay) + .execute(&pool) + .await?; + } + for (id, source, days_old) in [ + (old, decaying, 25), + (recent, decaying, 10), + (read, decaying, 25), + (unwatched, plain, 400), + ] { + sqlx::query( + "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status, created_at) + VALUES ($1, $2, $3, $1::text, $1::text, 'ready', now() - make_interval(days => $4))", + ) + .bind(id) + .bind(kb) + .bind(source) + .bind(days_old) + .execute(&pool) + .await?; + } + + let run = async { + let all = [old, recent, read, unwatched]; + let stale = stale_documents(&pool, &all).await?; + assert_eq!( + stale, + [old, read].into_iter().collect(), + "past 20 days, in a decaying source" + ); + + record_retrievals(&pool, &[read]).await?; + let stale = stale_documents(&pool, &all).await?; + assert_eq!( + stale, + [old].into_iter().collect(), + "a retrieval makes it fresh" + ); + assert!(stale_documents(&pool, &[]).await?.is_empty()); + anyhow::Ok(()) + } + .await; + + sqlx::query("DELETE FROM organizations WHERE id = $1") + .bind(org) + .execute(&pool) + .await?; + run +} diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs index 995ed0eb0..2eb46bc8f 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -102,6 +102,7 @@ mod a_source_decays_only_when_asked; mod a_source_kind_is_listed_once; mod a_source_over_its_cap_gives_up_its_lowest_scores; mod a_source_reaches_only_where_it_was_granted; +mod a_stale_document_is_found_among_a_decaying_sources; mod a_statement_is_attested_by_what_its_document_says; mod a_stopped_chat_is_replayed_as_incomplete; mod a_time_mention_is_resolved_against_its_document; diff --git a/docs/decisions/re-cinq/RC-003-a-source-may-decay.md b/docs/decisions/re-cinq/RC-003-a-source-may-decay.md index 209438fa5..c7166a8a4 100644 --- a/docs/decisions/re-cinq/RC-003-a-source-may-decay.md +++ b/docs/decisions/re-cinq/RC-003-a-source-may-decay.md @@ -24,12 +24,12 @@ Not every source wants this. A folder of specifications must not forget. So deca 2. Setting the option on a source. 3. Recording retrievals. 4. A daily sweep that takes a source over `max_items` back to it: from the documents older than `min_age_days`, the `excess` with the lowest score are deleted the way a person deletes them, so they can be restored. -5. Stale documents rank at 0.6 of their search score, and a result says its score. +5. A stale document ranks at 0.6 of its search score, before paging, and its hit says `stale: true`. ## Consequences - A base where no source sets the option stores nothing new and ranks as before. -- The sweep needs a source to be a bounded list; a source with no cap in its option never loses a document. +- Setting the option caps the source: a missing `max_items` is 500, not unlimited, so `{}` already evicts once a source holds more than 500 documents. - The fact purge Lore runs on facts invalidated more than 30 days ago is not part of this. The ledger is append-only. ## Open questions diff --git a/docs/design/chat-and-mcp.md b/docs/design/chat-and-mcp.md index 3be12dadd..ebc21d6b2 100644 --- a/docs/design/chat-and-mcp.md +++ b/docs/design/chat-and-mcp.md @@ -85,6 +85,9 @@ lose (2026-10-19). A search that returns a document of a source that decays counts as a use of it, in the background and never failing the read ([RC-003](../decisions/re-cinq/RC-003-a-source-may-decay.md)): `search_chunks` always does, and the REST body may carry `record: false` for a probe, an eval or a health check. +A hit on a document of a decaying source that nobody has retrieved for the source's `stale_after_days` +scores at 0.6 of its RRF score, before paging, and carries `stale: true`; a base where no source +decays never sees the field. **`remember`** writes a memory document at once; its statements go through open extraction and wait in `pending_facts`; the assistant says the sentence is recorded and its statements will be shown