Skip to content

World's first open-source enterprise world model.

Purging a deleted document removes its content for good (#283)

WaylandYang1c5d9889924c
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 5990aa86..10440ef3 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -109,6 +109,8 @@ pub struct Document {
/// 墓碑(#268):删除是认知轴上的一个事件。行、分块、证据、原始文件都留着,
/// 只是不再算活的;撤销、同步撞见、同内容重传都能把它复活
pub deleted_at: Option<DateTime<Utc>>,
+ /// 真删(#268 下半):内容已抹掉,回不来。行留作墓碑
+ pub purged_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -1190,6 +1192,8 @@ pub struct DocumentPage {
pub ready: i64,
pub extracting: i64,
pub failed: i64,
+ /// 整库的墓碑数(删了、没清的)——左栏「已删除」那一行的数字,不随作用域变
+ pub deleted: i64,
}
/// 一枚个人访问令牌的元信息(0014)。**永远不含明文**——
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rs
index 08a3f680..d3e311c3 100644
--- a/crates/utopia-server/src/api/documents_routes.rs
+++ b/crates/utopia-server/src/api/documents_routes.rs
@@ -118,6 +118,9 @@ pub struct DocsQuery {
/// 抽取状态:none | queued | extracting | done | failed
#[serde(default)]
pub graph: Option<String>,
+ /// `deleted` = 「已删除」视图:只列墓碑(#268)。缺省 = 活着的
+ #[serde(default)]
+ pub state: Option<String>,
#[serde(default)]
pub limit: Option<i64>,
#[serde(default)]
@@ -141,6 +144,7 @@ pub async fn list(
parse_scope(q.source.as_deref()),
q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()),
q.graph.as_deref().filter(|s| !s.is_empty()),
+ q.state.as_deref() == Some("deleted"),
q.limit.unwrap_or(15).clamp(1, 200),
q.offset.unwrap_or(0).max(0),
)
@@ -281,6 +285,42 @@ pub async fn restore(
Ok(Json(json!({ "ok": true })))
}
+/// 真删(#268 下半):内容抹掉,不可撤销,只对已删除的文档开放,库管理员才能按。
+/// 库里先记账(purged_at),再删文件:删文件失败只是漏一份孤儿原文,反过来则是
+/// 库说「还能恢复」而原文已经没了
+pub async fn purge(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Admin).await?;
+ let report = utopia_store::documents::purge(&state.pool, doc.kb_id, id).await?;
+ for sha in &report.blobs {
+ if let Err(e) = state.blob.delete(sha).await {
+ tracing::warn!(document = %id, sha, error = %e, "purge: blob left behind");
+ }
+ }
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(doc.kb_id),
+ user.id,
+ "document.purged",
+ "document",
+ Some(id),
+ json!({
+ "filename": doc.filename,
+ "chunks": report.chunks,
+ "blobs": report.blobs.len(),
+ }),
+ )
+ .await;
+ state.emit_document(doc.kb_id, id);
+ Ok(Json(
+ json!({ "ok": true, "chunks": report.chunks, "blobs": report.blobs.len() }),
+ ))
+}
+
/// 复活的文档回到全文索引:分块的正文一直都在,只是重写一遍索引条目
pub async fn reindex(state: &AppState, doc: &Document) -> utopia_core::AppResult<()> {
let chunks =
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index a04b102b..aead03ad 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -278,6 +278,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
)
// 撤销删除(#268):删除是墓碑,所以有得撤
.route("/documents/{id}/restore", post(documents_routes::restore))
+ // 真删(#268 下半):只对已删除的开放,库管理员
+ .route("/documents/{id}/purge", post(documents_routes::purge))
.route("/documents/{id}/extract", post(graph_routes::extract))
.route("/kbs/{id}/graph/overview", get(graph_routes::overview))
.route(
diff --git a/crates/utopia-server/src/blob.rs b/crates/utopia-server/src/blob.rs
index cef08a1b..75de56f9 100644
--- a/crates/utopia-server/src/blob.rs
+++ b/crates/utopia-server/src/blob.rs
@@ -18,6 +18,8 @@ pub trait BlobStore: Send + Sync {
async fn get(&self, sha256: &str) -> anyhow::Result<Vec<u8>>;
#[allow(dead_code)] // 接口完整性:回放/GC 路径的将来消费者
async fn exists(&self, sha256: &str) -> anyhow::Result<bool>;
+ /// 真删(#268 下半):只在库里确认没人再引用这份指纹之后调用。幂等:不存在也算成功
+ async fn delete(&self, sha256: &str) -> anyhow::Result<()>;
}
/// 本地磁盘实现:`{dir}/{sha256}` 平铺存放(与历史行为逐字节一致)。
@@ -49,4 +51,12 @@ impl BlobStore for LocalBlobStore {
async fn exists(&self, sha256: &str) -> anyhow::Result<bool> {
Ok(self.dir.join(sha256).exists())
}
+
+ async fn delete(&self, sha256: &str) -> anyhow::Result<()> {
+ match tokio::fs::remove_file(self.dir.join(sha256)).await {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e.into()),
+ }
+ }
}
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 235a8bad..9b4b9567 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -288,6 +288,11 @@ async fn resolve(
async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) -> anyhow::Result<()> {
let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ // 排队之后被删了(#268):墓碑不抽——抽出来的事实会活在一个已删除的出处上
+ if doc.deleted_at.is_some() {
+ tracing::info!(document = %document_id, "skipping a deleted document");
+ return Ok(());
+ }
let kb = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
.await?
diff --git a/crates/utopia-server/src/pipeline.rs b/crates/utopia-server/src/pipeline.rs
index c8802062..25d225a9 100644
--- a/crates/utopia-server/src/pipeline.rs
+++ b/crates/utopia-server/src/pipeline.rs
@@ -23,6 +23,11 @@ pub async fn process_document(state: &AppState, document_id: Uuid) -> anyhow::Re
async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ // 排队之后被删了(#268):墓碑不重建分块、不回索引;清过的连原文都没了
+ if doc.deleted_at.is_some() {
+ tracing::info!(document = %document_id, "skipping a deleted document");
+ return Ok(());
+ }
// 1. 解析(CPU 密集,放 blocking 线程)
utopia_store::documents::set_status(&state.pool, document_id, "parsing").await?;
@@ -101,6 +106,10 @@ pub async fn memory_ingest(
proposed_by: Option<Uuid>,
) -> anyhow::Result<()> {
let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ if doc.deleted_at.is_some() {
+ tracing::info!(document = %document_id, "skipping a deleted document");
+ return Ok(());
+ }
let kb_row = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
let settings = utopia_store::settings::get(&state.pool, kb_row.workspace_id).await?;
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
index e5328455..54a93958 100644
--- a/crates/utopia-store/src/documents.rs
+++ b/crates/utopia-store/src/documents.rs
@@ -20,7 +20,8 @@ pub async fn create(
// 同样的内容回来了,而它只是被删过:复活那一篇,而不是撞 (kb_id, sha256) 的唯一
// 索引报「已存在」。撤销删除的一种自然形态——重传就是「我要它回来」(#268)
if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
- "SELECT id FROM documents WHERE kb_id = $1 AND sha256 = $2 AND deleted_at IS NOT NULL",
+ "SELECT id FROM documents
+ WHERE kb_id = $1 AND sha256 = $2 AND deleted_at IS NOT NULL AND purged_at IS NULL",
)
.bind(kb_id)
.bind(sha256)
@@ -84,6 +85,8 @@ pub async fn page(
source: Option<Option<Uuid>>,
q: Option<&str>,
graph_status: Option<&str>,
+ // true = 「已删除」视图:只列墓碑(删了、没清的);false = 活着的
+ deleted: bool,
limit: i64,
offset: i64,
) -> AppResult<DocumentPage> {
@@ -91,7 +94,9 @@ pub async fn page(
// `$2 = 'any'` 那一支是「不按来源筛」,`'none'` 是「只看没有来源的」——
// 用两个哨兵字符串而不是两个可空参数,因为 NULL 在这里有歧义:
// 它既可能是「不筛」,也可能是「筛出 source_id IS NULL 的」
- const WHERE: &str = "WHERE kb_id = $1 AND deleted_at IS NULL
+ const WHERE: &str = "WHERE kb_id = $1
+ AND (($5::bool AND deleted_at IS NOT NULL AND purged_at IS NULL)
+ OR (NOT $5::bool AND deleted_at IS NULL))
AND ($2 = 'any'
OR ($2 = 'none' AND source_id IS NULL)
OR source_id::text = $2)
@@ -104,12 +109,15 @@ pub async fn page(
};
let docs: Vec<Document> = sqlx::query_as(&format!(
- "SELECT * FROM documents {WHERE} ORDER BY created_at DESC LIMIT $5 OFFSET $6"
+ "SELECT * FROM documents {WHERE}
+ ORDER BY (CASE WHEN $5::bool THEN deleted_at ELSE created_at END) DESC
+ LIMIT $6 OFFSET $7"
))
.bind(kb_id)
.bind(&scope)
.bind(q)
.bind(graph_status)
+ .bind(deleted)
.bind(limit)
.bind(offset)
.fetch_all(pool)
@@ -120,6 +128,7 @@ pub async fn page(
.bind(&scope)
.bind(q)
.bind(graph_status)
+ .bind(deleted)
.fetch_one(pool)
.await?;
@@ -140,12 +149,22 @@ pub async fn page(
.fetch_one(pool)
.await?;
+ // 墓碑数是整库的:左栏那一行不随作用域变
+ let (deleted_total,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM documents
+ WHERE kb_id = $1 AND deleted_at IS NOT NULL AND purged_at IS NULL",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+
Ok(DocumentPage {
docs,
total,
ready: stats.0,
extracting: stats.1,
failed: stats.2,
+ deleted: deleted_total,
})
}
@@ -517,6 +536,17 @@ pub async fn restore(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Document
let Some((deletion_id, fact_ids, chunk_ids)) = row else {
return Err(AppError::Conflict("Document is not deleted".into()));
};
+ // 清过的没东西可复活:分块、原文都不在了
+ let purged: bool =
+ sqlx::query_scalar("SELECT purged_at IS NOT NULL FROM documents WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ if purged {
+ return Err(AppError::Conflict(
+ "The document's content was purged; there is nothing to restore".into(),
+ ));
+ }
let mut tx = pool.begin().await?;
let hit = sqlx::query(
"UPDATE documents SET deleted_at = NULL, updated_at = now()
@@ -548,6 +578,87 @@ pub async fn restore(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Document
get(pool, id).await
}
+/// 一次真删的产出。`blobs` 是这篇(连同历史版本)独占的原文指纹——别处还引用的
+/// 不在名单上。BlobStore 归服务端,删文件由调用方做
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PurgeReport {
+ pub blobs: Vec<String>,
+ pub chunks: u64,
+}
+
+/// 真删(#268 下半):把内容真的抹掉,**只对已删除的文档开放,不可撤销**。
+///
+/// 删除是事件、可撤销([`delete`] / [`restore`]);这里是另一个动作:分块行删掉
+/// (证据引文随外键级联)、版本行删掉、文档行留作墓碑打 `purged_at`。`external_key`
+/// 清空——身份让出来,同步源里若还有这篇,下次同步当新文档重新摄入;同一份内容也
+/// 可以再传(唯一索引只管没清的行)。事实保持作废,`document_deletions` 那条账留着:
+/// 「曾经有过这么一篇,某时被删、某时被清」
+pub async fn purge(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<PurgeReport> {
+ let mut tx = pool.begin().await?;
+ type Stamp = Option<chrono::DateTime<chrono::Utc>>;
+ let row: Option<(String, Stamp, Stamp)> = sqlx::query_as(
+ "SELECT sha256, deleted_at, purged_at FROM documents
+ WHERE id = $1 AND kb_id = $2 FOR UPDATE",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some((sha, deleted_at, purged_at)) = row else {
+ return Err(AppError::NotFound);
+ };
+ if purged_at.is_some() {
+ return Err(AppError::Conflict("The document was already purged".into()));
+ }
+ if deleted_at.is_none() {
+ return Err(AppError::Conflict(
+ "Delete the document before purging it".into(),
+ ));
+ }
+ let mut shas: Vec<String> =
+ sqlx::query_scalar("SELECT DISTINCT sha256 FROM document_versions WHERE document_id = $1")
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?;
+ if !shas.contains(&sha) {
+ shas.push(sha);
+ }
+ let chunks = sqlx::query("DELETE FROM chunks WHERE document_id = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?
+ .rows_affected();
+ sqlx::query("DELETE FROM document_versions WHERE document_id = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "UPDATE documents
+ SET purged_at = now(), external_key = NULL, text_len = 0, chunk_count = 0,
+ updated_at = now()
+ WHERE id = $1",
+ )
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ // 原文按内容寻址,别的文档(任何库)可能共用同一份:只交出没人再引用的
+ let mut blobs = Vec::new();
+ for s in shas {
+ let (referenced,): (bool,) = sqlx::query_as(
+ "SELECT EXISTS (SELECT 1 FROM documents WHERE sha256 = $1 AND purged_at IS NULL)
+ OR EXISTS (SELECT 1 FROM document_versions WHERE sha256 = $1)",
+ )
+ .bind(&s)
+ .fetch_one(&mut *tx)
+ .await?;
+ if !referenced {
+ blobs.push(s);
+ }
+ }
+ tx.commit().await?;
+ Ok(PurgeReport { blobs, chunks })
+}
+
/// 重建文档分块(事务内,幂等)。返回 (chunk_id, text) 供全文索引。
///
/// 认领式增量:新块先按文本内容在现行块里找同款——找到即"认领"(原行只更新
diff --git a/crates/utopia-store/tests/a_deletion_is_an_event.rs b/crates/utopia-store/tests/a_deletion_is_an_event.rs
index 8e2a21f1..6daea47c 100644
--- a/crates/utopia-store/tests/a_deletion_is_an_event.rs
+++ b/crates/utopia-store/tests/a_deletion_is_an_event.rs
@@ -303,6 +303,11 @@ async fn a_deletion_is_an_event() -> anyhow::Result<()> {
}
.await;
+ // 组织删除不级联到库:库自己删,别在共用的测试库里留墓碑
+ let _ = sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await;
let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
.bind(f.org)
.execute(&pool)
diff --git a/crates/utopia-store/tests/a_purge_is_final.rs b/crates/utopia-store/tests/a_purge_is_final.rs
new file mode 100644
index 00000000..b9431fac
--- /dev/null
+++ b/crates/utopia-store/tests/a_purge_is_final.rs
@@ -0,0 +1,315 @@
+//! #268 下半:真删是终点。
+//!
+//! 删除是事件、可撤销;purge 把内容真的抹掉,只对已删除的文档开放。这里守五件事:
+//!
+//! 1. **没删不能清。** 活着的文档 purge 报错。
+//! 2. **清的是内容,不是记录。** 分块行、证据、版本行没了;文档行还在,打了 `purged_at`,
+//! `external_key` 清空;事实保持作废;删除账本那行还在。
+//! 3. **别处还引用的原文不交出去。** 历史版本的指纹被另一篇文档用着,就不在待删名单上;
+//! 只有这篇独占的指纹才交给调用方去删文件。
+//! 4. **清了就回不来。** restore 报错,再 purge 也报错。
+//! 5. **身份让出来。** 同一份内容、同一个 external_key 可以再进来——是一篇新文档,不是
+//! 复活;「已删除」视图只列没清的墓碑。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use utopia_store::documents;
+use uuid::Uuid;
+
+struct Fx {
+ org: Uuid,
+ user: Uuid,
+ kb: Uuid,
+ src: Uuid,
+ etype: Uuid,
+ rel: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fx> {
+ let (org, ws, kb, user) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ let (src, etype, rel) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'purge-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'purge-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash)
+ VALUES ($1, $2, $1 || '@purge.test', 'p', 'x')",
+ )
+ .bind(user)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'purge-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO sources (id, kb_id, kind, name) VALUES ($1, $2, 'folder', 'f')")
+ .bind(src)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'knows', 'knows')",
+ )
+ .bind(rel)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ Ok(Fx {
+ org,
+ user,
+ kb,
+ src,
+ etype,
+ rel,
+ })
+}
+
+async fn document(
+ pool: &PgPool,
+ f: &Fx,
+ name: &str,
+ sha: &str,
+ key: Option<&str>,
+) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status, external_key)
+ VALUES ($1, $2, $3, $4, $5, 'ready', $6)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.src)
+ .bind(name)
+ .bind(sha)
+ .bind(key)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn chunk(pool: &PgPool, f: &Fx, doc: Uuid) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text) VALUES ($1, $2, $3, 0, 'gone soon')",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(doc)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn version(pool: &PgPool, doc: Uuid, sha: &str) -> anyhow::Result<()> {
+ sqlx::query(
+ "INSERT INTO document_versions (id, document_id, version, sha256) VALUES ($1, $2, 1, $3)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(doc)
+ .bind(sha)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn entity(pool: &PgPool, f: &Fx, name: &str) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn fact(pool: &PgPool, f: &Fx, s: Uuid, o: Uuid, chunk: Uuid) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
+ VALUES ($1, $2, $3, $4, $5, 0.9)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(s)
+ .bind(f.rel)
+ .bind(o)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO fact_evidence (fact_id, chunk_id, quote) VALUES ($1, $2, 'q')")
+ .bind(id)
+ .bind(chunk)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn count(pool: &PgPool, sql: &str, id: Uuid) -> anyhow::Result<i64> {
+ Ok(sqlx::query_scalar(sql).bind(id).fetch_one(pool).await?)
+}
+
+/// (deleted_at 有, purged_at 有, external_key)
+async fn tombstone(pool: &PgPool, id: Uuid) -> anyhow::Result<(bool, bool, Option<String>)> {
+ Ok(sqlx::query_as(
+ "SELECT deleted_at IS NOT NULL, purged_at IS NOT NULL, external_key
+ FROM documents WHERE id = $1",
+ )
+ .bind(id)
+ .fetch_one(pool)
+ .await?)
+}
+
+#[tokio::test]
+async fn a_purge_is_final() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ // 原文按内容寻址、跨库共用:指纹带上本次运行的随机后缀,别和库里残留的撞上
+ let tag = Uuid::now_v7().simple().to_string();
+ let (sha_a, sha_old, sha_b) = (
+ format!("sha-a-{tag}"),
+ format!("sha-old-{tag}"),
+ format!("sha-b-{tag}"),
+ );
+ let run = async {
+ // 甲:现行内容 sha-a,历史版本 sha-old;丙的现行内容也是 sha-old——那份原文不独占
+ let a = document(&pool, &f, "a.md", &sha_a, Some("key-a")).await?;
+ version(&pool, a, &sha_old).await?;
+ let _c = document(&pool, &f, "c.md", &sha_old, None).await?;
+ // 乙:删了但不清,该留在「已删除」视图里
+ let b = document(&pool, &f, "b.md", &sha_b, None).await?;
+ let a1 = chunk(&pool, &f, a).await?;
+ let (x, y) = (entity(&pool, &f, "X").await?, entity(&pool, &f, "Y").await?);
+ let only_a = fact(&pool, &f, x, y, a1).await?;
+
+ // 1. 没删不能清
+ assert!(documents::purge(&pool, f.kb, a).await.is_err());
+
+ documents::delete(&pool, f.kb, a, Some(f.user)).await?;
+ documents::delete(&pool, f.kb, b, Some(f.user)).await?;
+
+ // 2 + 3. 清内容,留记录;只交出独占的原文
+ let report = documents::purge(&pool, f.kb, a).await?;
+ assert_eq!(report.chunks, 1);
+ assert_eq!(
+ report.blobs,
+ vec![sha_a.clone()],
+ "sha-old is still c's content, so it stays"
+ );
+ assert_eq!(
+ count(
+ &pool,
+ "SELECT count(*) FROM chunks WHERE document_id = $1",
+ a
+ )
+ .await?,
+ 0
+ );
+ assert_eq!(
+ count(
+ &pool,
+ "SELECT count(*) FROM fact_evidence WHERE fact_id = $1",
+ only_a
+ )
+ .await?,
+ 0,
+ "the quote goes with the chunk"
+ );
+ assert_eq!(
+ count(
+ &pool,
+ "SELECT count(*) FROM document_versions WHERE document_id = $1",
+ a
+ )
+ .await?,
+ 0
+ );
+ assert_eq!(tombstone(&pool, a).await?, (true, true, None));
+ let retired: bool =
+ sqlx::query_scalar("SELECT invalidated_at IS NOT NULL FROM facts WHERE id = $1")
+ .bind(only_a)
+ .fetch_one(&pool)
+ .await?;
+ assert!(retired, "the fact stays retired");
+ assert_eq!(
+ count(
+ &pool,
+ "SELECT count(*) FROM document_deletions WHERE document_id = $1",
+ a
+ )
+ .await?,
+ 1,
+ "the deletion stays on record"
+ );
+
+ // 4. 回不来
+ assert!(documents::restore(&pool, f.kb, a).await.is_err());
+ assert!(documents::purge(&pool, f.kb, a).await.is_err());
+
+ // 5. 身份让出来:同内容同键再进来是一篇新文档;「已删除」视图只有乙
+ let again = documents::create(
+ &pool,
+ f.kb,
+ "a.md",
+ "text/markdown",
+ 9,
+ &sha_a,
+ Some(f.src),
+ None,
+ Some("key-a"),
+ )
+ .await?;
+ assert_ne!(again.id, a, "a new document, not a revival");
+ assert!(again.deleted_at.is_none());
+ let deleted = documents::page(&pool, f.kb, None, None, None, true, 50, 0).await?;
+ let ids: Vec<Uuid> = deleted.docs.iter().map(|d| d.id).collect();
+ assert_eq!(ids, vec![b], "purged tombstones are not listed");
+ assert_eq!(deleted.deleted, 1);
+ let live = documents::page(&pool, f.kb, None, None, None, false, 50, 0).await?;
+ let ids: Vec<Uuid> = live.docs.iter().map(|d| d.id).collect();
+ assert!(ids.contains(&again.id));
+ assert!(!ids.contains(&a) && !ids.contains(&b));
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ // 组织删除不级联到库:库自己删,别在共用的测试库里留墓碑
+ let _ = sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await;
+ let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await;
+ run
+}
diff --git a/migrations/0023_purge_is_final.sql b/migrations/0023_purge_is_final.sql
new file mode 100644
index 00000000..a484c849
--- /dev/null
+++ b/migrations/0023_purge_is_final.sql
@@ -0,0 +1,9 @@
+-- 真删(#268 下半)。删除是认知轴上的事件、可撤销(0022);purge 是把内容真的抹掉,
+-- 不可撤销,只对已删除的文档开放:原文 blob(别处不再引用的才删)、分块行(证据引文
+-- 随外键级联)、版本行都没了;文档行留作墓碑打 purged_at,事实保持作废,
+-- document_deletions 那条账留着——「曾经有过这么一篇,某时被删、某时被清」。
+ALTER TABLE documents ADD COLUMN purged_at TIMESTAMPTZ;
+-- 清掉的行让出身份:external_key 清空(同步源里若还有这篇,下次当新文档重新摄入),
+-- 同一份内容也可以再传——唯一索引只管没清的行
+DROP INDEX documents_kb_sha_idx;
+CREATE UNIQUE INDEX documents_kb_sha_idx ON documents (kb_id, sha256) WHERE purged_at IS NULL;
diff --git a/web/src/api.ts b/web/src/api.ts
index ef086f1c..40ed1a0d 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -166,6 +166,8 @@ export interface Doc {
missing_since: string | null;
/** 墓碑(#268):删了但留着,可撤销 */
deleted_at: string | null;
+ /** 真删过:内容没了,回不来 */
+ purged_at: string | null;
created_at: string;
}
@@ -1307,6 +1309,8 @@ export const api = {
source?: string;
q?: string;
graph?: string;
+ /** "deleted" = 「已删除」视图:只列墓碑(#268) */
+ state?: "deleted";
limit: number;
offset: number;
},
@@ -1318,6 +1322,7 @@ export const api = {
if (opts.source) p.set("source", opts.source);
if (opts.q) p.set("q", opts.q);
if (opts.graph) p.set("graph", opts.graph);
+ if (opts.state) p.set("state", opts.state);
return request<{
docs: Doc[];
total: number;
@@ -1326,6 +1331,8 @@ export const api = {
ready: number;
extracting: number;
failed: number;
+ /** 整库的墓碑数(删了、没清的),不随作用域变 */
+ deleted: number;
}>(`/api/v1/kbs/${kbId}/documents?${p}`);
},
/** 一键重试这个作用域里全部抽取失败的文档 */
@@ -1356,6 +1363,12 @@ export const api = {
/** 撤销删除(#268):文档、分块、随之作废的事实原路复活 */
restoreDocument: (id: string) =>
request<{ ok: boolean }>(`/api/v1/documents/${id}/restore`, { method: "POST" }),
+ /** 真删(#268 下半):只对已删除的开放,库管理员,不可撤销 */
+ purgeDocument: (id: string) =>
+ request<{ ok: boolean; chunks: number; blobs: number }>(
+ `/api/v1/documents/${id}/purge`,
+ { method: "POST" },
+ ),
search: (kbId: string, q: string) =>
request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 1f23c13d..71d562ad 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -311,7 +311,7 @@ export const en = {
{
h: "Retention and deletion",
body: [
- "Deleting a document removes it from the base and retires the facts that had no other source; facts with another source keep it as provenance. The content is kept so the deletion can be undone; a deleted document can be restored, and a re-upload of the same file restores it too. Deleting a knowledge base permanently removes its documents, graph and sources.",
+ "Deleting a document removes it from the base and retires the facts that had no other source; facts with another source keep it as provenance. The content is kept so the deletion can be undone; a deleted document can be restored, and a re-upload of the same file restores it too. A knowledge-base admin can purge a deleted document, which removes its stored content for good. Deleting a knowledge base permanently removes its documents, graph and sources.",
],
},
{
@@ -372,6 +372,19 @@ export const en = {
: `Document deleted · ${n} facts retired with it`,
undo: "Undo",
restored: "Document restored",
+ /** 「已删除」视图与真删(#268 下半) */
+ deleted: "Deleted",
+ colDeleted: "Deleted",
+ restore: "Restore",
+ purge: "Purge",
+ purgeTitle: "Purge this document?",
+ purgeHint: (name: string) =>
+ `“${name}” is deleted, and its content is still stored so the deletion can be undone. ` +
+ "Purging removes the stored file, its chunks and its evidence quotes for good. " +
+ "The facts it retired stay retired, and the deletion stays on record. This cannot be undone.",
+ purgeConfirm: "Purge",
+ purged: "Content purged",
+ deletedEmpty: "Nothing deleted. Deleted documents wait here until they are restored or purged.",
title: "Library",
upload: "Upload files",
uploading: "Uploading…",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index ed9f6033..59fb884b 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -284,7 +284,7 @@ export const zh: Strings = {
{
h: "留存与删除",
body: [
- "删除一篇文档会把它移出知识库,并让只以它为出处的事实一并失效;另有出处的事实保留,出处照旧。内容会留着以便撤销:删除可以恢复,重新上传同一份文件也会恢复它。删除一个知识库会永久移除它的文档、图谱与来源。",
+ "删除一篇文档会把它移出知识库,并让只以它为出处的事实一并失效;另有出处的事实保留,出处照旧。内容会留着以便撤销:删除可以恢复,重新上传同一份文件也会恢复它。知识库管理员可以清除已删除的文档,其存储内容将被彻底移除。删除一个知识库会永久移除它的文档、图谱与来源。",
],
},
{
@@ -340,6 +340,17 @@ export const zh: Strings = {
n === 0 ? "文档已删除" : `文档已删除 · 随之失效 ${n} 条事实`,
undo: "撤销",
restored: "文档已恢复",
+ deleted: "已删除",
+ colDeleted: "删除时间",
+ restore: "恢复",
+ purge: "清除",
+ purgeTitle: "清除这篇文档?",
+ purgeHint: (name: string) =>
+ `「${name}」已删除,内容还留着以便撤销。清除会把原文、分块与证据引文彻底移除;` +
+ "随它失效的事实保持失效,删除记录保留。此操作不可撤销。",
+ purgeConfirm: "清除",
+ purged: "内容已清除",
+ deletedEmpty: "没有已删除的文档。删掉的文档会在这里等着被恢复或清除。",
title: "文库",
upload: "上传文件",
uploading: "上传中…",
diff --git a/web/src/pages/Library.tsx b/web/src/pages/Library.tsx
index 8fdb893a..5a9eda96 100644
--- a/web/src/pages/Library.tsx
+++ b/web/src/pages/Library.tsx
@@ -350,7 +350,13 @@ export function Library() {
queryKey: ["documents", kb?.id, selection, filter, graphFilter, page],
queryFn: () =>
api.documents(kb!.id, {
- source: selection === "all" ? undefined : selection === "uploads" ? "none" : selection,
+ source:
+ selection === "all" || selection === "deleted"
+ ? undefined
+ : selection === "uploads"
+ ? "none"
+ : selection,
+ state: selection === "deleted" ? "deleted" : undefined,
q: filter.trim() || undefined,
graph: graphFilter || undefined,
limit: PAGE_SIZE,
@@ -436,6 +442,17 @@ export function Library() {
invalidate();
},
});
+ // 真删(#268 下半):打字级确认,库管理员,回不来
+ const [purging, setPurging] = useState<Doc | null>(null);
+ const purge = useMutation({
+ mutationFn: (id: string) => api.purgeDocument(id),
+ onSuccess: () => {
+ setPurging(null);
+ toast.success(S.library.purged);
+ invalidate();
+ },
+ onError: (e) => toast.error(String(e)),
+ });
const extract = useMutation({ mutationFn: (id: string) => api.extractDocument(id), onSuccess: invalidate });
const reprocess = useMutation({
mutationFn: (id: string) => api.reprocessDocument(id),
@@ -551,7 +568,11 @@ export function Library() {
<div className="flex items-center justify-between mb-4">
<h1 className="u-title text-lg">
{selectedSource?.name ??
- (selection === "uploads" ? S.library.uploads : S.library.title)}
+ (selection === "uploads"
+ ? S.library.uploads
+ : selection === "deleted"
+ ? S.library.deleted
+ : S.library.title)}
</h1>
<div className="flex items-center gap-2">
{/* 历史视图下过滤框只藏不撤(invisible 保留占位),标题行高度不塌、不抖 */}
@@ -579,6 +600,7 @@ export function Library() {
{/* 按抽取状态筛。**选项写死成那五个**,不按库里实际有的填——
它是一组固定的管道状态,而「这个库现在没有失败的」正是用户
想通过筛一下确认的事 */}
+ {selection !== "deleted" && (
<select
className="input-dark px-2 py-1.5 text-[13px] shrink-0"
value={graphFilter}
@@ -594,6 +616,7 @@ export function Library() {
<option value="extracting">{S.library.statusExtracting}</option>
<option value="none">{S.library.statusNone}</option>
</select>
+ )}
{/* 一键重试。**只在真有失败时出现**——没有失败的库不该看到一个
点了什么都不会发生的按钮。数字写在按钮上,点之前就知道会动几篇 */}
{(docs.data?.failed ?? 0) > 0 && canUpload && (
@@ -690,7 +713,15 @@ export function Library() {
) : (
<>
<div className={`glass rounded-2xl glass-hover ${dragging ? "u-highlight" : ""}`}>
- {pagedDocs.length ? (
+ {selection === "deleted" ? (
+ <DeletedTable
+ docs={pagedDocs}
+ sources={sourceList}
+ canPurge={canRebuild}
+ onRestore={(id) => restore.mutate(id)}
+ onPurge={setPurging}
+ />
+ ) : pagedDocs.length ? (
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-neutral-500 border-b border-white/10">
@@ -830,6 +861,19 @@ export function Library() {
onClose={() => setDropsView(null)}
/>
)}
+ {/* 真删:打字级确认(内容没了,回不来) */}
+ {purging && (
+ <DangerConfirm
+ title={S.library.purgeTitle}
+ hint={S.library.purgeHint(purging.filename)}
+ requireText={purging.filename}
+ confirmLabel={S.library.purgeConfirm}
+ cancelLabel={S.library.cancel}
+ busy={purge.isPending}
+ onConfirm={() => purge.mutate(purging.id)}
+ onCancel={() => setPurging(null)}
+ />
+ )}
{/* 全库重建:打字级确认(清空图层不可逆) */}
{rebuilding && (
<DangerConfirm
@@ -2087,6 +2131,69 @@ function SourceEditModal({
);
}
+/** 「已删除」视图(#268):墓碑在这里等着被恢复或清除。清除只有库管理员能按 */
+function DeletedTable({
+ docs,
+ sources,
+ canPurge,
+ onRestore,
+ onPurge,
+}: {
+ docs: Doc[];
+ sources: SourceView[];
+ canPurge: boolean;
+ onRestore: (id: string) => void;
+ onPurge: (doc: Doc) => void;
+}) {
+ if (!docs.length) {
+ return (
+ <div className="py-20 text-center text-sm text-neutral-500">{S.library.deletedEmpty}</div>
+ );
+ }
+ return (
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-neutral-500 border-b border-white/10">
+ <th className="px-4 py-2.5 font-medium">{S.library.colFile}</th>
+ <th className="px-4 py-2.5 font-medium">{S.library.colSource}</th>
+ <th className="px-4 py-2.5 font-medium">{S.library.colDeleted}</th>
+ <th className="px-4 py-2.5"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {docs.map((d) => {
+ const src = sources.find((s) => s.id === d.source_id);
+ return (
+ <tr key={d.id} className="border-b border-white/[0.06] last:border-0">
+ <td className="px-4 py-2.5 text-neutral-300">{d.filename}</td>
+ <td className="px-4 py-2.5 text-neutral-500">{src?.name ?? S.library.uploads}</td>
+ <td className="px-4 py-2.5 u-num text-neutral-500">
+ {d.deleted_at ? new Date(d.deleted_at).toLocaleString() : ""}
+ </td>
+ <td className="px-4 py-2.5 text-right whitespace-nowrap">
+ <button
+ onClick={() => onRestore(d.id)}
+ className="text-xs text-neutral-400 hover:text-neutral-100"
+ >
+ {S.library.restore}
+ </button>
+ {canPurge && (
+ <button
+ onClick={() => onPurge(d)}
+ className="ml-4 text-xs text-neutral-500 hover:text-rose-400"
+ >
+ {S.library.purge}
+ </button>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ );
+}
+
function DocRow({
doc,
source,
diff --git a/web/src/pages/SourcesRail.tsx b/web/src/pages/SourcesRail.tsx
index d403f148..b5341f8f 100644
--- a/web/src/pages/SourcesRail.tsx
+++ b/web/src/pages/SourcesRail.tsx
@@ -25,6 +25,7 @@ import {
Rss,
Server,
SquareKanban,
+ Trash2,
Upload,
Users,
Webhook,
@@ -35,7 +36,8 @@ import { S } from "../i18n";
import { RAIL_CLS } from "../ui";
/** 左栏选择:全部 / 手动上传 / 某个来源 id */
-export type LibrarySelection = "all" | "uploads" | string;
+/** "deleted" = 墓碑视图(#268):删了、还能恢复或清除的文档 */
+export type LibrarySelection = "all" | "uploads" | "deleted" | string;
/** 可选的来源图标(lucide 图标名 → 组件)。 */
export const SOURCE_ICONS: Record<string, LucideIcon> = {
@@ -220,6 +222,18 @@ export function SourcesRail({
);
})}
</div>
+ {/* 已删除(#268):墓碑在这里等着被恢复或清除。一个都没有就不占一行 */}
+ {((docs.data?.deleted ?? 0) > 0 || active === "deleted") && (
+ <div className="px-2 pb-3">
+ <RailItem
+ active={active === "deleted"}
+ onClick={() => onSelect("deleted")}
+ icon={<Trash2 size={14} />}
+ label={S.library.deleted}
+ count={docs.data?.deleted ?? 0}
+ />
+ </div>
+ )}
</aside>
);
}