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
2 changes: 1 addition & 1 deletion crates/utopia-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
days,
vectors_cleared = pruned.vectors_cleared,
chunks_deleted = pruned.chunks_deleted,
"superseded chunks pruned"
"被取代的分块清理完成"
);
Ok(())
}
Expand Down
27 changes: 20 additions & 7 deletions crates/utopia-store/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1656,9 +1656,25 @@ pub async fn search_entities(
let visible = |param: usize| crate::record_axis::entity_visible_at("e", as_of.map(|_| param));
let rewind = as_of.map(|_| 6);
let same_name = crate::names::has_name_in("e", 1, 5);
// 精确时走 `(kb_id, lower(canonical_name))` 索引,排序用的就是同一个判法;`$2` 绑着不用,参数位不挪
// 精确时把规范名与别名写成一个 id 集合,各走各的索引(`entities_kb_name_idx`、
// `facts_value_text_idx`)。写成 `OR` 的话一边是子查询,规划器只能把库里的实体扫一遍。
// 规范名那个索引只收没被合并的实体:不回放时这与 `visible` 是一回事,带上它;回放时
// 被并者当时还在,不能带,那一支退回按库扫。`$2` 绑着不用,参数位不挪
let exactly_named = |names: usize| {
format!(
"e.id IN (SELECT x.id FROM entities x
WHERE x.kb_id = $1 AND lower(x.canonical_name) = ANY(${names}){unmerged}
UNION ALL {aliases})",
unmerged = if as_of.is_none() {
" AND x.merged_into IS NULL"
} else {
""
},
aliases = crate::names::named_ids(1, names),
)
};
let matches = if exact {
format!("(lower(e.canonical_name) = ANY($5) OR {same_name})")
exactly_named(5)
} else {
format!("(e.canonical_name ILIKE $2 OR {named})")
};
Expand All @@ -1682,10 +1698,7 @@ pub async fn search_entities(
let nodes: Vec<GraphNode> = nodes_query.fetch_all(pool).await?;
// 数量那条的名字列表在 `$3`,时刻挪到 `$4`
let count_matches = if exact {
format!(
"(lower(e.canonical_name) = ANY($3) OR {})",
crate::names::has_name_in("e", 1, 3)
)
exactly_named(3)
} else {
format!("(e.canonical_name ILIKE $2 OR {named})")
};
Expand Down Expand Up @@ -1887,7 +1900,7 @@ pub async fn entity_detail(
holds_to = crate::world_axis::facts_holds_to("f"),
subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false),
object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true),
awaits = crate::review::AWAITS_A_NEW_VERSION,
awaits = crate::review::awaits_a_new_version_at(as_of.map(|_| 3)),
follows_its_statement = crate::review::FOLLOWS_ITS_STATEMENT,
chunk_live = crate::record_axis::chunk_live_at("c", as_of.map(|_| 3)),
violation_open = crate::record_axis::violation_open_at("v", as_of.map(|_| 3)),
Expand Down
65 changes: 34 additions & 31 deletions crates/utopia-store/src/materialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,37 +190,11 @@ async fn materialize_in_tx(
.rows_affected();

// 1. 删不再成立的来源:陈述死了、行死了、签名没绑着、属性或方向变了、陈述带了 mood
// The sources that still hold are collected once and the rest are deleted against that
// set: as a correlated NOT EXISTS the planner guessed one row for the binding match and
// rescanned it per source, which ran for twelve hours on a base of 690k sources and
// takes two minutes this way. Same conditions, same rows.
sqlx::query(&format!(
"WITH holding AS MATERIALIZED (
SELECT src.fact_id, src.statement_id
FROM typed_fact_sources src
JOIN facts t ON t.id = src.fact_id AND t.kb_id = $1 AND t.invalidated_at IS NULL
JOIN facts s ON s.id = src.statement_id AND s.kb_id = $1
AND s.invalidated_at IS NULL
JOIN entities se ON se.id = s.subject_id
LEFT JOIN entities oe ON oe.id = s.object_id
JOIN phrase_bindings b ON {MATCH}
WHERE b.status = 'bound'
AND b.relation_type_id = t.predicate_id
AND ((b.direction = 'forward' AND t.subject_id = s.subject_id)
OR (b.direction = 'reverse' AND t.subject_id = s.object_id))
AND {NO_MOOD})
DELETE FROM typed_fact_sources src
USING facts t
WHERE src.fact_id = t.id AND t.kb_id = $1
AND NOT EXISTS (SELECT 1 FROM holding h
WHERE h.fact_id = src.fact_id
AND h.statement_id = src.statement_id)",
NO_MOOD = no_mood_spoken(),
))
.persistent(false)
.bind(kb_id)
.execute(&mut **tx)
.await?;
sqlx::query(&source_cleanup_sql())
.persistent(false)
.bind(kb_id)
.execute(&mut **tx)
.await?;

// 1b. 隐含行的来源:规则不再批准、触发它的陈述死了或换了签名、实体没了或换了类别词,
// 来源就删;与 1 同一条规矩,只是来源表是另一张(implied_fact_sources)
Expand Down Expand Up @@ -867,6 +841,35 @@ pub async fn count(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {
.await?)
}

/// 步骤 1 的语句:仍然成立的来源只算一遍(CTE),再用反连接删掉其余的。
/// 写成相关的 NOT EXISTS 时,规划器把绑定匹配估成一行,对每个来源重扫一遍:
/// 69 万个来源的库上跑了十二小时,这样写两分钟。条件和删掉的行都没变。
fn source_cleanup_sql() -> String {
format!(
"WITH holding AS MATERIALIZED (
SELECT src.fact_id, src.statement_id
FROM typed_fact_sources src
JOIN facts t ON t.id = src.fact_id AND t.kb_id = $1 AND t.invalidated_at IS NULL
JOIN facts s ON s.id = src.statement_id AND s.kb_id = $1
AND s.invalidated_at IS NULL
JOIN entities se ON se.id = s.subject_id
LEFT JOIN entities oe ON oe.id = s.object_id
JOIN phrase_bindings b ON {MATCH}
WHERE b.status = 'bound'
AND b.relation_type_id = t.predicate_id
AND ((b.direction = 'forward' AND t.subject_id = s.subject_id)
OR (b.direction = 'reverse' AND t.subject_id = s.object_id))
AND {NO_MOOD})
DELETE FROM typed_fact_sources src
USING facts t
WHERE src.fact_id = t.id AND t.kb_id = $1
AND NOT EXISTS (SELECT 1 FROM holding h
WHERE h.fact_id = src.fact_id
AND h.statement_id = src.statement_id)",
NO_MOOD = no_mood_spoken(),
)
}

#[cfg(test)]
#[path = "materialize_delivery_tests.rs"]
mod delivery_tests;
Expand Down
26 changes: 26 additions & 0 deletions crates/utopia-store/src/materialize_plan_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,29 @@ async fn a_recompute_leaves_none_of_its_whole_base_statements_cached_on_its_conn
assert_eq!(cached, Vec::<String>::new());
Ok(())
}

#[tokio::test]
async fn the_source_cleanup_plans_the_sources_that_hold_once_as_a_cte_the_delete_scans(
) -> anyhow::Result<()> {
let Some(url) = crate::test_db::url() else {
return Ok(());
};
let pool = PgPoolOptions::new()
.max_connections(1)
.connect(&url)
.await?;

let plan_lines: Vec<String> =
sqlx::query_scalar(&format!("EXPLAIN {}", super::source_cleanup_sql()))
.persistent(false)
.bind(Uuid::now_v7())
.fetch_all(&pool)
.await?;
let plan = plan_lines.join("\n");

assert!(
plan.contains("CTE holding") && plan.contains("CTE Scan on holding"),
"the delete must anti-join a CTE built once, not rescan the binding match per source, got:\n{plan}"
);
Ok(())
}
9 changes: 7 additions & 2 deletions crates/utopia-store/src/names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,17 @@ pub async fn record(
/// 相关子查询 `nf.subject_id = e.id` 不带库,规划器用不上这个索引,每次召回都要
/// 扫全表的 facts——所有库的
pub fn has_name_in(entity: &str, kb: usize, names: usize) -> String {
format!("{entity}.id IN ({})", named_ids(kb, names))
}

/// [`has_name_in`] 的子查询本身:有这些名字之一的实体的 id
pub fn named_ids(kb: usize, names: usize) -> String {
format!(
"{entity}.id IN (SELECT nf.subject_id FROM facts nf
"SELECT nf.subject_id FROM facts nf
JOIN relation_types nr ON nr.id = nf.predicate_id
WHERE nf.kb_id = ${kb} AND nr.kb_id = ${kb} AND nr.builtin AND nr.key = '{KNOWN_AS}'
AND nf.invalidated_at IS NULL AND nf.object_value IS NOT NULL
AND lower(nf.object_value->>'value') = ANY(${names}))"
AND lower(nf.object_value->>'value') = ANY(${names})"
)
}

Expand Down
72 changes: 28 additions & 44 deletions crates/utopia-store/src/retention.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
//! An old version keeps no vector (RC-007).
//! 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` and
//! `time_mentions` 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.
//! 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 and its document
//! is not deleted: evidence on a superseded chunk is the signal RC-004 and RC-006 close
//! a fact on (the close time is the chunk's `superseded_at`), and the chunks of a deleted
//! document come back when the deletion is reverted.
//! 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;

use crate::vector_index::{self, Target};
/// 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;
Expand All @@ -45,25 +51,21 @@ pub async fn prune_superseded(
older_than: Duration,
) -> AppResult<Pruned> {
let cutoff = Utc::now() - older_than;
let pruned = Pruned {
Ok(Pruned {
vectors_cleared: clear_vectors(pool, kb_id, cutoff).await?,
chunks_deleted: delete_unreferenced(pool, kb_id, cutoff).await?,
};
if pruned != Pruned::default() {
request_index(pool, kb_id).await?;
}
Ok(pruned)
})
}

async fn clear_vectors(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>) -> AppResult<u64> {
let mut total = 0;
loop {
let cleared = sqlx::query(
let cleared = sqlx::query(&format!(
"UPDATE chunks SET embedding = NULL
WHERE id IN (SELECT id FROM chunks
WHERE kb_id = $1 AND superseded_at < $2 AND embedding IS NOT NULL
LIMIT $3)",
)
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)
Expand All @@ -80,16 +82,15 @@ async fn clear_vectors(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>) -> App
async fn delete_unreferenced(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>) -> AppResult<u64> {
let mut total = 0;
loop {
let deleted = sqlx::query(
let deleted = sqlx::query(&format!(
"DELETE FROM chunks
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
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)
LIMIT $3)",
)
AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.chunk_id = c.id)
LIMIT $3)"
))
.bind(kb_id)
.bind(cutoff)
.bind(BATCH)
Expand All @@ -102,20 +103,3 @@ async fn delete_unreferenced(pool: &PgPool, kb_id: Uuid, cutoff: DateTime<Utc>)
}
}
}

/// The HNSW index drops the pruned entries on its own; this only makes sure the base's live
/// dimension has an index at all, the way every write of a vector does.
async fn request_index(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
let dims: Option<(i32,)> = sqlx::query_as(
"SELECT vector_dims(embedding) FROM chunks
WHERE kb_id = $1 AND superseded_at IS NULL AND embedding IS NOT NULL
LIMIT 1",
)
.bind(kb_id)
.fetch_optional(pool)
.await?;
if let Some((dims,)) = dims {
vector_index::request(pool, Target::Chunks, dims as usize).await?;
}
Ok(())
}
36 changes: 33 additions & 3 deletions crates/utopia-store/src/review.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,25 @@ use uuid::Uuid;
/// 迟早分叉成「徽标说 12 条,点进去 9 条」。
pub const LOW_CONFIDENCE_BELOW: f32 = 0.75;

/// 文档 `d` 的新版本还会被读:还在摄入,或排着队、正在抽取
macro_rules! will_still_be_read {
() => {
"(d.graph_status IN ('queued', 'extracting')
OR d.status IN ('pending', 'parsing', 'indexing', 'embedding'))"
};
}

macro_rules! awaits_a_new_version {
() => {
"EXISTS (SELECT 1 FROM fact_evidence fe
concat!(
"EXISTS (SELECT 1 FROM fact_evidence fe
JOIN chunks c ON c.document_id = fe.document_id
JOIN documents d ON d.id = fe.document_id
WHERE fe.fact_id = f.id AND c.superseded_at IS NULL AND c.extracted_at IS NULL
AND (d.graph_status IN ('queued', 'extracting')
OR d.status IN ('pending', 'parsing', 'indexing', 'embedding')))"
AND ",
will_still_be_read!(),
")"
)
};
}

Expand Down Expand Up @@ -76,6 +87,25 @@ pub const AWAITS_A_NEW_VERSION: &str = awaits_a_new_version!();
/// 类型化行跟它的陈述同判(RC-005),见 [`UNCONFIRMED_FACT`]。
pub const FOLLOWS_ITS_STATEMENT: &str = follows_its_statement!();

/// [`AWAITS_A_NEW_VERSION`] 按记录轴(0019)读:T 时刻现行、而那时还没被读的分块。
/// 后来读过的(`extracted_at` 晚于 T),那时确实在等;至今没读的照现在的状态看,
/// 文档的状态没有历史。`as_of` 是时刻参数的位置,`None` 即当下
pub fn awaits_a_new_version_at(as_of: Option<usize>) -> String {
let Some(param) = as_of else {
return AWAITS_A_NEW_VERSION.into();
};
format!(
"EXISTS (SELECT 1 FROM fact_evidence fe
JOIN chunks c ON c.document_id = fe.document_id
JOIN documents d ON d.id = fe.document_id
WHERE fe.fact_id = f.id AND {live}
AND (c.extracted_at > coalesce(${param}, now())
OR (c.extracted_at IS NULL AND {coming})))",
live = crate::record_axis::chunk_live_at("c", as_of),
coming = will_still_be_read!(),
)
}

pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {
let sql = format!(
"SELECT
Expand Down
Loading
Loading