| 1 | use pgvector::Vector; |
| 2 | use sqlx::PgPool; |
| 3 | use utopia_core::models::{ChunkView, Document, DocumentPage}; |
| 4 | use utopia_core::{AppError, AppResult}; |
| 5 | use utopia_ingest::ChunkPiece; |
| 6 | use uuid::Uuid; |
| 7 | |
| 8 | #[allow(clippy::too_many_arguments)] |
| 9 | pub async fn create( |
| 10 | pool: &PgPool, |
| 11 | kb_id: Uuid, |
| 12 | filename: &str, |
| 13 | mime: &str, |
| 14 | size_bytes: i64, |
| 15 | sha256: &str, |
| 16 | source_id: Option<Uuid>, |
| 17 | doc_time: Option<chrono::DateTime<chrono::Utc>>, |
| 18 | external_key: Option<&str>, |
| 19 | ) -> AppResult<Document> { |
| 20 | sqlx::query_as( |
| 21 | "INSERT INTO documents (id, kb_id, filename, mime, size_bytes, sha256, source_id, |
| 22 | doc_time, doc_time_source, external_key) |
| 23 | VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, now()), $9, $10) RETURNING *", |
| 24 | ) |
| 25 | .bind(Uuid::now_v7()) |
| 26 | .bind(kb_id) |
| 27 | .bind(filename) |
| 28 | .bind(mime) |
| 29 | .bind(size_bytes) |
| 30 | .bind(sha256) |
| 31 | .bind(source_id) |
| 32 | .bind(doc_time) |
| 33 | .bind(if doc_time.is_some() { |
| 34 | "source" |
| 35 | } else { |
| 36 | "upload_time" |
| 37 | }) |
| 38 | .bind(external_key) |
| 39 | .fetch_one(pool) |
| 40 | .await |
| 41 | .map_err(|e| match &e { |
| 42 | sqlx::Error::Database(db) if db.is_unique_violation() => AppError::Conflict(format!( |
| 43 | "File already exists (identical content): {filename}" |
| 44 | )), |
| 45 | _ => AppError::Db(e), |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Document>> { |
| 50 | let rows = sqlx::query_as("SELECT * FROM documents WHERE kb_id = $1 ORDER BY created_at DESC") |
| 51 | .bind(kb_id) |
| 52 | .fetch_all(pool) |
| 53 | .await?; |
| 54 | Ok(rows) |
| 55 | } |
| 56 | |
| 57 | /// 文库一页,**带筛选与统计**。 |
| 58 | /// |
| 59 | /// 从前是 `SELECT * FROM documents WHERE kb_id = $1` 不带上限、前端客户端分页。 |
| 60 | /// 27 篇没事,两万篇会把整张表打进浏览器;而客户端筛选还有个更隐蔽的毛病—— |
| 61 | /// 它只筛得到已经拿下来的那些。 |
| 62 | /// |
| 63 | /// 统计单独算,而且**只按来源作用域算,不受名字/状态筛选影响**: |
| 64 | /// 「这个来源里有几篇可抽」是那两个批量按钮的作用范围,跟你此刻在搜什么无关。 |
| 65 | #[allow(clippy::too_many_arguments)] |
| 66 | pub async fn page( |
| 67 | pool: &PgPool, |
| 68 | kb_id: Uuid, |
| 69 | // None = 全部;Some(None) = 只看没有来源的;Some(Some(id)) = 某个来源 |
| 70 | source: Option<Option<Uuid>>, |
| 71 | q: Option<&str>, |
| 72 | graph_status: Option<&str>, |
| 73 | limit: i64, |
| 74 | offset: i64, |
| 75 | ) -> AppResult<DocumentPage> { |
| 76 | // 三个筛选都写成「参数为空就不生效」,一条 SQL 覆盖全部组合。 |
| 77 | // `$2 = 'any'` 那一支是「不按来源筛」,`'none'` 是「只看没有来源的」—— |
| 78 | // 用两个哨兵字符串而不是两个可空参数,因为 NULL 在这里有歧义: |
| 79 | // 它既可能是「不筛」,也可能是「筛出 source_id IS NULL 的」 |
| 80 | const WHERE: &str = "WHERE kb_id = $1 |
| 81 | AND ($2 = 'any' |
| 82 | OR ($2 = 'none' AND source_id IS NULL) |
| 83 | OR source_id::text = $2) |
| 84 | AND ($3::text IS NULL OR filename ILIKE '%' || $3 || '%') |
| 85 | AND ($4::text IS NULL OR graph_status = $4)"; |
| 86 | let scope = match source { |
| 87 | None => "any".to_string(), |
| 88 | Some(None) => "none".to_string(), |
| 89 | Some(Some(id)) => id.to_string(), |
| 90 | }; |
| 91 | |
| 92 | let docs: Vec<Document> = sqlx::query_as(&format!( |
| 93 | "SELECT * FROM documents {WHERE} ORDER BY created_at DESC LIMIT $5 OFFSET $6" |
| 94 | )) |
| 95 | .bind(kb_id) |
| 96 | .bind(&scope) |
| 97 | .bind(q) |
| 98 | .bind(graph_status) |
| 99 | .bind(limit) |
| 100 | .bind(offset) |
| 101 | .fetch_all(pool) |
| 102 | .await?; |
| 103 | |
| 104 | let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM documents {WHERE}")) |
| 105 | .bind(kb_id) |
| 106 | .bind(&scope) |
| 107 | .bind(q) |
| 108 | .bind(graph_status) |
| 109 | .fetch_one(pool) |
| 110 | .await?; |
| 111 | |
| 112 | // 统计只按来源作用域算:那两个批量按钮作用于整个来源,不是你搜出来的那几条 |
| 113 | let stats: (i64, i64, i64) = sqlx::query_as( |
| 114 | "SELECT |
| 115 | count(*) FILTER (WHERE status = 'ready'), |
| 116 | count(*) FILTER (WHERE graph_status IN ('queued', 'extracting')), |
| 117 | count(*) FILTER (WHERE graph_status = 'failed') |
| 118 | FROM documents |
| 119 | WHERE kb_id = $1 |
| 120 | AND ($2 = 'any' |
| 121 | OR ($2 = 'none' AND source_id IS NULL) |
| 122 | OR source_id::text = $2)", |
| 123 | ) |
| 124 | .bind(kb_id) |
| 125 | .bind(&scope) |
| 126 | .fetch_one(pool) |
| 127 | .await?; |
| 128 | |
| 129 | Ok(DocumentPage { |
| 130 | docs, |
| 131 | total, |
| 132 | ready: stats.0, |
| 133 | extracting: stats.1, |
| 134 | failed: stats.2, |
| 135 | }) |
| 136 | } |
| 137 | |
| 138 | /// 这个来源(或整库)里抽取失败的文档 id。**一键重试要的就是这份名单**。 |
| 139 | pub async fn failed_ids( |
| 140 | pool: &PgPool, |
| 141 | kb_id: Uuid, |
| 142 | source: Option<Option<Uuid>>, |
| 143 | ) -> AppResult<Vec<Uuid>> { |
| 144 | let scope = match source { |
| 145 | None => "any".to_string(), |
| 146 | Some(None) => "none".to_string(), |
| 147 | Some(Some(id)) => id.to_string(), |
| 148 | }; |
| 149 | Ok(sqlx::query_scalar( |
| 150 | "SELECT id FROM documents |
| 151 | WHERE kb_id = $1 AND graph_status = 'failed' |
| 152 | AND ($2 = 'any' |
| 153 | OR ($2 = 'none' AND source_id IS NULL) |
| 154 | OR source_id::text = $2)", |
| 155 | ) |
| 156 | .bind(kb_id) |
| 157 | .bind(&scope) |
| 158 | .fetch_all(pool) |
| 159 | .await?) |
| 160 | } |
| 161 | |
| 162 | pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Document> { |
| 163 | sqlx::query_as("SELECT * FROM documents WHERE id = $1") |
| 164 | .bind(id) |
| 165 | .fetch_optional(pool) |
| 166 | .await? |
| 167 | .ok_or(AppError::NotFound) |
| 168 | } |
| 169 | |
| 170 | /// 按来源内逻辑身份查文档(同步三路判定用)。 |
| 171 | pub async fn find_by_external_key( |
| 172 | pool: &PgPool, |
| 173 | source_id: Uuid, |
| 174 | external_key: &str, |
| 175 | ) -> AppResult<Option<Document>> { |
| 176 | Ok( |
| 177 | sqlx::query_as("SELECT * FROM documents WHERE source_id = $1 AND external_key = $2") |
| 178 | .bind(source_id) |
| 179 | .bind(external_key) |
| 180 | .fetch_optional(pool) |
| 181 | .await?, |
| 182 | ) |
| 183 | } |
| 184 | |
| 185 | /// 按来源 + 内容哈希查文档(改名/移动识别用)。 |
| 186 | pub async fn find_by_source_sha( |
| 187 | pool: &PgPool, |
| 188 | source_id: Uuid, |
| 189 | sha256: &str, |
| 190 | ) -> AppResult<Option<Document>> { |
| 191 | Ok( |
| 192 | sqlx::query_as("SELECT * FROM documents WHERE source_id = $1 AND sha256 = $2 LIMIT 1") |
| 193 | .bind(source_id) |
| 194 | .bind(sha256) |
| 195 | .fetch_optional(pool) |
| 196 | .await?, |
| 197 | ) |
| 198 | } |
| 199 | |
| 200 | /// 迁移前的历史文档(无 external_key)按文件名认领——0008 之前建的行的一次性兜底。 |
| 201 | pub async fn find_legacy_by_filename( |
| 202 | pool: &PgPool, |
| 203 | source_id: Uuid, |
| 204 | filename: &str, |
| 205 | ) -> AppResult<Option<Document>> { |
| 206 | Ok(sqlx::query_as( |
| 207 | "SELECT * FROM documents |
| 208 | WHERE source_id = $1 AND external_key IS NULL AND filename = $2 LIMIT 1", |
| 209 | ) |
| 210 | .bind(source_id) |
| 211 | .bind(filename) |
| 212 | .fetch_optional(pool) |
| 213 | .await?) |
| 214 | } |
| 215 | |
| 216 | /// 给历史文档补上逻辑身份。 |
| 217 | pub async fn adopt_external_key(pool: &PgPool, id: Uuid, external_key: &str) -> AppResult<()> { |
| 218 | sqlx::query("UPDATE documents SET external_key = $2, updated_at = now() WHERE id = $1") |
| 219 | .bind(id) |
| 220 | .bind(external_key) |
| 221 | .execute(pool) |
| 222 | .await?; |
| 223 | Ok(()) |
| 224 | } |
| 225 | |
| 226 | /// 变更:原地替换文档内容(新 sha),状态回 pending 待重跑管道。 |
| 227 | #[allow(clippy::too_many_arguments)] |
| 228 | pub async fn replace_content( |
| 229 | pool: &PgPool, |
| 230 | id: Uuid, |
| 231 | filename: &str, |
| 232 | mime: &str, |
| 233 | size_bytes: i64, |
| 234 | sha256: &str, |
| 235 | doc_time: Option<chrono::DateTime<chrono::Utc>>, |
| 236 | ) -> AppResult<()> { |
| 237 | sqlx::query( |
| 238 | "UPDATE documents SET filename = $2, mime = $3, size_bytes = $4, sha256 = $5, |
| 239 | doc_time = COALESCE($6, doc_time), |
| 240 | status = 'pending', graph_status = 'none', error = NULL, |
| 241 | missing_since = NULL, updated_at = now() |
| 242 | WHERE id = $1", |
| 243 | ) |
| 244 | .bind(id) |
| 245 | .bind(filename) |
| 246 | .bind(mime) |
| 247 | .bind(size_bytes) |
| 248 | .bind(sha256) |
| 249 | .bind(doc_time) |
| 250 | .execute(pool) |
| 251 | .await?; |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | /// 移动/改名:同内容换了路径,只更新身份,不重跑管道。 |
| 256 | pub async fn update_location( |
| 257 | pool: &PgPool, |
| 258 | id: Uuid, |
| 259 | filename: &str, |
| 260 | external_key: &str, |
| 261 | ) -> AppResult<()> { |
| 262 | sqlx::query( |
| 263 | "UPDATE documents SET filename = $2, external_key = $3, missing_since = NULL, |
| 264 | updated_at = now() WHERE id = $1", |
| 265 | ) |
| 266 | .bind(id) |
| 267 | .bind(filename) |
| 268 | .bind(external_key) |
| 269 | .execute(pool) |
| 270 | .await?; |
| 271 | Ok(()) |
| 272 | } |
| 273 | |
| 274 | /// 记录一个内容版本(版本号自增)。 |
| 275 | pub async fn record_version( |
| 276 | pool: &PgPool, |
| 277 | document_id: Uuid, |
| 278 | sha256: &str, |
| 279 | size_bytes: i64, |
| 280 | ) -> AppResult<()> { |
| 281 | sqlx::query( |
| 282 | "INSERT INTO document_versions (id, document_id, version, sha256, size_bytes) |
| 283 | VALUES ($1, $2, |
| 284 | (SELECT coalesce(max(version), 0) + 1 FROM document_versions WHERE document_id = $2), |
| 285 | $3, $4)", |
| 286 | ) |
| 287 | .bind(Uuid::now_v7()) |
| 288 | .bind(document_id) |
| 289 | .bind(sha256) |
| 290 | .bind(size_bytes) |
| 291 | .execute(pool) |
| 292 | .await?; |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | /// 全集对账(仅适用于能看到来源完整现状的类型,如 url 的配置列表): |
| 297 | /// 本轮见到的 key 清除 missing 标记,没见到的打上标记。 |
| 298 | /// rss(滑动窗口)与 custom 的增量响应(?since=)不可用此函数——缺席≠删除。 |
| 299 | pub async fn reconcile_missing( |
| 300 | pool: &PgPool, |
| 301 | source_id: Uuid, |
| 302 | seen_keys: &[String], |
| 303 | ) -> AppResult<()> { |
| 304 | clear_missing_keys(pool, source_id, seen_keys).await?; |
| 305 | sqlx::query( |
| 306 | "UPDATE documents SET missing_since = now(), updated_at = now() |
| 307 | WHERE source_id = $1 AND missing_since IS NULL |
| 308 | AND external_key IS NOT NULL AND NOT (external_key = ANY($2))", |
| 309 | ) |
| 310 | .bind(source_id) |
| 311 | .bind(seen_keys) |
| 312 | .execute(pool) |
| 313 | .await?; |
| 314 | Ok(()) |
| 315 | } |
| 316 | |
| 317 | /// 本轮出现的条目清除 missing 标记(条目失而复得)。 |
| 318 | pub async fn clear_missing_keys(pool: &PgPool, source_id: Uuid, keys: &[String]) -> AppResult<()> { |
| 319 | sqlx::query( |
| 320 | "UPDATE documents SET missing_since = NULL, updated_at = now() |
| 321 | WHERE source_id = $1 AND missing_since IS NOT NULL AND external_key = ANY($2)", |
| 322 | ) |
| 323 | .bind(source_id) |
| 324 | .bind(keys) |
| 325 | .execute(pool) |
| 326 | .await?; |
| 327 | Ok(()) |
| 328 | } |
| 329 | |
| 330 | /// 显式墓碑(custom 响应的 deleted[]):来源声明删除才打标,绝不因缺席推断。 |
| 331 | pub async fn mark_missing_keys(pool: &PgPool, source_id: Uuid, keys: &[String]) -> AppResult<u64> { |
| 332 | let res = sqlx::query( |
| 333 | "UPDATE documents SET missing_since = now(), updated_at = now() |
| 334 | WHERE source_id = $1 AND missing_since IS NULL AND external_key = ANY($2)", |
| 335 | ) |
| 336 | .bind(source_id) |
| 337 | .bind(keys) |
| 338 | .execute(pool) |
| 339 | .await?; |
| 340 | Ok(res.rows_affected()) |
| 341 | } |
| 342 | |
| 343 | /// 该来源下所有已标记 missing 的文档 id(批量清理用)。 |
| 344 | pub async fn list_missing(pool: &PgPool, source_id: Uuid) -> AppResult<Vec<Uuid>> { |
| 345 | let rows: Vec<(Uuid,)> = sqlx::query_as( |
| 346 | "SELECT id FROM documents WHERE source_id = $1 AND missing_since IS NOT NULL", |
| 347 | ) |
| 348 | .bind(source_id) |
| 349 | .fetch_all(pool) |
| 350 | .await?; |
| 351 | Ok(rows.into_iter().map(|(id,)| id).collect()) |
| 352 | } |
| 353 | |
| 354 | pub async fn set_status(pool: &PgPool, id: Uuid, status: &str) -> AppResult<()> { |
| 355 | sqlx::query("UPDATE documents SET status = $2, error = NULL, updated_at = now() WHERE id = $1") |
| 356 | .bind(id) |
| 357 | .bind(status) |
| 358 | .execute(pool) |
| 359 | .await?; |
| 360 | Ok(()) |
| 361 | } |
| 362 | |
| 363 | pub async fn set_failed(pool: &PgPool, id: Uuid, error: &str) -> AppResult<()> { |
| 364 | sqlx::query( |
| 365 | "UPDATE documents SET status = 'failed', error = $2, updated_at = now() WHERE id = $1", |
| 366 | ) |
| 367 | .bind(id) |
| 368 | .bind(error) |
| 369 | .execute(pool) |
| 370 | .await?; |
| 371 | Ok(()) |
| 372 | } |
| 373 | |
| 374 | pub async fn set_ready(pool: &PgPool, id: Uuid, text_len: i32, chunk_count: i32) -> AppResult<()> { |
| 375 | sqlx::query( |
| 376 | "UPDATE documents SET status = 'ready', error = NULL, text_len = $2, chunk_count = $3, |
| 377 | updated_at = now() WHERE id = $1", |
| 378 | ) |
| 379 | .bind(id) |
| 380 | .bind(text_len) |
| 381 | .bind(chunk_count) |
| 382 | .execute(pool) |
| 383 | .await?; |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> { |
| 388 | let res = sqlx::query("DELETE FROM documents WHERE id = $1") |
| 389 | .bind(id) |
| 390 | .execute(pool) |
| 391 | .await?; |
| 392 | if res.rows_affected() == 0 { |
| 393 | return Err(AppError::NotFound); |
| 394 | } |
| 395 | Ok(()) |
| 396 | } |
| 397 | |
| 398 | /// 重建文档分块(事务内,幂等)。返回 (chunk_id, text) 供全文索引。 |
| 399 | /// |
| 400 | /// 认领式增量:新块先按文本内容在现行块里找同款——找到即"认领"(原行只更新 |
| 401 | /// 序号/偏移/版本,身份延续:embedding、extracted_at、证据链接全部原地保鲜, |
| 402 | /// 未变段落不重抽也不会被误标"证据过期");没同款的才新建。落选的旧块软删除 |
| 403 | /// (superseded_at 打标)而非物理删除——fact_evidence 引用不断链、旧版可回放, |
| 404 | /// embedding 清空(旧版不参与检索,向量是存储大头不留)。 |
| 405 | pub async fn replace_chunks( |
| 406 | pool: &PgPool, |
| 407 | kb_id: Uuid, |
| 408 | document_id: Uuid, |
| 409 | pieces: &[ChunkPiece], |
| 410 | ) -> AppResult<Vec<(String, String)>> { |
| 411 | let mut tx = pool.begin().await?; |
| 412 | let (version,): (i32,) = sqlx::query_as( |
| 413 | "SELECT COALESCE(MAX(version), 1) FROM document_versions WHERE document_id = $1", |
| 414 | ) |
| 415 | .bind(document_id) |
| 416 | .fetch_one(&mut *tx) |
| 417 | .await?; |
| 418 | |
| 419 | // 认领池:现行块按文本分组(同文重复块按多重集配对,各认领各的) |
| 420 | let old: Vec<(Uuid, String)> = sqlx::query_as( |
| 421 | "SELECT id, text FROM chunks WHERE document_id = $1 AND superseded_at IS NULL", |
| 422 | ) |
| 423 | .bind(document_id) |
| 424 | .fetch_all(&mut *tx) |
| 425 | .await?; |
| 426 | let mut claim_pool: std::collections::HashMap<String, Vec<Uuid>> = |
| 427 | std::collections::HashMap::new(); |
| 428 | for (id, text) in old { |
| 429 | claim_pool.entry(text).or_default().push(id); |
| 430 | } |
| 431 | |
| 432 | // 第一阶段:认领(原行更新)与待插清单——新块必须等软删跑完再插, |
| 433 | // 否则"落选"判定会把本轮刚插入的新块一并软删 |
| 434 | let mut adopted: Vec<Uuid> = Vec::new(); |
| 435 | let mut to_insert: Vec<(Uuid, &ChunkPiece)> = Vec::new(); |
| 436 | let mut out = Vec::with_capacity(pieces.len()); |
| 437 | for piece in pieces { |
| 438 | let claimed = claim_pool.get_mut(&piece.text).and_then(|ids| ids.pop()); |
| 439 | if let Some(id) = claimed { |
| 440 | sqlx::query( |
| 441 | "UPDATE chunks SET seq = $2, char_start = $3, char_end = $4, doc_version = $5 |
| 442 | WHERE id = $1", |
| 443 | ) |
| 444 | .bind(id) |
| 445 | .bind(piece.seq) |
| 446 | .bind(piece.char_start) |
| 447 | .bind(piece.char_end) |
| 448 | .bind(version) |
| 449 | .execute(&mut *tx) |
| 450 | .await?; |
| 451 | adopted.push(id); |
| 452 | out.push((id.to_string(), piece.text.clone())); |
| 453 | } else { |
| 454 | let id = Uuid::now_v7(); |
| 455 | to_insert.push((id, piece)); |
| 456 | out.push((id.to_string(), piece.text.clone())); |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | // 第二阶段:落选旧块(新版里没有同款文本)→ 软删 |
| 461 | sqlx::query( |
| 462 | "UPDATE chunks SET superseded_at = now(), embedding = NULL |
| 463 | WHERE document_id = $1 AND superseded_at IS NULL AND NOT (id = ANY($2))", |
| 464 | ) |
| 465 | .bind(document_id) |
| 466 | .bind(&adopted) |
| 467 | .execute(&mut *tx) |
| 468 | .await?; |
| 469 | |
| 470 | // 第三阶段:插入新块 |
| 471 | for (id, piece) in to_insert { |
| 472 | sqlx::query( |
| 473 | "INSERT INTO chunks |
| 474 | (id, kb_id, document_id, seq, text, char_start, char_end, doc_version) |
| 475 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", |
| 476 | ) |
| 477 | .bind(id) |
| 478 | .bind(kb_id) |
| 479 | .bind(document_id) |
| 480 | .bind(piece.seq) |
| 481 | .bind(&piece.text) |
| 482 | .bind(piece.char_start) |
| 483 | .bind(piece.char_end) |
| 484 | .bind(version) |
| 485 | .execute(&mut *tx) |
| 486 | .await?; |
| 487 | } |
| 488 | tx.commit().await?; |
| 489 | Ok(out) |
| 490 | } |
| 491 | |
| 492 | /// 抽取完成一个分块即打标(认领的块携带标记跳过重抽;也让中断的抽取可续跑)。 |
| 493 | pub async fn mark_chunk_extracted(pool: &PgPool, chunk_id: Uuid) -> AppResult<()> { |
| 494 | sqlx::query("UPDATE chunks SET extracted_at = now() WHERE id = $1") |
| 495 | .bind(chunk_id) |
| 496 | .execute(pool) |
| 497 | .await?; |
| 498 | Ok(()) |
| 499 | } |
| 500 | |
| 501 | /// 单篇排队重抽(手动 Extract = 强制全量):清增量标记、解雇在跑的任务、置 |
| 502 | /// queued、建抽取任务——与 `queue_extraction` 同一套语义,只是作用于一篇。返回 job id。 |
| 503 | /// |
| 504 | /// 整体一个事务。分开做时任一步失败都会留下半截状态:清了标记却没换 epoch, |
| 505 | /// 旧任务察觉不到自己已被顶替;或者置了 queued 却没建成任务,文档就此无人接手。 |
| 506 | pub async fn queue_extraction_one(pool: &PgPool, document_id: Uuid) -> AppResult<i64> { |
| 507 | let mut tx = pool.begin().await?; |
| 508 | sqlx::query( |
| 509 | "UPDATE chunks SET extracted_at = NULL |
| 510 | WHERE document_id = $1 AND superseded_at IS NULL", |
| 511 | ) |
| 512 | .bind(document_id) |
| 513 | .execute(&mut *tx) |
| 514 | .await?; |
| 515 | // 未开跑的旧任务顺手删掉:连点两次 Extract 不该攒出两个任务同抽一篇 |
| 516 | sqlx::query( |
| 517 | "DELETE FROM jobs WHERE kind = 'extract_document' AND status = 'queued' |
| 518 | AND payload->>'document_id' = $1", |
| 519 | ) |
| 520 | .bind(document_id.to_string()) |
| 521 | .execute(&mut *tx) |
| 522 | .await?; |
| 523 | sqlx::query( |
| 524 | "UPDATE documents SET graph_status = 'queued', graph_error = NULL, |
| 525 | extract_epoch = extract_epoch + 1 |
| 526 | WHERE id = $1", |
| 527 | ) |
| 528 | .bind(document_id) |
| 529 | .execute(&mut *tx) |
| 530 | .await?; |
| 531 | let (job_id,): (i64,) = sqlx::query_as( |
| 532 | "INSERT INTO jobs (kind, payload) |
| 533 | VALUES ('extract_document', jsonb_build_object('document_id', $1::text)) |
| 534 | RETURNING id", |
| 535 | ) |
| 536 | .bind(document_id) |
| 537 | .fetch_one(&mut *tx) |
| 538 | .await?; |
| 539 | tx.commit().await?; |
| 540 | Ok(job_id) |
| 541 | } |
| 542 | |
| 543 | /// 文档查看器:全部分块(按顺序)。 |
| 544 | pub async fn chunks_full( |
| 545 | pool: &PgPool, |
| 546 | document_id: Uuid, |
| 547 | ) -> AppResult<Vec<utopia_core::models::ChunkFull>> { |
| 548 | let rows = sqlx::query_as( |
| 549 | "SELECT id, seq, text FROM chunks |
| 550 | WHERE document_id = $1 AND superseded_at IS NULL ORDER BY seq", |
| 551 | ) |
| 552 | .bind(document_id) |
| 553 | .fetch_all(pool) |
| 554 | .await?; |
| 555 | Ok(rows) |
| 556 | } |
| 557 | |
| 558 | /// 抽取用分块:文本 + 摄入阶段已算好的 embedding(消解 v2 复用,零额外 embed 调用)。 |
| 559 | #[derive(Debug, sqlx::FromRow)] |
| 560 | pub struct ChunkForExtract { |
| 561 | pub id: Uuid, |
| 562 | pub seq: i32, |
| 563 | pub text: String, |
| 564 | pub embedding: Option<Vector>, |
| 565 | } |
| 566 | |
| 567 | pub async fn chunks_for_extraction( |
| 568 | pool: &PgPool, |
| 569 | document_id: Uuid, |
| 570 | ) -> AppResult<Vec<ChunkForExtract>> { |
| 571 | // 只取未抽取的分块:认领的未变段落携带 extracted_at 跳过(增量抽取 + 断点续抽) |
| 572 | let rows = sqlx::query_as( |
| 573 | "SELECT id, seq, text, embedding FROM chunks |
| 574 | WHERE document_id = $1 AND superseded_at IS NULL AND extracted_at IS NULL |
| 575 | ORDER BY seq", |
| 576 | ) |
| 577 | .bind(document_id) |
| 578 | .fetch_all(pool) |
| 579 | .await?; |
| 580 | Ok(rows) |
| 581 | } |
| 582 | |
| 583 | /// 推进抽取状态(顺带清空上一轮的失败原因——重跑即翻篇)。 |
| 584 | pub async fn set_graph_status(pool: &PgPool, id: Uuid, status: &str) -> AppResult<()> { |
| 585 | sqlx::query( |
| 586 | "UPDATE documents SET graph_status = $2, graph_error = NULL, updated_at = now() |
| 587 | WHERE id = $1", |
| 588 | ) |
| 589 | .bind(id) |
| 590 | .bind(status) |
| 591 | .execute(pool) |
| 592 | .await?; |
| 593 | Ok(()) |
| 594 | } |
| 595 | |
| 596 | /// 该文档尚未 embedding 的分块(id + 文本)。 |
| 597 | pub async fn chunks_pending_embedding( |
| 598 | pool: &PgPool, |
| 599 | document_id: Uuid, |
| 600 | ) -> AppResult<Vec<(Uuid, String)>> { |
| 601 | let rows: Vec<(Uuid, String)> = sqlx::query_as( |
| 602 | "SELECT id, text FROM chunks |
| 603 | WHERE document_id = $1 AND embedding IS NULL AND superseded_at IS NULL ORDER BY seq", |
| 604 | ) |
| 605 | .bind(document_id) |
| 606 | .fetch_all(pool) |
| 607 | .await?; |
| 608 | Ok(rows) |
| 609 | } |
| 610 | |
| 611 | pub async fn set_embeddings(pool: &PgPool, items: &[(Uuid, Vec<f32>)]) -> AppResult<()> { |
| 612 | let mut tx = pool.begin().await?; |
| 613 | for (id, emb) in items { |
| 614 | sqlx::query("UPDATE chunks SET embedding = $2 WHERE id = $1") |
| 615 | .bind(id) |
| 616 | .bind(Vector::from(emb.clone())) |
| 617 | .execute(&mut *tx) |
| 618 | .await?; |
| 619 | } |
| 620 | tx.commit().await?; |
| 621 | Ok(()) |
| 622 | } |
| 623 | |
| 624 | /// 向量近邻检索(余弦距离,顺扫;P1 规模足够)。 |
| 625 | pub async fn vector_search( |
| 626 | pool: &PgPool, |
| 627 | kb_id: Uuid, |
| 628 | embedding: &[f32], |
| 629 | limit: i64, |
| 630 | ) -> AppResult<Vec<Uuid>> { |
| 631 | let query_vec = Vector::from(embedding.to_vec()); |
| 632 | let rows: Vec<(Uuid,)> = sqlx::query_as( |
| 633 | "SELECT id FROM chunks |
| 634 | WHERE kb_id = $1 AND embedding IS NOT NULL AND superseded_at IS NULL |
| 635 | AND vector_dims(embedding) = vector_dims($2) |
| 636 | ORDER BY embedding <=> $2 |
| 637 | LIMIT $3", |
| 638 | ) |
| 639 | .bind(kb_id) |
| 640 | .bind(&query_vec) |
| 641 | .bind(limit) |
| 642 | .fetch_all(pool) |
| 643 | .await?; |
| 644 | Ok(rows.into_iter().map(|(id,)| id).collect()) |
| 645 | } |
| 646 | |
| 647 | /// 按 id 集合取分块(带文档名),保持传入顺序。 |
| 648 | pub async fn chunks_by_ids(pool: &PgPool, kb_id: Uuid, ids: &[Uuid]) -> AppResult<Vec<ChunkView>> { |
| 649 | let rows: Vec<ChunkView> = sqlx::query_as( |
| 650 | "SELECT c.id, c.document_id, c.seq, c.text, d.filename |
| 651 | FROM chunks c JOIN documents d ON d.id = c.document_id |
| 652 | WHERE c.kb_id = $1 AND c.id = ANY($2)", |
| 653 | ) |
| 654 | .bind(kb_id) |
| 655 | .bind(ids) |
| 656 | .fetch_all(pool) |
| 657 | .await?; |
| 658 | // 恢复 RRF 排名顺序 |
| 659 | let mut by_id: std::collections::HashMap<Uuid, ChunkView> = |
| 660 | rows.into_iter().map(|c| (c.id, c)).collect(); |
| 661 | Ok(ids.iter().filter_map(|id| by_id.remove(id)).collect()) |
| 662 | } |
| 663 | |
| 664 | /// 批量排队全量重抽:ready 文档清增量标记 → graph_status=queued → 建抽取任务, |
| 665 | /// 返回待抽文档 id。`source_id` 给定则限定该来源,否则整库。 |
| 666 | /// |
| 667 | /// 正在抽取的文档一并重排——epoch 自增即"解雇"在跑的那个任务(见 |
| 668 | /// `extract_epoch`),不必跳过、也不会两个 worker 同抽一篇。 |
| 669 | /// 尚未开跑的 extract 任务顺手删掉(payload 用文本比较:历史脏 payload 无法转 uuid)。 |
| 670 | /// |
| 671 | /// 建任务与置状态同事务:分开做时,中途出错会留下一批 graph_status=queued |
| 672 | /// 却没有任务的文档——不会有 worker 来接,界面上永远停在"排队中"。 |
| 673 | pub async fn queue_extraction( |
| 674 | pool: &PgPool, |
| 675 | kb_id: Uuid, |
| 676 | source_id: Option<Uuid>, |
| 677 | ) -> AppResult<Vec<Uuid>> { |
| 678 | let mut tx = pool.begin().await?; |
| 679 | let ids: Vec<(Uuid,)> = sqlx::query_as( |
| 680 | "SELECT id FROM documents |
| 681 | WHERE kb_id = $1 AND status = 'ready' AND ($2::uuid IS NULL OR source_id = $2) |
| 682 | ORDER BY created_at", |
| 683 | ) |
| 684 | .bind(kb_id) |
| 685 | .bind(source_id) |
| 686 | .fetch_all(&mut *tx) |
| 687 | .await?; |
| 688 | let ids: Vec<Uuid> = ids.into_iter().map(|(id,)| id).collect(); |
| 689 | if ids.is_empty() { |
| 690 | tx.commit().await?; |
| 691 | return Ok(ids); |
| 692 | } |
| 693 | |
| 694 | sqlx::query( |
| 695 | "DELETE FROM jobs WHERE kind = 'extract_document' AND status = 'queued' |
| 696 | AND payload->>'document_id' = ANY($1)", |
| 697 | ) |
| 698 | .bind(ids.iter().map(|i| i.to_string()).collect::<Vec<_>>()) |
| 699 | .execute(&mut *tx) |
| 700 | .await?; |
| 701 | sqlx::query( |
| 702 | "UPDATE chunks SET extracted_at = NULL |
| 703 | WHERE document_id = ANY($1) AND superseded_at IS NULL", |
| 704 | ) |
| 705 | .bind(&ids) |
| 706 | .execute(&mut *tx) |
| 707 | .await?; |
| 708 | sqlx::query( |
| 709 | "UPDATE documents SET graph_status = 'queued', graph_error = NULL, |
| 710 | extract_epoch = extract_epoch + 1 |
| 711 | WHERE id = ANY($1)", |
| 712 | ) |
| 713 | .bind(&ids) |
| 714 | .execute(&mut *tx) |
| 715 | .await?; |
| 716 | // payload 形状与 jobs::enqueue(json!({"document_id": id})) 一致:uuid 序列化为字符串 |
| 717 | sqlx::query( |
| 718 | "INSERT INTO jobs (kind, payload) |
| 719 | SELECT 'extract_document', jsonb_build_object('document_id', id::text) |
| 720 | FROM unnest($1::uuid[]) AS t(id)", |
| 721 | ) |
| 722 | .bind(&ids) |
| 723 | .execute(&mut *tx) |
| 724 | .await?; |
| 725 | tx.commit().await?; |
| 726 | Ok(ids) |
| 727 | } |
| 728 | |
| 729 | /// 抽取失败:状态与原因一起落库,界面才有东西可展示。 |
| 730 | pub async fn set_graph_failed(pool: &PgPool, id: Uuid, error: &str) -> AppResult<()> { |
| 731 | sqlx::query( |
| 732 | "UPDATE documents SET graph_status = 'failed', graph_error = $2, updated_at = now() |
| 733 | WHERE id = $1", |
| 734 | ) |
| 735 | .bind(id) |
| 736 | .bind(error) |
| 737 | .execute(pool) |
| 738 | .await?; |
| 739 | Ok(()) |
| 740 | } |
| 741 | |
| 742 | /// 抽取任务的所有权凭证:每次"开始新一轮抽取"自增。 |
| 743 | /// |
| 744 | /// 单靠 graph_status 认领无效——旧任务回读时,接手的新任务可能已把状态写回 |
| 745 | /// extracting,旧任务会误判自己仍在岗。epoch 单调递增,旧任务一比即知已被接管。 |
| 746 | pub async fn extract_epoch(pool: &PgPool, id: Uuid) -> AppResult<i32> { |
| 747 | let (epoch,): (i32,) = sqlx::query_as("SELECT extract_epoch FROM documents WHERE id = $1") |
| 748 | .bind(id) |
| 749 | .fetch_one(pool) |
| 750 | .await?; |
| 751 | Ok(epoch) |
| 752 | } |
| 753 | |
| 754 | /// 这个库还有没有在排队或正在跑的抽取。 |
| 755 | /// |
| 756 | /// 冷启动自动扩本体要等一批文档都抽完再动手:只看第一篇的话, |
| 757 | /// 先到的那篇的词汇会独占本体。最后一篇跑完的任务负责触发。 |
| 758 | pub async fn extraction_idle(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> { |
| 759 | let (pending,): (i64,) = sqlx::query_as( |
| 760 | "SELECT count(*) FROM documents |
| 761 | WHERE kb_id = $1 AND graph_status IN ('queued', 'extracting')", |
| 762 | ) |
| 763 | .bind(kb_id) |
| 764 | .fetch_one(pool) |
| 765 | .await?; |
| 766 | Ok(pending == 0) |
| 767 | } |
| 768 | |
| 769 | /// 全库分块,按文档分组,供检索索引重建用。 |
| 770 | /// |
| 771 | /// **一次全取**:这条只在启动发现索引落空时跑,那时候要的正是全部; |
| 772 | /// 而它跑完之后就再也不跑了。 |
| 773 | pub async fn all_chunks_for_index(pool: &PgPool) -> AppResult<Vec<(Uuid, Uuid, Uuid, String)>> { |
| 774 | Ok(sqlx::query_as( |
| 775 | "SELECT kb_id, document_id, id, text FROM chunks |
| 776 | WHERE superseded_at IS NULL |
| 777 | ORDER BY document_id, seq", |
| 778 | ) |
| 779 | .fetch_all(pool) |
| 780 | .await?) |
| 781 | } |
| 782 | |
| 783 | /// 库里一共有多少条在用的分块。启动时拿它跟索引对账。 |
| 784 | pub async fn live_chunk_count(pool: &PgPool) -> AppResult<i64> { |
| 785 | Ok( |
| 786 | sqlx::query_scalar("SELECT count(*) FROM chunks WHERE superseded_at IS NULL") |
| 787 | .fetch_one(pool) |
| 788 | .await?, |
| 789 | ) |
| 790 | } |