From ffc1e8d557998c1ab03026f2490f42daa0e9560f Mon Sep 17 00:00:00 2001 From: Daniel <118035379+Floating-Y@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:59:43 +0800 Subject: [PATCH 1/2] Record why source syncs stop at timestamp boundaries (#1213) * Record why source checkpoints need bounded continuation Signed-off-by: Floating-Y <118035379+Floating-Y@users.noreply.github.com> * Record why source syncs stop at timestamp boundaries Signed-off-by: Floating-Y <118035379+Floating-Y@users.noreply.github.com> * Clarify how source syncs advance past a completed timestamp group Signed-off-by: Floating-Y <118035379+Floating-Y@users.noreply.github.com> --------- Signed-off-by: Floating-Y <118035379+Floating-Y@users.noreply.github.com> --- ...checkpoint-ends-at-a-timestamp-boundary.md | 129 ++++++++++++++++++ docs/decisions/README.md | 1 + 2 files changed, 130 insertions(+) create mode 100644 docs/decisions/0072-a-source-checkpoint-ends-at-a-timestamp-boundary.md diff --git a/docs/decisions/0072-a-source-checkpoint-ends-at-a-timestamp-boundary.md b/docs/decisions/0072-a-source-checkpoint-ends-at-a-timestamp-boundary.md new file mode 100644 index 000000000..d0f0bbbc9 --- /dev/null +++ b/docs/decisions/0072-a-source-checkpoint-ends-at-a-timestamp-boundary.md @@ -0,0 +1,129 @@ +# A source checkpoint ends at a timestamp boundary + +Proposed 2026-10-19 (#1212, #1213); open: implementation and regression coverage. + +## Context + +Source syncs can stop after 200 items and still record success. The next run +uses that successful run's start time as its lower bound, so it can skip items +that were never imported. [Issue #1212](https://github.com/deeplethe/utopia/issues/1212) +reproduces this with a custom response containing 201 items. + +A checkpoint must describe the data consumed. For GitHub and Jira, an item's +source update time provides that position, but a timestamp cannot identify a +position inside a group of items that share the same time. + +The [reader probes](https://github.com/deeplethe/utopia/issues/1212#issuecomment-6183423449) +show why that distinction matters. With one shared update time, GitHub's +1,001 items span eleven 100-item pages; Jira's 501 items span eleven 50-item +pages. A fixed ten-page limit repeatedly returns the same prefix. Keeping the +timestamp repeats that prefix; advancing past it loses the unread tail. + +## Decision + +Use a timestamp watermark: the latest source update time whose entire group +has been consumed. **A GitHub or Jira run stops only at a timestamp boundary.** +This follows the [maintainer's decision](https://github.com/deeplethe/utopia/issues/1212#issuecomment-6261482074). + +### GitHub and Jira + +Read items in ascending update-time order. Skip items at or before the +checkpoint before counting either budget. When the 200-item processing budget +or ten-page listing budget is exhausted inside a group, continue reading and +processing until that group is complete. Stop before consuming the next +timestamp group, then save the completed group's time as the checkpoint. +Reading ahead to identify the next group does not make that group consumed. + +For example, if item 200 belongs to a group ending at item 240, consume all +240 items and leave the next group for the next run. The 1,001-item GitHub +and 501-item Jira groups above must each arrive in full on the first run. + +The next run consumes only items updated strictly after the checkpoint. +GitHub's `since` is inclusive in practice, and Jira's `updated >=` bound is +rounded to the minute, so either provider can return items already consumed. +Skip every returned item at or before the checkpoint; these items count against +neither the 200-item processing budget nor the ten-page listing budget. +Pages containing only skipped items therefore cannot exhaust the listing +budget. For GitHub, `since` can be the checkpoint plus one second. + +Store the completed timestamp on the source, independently of retained sync +audit rows. Do not derive it from a run's start or finish time, or advance it +to the clock time merely because a query is empty. A failed run leaves the +previous checkpoint intact. Retry already committed items through the existing +document, version and processing-job deduplication. + +There is no persisted page, offset, fetched response or continuation state. +An unusually large timestamp group makes one run longer. Do not add a separate +group cap or a group-size alert; use the existing rate-limit backoff. The +exception applies to source listing and processing, not permission to replace +a GitHub document with a truncated comments or events history. + +### Custom + +The endpoint already returns the whole requested response. Walk its items in +order, charging only `Created` and `Updated` outcomes against the 200-item +budget. `Unchanged` items do not consume that budget. Mark the batch incomplete +only when processing stops with items left, and retain the previous checkpoint. +Retries can then pass the unchanged prefix and reach the remaining items. + +Once the whole response, including its deletions, is processed successfully, +advance the checkpoint to that run's start time, preserving the existing +protection for changes during the run. Keep the committed counts visible for +incomplete runs. No source-update field, pagination token or saved response is +added to the custom protocol; `doc_time` remains document time. + +The custom fix is being reviewed in +[PR #1246](https://github.com/deeplethe/utopia/pull/1246). It does not resolve +the GitHub and Jira parts of #1212. + +## Recovery and tradeoffs + +Old successful runs cannot prove that their windows were complete. On upgrade, +clear the checkpoint once for these three source kinds and recover from the +beginning using the same rules. Preserve documents, versions, jobs and audit +history; deduplication keeps unchanged content from creating new versions. +Resume incremental reads afterward. + +This design trades a hard per-run bound for progress through a timestamp group. +It does not make a provider's paginated result an atomic snapshot. Concurrent +updates and failures still need coverage before the implementation can claim +that checkpoints never cross unread data. + +## Rejected approaches + +- **Keep the old checkpoint but always take the first 200 items.** Retries + never reach the tail. This is why custom must count changed items only. +- **Use a timestamp with an unconditional ten-page limit.** The equal-time + examples above still stall. Completing the group removes that limitation. +- **Persist continuation state or a full response snapshot.** The original + proposal stored pages and consumption positions in `sources.sync_state`. + Finishing each timestamp group avoids that storage and recovery machinery. +- **Resume from a saved offset, even in creation order.** Deletions, transfers + and permission changes can move page boundaries. Keeping boundary identities + and restarting scans adds complexity the chosen design does not need. +- **Advance to the run's start time after partial work, or use custom + `doc_time`.** Neither proves that the remaining source changes were consumed. + +## Acceptance + +Reuse the real readers and existing HTTP/database fixtures. The implementation +must demonstrate: + +- GitHub's 1,001-item and Jira's 501-item equal-time groups are fully imported + in the first run, beyond ten pages. +- Exhausting either budget completes the current group but leaves the next + group for the next run, with the correct persisted checkpoint and queries. +- After importing the 1,001-item group at time T, the next run skips any + returned items at or before T without charging either budget, imports a + later group and advances the checkpoint past T. +- GitHub's inclusive boundary and Jira's minute-rounded query bound preserve + this progress without omissions or duplicate versions and processing jobs. +- A failed page fetch, detail fetch or write cannot advance the checkpoint; + retry recovers the whole group. Updates during pagination remain reachable. +- Custom's 201 changed items finish on the second run; 450 finish over three + capped runs. Cover an unchanged prefix and no custom update field. +- The one-time recovery scan preserves existing data and returns to incremental + sync. GitHub replacements retain complete discussion content. + +Database assertions must run with PostgreSQL/pgvector and +`UTOPIA_TEST_REQUIRE_DB=1`. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 727d60be0..2d0b81998 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -114,6 +114,7 @@ By domain; the domains are the files of [../design/](../design/README.md). **Sta | 0052 | [Document content is a read contract over the retained ledger](0052-document-content-is-a-read-contract.md) | Proposed | | | 0054 | [A source may push statements in the open contract](0054-a-source-may-push-statements-in-the-open-contract.md) | Implemented | | | 0065 | [The OCR reader chooses its provider](0065-readers-choose-their-provider.md) | Implemented | | +| 0072 | [A source checkpoint ends at a timestamp boundary](0072-a-source-checkpoint-ends-at-a-timestamp-boundary.md) | Proposed | | ### [lakehouse-and-actions](../design/lakehouse-and-actions.md) From 353f03426a9d8d2ac4c3fddd25adb24783ec1887 Mon Sep 17 00:00:00 2001 From: Bogdan Szabo Date: Wed, 21 Oct 2026 21:52:13 +0200 Subject: [PATCH 2/2] A source can be set to decay: Lore's score, a retrieval record, and the option column Signed-off-by: Bogdan Szabo --- crates/utopia-cli/src/main.rs | 2 +- crates/utopia-store/src/decay.rs | 220 ++++++++++++++++++ crates/utopia-store/src/lib.rs | 1 + .../store/a_source_decays_only_when_asked.rs | 113 +++++++++ crates/utopia-store/tests/store/main.rs | 1 + .../re-cinq/RC-003-a-source-may-decay.md | 38 +++ migrations/9004_a_source_may_decay.sql | 16 ++ 7 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 crates/utopia-store/src/decay.rs create mode 100644 crates/utopia-store/tests/store/a_source_decays_only_when_asked.rs create mode 100644 docs/decisions/re-cinq/RC-003-a-source-may-decay.md create mode 100644 migrations/9004_a_source_may_decay.sql diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index 1d93a525b..2c85aaded 100644 --- a/crates/utopia-cli/src/main.rs +++ b/crates/utopia-cli/src/main.rs @@ -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 = 107; +const CURRENT_SCHEMA_VERSION: u32 = 108; fn main() -> anyhow::Result<()> { dotenvy::dotenv().ok(); diff --git a/crates/utopia-store/src/decay.rs b/crates/utopia-store/src/decay.rs new file mode 100644 index 000000000..9834b853f --- /dev/null +++ b/crates/utopia-store/src/decay.rs @@ -0,0 +1,220 @@ +//! 源级衰减(RC-003):Lore 的 `scoreImportance` 逐条移植,同样的输入给出同样的分。 +//! +//! 一个文档的分是 0–10 的整数:`round(10 · 0.5^(年龄/半衰期))` 加上几项修正。 +//! 年龄从最近一次被检索算起,没被检索过就从创建算起。强度与分都不存,读的时候算。 + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +pub const DEFAULT_HALF_LIFE_DAYS: f64 = 60.0; +pub const MAX_HALF_LIFE_DAYS: f64 = 365.0; +/// 每次被检索,半衰期加的天数(到 [`MAX_HALF_LIFE_DAYS`] 封顶)。 +pub const RETRIEVAL_HALF_LIFE_GAIN_DAYS: f64 = 2.0; + +const MILLIS_PER_DAY: f64 = 86_400_000.0; + +/// `sources.decay`:缺的字段取 Lore 的默认值,所以 `{}` 就是 Lore 今天的行为。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DecaySettings { + /// 源里文档超过这个数,每天的扫描才淘汰多出来的。 + pub max_items: u32, + pub half_life_days: u32, + /// 这么多天没被检索就算陈旧。 + pub stale_after_days: u32, + /// 比这新的文档不参与淘汰。 + pub min_age_days: u32, +} + +impl Default for DecaySettings { + fn default() -> Self { + Self { + max_items: 500, + half_life_days: 60, + stale_after_days: 30, + min_age_days: 30, + } + } +} + +/// 打分用到的一个文档:`key` 是文档名,`value` 是它的文字。 +pub struct Memory<'a> { + pub key: &'a str, + pub value: &'a str, + pub created_at: DateTime, + pub last_retrieved_at: Option>, + /// 0 或没有都取 [`DEFAULT_HALF_LIFE_DAYS`]。 + pub half_life_days: Option, + pub retrieval_count: u32, + pub stale: bool, +} + +pub fn score_importance(memory: &Memory, now: DateTime) -> u8 { + let strength_points = (decay_strength(memory, now) * 10.0).round() as i64; + let score = strength_points + importance_adjustments(memory); + score.clamp(0, 10) as u8 +} + +fn decay_strength(memory: &Memory, now: DateTime) -> f64 { + let half_life = memory + .half_life_days + .filter(|days| *days > 0.0) + .unwrap_or(DEFAULT_HALF_LIFE_DAYS); + let since = memory.last_retrieved_at.unwrap_or(memory.created_at); + let age_days = (now - since).num_milliseconds() as f64 / MILLIS_PER_DAY; + 0.5_f64.powf(age_days / half_life) +} + +fn importance_adjustments(memory: &Memory) -> i64 { + value_length_adjustment(memory.value) + + key_prefix_adjustment(memory.key) + + key_topic_adjustment(memory.key) + + retrieval_adjustment(memory.retrieval_count) + + if memory.stale { -1 } else { 0 } +} + +/// 长度按 UTF-16 码元数,和 Lore(JS 的 `string.length`)一致,表情符号算两个。 +fn value_length_adjustment(value: &str) -> i64 { + match value.encode_utf16().count() { + 0..=49 => -2, + 501.. => 1, + _ => 0, + } +} + +fn key_prefix_adjustment(key: &str) -> i64 { + let prefixes = ["auto-curation/", "session-summary/"]; + -(prefixes.iter().filter(|p| key.starts_with(**p)).count() as i64) +} + +fn key_topic_adjustment(key: &str) -> i64 { + let topics = ["gotcha", "decision", "convention", "pattern"]; + 2 * topics.iter().filter(|t| key.contains(**t)).count() as i64 +} + +fn retrieval_adjustment(retrievals: u32) -> i64 { + match retrievals { + 20.. => 2, + 5..=19 => 1, + _ => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::{Duration, TimeZone}; + + fn now() -> DateTime { + Utc.with_ymd_and_hms(2026, 10, 21, 0, 0, 0).unwrap() + } + + fn memory<'a>(key: &'a str, value: &'a str, created_days_ago: i64) -> Memory<'a> { + Memory { + key, + value, + created_at: now() - Duration::days(created_days_ago), + last_retrieved_at: None, + half_life_days: None, + retrieval_count: 0, + stale: false, + } + } + + /// 期望值由 Lore 的 `scoreImportance`(libs/shared/src/domain/memory-ranking.ts)在同一个 + /// `now` 下算出,不是照这里的实现推的。 + #[test] + fn a_score_matches_lores_for_every_vector() { + let mid = "x".repeat(100); + let long = "x".repeat(600); + let short = "x".repeat(10); + let thirty_emoji = "😀".repeat(30); + let twenty_emoji = "😀".repeat(20); + let at = |key, value: &str, days, tweak: fn(&mut Memory)| { + let mut m = memory(key, value, days); + tweak(&mut m); + score_importance(&m, now()) + }; + let same: fn(&mut Memory) = |_| {}; + + assert_eq!(at("notes/a", &mid, 0, same), 10, "fresh"); + assert_eq!(at("notes/a", &mid, 60, same), 5, "one half-life"); + assert_eq!(at("notes/a", &mid, 120, same), 3, "two half-lives"); + assert_eq!( + at("notes/a", &mid, 300, |m| { + m.last_retrieved_at = Some(now() - Duration::days(1)) + }), + 10, + "a retrieval restarts the age" + ); + assert_eq!( + at("notes/a", &mid, 30, |m| m.half_life_days = Some(30.0)), + 5, + "own half-life" + ); + assert_eq!( + at("notes/a", &mid, 60, |m| m.half_life_days = Some(0.0)), + 5, + "zero half-life means the default" + ); + assert_eq!(at("notes/a", &short, 0, same), 8, "short value"); + assert_eq!(at("notes/a", &long, 0, same), 10, "long value"); + assert_eq!(at("auto-curation/x", &mid, 0, same), 9, "auto-curation"); + assert_eq!(at("session-summary/x", &mid, 0, same), 9, "session-summary"); + assert_eq!(at("gotcha-pattern", &mid, 0, same), 10, "two topics"); + assert_eq!(at("decision/db", &mid, 90, same), 6, "topic, aged"); + assert_eq!( + at("notes/a", &mid, 60, |m| m.retrieval_count = 5), + 6, + "five retrievals" + ); + assert_eq!( + at("notes/a", &mid, 60, |m| m.retrieval_count = 20), + 7, + "twenty retrievals" + ); + assert_eq!(at("notes/a", &mid, 0, |m| m.stale = true), 9, "stale"); + assert_eq!( + at("session-summary/x", &short, 900, |m| m.stale = true), + 0, + "floor" + ); + assert_eq!( + at("decision-convention-gotcha-pattern", &long, 0, |m| { + m.retrieval_count = 30 + }), + 10, + "ceiling" + ); + assert_eq!( + at("notes/a", &thirty_emoji, 0, same), + 10, + "60 UTF-16 units is not short" + ); + assert_eq!( + at("notes/a", &twenty_emoji, 0, same), + 8, + "40 UTF-16 units is short" + ); + } + + #[test] + fn an_empty_settings_object_is_lores_defaults() { + let settings: DecaySettings = serde_json::from_str("{}").unwrap(); + assert_eq!( + settings, + DecaySettings { + max_items: 500, + half_life_days: 60, + stale_after_days: 30, + min_age_days: 30 + } + ); + } + + #[test] + fn a_misspelled_setting_is_refused() { + let parsed = serde_json::from_str::(r#"{"max_item": 5}"#); + assert!(parsed.is_err()); + } +} diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs index cdb6334f9..bb52d627e 100644 --- a/crates/utopia-store/src/lib.rs +++ b/crates/utopia-store/src/lib.rs @@ -12,6 +12,7 @@ pub mod competency_questions; pub mod conversations; pub mod datasources; pub mod db; +pub mod decay; pub mod documents; pub mod errata; pub mod execution_gate; diff --git a/crates/utopia-store/tests/store/a_source_decays_only_when_asked.rs b/crates/utopia-store/tests/store/a_source_decays_only_when_asked.rs new file mode 100644 index 000000000..23a389fcf --- /dev/null +++ b/crates/utopia-store/tests/store/a_source_decays_only_when_asked.rs @@ -0,0 +1,113 @@ +//! 源的衰减开关与文档的检索记录(RC-003),打在真库上。 +//! +//! 要钉住的行为: +//! +//! - **关着是默认**:新建的源 `decay` 为 NULL,没人要求就什么都不多写 +//! - **开关是个对象**:`decay` 只收 JSON 对象,别的形状数据库拒绝 +//! - **半衰期有范围**:`document_salience.half_life_days` 在 1 到 365 之外数据库拒绝 +//! - **跟着文档走**:文档删掉,它的检索记录一起没 +//! +//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 + +use sqlx::PgPool; +use uuid::Uuid; + +#[tokio::test] +async fn a_source_decays_only_when_asked() -> 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, source, document) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'source-decay-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'source-decay-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'source-decay-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO sources (id, kb_id, kind, name) VALUES ($1, $2, 'folder', 'f')") + .bind(source) + .bind(kb) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status) + VALUES ($1, $2, $3, 'a.md', 'x', 'ready')", + ) + .bind(document) + .bind(kb) + .bind(source) + .execute(&pool) + .await?; + + let run = async { + let decay: Option = + sqlx::query_scalar("SELECT decay FROM sources WHERE id = $1") + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(decay, None, "a new source does not decay"); + + let not_an_object = sqlx::query("UPDATE sources SET decay = '[]'::jsonb WHERE id = $1") + .bind(source) + .execute(&pool) + .await; + assert!(not_an_object.is_err(), "decay is an object or nothing"); + sqlx::query("UPDATE sources SET decay = '{}'::jsonb WHERE id = $1") + .bind(source) + .execute(&pool) + .await?; + + for half_life in [0.5_f32, 366.0] { + let out_of_range = sqlx::query( + "INSERT INTO document_salience (document_id, half_life_days) VALUES ($1, $2)", + ) + .bind(document) + .bind(half_life) + .execute(&pool) + .await; + assert!(out_of_range.is_err(), "{half_life} days is out of range"); + } + sqlx::query("INSERT INTO document_salience (document_id, half_life_days) VALUES ($1, 62)") + .bind(document) + .execute(&pool) + .await?; + + sqlx::query("DELETE FROM documents WHERE id = $1") + .bind(document) + .execute(&pool) + .await?; + let remaining: i64 = + sqlx::query_scalar("SELECT count(*) FROM document_salience WHERE document_id = $1") + .bind(document) + .fetch_one(&pool) + .await?; + assert_eq!(remaining, 0, "a deleted document leaves no record"); + 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 47874c03a..7f446a50a 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -95,6 +95,7 @@ mod a_signature_holds_on_every_path; mod a_signature_vector_lasts_while_its_text_does; mod a_similar_name_is_proposed_not_merged; mod a_single_name_candidate_is_not_counted; +mod a_source_decays_only_when_asked; mod a_source_kind_is_listed_once; mod a_source_reaches_only_where_it_was_granted; mod a_statement_is_attested_by_what_its_document_says; 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 new file mode 100644 index 000000000..209438fa5 --- /dev/null +++ b/docs/decisions/re-cinq/RC-003-a-source-may-decay.md @@ -0,0 +1,38 @@ +# RC-003 · A source may decay + +> re:cinq fork only. Status: accepted 2026-10-21, in progress. Upstream: to be proposed on [deeplethe/utopia#1277](https://github.com/deeplethe/utopia/issues/1277), where it narrows the unnumbered draft "Use decays; the ledger does not" to a per-source option. + +## Context + +Lore keeps agent memory with a decay model: every memory has a score from 0 to 10 that falls as it goes unread, rises when it is read, and decides which memories go when an agent holds more than 500. Lore is moving its stores into Utopia, and Utopia keeps everything with the same weight forever. A source that pushes memories (0054) grows without bound, and a note nobody has read in a year ranks the same as one read yesterday. + +Not every source wants this. A folder of specifications must not forget. So decay is a choice a source makes. + +## Decision + +**Decay is an option of a source, off by default.** `sources.decay` is NULL until someone sets it, and a source with NULL behaves as it does today and writes nothing extra. When set it is an object with `max_items` (500), `half_life_days` (60), `stale_after_days` (30) and `min_age_days` (30); a missing field takes Lore's value, so `{}` is Lore's behaviour. A field this record does not name is refused. + +**The score is Lore's, unchanged.** `decay::score_importance` returns an integer from 0 to 10: `round(10 · 0.5^(age / half-life))`, where age counts from the last retrieval and from creation if there is none, plus adjustments for the length of the text (under 50 UTF-16 units −2, over 500 +1), the key prefixes `auto-curation/` and `session-summary/` (−1 each), the key topics `gotcha`, `decision`, `convention` and `pattern` (+2 each), the retrieval count (5 or more +1, 20 or more +2) and staleness (−1). A document is a Lore memory: its name is the key and its text the value. The test compares the port with scores computed by Lore's own `scoreImportance`, so the two cannot drift apart unnoticed. + +**A retrieval is recorded beside the document.** `document_salience` holds a retrieval count, the time of the last retrieval and the half-life, one row per document, and only for documents of a source that decays. Each retrieval adds 2 days to the half-life up to 365. It is a side table because the document row should not change on every read. + +**Stale is read, not written.** Lore marks an unread fact `stale` in its confidence column. Here `stale` is worked out when it is read, from the last retrieval and the source's `stale_after_days`, and `confidence` is never touched. It says how sure the source was, [0011](../0011-a-mapping-is-not-a-fact.md) removed the one update in place the ledger ever had, and the review queue reads that column. + +## What is built in which step + +1. This record, the `sources.decay` column, the `document_salience` table and the score. +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. + +## 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. +- 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 + +- Whether a chunk of the memory log (`memory.rs`) should decay on its own, since it is one document of many chunks. +- Whether feedback (a merged pull request raises a half-life by 5, a rejected one lowers it by 3 down to 7) is reachable from outside, as an API. diff --git a/migrations/9004_a_source_may_decay.sql b/migrations/9004_a_source_may_decay.sql new file mode 100644 index 000000000..2b14bef13 --- /dev/null +++ b/migrations/9004_a_source_may_decay.sql @@ -0,0 +1,16 @@ +-- re:cinq fork only (RE-CINQ.md: fork migrations are numbered from 9000 and idempotent). +-- +-- 一个源可以让自己的文档衰减(RC-003)。`sources.decay` 为 NULL 就是关着:今天的行为, +-- 什么都不多写。打开之后形如 {"max_items":500,"half_life_days":60,"stale_after_days":30, +-- "min_age_days":30},缺的字段取 Lore 的默认值。 +ALTER TABLE sources + ADD COLUMN IF NOT EXISTS decay JSONB CHECK (decay IS NULL OR jsonb_typeof(decay) = 'object'); + +-- 文档被检索的记录:只给打开了衰减的源的文档写,边表而不是文档上的列, +-- 因为每次检索都要写,文档行不该被读搅动。半衰期每次检索 +2 天,上限 365。 +CREATE TABLE IF NOT EXISTS document_salience ( + document_id UUID PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, + retrieval_count INTEGER NOT NULL DEFAULT 0 CHECK (retrieval_count >= 0), + last_retrieved_at TIMESTAMPTZ, + half_life_days REAL NOT NULL CHECK (half_life_days >= 1 AND half_life_days <= 365) +);