mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 09:15:41 +08:00
fix: 超大会话索引改为分批流式,修复回填时主进程堆溢出闪退 #75
Fixes https://github.com/Wxw-Gu/TraceMemo/issues/75
This commit is contained in:
1 parent
b86582e606
commit
d436b064c3
41 files changed
+4214
-400
No files matched your search
@@ -311,6 +311,38 @@ describe('AskWechatService — 桌面问问微信主路径', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('指定多会话范围下 Runtime 失败 → 不回退 Legacy,避免扩大到全库', async () => {
|
||||
const runLegacy = vi.fn(async () => legacyResult({ status: 'completed' }))
|
||||
const provider: QueryAgentProvider = {
|
||||
getRuntimeConfig: () => ({
|
||||
configured: true,
|
||||
providerName: 'P',
|
||||
model: 'm',
|
||||
modelName: 'M'
|
||||
}),
|
||||
chatWithTools: vi.fn(async () => {
|
||||
throw new Error('unexpected internal failure')
|
||||
})
|
||||
}
|
||||
const service = new AskWechatService(new QueryAgentService(provider, vi.fn()), {
|
||||
entry: 'desktop',
|
||||
runLegacy
|
||||
})
|
||||
|
||||
const result = await service.ask({
|
||||
requestId: 'req-1',
|
||||
text: '这两个群最近聊了什么',
|
||||
// 用户只勾了 A、B 两个群。
|
||||
scope: { scope: { kind: 'selected', conversationIds: ['conversation-a', 'conversation-b'] } },
|
||||
// 旧版管线只能表达 global;回退就等于把范围悄悄放大到全部会话。
|
||||
legacy: { scope: 'global', range: '30d' }
|
||||
})
|
||||
|
||||
expect(runLegacy).not.toHaveBeenCalled()
|
||||
expect(result.engine).toBe('query-agent')
|
||||
expect(result.status).toBe('error')
|
||||
})
|
||||
|
||||
it('Runtime 异常且没有 Legacy 通道(Agent Hub)→ 明确文案,不抛异常', async () => {
|
||||
const provider: QueryAgentProvider = {
|
||||
getRuntimeConfig: () => ({ configured: true, providerName: 'P', model: 'm', modelName: 'M' }),
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
filterConversationOptions,
|
||||
formatConversationCount,
|
||||
sortConversationOptions,
|
||||
summarizeSelection,
|
||||
type ConversationSelectOption
|
||||
} from '../../src/renderer/src/components/search/ConversationMultiSelect'
|
||||
import { buildSearchCacheKey } from '../../src/renderer/src/components/search/searchUtils'
|
||||
|
||||
const option = (
|
||||
conversationId: string,
|
||||
name: string,
|
||||
messageCount: number | null,
|
||||
extra: Partial<ConversationSelectOption> = {}
|
||||
): ConversationSelectOption => ({
|
||||
conversationId,
|
||||
name,
|
||||
type: 'group',
|
||||
messageCount,
|
||||
approximate: false,
|
||||
countMeasured: messageCount !== null,
|
||||
lastActiveAt: null,
|
||||
keywords: '',
|
||||
...extra
|
||||
})
|
||||
|
||||
const OPTIONS: ConversationSelectOption[] = [
|
||||
option('c-family', '家庭群', 38_201, { type: 'user', lastActiveAt: 3 }),
|
||||
option('c-work', '工作项目群', 187_526, { lastActiveAt: 2 }),
|
||||
option('c-product', '产品交流群', 96_812, { keywords: '产品 老张 wxid_fixture_member' }),
|
||||
option('c-test', '测试群', 13_405),
|
||||
option('c-chat', '闲聊群', 1_248, { lastActiveAt: 9 }),
|
||||
option('c-unknown', '刚建的群', null)
|
||||
]
|
||||
|
||||
describe('conversation option sorting', () => {
|
||||
it('默认按消息数从多到少,未知数量排在最后', () => {
|
||||
const sorted = sortConversationOptions(OPTIONS, 'messages-desc')
|
||||
expect(sorted.map((item) => item.conversationId)).toEqual([
|
||||
'c-work',
|
||||
'c-product',
|
||||
'c-family',
|
||||
'c-test',
|
||||
'c-chat',
|
||||
'c-unknown'
|
||||
])
|
||||
})
|
||||
|
||||
it('升序时未知数量仍在最后,不会被当成 0 排到最前', () => {
|
||||
const sorted = sortConversationOptions(OPTIONS, 'messages-asc')
|
||||
expect(sorted.map((item) => item.conversationId)).toEqual([
|
||||
'c-chat',
|
||||
'c-test',
|
||||
'c-family',
|
||||
'c-product',
|
||||
'c-work',
|
||||
'c-unknown'
|
||||
])
|
||||
})
|
||||
|
||||
it('最近活跃与名称排序都稳定', () => {
|
||||
expect(sortConversationOptions(OPTIONS, 'recent')[0].conversationId).toBe('c-chat')
|
||||
const byName = sortConversationOptions(OPTIONS, 'name').map((item) => item.name)
|
||||
expect(byName).toEqual([...byName].sort((a, b) => a.localeCompare(b, 'zh-Hans-CN')))
|
||||
})
|
||||
|
||||
it('同数量时按名称做二级排序,结果与输入顺序无关', () => {
|
||||
const same = [option('b', '乙群', 10), option('a', '甲群', 10)]
|
||||
const forward = sortConversationOptions(same, 'messages-desc').map((item) => item.name)
|
||||
const reversed = sortConversationOptions([...same].reverse(), 'messages-desc').map(
|
||||
(item) => item.name
|
||||
)
|
||||
expect(forward).toEqual(reversed)
|
||||
})
|
||||
})
|
||||
|
||||
describe('conversation option filtering', () => {
|
||||
it('能用中文群名、备注或 wxid 搜到会话', () => {
|
||||
expect(filterConversationOptions(OPTIONS, { query: '产品' })).toHaveLength(1)
|
||||
expect(filterConversationOptions(OPTIONS, { query: '老张' })[0].conversationId).toBe(
|
||||
'c-product'
|
||||
)
|
||||
expect(filterConversationOptions(OPTIONS, { query: 'wxid_fixture_member' })[0].conversationId).toBe(
|
||||
'c-product'
|
||||
)
|
||||
})
|
||||
|
||||
it('按类型和「仅已选」过滤,且搜索不会改变选择集合', () => {
|
||||
expect(
|
||||
filterConversationOptions(OPTIONS, { typeFilter: 'user' }).map((item) => item.conversationId)
|
||||
).toEqual(['c-family'])
|
||||
expect(
|
||||
filterConversationOptions(OPTIONS, {
|
||||
onlySelected: true,
|
||||
selectedIds: ['c-work', 'c-chat']
|
||||
}).map((item) => item.conversationId)
|
||||
).toEqual(['c-work', 'c-chat'])
|
||||
})
|
||||
|
||||
it('统计中与统计失败显示不同文案,且都不会变成 0', () => {
|
||||
expect(formatConversationCount(null, false, false)).toBe('统计中')
|
||||
expect(formatConversationCount(null, false, true)).toBe('未知')
|
||||
expect(formatConversationCount(0, false, true)).toBe('0')
|
||||
expect(formatConversationCount(12_345, true, true)).toBe('≥ 12,345')
|
||||
})
|
||||
|
||||
it('未知数量不计入合计,但会被单独计数', () => {
|
||||
const summary = summarizeSelection(OPTIONS, ['c-work', 'c-unknown'])
|
||||
expect(summary.conversations).toBe(2)
|
||||
expect(summary.messages).toBe(187_526)
|
||||
expect(summary.unknownCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('search cache key carries scope identity', () => {
|
||||
it('不同会话集合生成不同缓存键,避免命中别的范围', () => {
|
||||
const base = buildSearchCacheKey('selected', '', 'all', '最近聊了什么', undefined, undefined, 'a,b')
|
||||
const other = buildSearchCacheKey('selected', '', 'all', '最近聊了什么', undefined, undefined, 'a,c')
|
||||
expect(base).not.toBe(other)
|
||||
// 集合相同但顺序不同 → 同一个键(范围身份与顺序无关)。
|
||||
const reordered = buildSearchCacheKey(
|
||||
'selected',
|
||||
'',
|
||||
'all',
|
||||
'最近聊了什么',
|
||||
undefined,
|
||||
undefined,
|
||||
'b,a'
|
||||
)
|
||||
expect(reordered).toBe(base)
|
||||
})
|
||||
|
||||
it('没有选择集合时保持旧格式,不影响既有缓存', () => {
|
||||
const legacy = buildSearchCacheKey('global', '', '30d', 'hello')
|
||||
expect(JSON.parse(legacy)).toEqual(['global', '', '30d', 'hello'])
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { chatState, getGroupSnapshotAsync, getGroupMemberNamesAsync, listContactsAsync, listMessagesAsync, getSourceLatestActivityMs, getConversationActivityMs, knowledgeService } =
|
||||
const { chatState, getGroupSnapshotAsync, getGroupMemberNamesAsync, listContactsAsync, listMessagesAsync, countConversationMessagesAsync, iterateMessagesAsync, getSourceLatestActivityMs, getConversationActivityMs, knowledgeService } =
|
||||
vi.hoisted(() => ({
|
||||
chatState: {
|
||||
ready: false,
|
||||
@@ -10,6 +10,11 @@ const { chatState, getGroupSnapshotAsync, getGroupMemberNamesAsync, listContacts
|
||||
getGroupMemberNamesAsync: vi.fn(),
|
||||
listContactsAsync: vi.fn(),
|
||||
listMessagesAsync: vi.fn(),
|
||||
// 增量窗口预检:默认 0,走原 delta 路径;用例需要时按会话返回大值。
|
||||
countConversationMessagesAsync: vi.fn(),
|
||||
// 分页读取的替身:默认把 `listMessagesAsync` 的结果当成一页,
|
||||
// 让只断言"读了哪个会话"的既有用例继续有效。
|
||||
iterateMessagesAsync: vi.fn(),
|
||||
getSourceLatestActivityMs: vi.fn(() => null as number | null),
|
||||
// 源侧每会话最后活跃时间(epoch ms)。默认空表 = 没有任何会话可被增量跳过,
|
||||
// 于是每个会话都会被真实处理 —— 这正是大部分用例想要的"全量"前提。
|
||||
@@ -29,6 +34,13 @@ const { chatState, getGroupSnapshotAsync, getGroupMemberNamesAsync, listContacts
|
||||
cancelled: false
|
||||
}),
|
||||
search: vi.fn(),
|
||||
// 分批索引的替身:按会话累计推入的条数,`finish` 用它回报处理量。
|
||||
streamCounts: new Map<string, number>(),
|
||||
startConversationStream: vi.fn(),
|
||||
pushConversationBatch: vi.fn(),
|
||||
finishConversationStream: vi.fn(),
|
||||
abortConversationStream: vi.fn(),
|
||||
writeSourceTotals: vi.fn(),
|
||||
// per-conversation checkpoint 读取:默认空表(没有会话已覆盖到任何时间点)。
|
||||
highWaterMarks: vi.fn().mockResolvedValue({}),
|
||||
cancelIndex: vi.fn().mockResolvedValue(false),
|
||||
@@ -58,26 +70,85 @@ vi.mock('../../src/main/services/chat-service', () => ({
|
||||
getGroupMemberNamesAsync,
|
||||
listContactsAsync,
|
||||
listMessagesAsync,
|
||||
countConversationMessagesAsync,
|
||||
iterateMessagesAsync,
|
||||
getSourceLatestActivityMs,
|
||||
getConversationActivityMs
|
||||
}))
|
||||
|
||||
// 索引范围来自设置文件;测试里不需要真的落盘,也不该拉起 electron。
|
||||
const settingsState = { knowledgeIndexScopes: {} as Record<string, unknown> }
|
||||
vi.mock('../../src/main/services/settings-store', () => ({
|
||||
loadSettings: () => settingsState,
|
||||
updateSettings: (patch: Record<string, unknown>) => Object.assign(settingsState, patch)
|
||||
}))
|
||||
|
||||
vi.mock('../../src/main/knowledge/knowledge-service', () => ({
|
||||
KnowledgeService: class {
|
||||
dispose = knowledgeService.dispose
|
||||
index = knowledgeService.index
|
||||
search = knowledgeService.search
|
||||
startConversationStream = knowledgeService.startConversationStream
|
||||
pushConversationBatch = knowledgeService.pushConversationBatch
|
||||
finishConversationStream = knowledgeService.finishConversationStream
|
||||
abortConversationStream = knowledgeService.abortConversationStream
|
||||
writeSourceTotals = knowledgeService.writeSourceTotals
|
||||
highWaterMarks = knowledgeService.highWaterMarks
|
||||
cancelIndex = knowledgeService.cancelIndex
|
||||
status = knowledgeService.status
|
||||
}
|
||||
}))
|
||||
|
||||
|
||||
/**
|
||||
* 分批索引替身:`listMessagesAsync` 的结果当一页,stream 三个方法按会话累计条数。
|
||||
*/
|
||||
function resetStreamDoubles(): void {
|
||||
settingsState.knowledgeIndexScopes = {}
|
||||
countConversationMessagesAsync.mockReset()
|
||||
countConversationMessagesAsync.mockResolvedValue({ count: 0, approximate: false, failedStores: [] })
|
||||
knowledgeService.streamCounts.clear()
|
||||
iterateMessagesAsync.mockReset()
|
||||
iterateMessagesAsync.mockImplementation(async function* (md5: string) {
|
||||
const messages = (await listMessagesAsync(md5)) ?? []
|
||||
yield { messages, failedStores: [] }
|
||||
})
|
||||
knowledgeService.startConversationStream.mockReset()
|
||||
knowledgeService.startConversationStream.mockImplementation(
|
||||
async (payload: { conversationId: string }) => {
|
||||
knowledgeService.streamCounts.set(payload.conversationId, 0)
|
||||
return { started: true, resumedFrom: null }
|
||||
}
|
||||
)
|
||||
knowledgeService.pushConversationBatch.mockReset()
|
||||
knowledgeService.pushConversationBatch.mockImplementation(
|
||||
async (payload: { conversationId: string; messages: unknown[] }) => {
|
||||
const current = knowledgeService.streamCounts.get(payload.conversationId) ?? 0
|
||||
knowledgeService.streamCounts.set(payload.conversationId, current + payload.messages.length)
|
||||
}
|
||||
)
|
||||
knowledgeService.finishConversationStream.mockReset()
|
||||
knowledgeService.finishConversationStream.mockImplementation(
|
||||
async (payload: { conversationId: string }) => ({
|
||||
conversationId: payload.conversationId,
|
||||
processedMessages: knowledgeService.streamCounts.get(payload.conversationId) ?? 0,
|
||||
chunkCount: 0,
|
||||
cancelled: false,
|
||||
resumeTime: null
|
||||
})
|
||||
)
|
||||
knowledgeService.abortConversationStream.mockReset()
|
||||
knowledgeService.abortConversationStream.mockResolvedValue(undefined)
|
||||
knowledgeService.writeSourceTotals.mockReset()
|
||||
knowledgeService.writeSourceTotals.mockResolvedValue(undefined)
|
||||
}
|
||||
|
||||
import { KnowledgeSearchService } from '../../src/main/knowledge/knowledge-search-service'
|
||||
import type { VoiceTranscriptUpdate } from '../../src/shared/voice-recognition'
|
||||
|
||||
describe('KnowledgeSearchService legacy fallback', () => {
|
||||
beforeEach(() => {
|
||||
resetStreamDoubles()
|
||||
chatState.ready = false
|
||||
chatState.accountId = ''
|
||||
getGroupSnapshotAsync.mockReset()
|
||||
@@ -139,7 +210,8 @@ describe('KnowledgeSearchService legacy fallback', () => {
|
||||
})
|
||||
expect(result.evidence).toEqual([
|
||||
expect.objectContaining({
|
||||
messageId: 'local:42',
|
||||
// 身份是 `local:<create_time>:<local_id>`:localId 单独跨分片会重号。
|
||||
messageId: 'local:1785895200:42',
|
||||
conversationId: 'fixture-conversation',
|
||||
sender: '脱敏成员',
|
||||
senderId: 'fixture-sender',
|
||||
@@ -217,22 +289,23 @@ describe('KnowledgeSearchService legacy fallback', () => {
|
||||
cached: true
|
||||
})
|
||||
|
||||
expect(knowledgeService.index).toHaveBeenCalledWith(
|
||||
// 语音重索引现在走分批回填:断言"重建的是这个会话"+"转写文本真的进了推送批次"。
|
||||
expect(knowledgeService.startConversationStream).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
accountId: chatState.accountId,
|
||||
conversations: [
|
||||
expect.objectContaining({
|
||||
conversationId: 'voice-conversation',
|
||||
completeSnapshot: true,
|
||||
messages: [
|
||||
expect.objectContaining({
|
||||
kind: 'voice',
|
||||
voiceTranscript: '缓存中的语音文字',
|
||||
voiceTranscriptState: 'transcribed'
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
conversationId: 'voice-conversation',
|
||||
completeSnapshot: true
|
||||
}),
|
||||
expect.any(Function)
|
||||
)
|
||||
const pushed = knowledgeService.pushConversationBatch.mock.calls.flatMap(
|
||||
(call) => (call[0] as { messages: Array<Record<string, unknown>> }).messages
|
||||
)
|
||||
expect(pushed).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'voice',
|
||||
voiceTranscript: '缓存中的语音文字',
|
||||
voiceTranscriptState: 'transcribed'
|
||||
})
|
||||
)
|
||||
await service.dispose()
|
||||
@@ -272,12 +345,13 @@ describe('KnowledgeSearchService legacy fallback', () => {
|
||||
}
|
||||
])
|
||||
let releaseFirstIndex: (() => void) | undefined
|
||||
knowledgeService.index.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
releaseFirstIndex = resolve
|
||||
})
|
||||
)
|
||||
// 卡在第一页读取:后续 update 必须排队合并,而不是各起一次重建。
|
||||
iterateMessagesAsync.mockImplementationOnce(async function* () {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseFirstIndex = resolve
|
||||
})
|
||||
yield { messages: [], failedStores: [] }
|
||||
})
|
||||
const { voiceAccountIdentity, voiceMessageIdentity } =
|
||||
await import('../../src/main/voice-pipeline/voice-message-identity')
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-knowledge-fallback', '/missing-worker.js')
|
||||
@@ -294,14 +368,14 @@ describe('KnowledgeSearchService legacy fallback', () => {
|
||||
}
|
||||
|
||||
const first = service.indexVoiceTranscript(update(18, 1_785_895_200))
|
||||
await vi.waitFor(() => expect(knowledgeService.index).toHaveBeenCalledTimes(1))
|
||||
await vi.waitFor(() => expect(iterateMessagesAsync).toHaveBeenCalledTimes(1))
|
||||
const second = service.indexVoiceTranscript(update(19, 1_785_895_201))
|
||||
const third = service.indexVoiceTranscript(update(18, 1_785_895_200))
|
||||
releaseFirstIndex?.()
|
||||
|
||||
await Promise.all([first, second, third])
|
||||
expect(knowledgeService.index).toHaveBeenCalledTimes(2)
|
||||
expect(listMessagesAsync).toHaveBeenCalledTimes(2)
|
||||
expect(knowledgeService.startConversationStream).toHaveBeenCalledTimes(2)
|
||||
expect(iterateMessagesAsync).toHaveBeenCalledTimes(2)
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
@@ -636,6 +710,7 @@ describe('KnowledgeSearchService legacy fallback', () => {
|
||||
|
||||
describe('KnowledgeSearchService freshness contract', () => {
|
||||
beforeEach(() => {
|
||||
resetStreamDoubles()
|
||||
chatState.ready = true
|
||||
chatState.accountId = 'fixture-account'
|
||||
getGroupSnapshotAsync.mockReset()
|
||||
@@ -716,6 +791,7 @@ describe('KnowledgeSearchService freshness contract', () => {
|
||||
|
||||
describe('KnowledgeSearchService 完整 pass 记录源数据边界', () => {
|
||||
beforeEach(() => {
|
||||
resetStreamDoubles()
|
||||
chatState.ready = true
|
||||
chatState.accountId = 'fixture-account'
|
||||
listContactsAsync.mockReset()
|
||||
@@ -744,12 +820,17 @@ describe('KnowledgeSearchService 完整 pass 记录源数据边界', () => {
|
||||
service.startCurrentAccountIndex()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
expect(knowledgeService.index).toHaveBeenCalledTimes(2)
|
||||
const calls = knowledgeService.index.mock.calls as Array<[Record<string, unknown>]>
|
||||
expect(calls[0][0].sourceLatestAt).toBeUndefined()
|
||||
expect(calls[0][0].sourceMessageCount).toBeUndefined()
|
||||
expect(calls[1][0].sourceLatestAt).toBe(9000 * 1000)
|
||||
expect(calls[1][0].sourceMessageCount).toBe(2)
|
||||
// 两个会话都走分批回填;全局源口径只在整遍结束时写一次。
|
||||
expect(knowledgeService.startConversationStream).toHaveBeenCalledTimes(2)
|
||||
expect(knowledgeService.index).not.toHaveBeenCalled()
|
||||
expect(knowledgeService.writeSourceTotals).toHaveBeenCalledTimes(1)
|
||||
const totals = knowledgeService.writeSourceTotals.mock.calls[0][0] as {
|
||||
sourceLatestAt: number
|
||||
sourceMessageCount: number
|
||||
}
|
||||
// 图片/空正文不建模,但 freshness 口径必须把它算进来。
|
||||
expect(totals.sourceLatestAt).toBe(9000 * 1000)
|
||||
expect(totals.sourceMessageCount).toBe(2)
|
||||
await service.dispose()
|
||||
})
|
||||
})
|
||||
@@ -760,6 +841,7 @@ describe('KnowledgeSearchService 完整 pass 记录源数据边界', () => {
|
||||
*/
|
||||
describe('KnowledgeSearchService sync contract', () => {
|
||||
beforeEach(() => {
|
||||
resetStreamDoubles()
|
||||
chatState.ready = true
|
||||
chatState.accountId = 'fixture-account'
|
||||
listContactsAsync.mockReset()
|
||||
@@ -802,6 +884,54 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
return { all, last: () => all[all.length - 1] }
|
||||
}
|
||||
|
||||
it('只索引勾选的会话:未选会话不读、不计入分母', async () => {
|
||||
listContactsAsync.mockResolvedValue([
|
||||
{ m_nsUsrName: 'fixture-a', m_nsNickName: 'A', md5: 'fixture-a', type: 'user' },
|
||||
{ m_nsUsrName: 'fixture-b', m_nsNickName: 'B', md5: 'fixture-b', type: 'user' },
|
||||
{ m_nsUsrName: 'fixture-c', m_nsNickName: 'C', md5: 'fixture-c', type: 'user' }
|
||||
])
|
||||
settingsState.knowledgeIndexScopes = {
|
||||
'fixture-account': { mode: 'selected', conversationIds: ['fixture-a', 'fixture-b'] }
|
||||
}
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-scope-selected', '/missing-worker.js')
|
||||
const statuses = captureStatuses(service)
|
||||
service.startCurrentAccountIndex()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
// 关键:C 一次都没被读过,也不该出现在分母里。
|
||||
expect(iterateMessagesAsync.mock.calls.map((call) => call[0])).toEqual([
|
||||
'fixture-a',
|
||||
'fixture-b'
|
||||
])
|
||||
const finished = statuses.all.find(
|
||||
(status) => (status.pass as { phase?: string } | undefined)?.phase === 'idle'
|
||||
)
|
||||
const pass = finished?.pass as {
|
||||
totalConversations: number
|
||||
excludedConversations: number
|
||||
}
|
||||
expect(pass.totalConversations).toBe(2)
|
||||
expect(pass.excludedConversations).toBe(1)
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
it('空选择不是「全部」:勾了「仅选择」但一个都没选时不索引任何会话', async () => {
|
||||
twoContacts()
|
||||
settingsState.knowledgeIndexScopes = {
|
||||
'fixture-account': { mode: 'selected', conversationIds: [] }
|
||||
}
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-scope-empty', '/missing-worker.js')
|
||||
service.startCurrentAccountIndex()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
// 退化成"搜全部"会让用户以为自己在按范围索引,实际把几百个群都建了。
|
||||
expect(iterateMessagesAsync).not.toHaveBeenCalled()
|
||||
expect(listMessagesAsync).not.toHaveBeenCalled()
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
it('skips conversations whose source activity is already covered by the checkpoint', async () => {
|
||||
twoContacts()
|
||||
// a 的源侧最后活跃时间早于它已经索引到的位置 → 没有任何新消息,必须整段跳过。
|
||||
@@ -819,9 +949,9 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
// 真正 delta 的核心:被跳过的会话**不读 WCDB**(这是把"每次全量重扫"变成分钟级以内的原因)。
|
||||
expect(listMessagesAsync).toHaveBeenCalledTimes(1)
|
||||
expect(listMessagesAsync.mock.calls[0][0]).toBe('fixture-b')
|
||||
expect(knowledgeService.index).toHaveBeenCalledTimes(1)
|
||||
expect(iterateMessagesAsync).toHaveBeenCalledTimes(1)
|
||||
expect(iterateMessagesAsync.mock.calls[0][0]).toBe('fixture-b')
|
||||
expect(knowledgeService.startConversationStream).toHaveBeenCalledTimes(1)
|
||||
|
||||
const finished = statuses.all.find(
|
||||
(status) => (status.pass as { phase?: string } | undefined)?.phase === 'idle'
|
||||
@@ -839,9 +969,7 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
expect(pass.cancellable).toBe(false)
|
||||
|
||||
// 有跳过时不能把这一遍的部分计数冒充成"全量总量"。
|
||||
const indexArgs = knowledgeService.index.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(indexArgs.sourceMessageCount).toBeUndefined()
|
||||
expect(indexArgs.sourceLatestAt).toBeUndefined()
|
||||
expect(knowledgeService.writeSourceTotals).not.toHaveBeenCalled()
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
@@ -861,70 +989,68 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
service.startCurrentAccountIndex()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
expect(listMessagesAsync).toHaveBeenCalledTimes(2)
|
||||
expect(knowledgeService.index).toHaveBeenCalledTimes(2)
|
||||
expect(iterateMessagesAsync).toHaveBeenCalledTimes(2)
|
||||
expect(knowledgeService.startConversationStream).toHaveBeenCalledTimes(2)
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
it('reports a cancelled pass as cancelled and never leaves a fake indexing state', async () => {
|
||||
twoContacts()
|
||||
let releaseSecond: (() => void) | undefined
|
||||
knowledgeService.index
|
||||
// 第二个会话在 Worker 侧提交返回"已中止":这是取消一路传到底之后的真实返回值。
|
||||
knowledgeService.finishConversationStream
|
||||
.mockResolvedValueOnce({
|
||||
accountId: 'fixture-account',
|
||||
conversationId: 'fixture-a',
|
||||
processedMessages: 1,
|
||||
indexedChunks: 1,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: false
|
||||
chunkCount: 1,
|
||||
cancelled: false,
|
||||
resumeTime: 1_000_000
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
conversationId: 'fixture-b',
|
||||
processedMessages: 0,
|
||||
chunkCount: 0,
|
||||
cancelled: true,
|
||||
resumeTime: 2_000_000
|
||||
})
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseSecond = () =>
|
||||
resolve({
|
||||
accountId: 'fixture-account',
|
||||
processedMessages: 0,
|
||||
indexedChunks: 0,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: true
|
||||
})
|
||||
})
|
||||
)
|
||||
knowledgeService.cancelIndex.mockResolvedValue(true)
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-sync-cancel', '/missing-worker.js')
|
||||
const statuses = captureStatuses(service)
|
||||
service.startCurrentAccountIndex()
|
||||
await vi.waitFor(() => expect(knowledgeService.index).toHaveBeenCalledTimes(2))
|
||||
|
||||
const ack = await service.cancelCurrentAccountIndex()
|
||||
expect(ack).toEqual({ cancellable: true, cancelled: true })
|
||||
// 取消请求一发出,UI 立刻就该看到"不可再取消"(按钮变「正在取消…」)。
|
||||
const cancelling = statuses.all.find(
|
||||
(status) => (status.pass as { cancellable?: boolean } | undefined)?.cancellable === false
|
||||
)
|
||||
expect(cancelling).toBeDefined()
|
||||
|
||||
releaseSecond?.()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
const finalStatus = await service.getStatus()
|
||||
expect(finalStatus.state).toBe('cancelled')
|
||||
expect(finalStatus.pass?.phase).toBe('cancelled')
|
||||
expect(finalStatus.pass?.cancellable).toBe(false)
|
||||
// 全程不允许出现"同步中"残留(run_state 不得留下假的 indexing)。
|
||||
// 全程不允许出现"同步中"残留。
|
||||
expect(statuses.all.some((status) => status.state === 'cancelled')).toBe(true)
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
it('acknowledges cancellation immediately and drops the cancel button', async () => {
|
||||
twoContacts()
|
||||
// 卡在第一页:取消必须在 Worker 侧生效,而不是等一整遍跑完。
|
||||
iterateMessagesAsync.mockImplementation(async function* () {
|
||||
await new Promise(() => {})
|
||||
yield { messages: [], failedStores: [] }
|
||||
})
|
||||
knowledgeService.cancelIndex.mockResolvedValue(true)
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-sync-cancel-ack', '/missing-worker.js')
|
||||
const statuses = captureStatuses(service)
|
||||
service.startCurrentAccountIndex()
|
||||
await vi.waitFor(() => expect(iterateMessagesAsync).toHaveBeenCalled())
|
||||
|
||||
const ack = await service.cancelCurrentAccountIndex()
|
||||
expect(ack).toEqual({ cancellable: true, cancelled: true })
|
||||
// 取消请求一发出,UI 立刻就该看到"不可再取消"。
|
||||
const cancelling = statuses.all.find(
|
||||
(status) => (status.pass as { cancellable?: boolean } | undefined)?.cancellable === false
|
||||
)
|
||||
expect(cancelling).toBeDefined()
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
it('keeps committed conversations when a pass is cancelled and resumes from the checkpoint', async () => {
|
||||
listContactsAsync.mockResolvedValue([
|
||||
{ m_nsUsrName: 'fixture-a', m_nsNickName: 'A', md5: 'fixture-a', type: 'user' },
|
||||
@@ -945,92 +1071,58 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
createTime: 1785895200
|
||||
}
|
||||
])
|
||||
let releaseThird: (() => void) | undefined
|
||||
knowledgeService.index
|
||||
// 前两个会话提交成功、第三个被中止:取消 ≠ 回滚,已提交的批次必须留下来。
|
||||
knowledgeService.finishConversationStream
|
||||
.mockResolvedValueOnce({
|
||||
accountId: 'fixture-account',
|
||||
conversationId: 'fixture-a',
|
||||
processedMessages: 1,
|
||||
indexedChunks: 1,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: false
|
||||
chunkCount: 1,
|
||||
cancelled: false,
|
||||
resumeTime: 1785895200
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
accountId: 'fixture-account',
|
||||
conversationId: 'fixture-b',
|
||||
processedMessages: 1,
|
||||
indexedChunks: 1,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: false
|
||||
chunkCount: 1,
|
||||
cancelled: false,
|
||||
resumeTime: 1785895200
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
conversationId: 'fixture-c',
|
||||
processedMessages: 0,
|
||||
chunkCount: 0,
|
||||
cancelled: true,
|
||||
resumeTime: 1785895200
|
||||
})
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseThird = () =>
|
||||
resolve({
|
||||
accountId: 'fixture-account',
|
||||
processedMessages: 0,
|
||||
indexedChunks: 0,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: true
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-sync-resume', '/missing-worker.js')
|
||||
const statuses = captureStatuses(service)
|
||||
service.startCurrentAccountIndex()
|
||||
await vi.waitFor(() => expect(knowledgeService.index).toHaveBeenCalledTimes(3))
|
||||
await service.cancelCurrentAccountIndex()
|
||||
releaseThird?.()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
// 取消 ≠ 回滚:前两个会话已经提交的索引必须留下来。
|
||||
const cancelled = statuses.all[statuses.all.length - 1]
|
||||
const pass = cancelled.pass as { indexedMessages: number; phase: string }
|
||||
expect(pass.phase).toBe('cancelled')
|
||||
expect(pass.indexedMessages).toBeGreaterThan(0)
|
||||
expect(pass.indexedMessages).toBe(2)
|
||||
|
||||
// 下一遍:两个已覆盖的会话必须被 checkpoint 跳过,只补没跑完的那个。
|
||||
knowledgeService.index.mockClear()
|
||||
listMessagesAsync.mockClear()
|
||||
knowledgeService.startConversationStream.mockClear()
|
||||
iterateMessagesAsync.mockClear()
|
||||
getConversationActivityMs.mockReturnValue(
|
||||
new Map<string, number>([
|
||||
['fixture-a', 1_785_895_200_000],
|
||||
['fixture-b', 1_785_895_200_000]
|
||||
['fixture-b', 1_785_895_200_000],
|
||||
['fixture-c', 1_785_895_200_000]
|
||||
])
|
||||
)
|
||||
// a 与 b 的 checkpoint 已追平它们的源侧活跃时间;c 仍然没有覆盖。
|
||||
knowledgeService.highWaterMarks.mockResolvedValue({
|
||||
'fixture-a': 1_785_895_200_000,
|
||||
'fixture-b': 1_785_895_200_000
|
||||
})
|
||||
knowledgeService.index.mockResolvedValue({
|
||||
accountId: 'fixture-account',
|
||||
processedMessages: 1,
|
||||
indexedChunks: 1,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: false
|
||||
})
|
||||
service.startCurrentAccountIndex()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
|
||||
expect(listMessagesAsync).toHaveBeenCalledTimes(1)
|
||||
expect(listMessagesAsync.mock.calls[0][0]).toBe('fixture-c')
|
||||
expect(iterateMessagesAsync.mock.calls.map((call) => call[0])).toEqual(['fixture-c'])
|
||||
await service.dispose()
|
||||
})
|
||||
|
||||
@@ -1049,29 +1141,18 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
it('does not let a cancelled pass shorten the catch-up threshold of the next pass', async () => {
|
||||
twoContacts()
|
||||
let releaseFirst: (() => void) | undefined
|
||||
knowledgeService.index.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseFirst = () =>
|
||||
resolve({
|
||||
accountId: 'fixture-account',
|
||||
processedMessages: 0,
|
||||
indexedChunks: 0,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: true
|
||||
})
|
||||
})
|
||||
)
|
||||
iterateMessagesAsync.mockImplementationOnce(async function* () {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseFirst = resolve
|
||||
})
|
||||
yield { messages: [], failedStores: [] }
|
||||
})
|
||||
knowledgeService.cancelIndex.mockResolvedValue(true)
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-sync-threshold', '/missing-worker.js')
|
||||
const statuses = captureStatuses(service)
|
||||
service.startCurrentAccountIndex()
|
||||
await vi.waitFor(() => expect(knowledgeService.index).toHaveBeenCalledTimes(1))
|
||||
await vi.waitFor(() => expect(iterateMessagesAsync).toHaveBeenCalledTimes(1))
|
||||
await service.cancelCurrentAccountIndex()
|
||||
releaseFirst?.()
|
||||
await expect(service.waitForIndexingComplete(2000)).resolves.toBe(true)
|
||||
@@ -1107,27 +1188,17 @@ describe('KnowledgeSearchService sync contract', () => {
|
||||
timings: {}
|
||||
})
|
||||
let releaseIndex: (() => void) | undefined
|
||||
knowledgeService.index.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseIndex = () =>
|
||||
resolve({
|
||||
accountId: 'fixture-account',
|
||||
processedMessages: 1,
|
||||
indexedChunks: 1,
|
||||
updatedChunks: 0,
|
||||
unchangedConversations: 0,
|
||||
databaseBytes: 0,
|
||||
walBytes: 0,
|
||||
elapsedMs: 0,
|
||||
cancelled: false
|
||||
})
|
||||
})
|
||||
)
|
||||
// 让第一页读取挂起:索引在跑,但查询不能因此被挡。
|
||||
iterateMessagesAsync.mockImplementationOnce(async function* () {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseIndex = resolve
|
||||
})
|
||||
yield { messages: [], failedStores: [] }
|
||||
})
|
||||
|
||||
const service = new KnowledgeSearchService('/tmp/wxe-sync-query', '/missing-worker.js')
|
||||
service.startCurrentAccountIndex()
|
||||
await vi.waitFor(() => expect(knowledgeService.index).toHaveBeenCalledTimes(1))
|
||||
await vi.waitFor(() => expect(iterateMessagesAsync).toHaveBeenCalledTimes(1))
|
||||
|
||||
const result = await service.search({
|
||||
text: '命中',
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { mkdtempSync } from 'fs'
|
||||
import { rm } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
type KnowledgeChunk,
|
||||
type KnowledgeFtsConfig,
|
||||
type KnowledgeSourceMessage
|
||||
} from '../../src/shared/knowledge'
|
||||
import { chunkConversation, createChunkStreamer } from '../../src/main/knowledge/chunker'
|
||||
import {
|
||||
getKnowledgeDatabasePath,
|
||||
KnowledgeStore
|
||||
} from '../../src/main/knowledge/knowledge-store'
|
||||
import { normalizeKnowledgeMessage } from '../../src/main/knowledge/normalizer'
|
||||
import { createSyntheticConversation, FIXTURE_ACCOUNT_A } from '../fixtures/knowledge-rag'
|
||||
|
||||
const fts: KnowledgeFtsConfig = {
|
||||
profileId: 'test-trigram-external-full',
|
||||
tokenizer: 'trigram',
|
||||
contentMode: 'external',
|
||||
detail: 'full',
|
||||
columnsize: 1
|
||||
}
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function makeRoot(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'wxe-knowledge-stream-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
async function* inBatches(
|
||||
messages: readonly KnowledgeSourceMessage[],
|
||||
size: number
|
||||
): AsyncGenerator<readonly KnowledgeSourceMessage[], void, void> {
|
||||
for (let index = 0; index < messages.length; index += size) {
|
||||
yield messages.slice(index, index + size)
|
||||
}
|
||||
}
|
||||
|
||||
function readChunks(root: string): Array<{ chunk_id: string; text: string }> {
|
||||
const database = new DatabaseSync(getKnowledgeDatabasePath(root, FIXTURE_ACCOUNT_A))
|
||||
try {
|
||||
return database
|
||||
.prepare('SELECT chunk_id, text FROM knowledge_chunks ORDER BY chunk_id')
|
||||
.all() as Array<{ chunk_id: string; text: string }>
|
||||
} finally {
|
||||
database.close()
|
||||
}
|
||||
}
|
||||
|
||||
function readState(root: string): Record<string, unknown> | undefined {
|
||||
const database = new DatabaseSync(getKnowledgeDatabasePath(root, FIXTURE_ACCOUNT_A))
|
||||
try {
|
||||
return database
|
||||
.prepare('SELECT * FROM knowledge_index_state WHERE conversation_id = ?')
|
||||
.get('conversation-stream') as Record<string, unknown> | undefined
|
||||
} finally {
|
||||
database.close()
|
||||
}
|
||||
}
|
||||
|
||||
describe('knowledge chunk streamer', () => {
|
||||
it('produces exactly the same chunks as the one-shot chunker for every batch size', () => {
|
||||
const conversation = createSyntheticConversation(
|
||||
FIXTURE_ACCOUNT_A,
|
||||
'conversation-stream',
|
||||
0,
|
||||
500,
|
||||
'mixed'
|
||||
)
|
||||
const normalized = conversation.messages
|
||||
.map(normalizeKnowledgeMessage)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.createTime - right.createTime || left.messageId.localeCompare(right.messageId)
|
||||
)
|
||||
const expected = chunkConversation(normalized, DEFAULT_KNOWLEDGE_CHUNKER)
|
||||
|
||||
for (const size of [1, 5, 12, 13, 64, 499]) {
|
||||
const streamer = createChunkStreamer(DEFAULT_KNOWLEDGE_CHUNKER)
|
||||
const actual: KnowledgeChunk[] = []
|
||||
for (let index = 0; index < normalized.length; index += size) {
|
||||
actual.push(...streamer.push(normalized.slice(index, index + size)))
|
||||
}
|
||||
actual.push(...streamer.drain())
|
||||
// 逐 chunk 比对 id 与正文:切点漂移会让正文变、id 也可能变。
|
||||
expect(actual.map((chunk) => chunk.chunkId)).toEqual(expected.map((chunk) => chunk.chunkId))
|
||||
expect(actual.map((chunk) => chunk.text)).toEqual(expected.map((chunk) => chunk.text))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('KnowledgeStore.indexConversationStreaming', () => {
|
||||
it('writes the same index as a one-shot snapshot', async () => {
|
||||
const conversation = createSyntheticConversation(
|
||||
FIXTURE_ACCOUNT_A,
|
||||
'conversation-stream',
|
||||
0,
|
||||
400,
|
||||
'mixed'
|
||||
)
|
||||
|
||||
const oneShotRoot = makeRoot()
|
||||
const oneShotStore = new KnowledgeStore(oneShotRoot, FIXTURE_ACCOUNT_A, fts)
|
||||
await oneShotStore.index(
|
||||
{ conversations: [conversation], chunker: DEFAULT_KNOWLEDGE_CHUNKER },
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
oneShotStore.close()
|
||||
const expected = readChunks(oneShotRoot)
|
||||
|
||||
const streamedRoot = makeRoot()
|
||||
const streamedStore = new KnowledgeStore(streamedRoot, FIXTURE_ACCOUNT_A, fts)
|
||||
const result = await streamedStore.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
inBatches(conversation.messages, 40),
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true, sourceHighWaterTime: 1_800_000_000_000 },
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
streamedStore.close()
|
||||
|
||||
expect(result.cancelled).toBe(false)
|
||||
expect(result.processedMessages).toBe(conversation.messages.length)
|
||||
expect(expected.length).toBeGreaterThan(0)
|
||||
expect(readChunks(streamedRoot)).toEqual(expected)
|
||||
|
||||
const state = readState(streamedRoot)
|
||||
// 整段读完后才能置 1;回填过程中一直是 0。
|
||||
expect(Number(state?.complete_snapshot)).toBe(1)
|
||||
expect(Number(state?.source_high_water_time)).toBe(1_800_000_000_000)
|
||||
expect(state?.backfill_resume_time).toBeNull()
|
||||
})
|
||||
|
||||
it('resumes from the last committed chunk without duplicating or dropping messages', async () => {
|
||||
const conversation = createSyntheticConversation(
|
||||
FIXTURE_ACCOUNT_A,
|
||||
'conversation-stream',
|
||||
0,
|
||||
300,
|
||||
'mixed'
|
||||
)
|
||||
|
||||
const referenceRoot = makeRoot()
|
||||
const referenceStore = new KnowledgeStore(referenceRoot, FIXTURE_ACCOUNT_A, fts)
|
||||
await referenceStore.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
inBatches(conversation.messages, 30),
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true },
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
referenceStore.close()
|
||||
const expected = readChunks(referenceRoot)
|
||||
|
||||
const root = makeRoot()
|
||||
const store = new KnowledgeStore(root, FIXTURE_ACCOUNT_A, fts)
|
||||
const controller = new AbortController()
|
||||
let emitted = 0
|
||||
const interrupted = (async function* () {
|
||||
for (let index = 0; index < conversation.messages.length; index += 30) {
|
||||
// 喂到大约三分之一就中止,确保有已提交批次、也有未收盘的尾巴。
|
||||
if (emitted >= 120) {
|
||||
controller.abort()
|
||||
return
|
||||
}
|
||||
emitted += 30
|
||||
yield conversation.messages.slice(index, index + 30)
|
||||
}
|
||||
})()
|
||||
|
||||
const first = await store.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
interrupted,
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true },
|
||||
controller.signal,
|
||||
() => undefined
|
||||
)
|
||||
expect(first.cancelled).toBe(true)
|
||||
expect(readChunks(root).length).toBeGreaterThan(0)
|
||||
|
||||
const resume = store.readBackfillResume('conversation-stream')
|
||||
expect(resume).not.toBeNull()
|
||||
|
||||
// 续跑:从边界时刻重读,已提交的 chunk 由消息 id 跳过。
|
||||
const remaining = conversation.messages.filter(
|
||||
(message) => message.createTime >= (resume as { time: number }).time
|
||||
)
|
||||
await store.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
inBatches(remaining, 30),
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true, resume: resume ?? undefined },
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
store.close()
|
||||
|
||||
// 不多不少:重复的 chunk 会在这里以重复 id 或多余正文显形。
|
||||
expect(readChunks(root)).toEqual(expected)
|
||||
const state = readState(root)
|
||||
expect(Number(state?.complete_snapshot)).toBe(1)
|
||||
expect(state?.backfill_resume_time).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the previous index usable when a pass is interrupted', async () => {
|
||||
const conversation = createSyntheticConversation(
|
||||
FIXTURE_ACCOUNT_A,
|
||||
'conversation-stream',
|
||||
0,
|
||||
120,
|
||||
'short'
|
||||
)
|
||||
const root = makeRoot()
|
||||
const store = new KnowledgeStore(root, FIXTURE_ACCOUNT_A, fts)
|
||||
await store.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
inBatches(conversation.messages, 20),
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true },
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
const before = readChunks(root)
|
||||
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
const aborted = await store.indexConversationStreaming(
|
||||
'conversation-stream',
|
||||
inBatches(conversation.messages, 20),
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
{ completeSnapshot: true },
|
||||
controller.signal,
|
||||
() => undefined
|
||||
)
|
||||
store.close()
|
||||
|
||||
expect(aborted.cancelled).toBe(true)
|
||||
// 取消不预删旧 chunk,所以中断之后原索引仍然完整。
|
||||
expect(readChunks(root)).toEqual(before)
|
||||
})
|
||||
})
|
||||
@@ -9,15 +9,63 @@ const fixture = vi.hoisted(() => ({
|
||||
{ m_nsUsrName: 'wxid-bobo-2', m_nsNickName: 'BOBO', md5: 'md5-bobo-2', type: 'user' as const }
|
||||
],
|
||||
messages: [
|
||||
{ id: 'm1', from: 'user', type: '图片', datetime: '2026/8/2 10:00:00', content: '', contentData: { type: 'image', md5: 'image-md5' }, isSender: false, name: 'BOBO', createTime: Math.floor(new Date('2026-08-02T10:00:00+08:00').getTime() / 1000) },
|
||||
{ id: 'm2', from: 'assistant', type: '文件', datetime: '2026/8/3 10:00:00', content: '', isSender: true, exportMediaType: 'file' as const, exportMediaName: 'a.pdf', createTime: Math.floor(new Date('2026-08-03T10:00:00+08:00').getTime() / 1000) }
|
||||
{ id: 'm1', localId: 1, from: 'user', type: '图片', datetime: '2026/8/2 10:00:00', content: '', contentData: { type: 'image', md5: 'image-md5' }, isSender: false, name: 'BOBO', createTime: Math.floor(new Date('2026-08-02T10:00:00+08:00').getTime() / 1000) },
|
||||
{ id: 'm2', localId: 2, from: 'assistant', type: '文件', datetime: '2026/8/3 10:00:00', content: '', isSender: true, exportMediaType: 'file' as const, exportMediaName: 'a.pdf', createTime: Math.floor(new Date('2026-08-03T10:00:00+08:00').getTime() / 1000) }
|
||||
]
|
||||
}))
|
||||
vi.mock('../../src/main/services/chat-service', () => ({
|
||||
isReady: () => true,
|
||||
listContactsAsync: vi.fn(async () => fixture.contacts),
|
||||
listMessagesAsync: vi.fn(async () => fixture.messages)
|
||||
}))
|
||||
vi.mock('../../src/main/services/chat-service', () => {
|
||||
// 定位/分页替身必须读**当前**的 `listMessagesAsync` 返回值:
|
||||
// 各用例会把它换成不同的消息列表(例如只包含一条语音消息)。
|
||||
const listMessagesAsync = vi.fn(async () => fixture.messages)
|
||||
return {
|
||||
isReady: () => true,
|
||||
listContactsAsync: vi.fn(async () => fixture.contacts),
|
||||
listMessagesAsync,
|
||||
/** 按 `local:<t>:<l>` / `local:<l>` / 纯 id 找;命中多条即 ambiguous。 */
|
||||
locateMessageAsync: vi.fn(async (_conversationId: string, messageId: string) => {
|
||||
const list = (await listMessagesAsync()) as unknown as Array<{
|
||||
id?: string
|
||||
createTime?: number
|
||||
localId?: number
|
||||
}>
|
||||
const text = String(messageId || '').replace(/^local:/, '')
|
||||
const parts = text.split(':')
|
||||
if (parts.length === 2 && /^\d+$/.test(parts[0]) && /^\d+$/.test(parts[1])) {
|
||||
const createTime = Number(parts[0])
|
||||
const localId = Number(parts[1])
|
||||
const hit = list.find(
|
||||
(message) => message.createTime === createTime && message.localId === localId
|
||||
)
|
||||
return hit
|
||||
? { status: 'found', location: { createTime, localId } }
|
||||
: { status: 'not_found' }
|
||||
}
|
||||
const hits = list.filter(
|
||||
(message) => String(message.id) === text || String(message.localId) === text
|
||||
)
|
||||
if (hits.length === 1) {
|
||||
return {
|
||||
status: 'found',
|
||||
location: {
|
||||
createTime: Number(hits[0].createTime) || 0,
|
||||
localId: Number(hits[0].localId) || 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return { status: hits.length ? 'ambiguous' : 'not_found' }
|
||||
}),
|
||||
iterateMessagesAsync: vi.fn(async function* (
|
||||
_conversationId: string,
|
||||
options?: { sinceMs?: number }
|
||||
) {
|
||||
const since = options?.sinceMs ? Math.floor(options.sinceMs / 1000) : undefined
|
||||
const list = ((await listMessagesAsync()) as unknown as Array<{ createTime?: number }>).filter(
|
||||
(message) => since === undefined || (message.createTime || 0) >= since
|
||||
)
|
||||
yield { messages: list, failedStores: [] }
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
import { LocalQueryApiService } from '../../src/main/services/local-query-api-service'
|
||||
import { listMessagesAsync } from '../../src/main/services/chat-service'
|
||||
@@ -32,7 +80,22 @@ describe('LocalQueryApiService', () => {
|
||||
waitForIndexingComplete: vi.fn(async () => false),
|
||||
lastPassDurationMs: vi.fn(() => 0),
|
||||
beginInteractiveQuery: vi.fn(),
|
||||
endInteractiveQuery: vi.fn()
|
||||
endInteractiveQuery: vi.fn(),
|
||||
/** 显式会话一律 complete;对象无自有键,`all` 范围仍落回时间判断。 */
|
||||
getConversationIndexStates: vi.fn(
|
||||
async () =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get: () => ({
|
||||
state: 'ready',
|
||||
completeSnapshot: true,
|
||||
sourceHighWaterTime: 0,
|
||||
indexedMessageCount: 1
|
||||
})
|
||||
}
|
||||
)
|
||||
)
|
||||
} as any
|
||||
/** 固定时钟:requestedEnd 由它决定。 */
|
||||
const NOW = new Date('2026-09-09T12:00:00+08:00').getTime()
|
||||
@@ -156,7 +219,8 @@ describe('LocalQueryApiService', () => {
|
||||
const result = await service.search({ timeRange: { kind: 'all' }, query: '健身', scope: { kind: 'all' } })
|
||||
expect(knowledge.search).toHaveBeenCalledWith(expect.objectContaining({ conversationIds: undefined }))
|
||||
// 跨会话检索不宣称"完整":派生索引不是完整性权威。
|
||||
expect(result.coverage).toEqual({ state: 'partial' })
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
})
|
||||
|
||||
it('scope 内的 target 越界会被结构化拒绝(而不是悄悄扩大范围)', async () => {
|
||||
@@ -241,7 +305,8 @@ describe('LocalQueryApiService', () => {
|
||||
|
||||
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
|
||||
|
||||
expect(result.coverage).toEqual({ state: 'partial' })
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
expect(result.evidenceCount).toBe(0)
|
||||
expect(result.indexLatestAt).toBe(NOW - 10 * DAY)
|
||||
expect(result.sourceLatestAt).toBe(NOW - 1000)
|
||||
@@ -321,7 +386,8 @@ describe('LocalQueryApiService', () => {
|
||||
|
||||
expect(result.resolvedTimeRange?.endTime).toEqual(expect.any(Number))
|
||||
// 请求边界(今天)晚于索引覆盖边界 4 分钟 → 只能 partial。
|
||||
expect(result.coverage).toEqual({ state: 'partial' })
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
expect(result.indexCoverage?.covered).toBe(false)
|
||||
expect(result.indexCoverage?.summary).toContain('暂时无法确认')
|
||||
})
|
||||
@@ -486,7 +552,8 @@ describe('LocalQueryApiService', () => {
|
||||
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
|
||||
|
||||
expect(result.freshness).toEqual({ catchUp: 'skipped' })
|
||||
expect(result.coverage).toEqual({ state: 'partial' })
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
expect(knowledge.requestCatchUp).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -524,17 +591,69 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => {
|
||||
waitForIndexingComplete: vi.fn(async () => false),
|
||||
lastPassDurationMs: vi.fn(() => 0),
|
||||
beginInteractiveQuery: vi.fn(),
|
||||
endInteractiveQuery: vi.fn()
|
||||
endInteractiveQuery: vi.fn(),
|
||||
getConversationIndexStates: vi.fn(
|
||||
async () =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get: () => ({
|
||||
state: 'ready',
|
||||
completeSnapshot: true,
|
||||
sourceHighWaterTime: 0,
|
||||
indexedMessageCount: 1
|
||||
})
|
||||
}
|
||||
)
|
||||
)
|
||||
} as never,
|
||||
() => new Date('2026-09-09T12:00:00+08:00')
|
||||
)
|
||||
fixture.contacts.splice(1)
|
||||
})
|
||||
|
||||
it('目标会话没有索引状态时不得报 complete(全局最新时间不是证明)', async () => {
|
||||
// 场景:A 群索引到今天、B 群一条没建;用户只搜 B。
|
||||
// 旧实现拿全局 indexLatestAt 判断会返回 complete,等于告诉用户"已完整搜索、确实没有"。
|
||||
const sparse = new Proxy(
|
||||
{},
|
||||
{
|
||||
get: () => undefined
|
||||
}
|
||||
) as Record<string, unknown>
|
||||
const service3 = new LocalQueryApiService(
|
||||
{
|
||||
search: vi.fn(async () => ({
|
||||
state: 'ready',
|
||||
evidence: [],
|
||||
indexLatestAt: NOW2 - 1000,
|
||||
sourceLatestAt: NOW2 - 1000,
|
||||
voiceCoverage: undefined
|
||||
})),
|
||||
requestCatchUp: vi.fn(() => ({ triggered: false, inProgress: false })),
|
||||
waitForIndexingComplete: vi.fn(async () => false),
|
||||
lastPassDurationMs: vi.fn(() => 0),
|
||||
beginInteractiveQuery: vi.fn(),
|
||||
endInteractiveQuery: vi.fn(),
|
||||
getConversationIndexStates: vi.fn(async () => sparse)
|
||||
} as never,
|
||||
() => new Date('2026-09-09T12:00:00+08:00')
|
||||
)
|
||||
const targetId = fixture.contacts[0]?.md5 as string
|
||||
const result = await service3.search({
|
||||
timeRange: { kind: 'all' },
|
||||
query: '健身',
|
||||
scope: { kind: 'selected', conversationIds: [targetId] }
|
||||
})
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
})
|
||||
|
||||
it('落后时给出可直接引用的本地时间结论,且明确"暂时无法确认"', async () => {
|
||||
// 同样刻意不带 target —— 见上一条:单会话已经会走直读兜底。
|
||||
const result = await service2.search({ timeRange: { kind: 'all' }, query: '健身' })
|
||||
expect(result.coverage).toEqual({ state: 'partial' })
|
||||
// 返回类型是宽 union(既有写法),这里只关心覆盖度字段。
|
||||
expect((result as { coverage?: unknown }).coverage).toEqual({ state: 'partial' })
|
||||
// 8/30 12:00 的本地时间标签(固定时钟下可断言)
|
||||
expect(result.indexCoverage?.covered).toBe(false)
|
||||
expect(result.indexCoverage?.indexLatestAtLabel).toBe('08-30 12:00')
|
||||
@@ -558,7 +677,7 @@ describe('LocalQueryApiService voice transcription', () => {
|
||||
localId: 31,
|
||||
createTime: Math.floor(new Date('2026-08-04T10:00:00+08:00').getTime() / 1000)
|
||||
}
|
||||
const textMessage = { id: 't1', from: 'user', type: '文本', datetime: '2026/8/4 10:01:00', content: '你好', isSender: false, name: 'BOBO', createTime: voiceMessage.createTime + 60 }
|
||||
const textMessage = { id: 't1', localId: 33, from: 'user', type: '文本', datetime: '2026/8/4 10:01:00', content: '你好', isSender: false, name: 'BOBO', createTime: voiceMessage.createTime + 60 }
|
||||
const voiceRef = encodeMessageRef('md5-bobo', 'v1')
|
||||
const textRef = encodeMessageRef('md5-bobo', 't1')
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sourceMessageId } from '../../src/main/knowledge/message-identity'
|
||||
import type { FormattedMessage } from '../../src/main/services/chat-service'
|
||||
|
||||
const message = (localId: number, createTime: number): FormattedMessage =>
|
||||
({
|
||||
id: String(localId),
|
||||
localId,
|
||||
createTime,
|
||||
from: 'fixture',
|
||||
type: '普通文本',
|
||||
datetime: '',
|
||||
content: '脱敏正文',
|
||||
isSender: false
|
||||
}) as FormattedMessage
|
||||
|
||||
describe('sourceMessageId', () => {
|
||||
it('同 local_id 不同时间必须生成不同 id', () => {
|
||||
// localId 跨分片会重号:只用它会让索引主键互相覆盖。
|
||||
expect(sourceMessageId(message(7, 1_700_000_000))).not.toBe(
|
||||
sourceMessageId(message(7, 1_700_000_060))
|
||||
)
|
||||
})
|
||||
|
||||
it('同一条消息重复读取时 id 稳定', () => {
|
||||
expect(sourceMessageId(message(7, 1_700_000_000))).toBe(
|
||||
sourceMessageId(message(7, 1_700_000_000))
|
||||
)
|
||||
})
|
||||
|
||||
it('没有 localId 时退回消息自带 id,不拼空时间', () => {
|
||||
expect(sourceMessageId({ ...message(0, 0), localId: undefined, id: 'fixture-id' })).toBe(
|
||||
'fixture-id'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,224 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Wcdb4Client, type Wcdb4MessagePage } from '../../src/main/wcdb4-client'
|
||||
|
||||
type Row = Record<string, unknown>
|
||||
|
||||
function row(localId: number, createTime: number, serverId: string, text: string): Row {
|
||||
return {
|
||||
local_id: localId,
|
||||
server_id: serverId,
|
||||
create_time: createTime,
|
||||
local_type: 1,
|
||||
message_content: text,
|
||||
mes_des: 0
|
||||
}
|
||||
}
|
||||
|
||||
const STORES = [
|
||||
{ tableName: 'Msg_a', dbPath: '/shard/a.db' },
|
||||
{ tableName: 'Msg_b', dbPath: '/shard/b.db' },
|
||||
{ tableName: 'Msg_c', dbPath: '/shard/c.db' }
|
||||
]
|
||||
|
||||
// 分片 b 的前 5 条与分片 a 的尾部重叠:模拟迁移留下的重复行。
|
||||
const SHARD_A = Array.from({ length: 40 }, (_, index) =>
|
||||
row(index + 1, 1_000_000 + index * 60, `srv-${index}`, `A-${index}`)
|
||||
)
|
||||
const SHARD_B = [
|
||||
...Array.from({ length: 5 }, (_, index) =>
|
||||
row(100 + index, 1_000_000 + (35 + index) * 60, `srv-${35 + index}`, `dup-${35 + index}`)
|
||||
),
|
||||
...Array.from({ length: 35 }, (_, index) =>
|
||||
row(200 + index, 1_000_000 + (40 + index) * 60, `srv-${40 + index}`, `B-${index}`)
|
||||
)
|
||||
]
|
||||
const SHARD_C = Array.from({ length: 20 }, (_, index) =>
|
||||
row(index + 1, 1_000_000 + (75 + index) * 60, `srv-${75 + index}`, `C-${index}`)
|
||||
)
|
||||
|
||||
function createClient(batchLimit?: number): Wcdb4Client {
|
||||
const data: Record<string, Row[]> = {
|
||||
'/shard/a.db': SHARD_A,
|
||||
'/shard/b.db': SHARD_B,
|
||||
'/shard/c.db': SHARD_C
|
||||
}
|
||||
const offsets = new Map<string, number>()
|
||||
|
||||
return Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
wcdbExecQuery: vi.fn(),
|
||||
displayNameCache: new Map(),
|
||||
avatarCache: new Map(),
|
||||
messageTypeColumnCache: new Map(),
|
||||
resolveMessageUsername: (value: string) => value,
|
||||
getGroupNicknames: () => new Map<string, string>(),
|
||||
getMyUsernameCandidates: () => [],
|
||||
listMessageStoresAsync: async () => STORES,
|
||||
// 只模拟"分片内按有序顺序取下一页",SQL 条件本身由真实 SQLite 保证。
|
||||
callJsonAsync: async (_fn: unknown, _kind: string, dbPath: string, sql: string) => {
|
||||
const limit = Number(/LIMIT (\d+)/.exec(sql)?.[1] ?? 1000)
|
||||
const rows = data[dbPath] ?? []
|
||||
const offset = offsets.get(dbPath) ?? 0
|
||||
offsets.set(dbPath, offset + limit)
|
||||
if (batchLimit !== undefined && rows.length > batchLimit) {
|
||||
return rows.slice(offset, Math.min(offset + limit, batchLimit))
|
||||
}
|
||||
return rows.slice(offset, offset + limit)
|
||||
}
|
||||
}) as unknown as Wcdb4Client
|
||||
}
|
||||
|
||||
async function collect(client: Wcdb4Client, pageSize: number): Promise<Wcdb4MessagePage[]> {
|
||||
const pages: Wcdb4MessagePage[] = []
|
||||
for await (const page of client.iterateMessagePagesAsync('fixture@chatroom', {
|
||||
pageSize,
|
||||
requestId: 'test'
|
||||
})) {
|
||||
pages.push(page)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
describe('iterateMessagePagesAsync', () => {
|
||||
it('merges shards into one stable order and drops cross-shard duplicates', async () => {
|
||||
const client = createClient()
|
||||
const pages = await collect(client, 10)
|
||||
const messages = pages.flatMap((page) => page.messages)
|
||||
|
||||
// 40 + 40 + 20 条里,分片 b 的前 5 条是分片 a 的重复行。
|
||||
expect(messages).toHaveLength(95)
|
||||
expect(new Set(messages.map((message) => message.serverId)).size).toBe(95)
|
||||
|
||||
const times = messages.map((message) => Number(message.msgCreateTime))
|
||||
expect(times).toEqual([...times].sort((left, right) => left - right))
|
||||
|
||||
expect(new Set(messages.map((message) => message.msgContent)).size).toBe(95)
|
||||
expect(pages.every((page) => page.failedStores.length === 0)).toBe(true)
|
||||
expect(pages[pages.length - 1]?.hasMore).toBe(false)
|
||||
})
|
||||
|
||||
it('never repeats or skips a message when pages are uneven', async () => {
|
||||
const reference = await collect(createClient(), 250)
|
||||
const referenceIds = reference.flatMap((page) => page.messages).map((m) => m.serverId)
|
||||
|
||||
for (const pageSize of [3, 7, 11]) {
|
||||
const pages = await collect(createClient(), pageSize)
|
||||
const ids = pages.flatMap((page) => page.messages).map((m) => m.serverId)
|
||||
expect(ids).toEqual(referenceIds)
|
||||
}
|
||||
})
|
||||
|
||||
it('reports the failing shard instead of silently returning a short result', async () => {
|
||||
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
wcdbExecQuery: vi.fn(),
|
||||
displayNameCache: new Map(),
|
||||
avatarCache: new Map(),
|
||||
messageTypeColumnCache: new Map(),
|
||||
resolveMessageUsername: (value: string) => value,
|
||||
getGroupNicknames: () => new Map<string, string>(),
|
||||
getMyUsernameCandidates: () => [],
|
||||
listMessageStoresAsync: async () => STORES,
|
||||
callJsonAsync: async (_fn: unknown, _kind: string, dbPath: string) => {
|
||||
if (dbPath === '/shard/b.db') throw new Error('shard unavailable')
|
||||
return dbPath === '/shard/a.db' ? SHARD_A : SHARD_C
|
||||
}
|
||||
}) as unknown as Wcdb4Client
|
||||
|
||||
const pages = await collect(client, 20)
|
||||
const failed = pages.flatMap((page) => page.failedStores)
|
||||
// 失败必须显式暴露:上层据此才能拒绝把这一遍标成完整。
|
||||
expect(failed).toContain('Msg_b')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* 反例:无法证明是副本时必须保留两条。
|
||||
*
|
||||
* 两个必须守住的边界:`server_id` 会被不同消息复用(同一个 id 出现在不同
|
||||
* create_time 上),而"同秒 + 同发送者 + 同正文"完全可能只是两句"收到"。
|
||||
*/
|
||||
describe('跨分片副本判据', () => {
|
||||
const buildClient = (data: Record<string, Row[]>, stores: typeof STORES): Wcdb4Client => {
|
||||
const offsets = new Map<string, number>()
|
||||
return Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
wcdbExecQuery: vi.fn(),
|
||||
displayNameCache: new Map(),
|
||||
avatarCache: new Map(),
|
||||
messageTypeColumnCache: new Map(),
|
||||
resolveMessageUsername: (value: string) => value,
|
||||
getGroupNicknames: () => new Map<string, string>(),
|
||||
getMyUsernameCandidates: () => [],
|
||||
listMessageStoresAsync: async () => stores,
|
||||
callJsonAsync: async (_fn: unknown, _kind: string, dbPath: string, sql: string) => {
|
||||
const limit = Number(/LIMIT (\d+)/.exec(sql)?.[1] ?? 1000)
|
||||
const rows = data[dbPath] ?? []
|
||||
const offset = offsets.get(dbPath) ?? 0
|
||||
offsets.set(dbPath, offset + limit)
|
||||
return rows.slice(offset, offset + limit)
|
||||
}
|
||||
}) as unknown as Wcdb4Client
|
||||
}
|
||||
|
||||
const collectAll = async (client: Wcdb4Client): Promise<Wcdb4MessagePage[]> => {
|
||||
const pages: Wcdb4MessagePage[] = []
|
||||
for await (const page of client.iterateMessagePagesAsync('fixture@chatroom', {
|
||||
pageSize: 50,
|
||||
requestId: 'test'
|
||||
})) {
|
||||
pages.push(page)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
it('同秒、同 local_id、同正文但 server_id 不同 → 两条都保留', async () => {
|
||||
const stores = [
|
||||
{ tableName: 'Msg_a', dbPath: '/x/a.db' },
|
||||
{ tableName: 'Msg_b', dbPath: '/x/b.db' }
|
||||
]
|
||||
const data = {
|
||||
'/x/a.db': [row(7, 1_700_000_000, 'srv-A', '收到')],
|
||||
'/x/b.db': [row(7, 1_700_000_000, 'srv-B', '收到')]
|
||||
}
|
||||
const messages = (await collectAll(buildClient(data, stores))).flatMap((page) => page.messages)
|
||||
expect(messages).toHaveLength(2)
|
||||
expect(messages.map((message) => message.serverId)).toEqual(['srv-A', 'srv-B'])
|
||||
})
|
||||
|
||||
it('server_id 被复用(不同 create_time)→ 两条都保留', async () => {
|
||||
const stores = [
|
||||
{ tableName: 'Msg_a', dbPath: '/y/a.db' },
|
||||
{ tableName: 'Msg_b', dbPath: '/y/b.db' }
|
||||
]
|
||||
const data = {
|
||||
'/y/a.db': [row(1, 1_700_000_000, 'srv-shared', '第一条')],
|
||||
'/y/b.db': [row(1, 1_700_000_060, 'srv-shared', '第二条')]
|
||||
}
|
||||
const messages = (await collectAll(buildClient(data, stores))).flatMap((page) => page.messages)
|
||||
expect(messages).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('同秒且同 server_id 的重复行才是副本 → 合并为一条', async () => {
|
||||
const stores = [
|
||||
{ tableName: 'Msg_a', dbPath: '/z/a.db' },
|
||||
{ tableName: 'Msg_b', dbPath: '/z/b.db' }
|
||||
]
|
||||
const data = {
|
||||
'/z/a.db': [row(1, 1_700_000_000, 'srv-same', '同一条')],
|
||||
'/z/b.db': [row(99, 1_700_000_000, 'srv-same', '同一条')]
|
||||
}
|
||||
const messages = (await collectAll(buildClient(data, stores))).flatMap((page) => page.messages)
|
||||
expect(messages).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('没有 server_id 时不按正文合并', async () => {
|
||||
const stores = [
|
||||
{ tableName: 'Msg_a', dbPath: '/w/a.db' },
|
||||
{ tableName: 'Msg_b', dbPath: '/w/b.db' }
|
||||
]
|
||||
const data = {
|
||||
'/w/a.db': [row(1, 1_700_000_000, '0', '好的')],
|
||||
'/w/b.db': [row(1, 1_700_000_000, '0', '好的')]
|
||||
}
|
||||
const messages = (await collectAll(buildClient(data, stores))).flatMap((page) => page.messages)
|
||||
expect(messages).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user