Skip to content
Merged
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
36 changes: 33 additions & 3 deletions crates/utopia-server/src/retrieval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
pub vector_rank: Option<u32>,
}
Expand Down Expand Up @@ -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<Uuid, utopia_search::Fused> = fused.into_iter().collect();
let results = live
let mut scored: Vec<ScoredChunk> = 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<Uuid> = 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,
Expand All @@ -164,6 +179,21 @@ pub fn record_retrievals(state: &AppState, mut document_ids: Vec<Uuid>) {
});
}

/// 陈旧文档的命中乘 [`utopia_store::decay::STALE_SEARCH_WEIGHT`] 后重排。没有陈旧的就不动,
/// 排序稳定,同分仍按原来的先后。
fn demote_stale(hits: &mut [ScoredChunk], stale: &std::collections::HashSet<Uuid>) {
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<usize>], channel: usize) -> Option<u32> {
ranks
Expand Down
90 changes: 90 additions & 0 deletions crates/utopia-server/src/retrieval_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,19 @@ impl Fixture {
Ok(chunks.into_iter().map(|c| c.id).collect())
}

async fn scored_search(&self) -> anyhow::Result<super::SearchPage> {
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)
Expand Down Expand Up @@ -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<_>>(),
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(())
}
24 changes: 24 additions & 0 deletions crates/utopia-store/src/decay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ pub fn is_stale(last_touched: DateTime<Utc>, 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<std::collections::HashSet<Uuid>> {
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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
1 change: 1 addition & 0 deletions crates/utopia-store/tests/store/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions docs/decisions/re-cinq/RC-003-a-source-may-decay.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/design/chat-and-mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading