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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ UTOPIA_OPEN_REGISTRATION=true
# 池子小于并发时症状是请求变慢、而不是任何一处说"池子不够"——调高 worker
# 并发时一并考虑这里,也别超过 Postgres 自己的 max_connections(默认 100)。
# UTOPIA_DB_MAX_CONNECTIONS=32
# 被取代的分块(文档新版本不再带的段落)把向量留几天。留空即可——向量一直留着,as-of 的
# 向量检索倒回多久都找得到。设了之后每天清一次超过这个天数的向量,行与正文不动;代价是
# 倒回到更早时刻的向量检索找不到那些被替换的段落。取值收在 1 到 3650 之间。
# 每次同步都整批重推的大库才用得上(0019)。
# UTOPIA_SUPERSEDED_VECTOR_DAYS=30

# --- 以下几项由 docker-compose 读取,不是应用配置 ---
# 数据库口令。默认值只适合本机开发,公开部署务必改。
Expand Down
2 changes: 1 addition & 1 deletion crates/utopia-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = 112;
const CURRENT_SCHEMA_VERSION: u32 = 113;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
Expand Down
9 changes: 9 additions & 0 deletions crates/utopia-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ pub struct AppConfig {
/// `UTOPIA_OIDC_ALLOWED_DOMAINS` 自动开户);打开就是身份提供方出事时的后门。
/// `UTOPIA_PASSWORD_LOGIN`
pub password_login: bool,
/// 被取代的分块把向量留几天。缺省不设:向量一直留着(0019 开放问题②),as-of 的
/// 向量检索倒回多久都找得到。设了之后每天清一次,行与正文不动。取值收在 1 到 3650
/// 之间(`retention::window`)。`UTOPIA_SUPERSEDED_VECTOR_DAYS`
pub superseded_vector_days: Option<i64>,
}

impl Default for AppConfig {
Expand All @@ -64,6 +68,7 @@ impl Default for AppConfig {
cookie_secure: false,
open_registration: true,
password_login: true,
superseded_vector_days: None,
}
}
}
Expand Down Expand Up @@ -184,9 +189,11 @@ mod tests {
Jail::expect_with(|jail| {
jail.set_env("UTOPIA_DB_MAX_CONNECTIONS", "");
jail.set_env("UTOPIA_COOKIE_SECURE", "");
jail.set_env("UTOPIA_SUPERSEDED_VECTOR_DAYS", "");
let cfg = AppConfig::load().unwrap();
assert_eq!(cfg.db_max_connections, None);
assert!(!cfg.cookie_secure);
assert_eq!(cfg.superseded_vector_days, None);
Ok(())
});
}
Expand All @@ -197,9 +204,11 @@ mod tests {
Jail::expect_with(|jail| {
jail.set_env("UTOPIA_DB_MAX_CONNECTIONS", "8");
jail.set_env("UTOPIA_COOKIE_SECURE", "true");
jail.set_env("UTOPIA_SUPERSEDED_VECTOR_DAYS", "30");
let cfg = AppConfig::load().unwrap();
assert_eq!(cfg.db_max_connections, Some(8));
assert!(cfg.cookie_secure);
assert_eq!(cfg.superseded_vector_days, Some(30));
Ok(())
});
}
Expand Down
52 changes: 52 additions & 0 deletions crates/utopia-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,36 @@ async fn main() -> anyhow::Result<()> {
}
});

// 被取代的分块留不留向量由部署决定:不设 `UTOPIA_SUPERSEDED_VECTOR_DAYS` 就什么都不排
if let Some(days) = cfg.superseded_vector_days {
let prune_state = state.clone();
tokio::spawn(async move {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(86_400));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tick.tick().await;
let bases = match utopia_store::retention::bases(&prune_state.pool).await {
Ok(bases) => bases,
Err(e) => {
tracing::warn!(error = %e, "列出要清理的库失败");
continue;
}
};
for kb_id in bases {
if let Err(e) = utopia_store::jobs::enqueue_unless_queued(
&prune_state.pool,
utopia_store::retention::JOB_KIND,
serde_json::json!({ "kb_id": kb_id, "days": days }),
)
.await
{
tracing::warn!(kb_id = %kb_id, error = %e, "清理任务入队失败");
}
}
}
});
}

let app = api::router(state, &cfg);
let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?;
tracing::info!("Utopia 服务启动于 http://{}", cfg.bind_addr);
Expand Down Expand Up @@ -588,6 +618,28 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
adjudication::adjudicate_entities(st, kb_id).await
}
utopia_store::retention::JOB_KIND => {
let kb_id: Uuid = job
.payload
.get("kb_id")
.and_then(|v| v.as_str())
.and_then(|s| s.parse().ok())
.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
let days = job
.payload
.get("days")
.and_then(|v| v.as_i64())
.ok_or_else(|| anyhow::anyhow!("payload 缺少 days"))?;
let vectors_cleared =
utopia_store::retention::prune_superseded(&st.pool, kb_id, days).await?;
tracing::info!(
%kb_id,
days,
vectors_cleared,
"被取代的分块清理完成"
);
Ok(())
}
"govern" => {
let kb_id: Uuid = job
.payload
Expand Down
4 changes: 4 additions & 0 deletions crates/utopia-store/src/documents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1675,6 +1675,10 @@ async fn replace_chunks_for_snapshot(
// 而省掉的是两者里更小的那一半:块的**正文**本来就留着(版本回放要它),
// 一条 1024 维向量不过几 KB。代价却是历史整段搜不出来——记录轴倒得回去,
// 检索却只认现在,as-of 检索一开口就是空的。
//
// 缺省如此。每次同步都整批重推的大库里,3072 维的向量才是大的那一半,部署可以设
// `UTOPIA_SUPERSEDED_VECTOR_DAYS`,让 `retention::prune_superseded` 每天清掉被取代
// 超过那么多天的向量;行与正文照旧留着(0019 的修订)。
sqlx::query(
"UPDATE chunks SET superseded_at = now()
WHERE document_id = $1 AND superseded_at IS NULL AND NOT (id = ANY($2))",
Expand Down
1 change: 1 addition & 0 deletions crates/utopia-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub mod phrase_bindings;
pub mod reasoning;
pub mod record_axis;
pub mod resolution;
pub mod retention;
pub mod review;
pub mod review_summary;
pub mod rss_full_content;
Expand Down
89 changes: 89 additions & 0 deletions crates/utopia-store/src/retention.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//! An old version keeps no vector, where a deployment asks for that.
//!
//! `replace_chunks` supersedes a chunk the new version of its document no longer
//! carries and keeps the row whole: the text for version replay and the vector for an
//! as-of search ([0019](../../../docs/decisions/0019-the-second-clock-can-be-rewound.md)
//! open question ②). A `statements` source pushes everything on every pass, so a base of
//! mirrored statements grows a superseded chunk, vector included, for every paragraph
//! that changed, forever. The vector is the larger part of the row by far.
//!
//! Off unless `UTOPIA_SUPERSEDED_VECTOR_DAYS` is set. Then a sweep runs once a day per
//! base, and a chunk superseded longer ago than that many days loses its vector. The row
//! stays: its text, and whatever evidence, pending fact, time mention or role word points
//! at it. A vector can be computed again from the text; a row could not.
//!
//! A deleted document is left whole. `documents::delete` supersedes its live chunks and
//! `documents::restore` makes them live again, so a vector cleared in between would bring
//! the document back unsearchable by meaning.
use chrono::{Duration, Utc};
use sqlx::PgPool;
use utopia_core::AppResult;
use uuid::Uuid;

pub const JOB_KIND: &str = "prune_superseded";
pub const SHORTEST_WINDOW_DAYS: i64 = 1;
pub const LONGEST_WINDOW_DAYS: i64 = 3650;
const BATCH: i64 = 10_000;

/// How long a superseded chunk keeps its vector. Zero or less would clear the vector of a
/// chunk superseded a moment ago, and `Duration::days` panics on a count it cannot hold
pub fn window(days: i64) -> Duration {
Duration::days(days.clamp(SHORTEST_WINDOW_DAYS, LONGEST_WINDOW_DAYS))
}

/// Every base, for the daily tick: a base with nothing old enough costs one index probe.
pub async fn bases(pool: &PgPool) -> AppResult<Vec<Uuid>> {
let ids: Vec<(Uuid,)> = sqlx::query_as("SELECT id FROM knowledge_bases")
.fetch_all(pool)
.await?;
Ok(ids.into_iter().map(|(id,)| id).collect())
}

/// Clears the vector of every chunk of the base superseded more than `days` ago
/// ([`window`]) and returns how many it cleared
pub async fn prune_superseded(pool: &PgPool, kb_id: Uuid, days: i64) -> AppResult<u64> {
let cutoff = Utc::now() - window(days);
let mut total = 0;
loop {
let cleared = sqlx::query(
"UPDATE chunks SET embedding = NULL
WHERE id IN (SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id
WHERE c.kb_id = $1 AND c.superseded_at < $2
AND d.deleted_at IS NULL AND c.embedding IS NOT NULL
LIMIT $3)",
)
.bind(kb_id)
.bind(cutoff)
.bind(BATCH)
.execute(pool)
.await?
.rows_affected();
total += cleared;
if cleared == 0 {
return Ok(total);
}
}
}

#[cfg(test)]
mod tests {
use super::window;
use chrono::Duration;

#[test]
fn a_window_of_30_days_is_30_days() {
assert_eq!(window(30), Duration::days(30));
}

#[test]
fn a_window_of_0_or_minus_5_days_is_1_day() {
assert_eq!(window(0), Duration::days(1));
assert_eq!(window(-5), Duration::days(1));
}

#[test]
fn a_window_of_i64_max_days_is_3650_days() {
assert_eq!(window(i64::MAX), Duration::days(3650));
}
}
Loading
Loading