pipeline.py
15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""索引流程:解析 -> 切块 -> 向量化 -> 入库,以及删除与中断修复。"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import time
from datetime import datetime
from typing import Any
from fastapi import HTTPException
from sqlalchemy import delete, func, select, update
from src.database.models import RagChunk, RagFile, RagIndexRun
from src.database.session import AsyncSessionLocal
from src.rag.core.config import RAG_INDEX_CONCURRENCY, RAG_QDRANT_UPSERT_BATCH_SIZE
from src.rag.core.errors import RagStructuredError
from src.rag.core.utils import safe_json_dumps, sha256_file
from src.rag.infra.serializers import _chunk_model_kwargs
from src.rag.infra.vector_store import vector_store
from src.rag.ingestion import RagChunkData, build_chunks, parse_document
from src.rag.ingestion.loaders.common import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.ingestion.loaders.pdf import doc_vlm_stats
logger = logging.getLogger(__name__)
_file_locks: dict[str, asyncio.Lock] = {}
_index_semaphore = asyncio.Semaphore(RAG_INDEX_CONCURRENCY)
def _lock_for(file_id: str) -> asyncio.Lock:
if file_id not in _file_locks:
_file_locks[file_id] = asyncio.Lock()
return _file_locks[file_id]
async def index_file(file_id: str) -> dict:
"""
为指定的文件启动解析、切块、向量化(Embedding)以及保存倒排/向量索引到 Qdrant 的完整流程。
该过程通常较慢,且会受并发控制,通过锁与状态防止重入。
"""
async with _lock_for(file_id):
start = time.time()
new_child_ids: list[str] = []
db_committed = False
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file or db_file.status == "Deleted":
raise HTTPException(status_code=404, detail="RAG file not found")
if db_file.status == "Indexing":
raise HTTPException(status_code=409, detail="文件正在索引中")
if not os.path.exists(db_file.source_path):
raise HTTPException(status_code=404, detail="源文件不存在")
current_hash = sha256_file(db_file.source_path)
if db_file.status == "Indexed" and db_file.content_hash == current_hash and db_file.chunk_count > 0:
return {"status": "skipped", "reason": "索引已是最新"}
old_chunk_ids = (await session.execute(select(RagChunk.chunk_id).where(RagChunk.file_id == file_id))).scalars().all()
db_file.status = "Indexing"
db_file.error_message = None
db_file.error_code = None
db_file.error_detail_json = None
db_file.index_started_at = datetime.now()
source_path = db_file.source_path
name = db_file.name
format_ext = db_file.format
await session.commit()
try:
async with _index_semaphore:
async with AsyncSessionLocal() as session:
check_file = await session.get(RagFile, file_id)
if not check_file or check_file.status == "Deleted":
return {"status": "skipped", "reason": "文件已被删除"}
logger.info("[RAG] 正在处理 %s(file_id=%s):开始解析…", name, file_id)
blocks = await asyncio.to_thread(parse_document, source_path)
parents, children = build_chunks(file_id, name, source_path, format_ext, blocks)
logger.info("[RAG] %s 切块完成:blocks=%d, parents=%d, children=%d;开始向量化…",
name, len(blocks), len(parents), len(children))
_prepare_chunks(parents + children, "active")
new_child_ids = [chunk.chunk_id for chunk in children]
vector_count = await asyncio.to_thread(vector_store.upsert_children, children, RAG_QDRANT_UPSERT_BATCH_SIZE)
logger.info("[RAG] %s 向量化完成:vectors=%d", name, vector_count)
async with AsyncSessionLocal() as session:
await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
for chunk in parents + children:
session.add(RagChunk(**_chunk_model_kwargs(chunk)))
db_file = await session.get(RagFile, file_id)
db_file.status = "Indexed"
db_file.content_hash = current_hash
db_file.error_code = None
db_file.error_detail_json = None
db_file.error_message = None
db_file.parser_version = _metadata_value(parents + children, "parser_version") or RAG_PARSER_VERSION
db_file.chunker_version = _metadata_value(parents + children, "chunker_version") or RAG_CHUNKER_VERSION
db_file.block_count = len(blocks)
db_file.word_count = sum(len(c.content) for c in parents)
db_file.chunk_count = len(parents) + len(children)
db_file.parent_chunk_count = len(parents)
db_file.child_chunk_count = len(children)
db_file.index_duration_ms = int((time.time() - start) * 1000)
vlm_stats = doc_vlm_stats(blocks)
db_file.vlm_page_count = int(vlm_stats.get("vlm_page_count") or 0)
db_file.vlm_total_tokens = int(vlm_stats.get("vlm_total_tokens") or 0)
db_file.vlm_duration_ms = int(vlm_stats.get("vlm_duration_ms") or 0)
db_file.indexed_at = datetime.now()
session.add(
RagIndexRun(
file_id=file_id,
status="Success",
parser_version=db_file.parser_version,
chunker_version=db_file.chunker_version,
block_count=len(blocks),
parent_chunk_count=len(parents),
child_chunk_count=len(children),
vector_count=vector_count,
duration_ms=db_file.index_duration_ms,
vlm_page_count=db_file.vlm_page_count,
vlm_total_tokens=db_file.vlm_total_tokens,
)
)
await session.commit()
db_committed = True
if old_chunk_ids:
await asyncio.to_thread(vector_store.delete_chunk_ids, list(old_chunk_ids))
duration_ms = int((time.time() - start) * 1000)
logger.info(
"[RAG] 索引完成: %s → parents=%d, children=%d, vectors=%d, 用时 %dms;"
"VLM 落库: 页=%d, tokens=%d, VLM耗时=%dms",
name, len(parents), len(children), vector_count, duration_ms,
db_file.vlm_page_count, db_file.vlm_total_tokens, db_file.vlm_duration_ms,
)
return {"status": "success", "parent_chunks": len(parents), "child_chunks": len(children),
"vectors": vector_count, "duration_ms": duration_ms,
"vlm_page_count": db_file.vlm_page_count, "vlm_total_tokens": db_file.vlm_total_tokens}
except Exception as exc:
if new_child_ids and not db_committed:
await asyncio.to_thread(vector_store.delete_chunk_ids, new_child_ids)
error_code = _error_code(exc)
error_detail_json = _error_detail_json(exc)
if isinstance(exc, RagStructuredError):
logger.error("[RAG] index failed with structured error: file_id=%s code=%s detail=%s", file_id, error_code, error_detail_json)
else:
logger.exception("[RAG] index failed: file_id=%s", file_id)
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if db_file:
db_file.status = "Failed" if isinstance(exc, RagStructuredError) else ("Indexed" if db_file.chunk_count > 0 else "Failed")
db_file.error_code = error_code
db_file.error_detail_json = error_detail_json
db_file.error_message = str(exc)
session.add(
RagIndexRun(
file_id=file_id,
status="Failed",
parser_version=getattr(db_file, "parser_version", None) or RAG_PARSER_VERSION,
chunker_version=getattr(db_file, "chunker_version", None) or RAG_CHUNKER_VERSION,
block_count=getattr(db_file, "block_count", 0) or 0,
parent_chunk_count=0,
child_chunk_count=0,
vector_count=0,
duration_ms=int((time.time() - start) * 1000),
error_code=error_code,
error_detail_json=error_detail_json,
error_message=str(exc),
)
)
await session.commit()
raise
async def delete_index(file_id: str, keep_status: bool = False, force: bool = False) -> dict:
"""
删除指定的已建索引(包括关系型数据库内的块记录以及 Qdrant 里的向量数据)。
如果 keep_status=False,文件状态将回退至 'Pending'。
"""
async with _lock_for(file_id):
await _delete_index_unlocked(file_id, keep_status, force)
return {"status": "success"}
async def _delete_index_unlocked(file_id: str, keep_status: bool = False, force: bool = False) -> None:
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file:
raise HTTPException(status_code=404, detail="RAG file not found")
if db_file.status == "Indexing" and not force:
raise HTTPException(status_code=409, detail="文件正在索引中,不能删除索引或文件")
await asyncio.to_thread(vector_store.delete_file, file_id)
await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
if not keep_status:
db_file.status = "Pending"
db_file.chunk_count = 0
db_file.parent_chunk_count = 0
db_file.child_chunk_count = 0
db_file.error_message = None
await session.commit()
async def repair_interrupted_indexes(cleanup_partial: bool = False) -> dict:
"""
系统自愈工具:扫描因为服务器宕机等异常原因处于 Uploading/Indexing 假死状态的任务,
尝试恢复或清理不完整的垃圾数据。
"""
repaired: list[dict] = []
async with AsyncSessionLocal() as session:
rows = (await session.execute(select(RagFile).where(RagFile.status.in_(["Uploading", "Indexing"])))).scalars().all()
for row in rows:
async with _lock_for(row.id):
repaired.append(await _repair_one_file(row.id, cleanup_partial))
return {"status": "success", "items": repaired}
async def _repair_one_file(file_id: str, cleanup_partial: bool) -> dict:
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file or db_file.status == "Deleted":
return {"file_id": file_id, "action": "skip"}
if db_file.status == "Uploading":
if os.path.exists(db_file.source_path) and os.path.getsize(db_file.source_path) > 0:
db_file.size = os.path.getsize(db_file.source_path)
db_file.content_hash = sha256_file(db_file.source_path)
db_file.status = "Pending"
db_file.error_message = None
action = "upload_recovered"
else:
db_file.status = "Failed"
db_file.error_message = "服务重启导致上传中断,请重新上传"
action = "upload_failed"
await session.commit()
return {"file_id": file_id, "action": action}
parent_count = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "parent"))).scalar() or 0
child_count = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "child"))).scalar() or 0
vector_count = await asyncio.to_thread(vector_store.count_file, file_id)
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file or db_file.status == "Deleted":
return {"file_id": file_id, "action": "skip"}
complete = child_count > 0 and (vector_count is None or vector_count >= child_count)
if complete:
active_children = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "child", RagChunk.status == "active"))).scalar() or 0
db_file.status = "Indexed" if active_children else "Disabled"
db_file.parent_chunk_count = parent_count
db_file.child_chunk_count = child_count
db_file.chunk_count = parent_count + child_count
db_file.error_message = None
db_file.indexed_at = db_file.indexed_at or datetime.now()
await session.commit()
return {"file_id": file_id, "action": "index_recovered", "parent_chunks": parent_count, "child_chunks": child_count, "vectors": vector_count}
if cleanup_partial:
await asyncio.to_thread(vector_store.delete_file, file_id)
await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
db_file.status = "Pending"
db_file.chunk_count = 0
db_file.parent_chunk_count = 0
db_file.child_chunk_count = 0
db_file.error_message = "已清理中断索引,请重新生成索引"
action = "partial_cleaned"
else:
await session.execute(update(RagChunk).where(RagChunk.file_id == file_id).values(status="disabled"))
await asyncio.to_thread(vector_store.set_file_status, file_id, "disabled")
db_file.status = "Failed"
db_file.error_message = f"索引被中断且数据不完整:DB child={child_count}, Qdrant points={vector_count},请重建索引"
action = "partial_disabled"
await session.commit()
return {"file_id": file_id, "action": action, "parent_chunks": parent_count, "child_chunks": child_count, "vectors": vector_count}
def _prepare_chunks(chunks: list[RagChunkData], status: str) -> None:
for chunk in chunks:
chunk.status = status
def _error_code(exc: Exception) -> str | None:
return getattr(exc, "error_code", None)
def _error_detail_json(exc: Exception) -> str | None:
if isinstance(exc, RagStructuredError):
return exc.to_json()
return None
def _metadata_value(chunks: list[RagChunkData], key: str) -> str | None:
for chunk in chunks:
value = chunk.metadata_json.get(key) if isinstance(chunk.metadata_json, dict) else None
if value:
return str(value)
return None