fix(rag): stop superseded indexing runs and refuse to wipe chunks on an empty reindex

- Each document gets an indexing run number; a reindex, synced replacement or
  delete makes the older run stop instead of embedding stale chunks, reporting
  'indexed' early and leaving a progress bar for a deleted document
- Reindexing a file that is now empty throws like addDocument instead of
  replacing the stored chunks with nothing
This commit is contained in:
Yun Chan 2026-10-21 00:24:38 +09:00
parent 45d8b1ddb1
commit c46713536d
2 changed files with 83 additions and 1 deletions

View file

@ -127,6 +127,8 @@ export class RAGService extends EventEmitter {
/** 진행 중인 색인·질의 수. 상태는 여기서 파생한다 — 겹쳐 실행돼도 서로의 상태를 덮지 않는다. */
private activeIndexing = 0
private activeQueries = 0
/** 문서별 색인 실행 번호. 재색인·동기화로 청크가 바뀌거나 문서가 지워지면 앞선 실행은 스스로 멈춘다. */
private readonly indexRuns = new Map<string, number>()
constructor(deps: RAGServiceDeps = defaultRAGServiceDeps()) {
super()
@ -217,6 +219,8 @@ export class RAGService extends EventEmitter {
/** 동기화: 다른 기기에서 지운 문서를 지운다(outbox에 넣지 않는다). */
removeRemote(documentId: string): boolean {
// 진행 중인 색인이 지운 문서를 끝까지 임베딩하며 진행 표시를 남기지 않게 멈춘다.
this.indexRuns.delete(documentId)
return this.deps.store.removeDocument(documentId)
}
@ -276,6 +280,10 @@ export class RAGService extends EventEmitter {
// 텍스트 재추출 + 재인덱싱
const content = await this._extractText(doc.filePath, doc.fileType)
const chunks = chunkText(content)
// 원본이 비었으면 저장된 청크를 지우지 않는다 — 지우면 이 기기에서 영영 되살릴 수 없다(빈 문서는 동기화되지 않음).
if (content.trim().length < 20 || chunks.length === 0) {
throw new D3ROError(ErrorCode.RAGIndexingFailed, 'No readable text content found in document')
}
this.deps.store.updateDocument(documentId, { chunkCount: chunks.length, indexed: false })
this.deps.store.replaceChunks(documentId, chunks)
@ -343,6 +351,15 @@ export class RAGService extends EventEmitter {
private async _indexChunks(docId: string, fileName: string, options: { force?: boolean }): Promise<void> {
const { store, embedder, notify } = this.deps
// 실행 번호는 첫 await 전에 올린다 — 이 시점 이후 앞선 실행이 쓰는 청크 id 는 이미 지워졌을 수 있다.
const run = (this.indexRuns.get(docId) ?? 0) + 1
this.indexRuns.set(docId, run)
const isCurrent = (): boolean => this.indexRuns.get(docId) === run
const stopSuperseded = (): void => {
// 문서가 지워졌으면 이어받을 실행이 없으니 진행 표시를 여기서 내린다.
if (!store.hasDocument(docId)) notify(IPC_CHANNELS.RAG.INDEX_COMPLETE, { documentId: docId, fileName })
logger.info(`RAG indexing superseded: ${fileName}`)
}
const chunks = store.listChunks(docId)
logger.info(`RAG indexing started: ${fileName} (${chunks.length} chunks)`)
@ -352,9 +369,11 @@ export class RAGService extends EventEmitter {
try {
await embedder.ensureModel()
} catch (err) {
if (!isCurrent()) return stopSuperseded()
store.updateDocument(docId, { indexed: false, indexedAt: null })
throw err
}
if (!isCurrent()) return stopSuperseded()
}
// 초기 진행률 즉시 전송
@ -374,7 +393,9 @@ export class RAGService extends EventEmitter {
continue
}
try {
store.setEmbedding(chunk.id, await embedder.embed(chunk.content))
const embedding = await embedder.embed(chunk.content)
if (!isCurrent()) return stopSuperseded()
store.setEmbedding(chunk.id, embedding)
successCount++
} catch (err) {
logger.warn(`RAG embedding failed for chunk ${i}/${chunks.length} of ${fileName}:`, err)
@ -390,7 +411,9 @@ export class RAGService extends EventEmitter {
} satisfies RAGIndexProgress)
await new Promise((r) => setTimeout(r, this.deps.yieldMs))
if (!isCurrent()) return stopSuperseded()
}
this.indexRuns.delete(docId)
// 한 청크도 임베딩하지 못했으면(임베딩 서버 없음 등) 색인됐다고 표시하지 않는다.
// indexed=true + 0 chunks 로 두면 문서가 검색 가능한 것처럼 보이지만 질의에 걸리지 않는다.