Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
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
53 changes: 53 additions & 0 deletions crates/utopia-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,32 @@ async fn main() -> anyhow::Result<()> {
}
});

// 每日清理被取代的分块:对每个库入队一个任务,多旧才算旧由任务自己判断
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;
match utopia_store::retention::bases(&prune_state.pool).await {
Ok(bases) => {
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 }),
)
.await
{
tracing::warn!(kb_id = %kb_id, error = %e, "清理任务入队失败");
}
}
}
Err(e) => tracing::warn!(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 +614,33 @@ 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())
.unwrap_or(utopia_store::retention::DEFAULT_AGE_DAYS);
let pruned = utopia_store::retention::prune_superseded(
&st.pool,
kb_id,
chrono::Duration::days(days),
)
.await?;
tracing::info!(
%kb_id,
days,
vectors_cleared = pruned.vectors_cleared,
chunks_deleted = pruned.chunks_deleted,
"被取代的分块清理完成"
);
Ok(())
}
"govern" => {
let kb_id: Uuid = job
.payload
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
105 changes: 105 additions & 0 deletions crates/utopia-store/src/retention.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
//! An old version keeps no vector.
//!
//! `replace_chunks` supersedes a chunk the new version of its document no longer
//! carries and keeps the row whole: the text for version replay, the vector for an
//! as-of search ([0019](../../../docs/decisions/0019-the-second-clock-can-be-rewound.md)
//! open question ②), and the row itself because `fact_evidence`, `pending_facts`,
//! `time_mentions` and `statement_qualifiers` cascade on it. 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.
//!
//! The sweep runs once a day per base. A chunk superseded longer ago than `older_than`
//! loses its vector. It loses its row too when nothing refers to it: evidence on a
//! superseded chunk is what tells a fact its source moved on (the close time is the
//! chunk's `superseded_at`).
//!
//! 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::{DateTime, Duration, Utc};
use sqlx::PgPool;
use utopia_core::AppResult;
use uuid::Uuid;

/// A chunk `c` superseded before `$2` in base `$1`, whose document `d` is not deleted
const OLD_IN_A_KEPT_DOCUMENT: &str = "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";

pub const JOB_KIND: &str = "prune_superseded";
pub const DEFAULT_AGE_DAYS: i64 = 7;
const BATCH: i64 = 10_000;

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Pruned {
pub vectors_cleared: u64,
pub chunks_deleted: u64,
}

/// Every base, for the daily tick: a base with nothing old enough costs two index probes.
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())
}

pub async fn prune_superseded(
pool: &PgPool,
kb_id: Uuid,
older_than: Duration,
) -> AppResult<Pruned> {
let cutoff = Utc::now() - older_than;
Ok(Pruned {
vectors_cleared: clear_vectors(pool, kb_id, cutoff).await?,
chunks_deleted: delete_unreferenced(pool, kb_id, cutoff).await?,
})
}

async fn clear_vectors(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>) -> AppResult<u64> {
let mut total = 0;
loop {
let cleared = sqlx::query(&format!(
"UPDATE chunks SET embedding = NULL
WHERE id IN (SELECT c.id FROM {OLD_IN_A_KEPT_DOCUMENT}
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);
}
}
}

async fn delete_unreferenced(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>) -> AppResult<u64> {
let mut total = 0;
loop {
let deleted = sqlx::query(&format!(
"DELETE FROM chunks
WHERE id IN (SELECT c.id FROM {OLD_IN_A_KEPT_DOCUMENT}
AND NOT EXISTS (SELECT 1 FROM fact_evidence e WHERE e.chunk_id = c.id)
AND NOT EXISTS (SELECT 1 FROM pending_facts p WHERE p.chunk_id = c.id)
AND NOT EXISTS (SELECT 1 FROM time_mentions m WHERE m.chunk_id = c.id)
AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.chunk_id = c.id)
LIMIT $3)"
))
.bind(kb_id)
.bind(cutoff)
.bind(BATCH)
.execute(pool)
.await?
.rows_affected();
total += deleted;
if deleted == 0 {
return Ok(total);
}
}
}
201 changes: 201 additions & 0 deletions crates/utopia-store/tests/store/an_old_version_keeps_no_vector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
//! An old version keeps no vector: a chunk superseded longer ago than the cutoff
//! loses its vector, and its row too when no evidence, pending fact, time mention or
//! statement qualifier refers to it. A chunk superseded more recently, a live one, and
//! one evidence still points at, keep what they have. So does every chunk of a deleted
//! document, which a restore makes live again.

use chrono::{Duration, Utc};
use pgvector::Vector;
use sqlx::PgPool;
use utopia_store::retention::{prune_superseded, Pruned};
use uuid::Uuid;

#[derive(Debug, PartialEq, sqlx::FromRow)]
struct Row {
id: Uuid,
has_vector: bool,
}

async fn rows(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<Row>> {
Ok(sqlx::query_as(
"SELECT id, embedding IS NOT NULL AS has_vector FROM chunks WHERE kb_id = $1 ORDER BY seq",
)
.bind(kb)
.fetch_all(pool)
.await?)
}

#[tokio::test]
async fn a_chunk_superseded_ten_days_ago_is_gone_and_a_cited_or_qualified_one_keeps_only_its_text(
) -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let [org, ws, kb, class, ada, bea, fact, doc, live, recent, old, cited, qualified] =
std::array::from_fn(|_| Uuid::now_v7());
let now = Utc::now();
let run = async {
sqlx::raw_sql(&format!(
"INSERT INTO organizations(id,name) VALUES ('{org}','prune');
INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','prune');
INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','prune');
INSERT INTO entity_types(id,kb_id,key,label) VALUES ('{class}','{kb}','thing','Thing');
INSERT INTO entities(id,kb_id,type_id,canonical_name) VALUES
('{ada}','{kb}','{class}','Ada'), ('{bea}','{kb}','{class}','Bea');
INSERT INTO facts (id,kb_id,subject_id,object_id,layer,phrase,confidence)
VALUES ('{fact}','{kb}','{ada}','{bea}','open','knows',0.9);
INSERT INTO documents(id,kb_id,filename,sha256) VALUES ('{doc}','{kb}','a.md','sha-{doc}');"
))
.execute(&pool)
.await?;
for (id, seq, superseded_at) in [
(live, 0, None),
(recent, 1, Some(now - Duration::days(2))),
(old, 2, Some(now - Duration::days(10))),
(cited, 3, Some(now - Duration::days(10))),
(qualified, 4, Some(now - Duration::days(10))),
] {
sqlx::query(
"INSERT INTO chunks (id, kb_id, document_id, seq, text, embedding, superseded_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
)
.bind(id)
.bind(kb)
.bind(doc)
.bind(seq)
.bind(format!("chunk {seq}"))
.bind(Vector::from(vec![0.1, 0.2, 0.3]))
.bind(superseded_at)
.execute(&pool)
.await?;
}
sqlx::query("INSERT INTO fact_evidence (fact_id, chunk_id, document_id, quote) VALUES ($1, $2, $3, 'q')")
.bind(fact)
.bind(cited)
.bind(doc)
.execute(&pool)
.await?;
sqlx::query("INSERT INTO statement_qualifiers (fact_id, role, value, chunk_id) VALUES ($1, 'since', '\"2020\"', $2)")
.bind(fact)
.bind(qualified)
.execute(&pool)
.await?;

let pruned = prune_superseded(&pool, kb, Duration::days(7)).await?;
assert_eq!(
pruned,
Pruned {
vectors_cleared: 3,
chunks_deleted: 1
}
);
assert_eq!(
rows(&pool, kb).await?,
vec![
Row {
id: live,
has_vector: true
},
Row {
id: recent,
has_vector: true
},
Row {
id: cited,
has_vector: false
},
Row {
id: qualified,
has_vector: false
},
]
);
let evidence: (i64,) =
sqlx::query_as("SELECT count(*) FROM fact_evidence WHERE fact_id = $1")
.bind(fact)
.fetch_one(&pool)
.await?;
assert_eq!(evidence.0, 1, "the evidence survives with its chunk");

assert_eq!(
prune_superseded(&pool, kb, Duration::days(7)).await?,
Pruned::default(),
"a second pass finds nothing"
);
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?;
run
}

#[tokio::test]
async fn a_document_restored_after_ten_days_in_the_trash_still_has_its_vector() -> anyhow::Result<()>
{
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
let [org, ws, kb, doc, chunk] = std::array::from_fn(|_| Uuid::now_v7());
let run = async {
sqlx::raw_sql(&format!(
"INSERT INTO organizations(id,name) VALUES ('{org}','prune-trash');
INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','prune-trash');
INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','prune-trash');
INSERT INTO documents(id,kb_id,filename,sha256) VALUES ('{doc}','{kb}','a.md','sha-{doc}');"
))
.execute(&pool)
.await?;
sqlx::query(
"INSERT INTO chunks (id, kb_id, document_id, seq, text, embedding)
VALUES ($1, $2, $3, 0, 'chunk 0', $4)",
)
.bind(chunk)
.bind(kb)
.bind(doc)
.bind(Vector::from(vec![0.1, 0.2, 0.3]))
.execute(&pool)
.await?;
utopia_store::documents::delete(&pool, kb, doc, None).await?;
sqlx::query("UPDATE chunks SET superseded_at = $2 WHERE id = $1")
.bind(chunk)
.bind(Utc::now() - Duration::days(10))
.execute(&pool)
.await?;

assert_eq!(
prune_superseded(&pool, kb, Duration::days(7)).await?,
Pruned::default(),
"a deleted document's chunks are left whole"
);
utopia_store::documents::restore(&pool, kb, doc).await?;
assert_eq!(
rows(&pool, kb).await?,
vec![Row {
id: chunk,
has_vector: true
}]
);
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?;
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 @@ -123,6 +123,7 @@ mod an_exploration_says_what_it_covered;
mod an_export_carries_the_whole_ledger;
mod an_identity_name_attaches_by_its_exact_name;
mod an_instance_list_names_what_a_type_lacks;
mod an_old_version_keeps_no_vector;
mod an_open_statement_keeps_the_documents_words;
mod an_sso_login_finds_or_opens_its_account;
mod an_undeclared_name_is_looked_up;
Expand Down
Loading
Loading