fix(rag): don't carry a query, upload or indexing run across an account switch
The chunk store reads whatever database is open at call time, so a query that was awaiting the model returned an answer built from the previous account's documents, and a large file being read was inserted into the new account's knowledge base and synced there. Each operation now remembers the account scope it started in and stops if it changed.
This commit is contained in:
parent
3e6cfd1ba8
commit
6fef05a39f
2 changed files with 79 additions and 1 deletions
|
|
@ -16,6 +16,7 @@ import { getLlmGateway } from './llm/LlmGateway'
|
||||||
import { getOllamaServerUrl } from './LocalLLMService'
|
import { getOllamaServerUrl } from './LocalLLMService'
|
||||||
import { getMainWindow } from '../windows/WindowManager'
|
import { getMainWindow } from '../windows/WindowManager'
|
||||||
import { getCloudSyncService } from './CloudSyncService'
|
import { getCloudSyncService } from './CloudSyncService'
|
||||||
|
import { currentAccountScope } from './account-scope'
|
||||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||||
import type { RAGDocument, RAGQueryResult, RAGState, RAGStateInfo, RAGIndexProgress } from '@d3ro/core/types'
|
import type { RAGDocument, RAGQueryResult, RAGState, RAGStateInfo, RAGIndexProgress } from '@d3ro/core/types'
|
||||||
|
|
@ -74,6 +75,8 @@ export interface RAGServiceDeps {
|
||||||
assertLicensed: () => Promise<void>
|
assertLicensed: () => Promise<void>
|
||||||
/** 청크 사이 양보 시간(ms) */
|
/** 청크 사이 양보 시간(ms) */
|
||||||
yieldMs: number
|
yieldMs: number
|
||||||
|
/** 지금 열린 계정 범위. 기다리는 사이 바뀌면 이전 계정의 작업을 새 계정 DB 에 이어 쓰지 않는다. */
|
||||||
|
accountScope?: () => string
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RAGServiceEvents {
|
interface RAGServiceEvents {
|
||||||
|
|
@ -119,6 +122,7 @@ export function defaultRAGServiceDeps(): RAGServiceDeps {
|
||||||
fileExists: (filePath) => fs.existsSync(filePath),
|
fileExists: (filePath) => fs.existsSync(filePath),
|
||||||
assertLicensed: assertLocalRagLicense,
|
assertLicensed: assertLocalRagLicense,
|
||||||
yieldMs: INDEX_YIELD_MS,
|
yieldMs: INDEX_YIELD_MS,
|
||||||
|
accountScope: currentAccountScope,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -153,6 +157,7 @@ export class RAGService extends EventEmitter {
|
||||||
* 문서 추가 + 인덱싱 (청킹 → 임베딩 → DB 저장)
|
* 문서 추가 + 인덱싱 (청킹 → 임베딩 → DB 저장)
|
||||||
*/
|
*/
|
||||||
async addDocument(filePath: string): Promise<RAGDocument> {
|
async addDocument(filePath: string): Promise<RAGDocument> {
|
||||||
|
const scope = this._scope()
|
||||||
await this.deps.assertLicensed()
|
await this.deps.assertLicensed()
|
||||||
|
|
||||||
const ext = path.extname(filePath).toLowerCase()
|
const ext = path.extname(filePath).toLowerCase()
|
||||||
|
|
@ -176,6 +181,8 @@ export class RAGService extends EventEmitter {
|
||||||
if (!content || content.trim().length < 20) {
|
if (!content || content.trim().length < 20) {
|
||||||
throw new D3ROError(ErrorCode.RAGIndexingFailed, 'No readable text content found in document')
|
throw new D3ROError(ErrorCode.RAGIndexingFailed, 'No readable text content found in document')
|
||||||
}
|
}
|
||||||
|
// 큰 파일을 읽는 사이 계정이 바뀌었으면 이전 계정의 문서를 새 계정 지식베이스에 넣지 않는다.
|
||||||
|
this._assertSameAccount(scope, ErrorCode.RAGIndexingFailed)
|
||||||
|
|
||||||
logger.info(`RAG text extracted: ${fileName} (${content.length} chars)`)
|
logger.info(`RAG text extracted: ${fileName} (${content.length} chars)`)
|
||||||
|
|
||||||
|
|
@ -278,7 +285,9 @@ export class RAGService extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 텍스트 재추출 + 재인덱싱
|
// 텍스트 재추출 + 재인덱싱
|
||||||
|
const scope = this._scope()
|
||||||
const content = await this._extractText(doc.filePath, doc.fileType)
|
const content = await this._extractText(doc.filePath, doc.fileType)
|
||||||
|
this._assertSameAccount(scope, ErrorCode.RAGIndexingFailed)
|
||||||
const chunks = chunkText(content)
|
const chunks = chunkText(content)
|
||||||
// 원본이 비었으면 저장된 청크를 지우지 않는다 — 지우면 이 기기에서 영영 되살릴 수 없다(빈 문서는 동기화되지 않음).
|
// 원본이 비었으면 저장된 청크를 지우지 않는다 — 지우면 이 기기에서 영영 되살릴 수 없다(빈 문서는 동기화되지 않음).
|
||||||
if (content.trim().length < 20 || chunks.length === 0) {
|
if (content.trim().length < 20 || chunks.length === 0) {
|
||||||
|
|
@ -296,6 +305,7 @@ export class RAGService extends EventEmitter {
|
||||||
*/
|
*/
|
||||||
async query(queryText: string, topK: number = DEFAULT_TOP_K): Promise<RAGQueryResult> {
|
async query(queryText: string, topK: number = DEFAULT_TOP_K): Promise<RAGQueryResult> {
|
||||||
this.activeQueries++
|
this.activeQueries++
|
||||||
|
const scope = this._scope()
|
||||||
try {
|
try {
|
||||||
// 원문만 있고 아직 임베딩되지 않은 청크는 검색 대상이 아니다.
|
// 원문만 있고 아직 임베딩되지 않은 청크는 검색 대상이 아니다.
|
||||||
const allChunks = this.deps.store.listEmbeddedChunks()
|
const allChunks = this.deps.store.listEmbeddedChunks()
|
||||||
|
|
@ -304,12 +314,15 @@ export class RAGService extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryEmbedding = await this.deps.embedder.embed(queryText)
|
const queryEmbedding = await this.deps.embedder.embed(queryText)
|
||||||
|
this._assertSameAccount(scope, ErrorCode.RAGQueryFailed)
|
||||||
const fileNames = new Map(this.deps.store.listDocuments().map((d) => [d.id, d.fileName]))
|
const fileNames = new Map(this.deps.store.listDocuments().map((d) => [d.id, d.fileName]))
|
||||||
const topResults = rankChunks(queryEmbedding, allChunks, fileNames, topK)
|
const topResults = rankChunks(queryEmbedding, allChunks, fileNames, topK)
|
||||||
const systemPrompt = buildAnswerSystemPrompt(topResults)
|
const systemPrompt = buildAnswerSystemPrompt(topResults)
|
||||||
|
|
||||||
// 답변 LLM 은 사용자가 고른 백엔드를 따른다(로컬 선택 시 문서 조각을 클라우드로 보내지 않는다)
|
// 답변 LLM 은 사용자가 고른 백엔드를 따른다(로컬 선택 시 문서 조각을 클라우드로 보내지 않는다)
|
||||||
const result = await this.deps.answerer().generate(queryText, { systemPrompt })
|
const result = await this.deps.answerer().generate(queryText, { systemPrompt })
|
||||||
|
// 답을 만드는 사이 다른 계정으로 바뀌었으면 이전 계정 문서에 근거한 답을 새 계정 화면에 내지 않는다.
|
||||||
|
this._assertSameAccount(scope, ErrorCode.RAGQueryFailed)
|
||||||
|
|
||||||
return { query: queryText, results: topResults, answer: result.text.trim() }
|
return { query: queryText, results: topResults, answer: result.text.trim() }
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -319,6 +332,14 @@ export class RAGService extends EventEmitter {
|
||||||
|
|
||||||
// ── 내부 메서드 ──
|
// ── 내부 메서드 ──
|
||||||
|
|
||||||
|
private _scope(): string {
|
||||||
|
return this.deps.accountScope?.() ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
private _assertSameAccount(scope: string, code: ErrorCode): void {
|
||||||
|
if (this._scope() !== scope) throw new D3ROError(code, 'Account changed while the request was running')
|
||||||
|
}
|
||||||
|
|
||||||
private async _extractText(filePath: string, fileType: RagFileType): Promise<string> {
|
private async _extractText(filePath: string, fileType: RagFileType): Promise<string> {
|
||||||
if (isPlainTextType(fileType)) {
|
if (isPlainTextType(fileType)) {
|
||||||
return (await this.deps.readFile(filePath)).toString('utf-8')
|
return (await this.deps.readFile(filePath)).toString('utf-8')
|
||||||
|
|
@ -354,7 +375,8 @@ export class RAGService extends EventEmitter {
|
||||||
// 실행 번호는 첫 await 전에 올린다 — 이 시점 이후 앞선 실행이 쓰는 청크 id 는 이미 지워졌을 수 있다.
|
// 실행 번호는 첫 await 전에 올린다 — 이 시점 이후 앞선 실행이 쓰는 청크 id 는 이미 지워졌을 수 있다.
|
||||||
const run = (this.indexRuns.get(docId) ?? 0) + 1
|
const run = (this.indexRuns.get(docId) ?? 0) + 1
|
||||||
this.indexRuns.set(docId, run)
|
this.indexRuns.set(docId, run)
|
||||||
const isCurrent = (): boolean => this.indexRuns.get(docId) === run
|
const scope = this._scope()
|
||||||
|
const isCurrent = (): boolean => this.indexRuns.get(docId) === run && this._scope() === scope
|
||||||
const stopSuperseded = (): void => {
|
const stopSuperseded = (): void => {
|
||||||
// 문서가 지워졌으면 이어받을 실행이 없으니 진행 표시를 여기서 내린다.
|
// 문서가 지워졌으면 이어받을 실행이 없으니 진행 표시를 여기서 내린다.
|
||||||
if (!store.hasDocument(docId)) notify(IPC_CHANNELS.RAG.INDEX_COMPLETE, { documentId: docId, fileName })
|
if (!store.hasDocument(docId)) notify(IPC_CHANNELS.RAG.INDEX_COMPLETE, { documentId: docId, fileName })
|
||||||
|
|
|
||||||
|
|
@ -453,3 +453,59 @@ describe('RAGService 색인 실행 겹침', () => {
|
||||||
expect(h.store.getDocument(doc.id)?.indexed).toBe(true)
|
expect(h.store.getDocument(doc.id)?.indexed).toBe(true)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('RAGService 계정 전환', () => {
|
||||||
|
it('질의 중에 계정이 바뀌면 이전 계정 문서로 만든 답을 돌려주지 않는다', async () => {
|
||||||
|
let scope = 'user-a'
|
||||||
|
let generated = 0
|
||||||
|
const h = harness({
|
||||||
|
accountScope: () => scope,
|
||||||
|
answerer: () => ({
|
||||||
|
generate: async () => {
|
||||||
|
generated++
|
||||||
|
scope = 'user-b'
|
||||||
|
return { text: 'answer from user-a documents' }
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
await h.service.addDocument(writeTemp('a.txt', LONG_TEXT))
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
await expect(h.service.query('planning')).rejects.toMatchObject({ code: ErrorCode.RAGQueryFailed })
|
||||||
|
expect(generated).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('파일을 읽는 사이 계정이 바뀌면 새 계정 지식베이스에 문서를 넣지 않는다', async () => {
|
||||||
|
let scope = 'user-a'
|
||||||
|
const h = harness({
|
||||||
|
accountScope: () => scope,
|
||||||
|
readFile: async (filePath) => {
|
||||||
|
scope = 'user-b'
|
||||||
|
return fs.promises.readFile(filePath)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(h.service.addDocument(writeTemp('a.txt', LONG_TEXT))).rejects.toMatchObject({
|
||||||
|
code: ErrorCode.RAGIndexingFailed,
|
||||||
|
})
|
||||||
|
expect(h.store.listDocuments()).toEqual([])
|
||||||
|
expect(h.pushed).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('색인 중에 계정이 바뀌면 남은 청크를 임베딩하지 않는다', async () => {
|
||||||
|
let scope = 'user-a'
|
||||||
|
const h = harness({ accountScope: () => scope })
|
||||||
|
let release: () => void = () => undefined
|
||||||
|
h.embedder.gate = new Promise<void>((r) => {
|
||||||
|
release = r
|
||||||
|
})
|
||||||
|
await h.service.addDocument(writeTemp('a.txt', LONG_TEXT))
|
||||||
|
await settle()
|
||||||
|
scope = 'user-b'
|
||||||
|
h.embedder.gate = null
|
||||||
|
release()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
expect(h.embedder.embedCalls).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue