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