@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backfill-child.js +310 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cordis.patch.yml +7 -0
- package/cursor.js +116 -0
- package/dedupe.js +101 -0
- package/egress.js +790 -0
- package/embed-child.js +152 -0
- package/embed.js +475 -0
- package/envelope.js +368 -0
- package/extract.js +420 -0
- package/idle-interrupt.js +922 -0
- package/index.js +154 -0
- package/migrate.js +1723 -0
- package/package.json +68 -3
- package/persona.js +949 -0
- package/providers.js +786 -0
- package/query-window.js +562 -0
- package/recall-stages.js +150 -0
- package/recall-trivium.js +916 -0
- package/recall.js +129 -0
- package/remove-legacy.mjs +720 -0
- package/retention-sweep.js +124 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +510 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +507 -0
- package/trivium-runtime.js +1900 -0
- package/README.md +0 -3
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 三路可解释召回(P1 任务 14):文本 BM25 + 向量 ANN + 图扩散,应用层融合、逐条解释、预算装填。
|
|
3
|
+
*
|
|
4
|
+
* 为什么三样都必须写在应用层(实测,见 `docs/research/triviumdb.md` §一/§五):
|
|
5
|
+
* - 文本臂是引擎原生的(`TEXT BM25 … text_score(_)`),但它只有文本一路;
|
|
6
|
+
* - 向量臂是引擎原生的 ANN(`search`),但它默认 `expandDepth: 0`,本身不做图扩展;
|
|
7
|
+
* - **引擎没有原生三路融合**:`searchHybrid` 只融合文本 + 向量;`UNION` / `WITH … EXPAND` 在 0.9.3 里
|
|
8
|
+
* 全部报 `TDB_QUERY_PARSE`。所以 RRF(`k = 60`)在这里手写——这同时满足「每条召回带来源与分数」。
|
|
9
|
+
* - **引擎没有原生衰减算子**:`RETURN exp(…)` 在解析期被拒(`TDB_QUERY_PARSE`)。年龄衰减也在本文件实现,
|
|
10
|
+
* 半衰期是显式参数(默认 30 天),乘法作用在融合分上。
|
|
11
|
+
*
|
|
12
|
+
* 三个必须守住的契约:
|
|
13
|
+
* 1. **向量宽度 = 当前 profile 的维度**(未配置 API 时为契约值 `EMBEDDING_DIM` = 384,配置 bge-m3 时为 1024)。
|
|
14
|
+
* `store-trivium.js` 的 `DEFAULT_DIM` 是 1536 的占位,
|
|
15
|
+
* 调用方必须显式传 384;本模块在构造时断言(`stats().dim`)与 `embedder.dim` 都等于 384,不符即
|
|
16
|
+
* `KANABO_RECALL_DIMENSION`,绝不 pad/截断。
|
|
17
|
+
* 2. **查询用 `query: ` 前缀、入库文本用 `passage: ` 前缀**(e5 的训练口径)。本模块只负责查询侧;
|
|
18
|
+
* 写入侧(任务 13 的迁移)必须用 `passageText()` 生成被嵌入的文本,而 `indexText` 用**裸文本**
|
|
19
|
+
* (否则 BM25 的每一篇都会多一个无信息量的 `passage` 词元)。
|
|
20
|
+
* 3. **TriviumDB 是文件级独占租约**(实测:第二个句柄在 open 就 `TDB_DATABASE_LOCKED`,不是等待)。
|
|
21
|
+
* 因此本模块**接受已打开的门面注入**(`options.store`),也**只在调用方没给门面时**自己开一个;
|
|
22
|
+
* 它绝不建进程级注册表——「迁移 / 召回 / serve 共用同一个门面」是任务 16 的交付物。
|
|
23
|
+
* 同一个库路径在同一进程里开第二个门面会立刻失败,这不是重试能解决的问题,是测试路径冲突。
|
|
24
|
+
*
|
|
25
|
+
* 图的形状(任务 11 的边标签):`belongs_to_session` / `triggered_by` / `followed_by`。
|
|
26
|
+
* 扩散按边的方向走(`MATCH (a)-[r:label]->(b)`),逐跳用 `a.id == … OR …` 把前沿节点作为起点,
|
|
27
|
+
* 引擎不支持 `a.id IN [...]`(实测 `TDB_QUERY_PARSE`),所以这里拼 OR 串并对前沿设上限。
|
|
28
|
+
*/
|
|
29
|
+
import { EDGE_LABELS, EMBEDDING_DIM } from './contract.js'
|
|
30
|
+
import { activeEmbeddingDim, activeEmbeddingPrefixes, judgeState } from './providers.js'
|
|
31
|
+
import { applyJudge, applyRerank } from './recall-stages.js'
|
|
32
|
+
import { createTriviumStore } from './store-trivium.js'
|
|
33
|
+
|
|
34
|
+
/** 三臂名字:关掉其中任意两个必须改变结果集,这是验收 (a)。 */
|
|
35
|
+
export const ARM_NAMES = Object.freeze(['text', 'vector', 'graph'])
|
|
36
|
+
/** 倒数排名融合的常数:分数 = Σ weight / (k + rank),rank 从 1 开始。 */
|
|
37
|
+
export const RRF_K = 60
|
|
38
|
+
/** 年龄衰减半衰期(毫秒):默认 30 天;引擎无原生算子,故在此实现(`docs/research/triviumdb.md` §五)。 */
|
|
39
|
+
export const DEFAULT_HALF_LIFE_MS = 30 * 24 * 60 * 60 * 1000
|
|
40
|
+
/** 默认预算(字符数,按 Unicode 码点计)。 */
|
|
41
|
+
export const DEFAULT_BUDGET_CHARS = 2000
|
|
42
|
+
/** e5 的查询前缀;入库文本用 `PASSAGE_PREFIX`。 */
|
|
43
|
+
export const QUERY_PREFIX = 'query: '
|
|
44
|
+
export const PASSAGE_PREFIX = 'passage: '
|
|
45
|
+
/** 查询串上限:BM25 的查询是拼进 TQL 字符串字面量的,过长既无收益又放大注入面。 */
|
|
46
|
+
export const MAX_QUERY_CHARS = 512
|
|
47
|
+
/** 单次召回的总期限:超时以 `KANABO_RECALL_TIMEOUT` 拒绝,绝不挂起调用方。 */
|
|
48
|
+
export const DEFAULT_TIMEOUT_MS = 5_000
|
|
49
|
+
/** 图臂默认参数:2 跳、每臂取 8 个种子、每跳前沿最多 32 个节点、每跳衰减 0.5。 */
|
|
50
|
+
export const DEFAULT_GRAPH = Object.freeze({
|
|
51
|
+
maxHops: 2,
|
|
52
|
+
seedsPerArm: 8,
|
|
53
|
+
frontierLimit: 32,
|
|
54
|
+
hopDecay: 0.5,
|
|
55
|
+
minEdgeWeight: 0.01,
|
|
56
|
+
/** 单次边查询的行上限:防止星形枢纽(会话锚点)一次扇出整库。 */
|
|
57
|
+
rowLimit: 128,
|
|
58
|
+
labels: EDGE_LABELS,
|
|
59
|
+
})
|
|
60
|
+
export const DEFAULT_ARMS = Object.freeze({ text: true, vector: true, graph: true })
|
|
61
|
+
/**
|
|
62
|
+
* 默认臂权重:文本 1、向量 1、图 1.4。
|
|
63
|
+
*
|
|
64
|
+
* 为什么图不是 1、也不是 2——这是量出来的,不是拍的(`task-14.log` §3 权重扫描;同一个 2102 节点语料、
|
|
65
|
+
* 同一组查询、limit=10,统计“只由 graph 臂贡献”的命中占 top-10 的比例):
|
|
66
|
+
* - 0.8 / 1.2:图命中数 **0/10**(四至六个查询全部),即图开关对结果集完全无效;
|
|
67
|
+
* - 1.4:图占 **0–3/10**,Jaccard(full, text+vector) = 0.54–0.82(有图就变、但直接命中仍在头部);
|
|
68
|
+
* - 1.6 / 1.8:图升到 **4–6/10**,开始把直接命中挤出去。
|
|
69
|
+
* 另外:纯等权 RRF(无臂内归一化)时图臂头名与文本头名同分,按 nodeId 并列规则排序会让 top-10 全是图节点
|
|
70
|
+
* (实测 Jaccard(full, text-only)=0),这就是 `norm_arm` 存在的原因。
|
|
71
|
+
*/
|
|
72
|
+
export const DEFAULT_WEIGHTS = Object.freeze({ text: 1, vector: 1, graph: 1.4 })
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 臂级降级原因码(稳定字符串,供调用方分类,不随文案变化)。
|
|
76
|
+
* `NO_EDGES` 只表示「库里一条边都没有」;有边却一条命中都留不下(例如单条目会话只有
|
|
77
|
+
* 「条目↔锚点」两条边,而锚点不是命中)是 `NO_HITS`——两者必须可区分。
|
|
78
|
+
*/
|
|
79
|
+
export const DEGRADED = Object.freeze({
|
|
80
|
+
EMPTY_QUERY: 'empty_query',
|
|
81
|
+
VECTOR_UNAVAILABLE: 'vector_unavailable',
|
|
82
|
+
NO_SEEDS: 'no_seeds',
|
|
83
|
+
NO_EDGES: 'no_edges',
|
|
84
|
+
NO_HITS: 'no_hits',
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
function recallError(code, message, extra = {}) {
|
|
88
|
+
const error = new Error(message, extra.cause === undefined ? undefined : { cause: extra.cause })
|
|
89
|
+
error.code = code
|
|
90
|
+
if (extra.details !== undefined) error.details = extra.details
|
|
91
|
+
return error
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 预算口径:Unicode 码点(中文一字一元,emoji 不被算成两个)。所有成本都用它,绝不混用 `.length`。 */
|
|
95
|
+
export function charCost(text) {
|
|
96
|
+
let count = 0
|
|
97
|
+
for (const _ of String(text ?? '')) count += 1
|
|
98
|
+
return count
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 把用户查询变成 TQL 字符串字面量的内容:反斜杠与双引号转义(实测 `\"` / `\\` 可解析),
|
|
103
|
+
* 控制字符换成空格(换行会截断 TQL 语句),并截到 `MAX_QUERY_CHARS`。
|
|
104
|
+
* 这是唯一一处把外部文本拼进 TQL 的地方;其余查询只拼数字与 JSON 字符串字面量。
|
|
105
|
+
*/
|
|
106
|
+
export function tqlStringBody(text) {
|
|
107
|
+
return String(text ?? '')
|
|
108
|
+
.slice(0, MAX_QUERY_CHARS)
|
|
109
|
+
.replace(/[\u0000-\u001f\u007f]+/g, ' ')
|
|
110
|
+
.replace(/\\/g, '\\\\')
|
|
111
|
+
.replace(/"/g, '\\"')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 被嵌入的存储文本:`passage: ` 前缀(任务 13 的迁移必须用它;`indexText` 仍用裸文本)。 */
|
|
115
|
+
export function passageText(text) {
|
|
116
|
+
return `${PASSAGE_PREFIX}${String(text ?? '')}`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 从 payload 里挑可读文本:与 `payload.text` 同口径的字段按优先级取第一个非空。 */
|
|
120
|
+
export function textOfPayload(payload) {
|
|
121
|
+
if (payload === null || typeof payload !== 'object') return ''
|
|
122
|
+
for (const key of ['text', 'scene_description', 'topic', 'tool_name']) {
|
|
123
|
+
const value = payload[key]
|
|
124
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
125
|
+
}
|
|
126
|
+
return ''
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 迁移(任务 13)写入的 payload 是**两层**的:
|
|
131
|
+
* `{ kind: 'kanabo-envelope', legacy_id, ts, text_sha256, envelope: { id, ts, text, … } }`。
|
|
132
|
+
* 所以取业务字段前先剥一层;平铺 payload(手写夹具、未迁移的旧形状)原样返回。
|
|
133
|
+
*/
|
|
134
|
+
function envelopeOf(payload) {
|
|
135
|
+
if (payload !== null && typeof payload === 'object'
|
|
136
|
+
&& payload.envelope !== null && typeof payload.envelope === 'object') {
|
|
137
|
+
return payload.envelope
|
|
138
|
+
}
|
|
139
|
+
return payload
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 稳定排序:分数降序,同分按节点 id 升序——这就是「同分时的并列规则」,重跑必然同一排名。 */
|
|
143
|
+
function byScoreThenId(a, b) {
|
|
144
|
+
return b.score - a.score || a.id - b.id
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 数值化引擎返回的 id(TQL 返回的可能是数字或十进制字符串;超出安全整数就丢弃而不是静默失真)。 */
|
|
148
|
+
function nodeIdOf(value) {
|
|
149
|
+
const id = typeof value === 'number' ? value : Number(value)
|
|
150
|
+
return Number.isSafeInteger(id) && id >= 0 ? id : null
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 带硬期限的等待:超时以 `KANABO_RECALL_TIMEOUT` 拒绝;原 promise 的迟到结果被吞掉。 */
|
|
154
|
+
function withTimeout(promise, timeoutMs, label) {
|
|
155
|
+
let timer
|
|
156
|
+
const expiry = new Promise((_, reject) => {
|
|
157
|
+
timer = setTimeout(() => {
|
|
158
|
+
reject(recallError('KANABO_RECALL_TIMEOUT', `${label} 超过 ${timeoutMs}ms 期限。`, { details: { timeoutMs } }))
|
|
159
|
+
}, timeoutMs)
|
|
160
|
+
})
|
|
161
|
+
promise.catch(() => {}) // 超时后原 promise 仍会 settle,必须消费掉。
|
|
162
|
+
return Promise.race([promise, expiry]).finally(() => clearTimeout(timer))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 文本臂:TQL `TEXT BM25`。返回按 (分数降序, id 升序) 排好的 `{id, score}`。 */
|
|
166
|
+
async function textArm(store, query, limit) {
|
|
167
|
+
const body = tqlStringBody(query)
|
|
168
|
+
if (body.trim() === '') return { hits: [], degraded: DEGRADED.EMPTY_QUERY }
|
|
169
|
+
const top = Math.max(1, Math.min(200, Math.floor(limit)))
|
|
170
|
+
const rows = await store.tql(
|
|
171
|
+
`TEXT BM25 "${body}" TOP ${top} RETURN _.id AS id, text_score(_) AS s ORDER BY s DESC`)
|
|
172
|
+
const hits = []
|
|
173
|
+
for (const row of Array.isArray(rows?.rows) ? rows.rows : []) {
|
|
174
|
+
const id = nodeIdOf(row?.id)
|
|
175
|
+
if (id === null) continue
|
|
176
|
+
hits.push({ id, score: Number(row.s) || 0 })
|
|
177
|
+
}
|
|
178
|
+
hits.sort(byScoreThenId)
|
|
179
|
+
return { hits, degraded: null }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 向量臂:`embedder.embed(query, { prefix: QUERY_PREFIX })` → `store.search(..., expandDepth: 0)`。
|
|
184
|
+
* 嵌入不可用(模型缺失/超时/维度不符)时**不抛错**,返回空列表 + 原因码,其余两臂照常工作。
|
|
185
|
+
*/
|
|
186
|
+
async function vectorArm(store, query, limit, embedder, options) {
|
|
187
|
+
if (embedder === undefined || embedder === null) return { hits: [], degraded: DEGRADED.VECTOR_UNAVAILABLE }
|
|
188
|
+
if (String(query ?? '').trim() === '') return { hits: [], degraded: DEGRADED.EMPTY_QUERY }
|
|
189
|
+
const embedded = await embedder.embed(query, { prefix: options.queryPrefix })
|
|
190
|
+
if (embedded?.degraded === true || embedded?.vector === null || embedded?.vector === undefined) {
|
|
191
|
+
return { hits: [], degraded: embedded?.reason ?? DEGRADED.VECTOR_UNAVAILABLE }
|
|
192
|
+
}
|
|
193
|
+
const vector = Array.from(embedded.vector)
|
|
194
|
+
if (vector.length !== options.dim) {
|
|
195
|
+
throw recallError(
|
|
196
|
+
'KANABO_RECALL_DIMENSION',
|
|
197
|
+
`查询向量是 ${vector.length} 维,当前 profile 是 ${options.dim} 维;拒绝查询。`,
|
|
198
|
+
{ details: { expected: options.dim, received: vector.length } })
|
|
199
|
+
}
|
|
200
|
+
const top = Math.max(1, Math.min(200, Math.floor(limit)))
|
|
201
|
+
const result = await store.search({
|
|
202
|
+
vector,
|
|
203
|
+
topK: top,
|
|
204
|
+
expandDepth: 0,
|
|
205
|
+
minScore: options.minVectorScore,
|
|
206
|
+
exact: options.exact === true,
|
|
207
|
+
})
|
|
208
|
+
const hits = []
|
|
209
|
+
const meta = new Map()
|
|
210
|
+
for (const hit of Array.isArray(result?.hits) ? result.hits : []) {
|
|
211
|
+
const id = nodeIdOf(hit?.id)
|
|
212
|
+
if (id === null) continue
|
|
213
|
+
const score = Number(hit.score)
|
|
214
|
+
if (!Number.isFinite(score) || score <= options.minVectorScore) continue
|
|
215
|
+
hits.push({ id, score })
|
|
216
|
+
if (hit.payload !== null && typeof hit.payload === 'object') meta.set(id, payloadMeta(hit.payload, id))
|
|
217
|
+
}
|
|
218
|
+
hits.sort(byScoreThenId)
|
|
219
|
+
return { hits, degraded: null, meta }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** `n AS payload` 投影的是节点包装(`{ id, numEdges, payload }`),业务字段在里层。 */
|
|
223
|
+
function unwrapNode(value) {
|
|
224
|
+
if (value === null || typeof value !== 'object') return null
|
|
225
|
+
return value.payload !== null && typeof value.payload === 'object' ? value.payload : null
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 一条命中的元数据:`key` 是 Envelope 的 `id`(迁移必须保留它,否则与旧库对不上号),
|
|
230
|
+
* `text` 用于预算成本与解释,`ts` 用于年龄衰减。缺 `ts` 时记 null(衰减因子按 1 并在解释里说明)。
|
|
231
|
+
*/
|
|
232
|
+
function payloadMeta(payload, nodeId) {
|
|
233
|
+
const fields = envelopeOf(payload)
|
|
234
|
+
const ts = Number(payload?.ts ?? fields?.ts)
|
|
235
|
+
const rawKey = payload?.legacy_id ?? fields?.id ?? payload?.id ?? payload?.mem_id
|
|
236
|
+
return {
|
|
237
|
+
nodeId,
|
|
238
|
+
key: rawKey === undefined || rawKey === null || rawKey === '' ? String(nodeId) : String(rawKey),
|
|
239
|
+
ts: Number.isFinite(ts) ? ts : null,
|
|
240
|
+
text: textOfPayload(fields),
|
|
241
|
+
graphRole: payload?.graph_role === 'anchor' ? 'anchor' : null,
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 锚点剔除(复核 N1):会话锚点是图的基础设施,不是记忆——**任何臂**的命中里都不许出现它。
|
|
247
|
+
*
|
|
248
|
+
* 判据取 payload 上的 `graph_role:'anchor'`(迁移的 `anchorPayload` 写的就是它),而不是去动索引:
|
|
249
|
+
* 锚点的 `text` 是 `session <id>`,只要它进了文本索引,任何「不索引」以外的排除都得覆盖所有臂;
|
|
250
|
+
* 放在召回侧按 payload 过滤,对迁移库与活写入库是同一套规则,也不需要重建旧库。
|
|
251
|
+
*/
|
|
252
|
+
function dropAnchors(hits, meta) {
|
|
253
|
+
return (Array.isArray(hits) ? hits : []).filter((hit) => meta.get(hit.id)?.graphRole !== 'anchor')
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 图臂没有命中时的原因:只有库里真的零条边(`graphStats.edgeCount === 0`)才是 `no_edges`;
|
|
258
|
+
* 有边但命中全被剔除是 `no_hits`(复核 N2:单条目会话有 2 条边,过去被误报成 `no_edges`)。
|
|
259
|
+
* 先问门面的图摘要(`edges()` 只取 1 行就带回 `graphStats`),门面没这个能力才退化成「扫一条边」。
|
|
260
|
+
*/
|
|
261
|
+
async function emptyGraphReason(store) {
|
|
262
|
+
try {
|
|
263
|
+
if (typeof store?.edges === 'function') {
|
|
264
|
+
const result = await store.edges(undefined, { limit: 1 })
|
|
265
|
+
const edgeCount = Number(result?.graph?.edgeCount)
|
|
266
|
+
if (Number.isFinite(edgeCount)) return edgeCount === 0 ? DEGRADED.NO_EDGES : DEGRADED.NO_HITS
|
|
267
|
+
}
|
|
268
|
+
const rows = await store.tql('MATCH (a)-[r]->(b) RETURN a.id AS s LIMIT 1')
|
|
269
|
+
return Array.isArray(rows?.rows) && rows.rows.length > 0 ? DEGRADED.NO_HITS : DEGRADED.NO_EDGES
|
|
270
|
+
} catch {
|
|
271
|
+
// 问不出图规模时给中性标记:绝不把「不知道」说成「没有边」。
|
|
272
|
+
return DEGRADED.NO_HITS
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 图臂:以文本臂与向量臂的头部命中(外加调用方显式给的 `seedIds`)为种子,逐跳扩散。
|
|
278
|
+
*
|
|
279
|
+
* 打分(逐跳连乘,边权与跳数都进入分数,因此「一条低权边」不会与「一条高权边」等价):
|
|
280
|
+
* score(路径) = seedScore × Π max(edgeWeight, minEdgeWeight) × hopDecay^hop
|
|
281
|
+
* `seedScore` 是该种子在本臂归一化后的证据强度(臂内最高分 = 1);同一条路径上的节点不重复访问。
|
|
282
|
+
* 返回的每个命中都带 `why.path`(节点 id 链)与 `why.edges`(每跳的标签与权重),供解释直接用。
|
|
283
|
+
*/
|
|
284
|
+
async function graphArm(store, seeds, config) {
|
|
285
|
+
const arms = config
|
|
286
|
+
if (seeds.size === 0) return { hits: [], degraded: DEGRADED.NO_SEEDS, meta: new Map() }
|
|
287
|
+
const best = new Map() // nodeId → { score, hop, path, edges }
|
|
288
|
+
const meta = new Map()
|
|
289
|
+
const seedSet = new Set(seeds.keys())
|
|
290
|
+
let frontier = new Map([...seeds.entries()].map(([id, seed]) => [id, seed.score]))
|
|
291
|
+
const traversed = []
|
|
292
|
+
|
|
293
|
+
for (let hop = 1; hop <= arms.maxHops; hop += 1) {
|
|
294
|
+
const ordered = [...frontier.entries()]
|
|
295
|
+
.sort((a, b) => b[1] - a[1] || a[0] - b[0])
|
|
296
|
+
.slice(0, Math.max(1, arms.frontierLimit))
|
|
297
|
+
if (ordered.length === 0) break
|
|
298
|
+
const where = ordered.map(([id]) => `a.id == ${id}`).join(' OR ')
|
|
299
|
+
const next = new Map()
|
|
300
|
+
for (const label of arms.labels) {
|
|
301
|
+
// 只拼数字 id:这里绝不影响注入面。
|
|
302
|
+
// `LIMIT` 是必需的:会话锚点是星形枢纽(一个锚点连它整段会话的全部条目),不设上限时
|
|
303
|
+
// 一跳就能取回整库的行(实测 2500 行 / 535ms,默认页上限处 5000 行 / 874ms)。
|
|
304
|
+
const rows = await store.tql(
|
|
305
|
+
`MATCH (a)-[r:${label}]->(b) WHERE ${where} `
|
|
306
|
+
+ `RETURN a.id AS s, b.id AS t, r.weight AS w, b AS payload LIMIT ${arms.rowLimit}`)
|
|
307
|
+
const list = Array.isArray(rows?.rows) ? rows.rows : []
|
|
308
|
+
if (list.length > 0) traversed.push({ hop, label, rows: list.length })
|
|
309
|
+
for (const row of list) {
|
|
310
|
+
const from = nodeIdOf(row.s)
|
|
311
|
+
const to = nodeIdOf(row.t)
|
|
312
|
+
if (from === null || to === null || from === to) continue
|
|
313
|
+
const parentScore = frontier.get(from)
|
|
314
|
+
if (parentScore === undefined) continue
|
|
315
|
+
const weight = Number(row.w)
|
|
316
|
+
const edgeWeight = Number.isFinite(weight) ? Math.max(0, Math.min(1, weight)) : 1
|
|
317
|
+
const score = parentScore * Math.max(edgeWeight, arms.minEdgeWeight) * arms.hopDecay
|
|
318
|
+
if (score <= 0) continue
|
|
319
|
+
const previous = best.get(to)
|
|
320
|
+
if (previous !== undefined && previous.score >= score) continue
|
|
321
|
+
const parent = best.get(from)
|
|
322
|
+
const path = parent !== undefined ? [...parent.path, to] : [...(seedPath(seeds, from) ?? [from]), to]
|
|
323
|
+
const edges = parent !== undefined
|
|
324
|
+
? [...parent.edges, { from, to, label, weight: edgeWeight }]
|
|
325
|
+
: [{ from, to, label, weight: edgeWeight }]
|
|
326
|
+
best.set(to, { score, hop, path, edges })
|
|
327
|
+
if (!next.has(to) || next.get(to) < score) next.set(to, score)
|
|
328
|
+
const payload = unwrapNode(row.payload)
|
|
329
|
+
if (payload !== null && !meta.has(to)) meta.set(to, payloadMeta(payload, to))
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
frontier = next
|
|
333
|
+
if (frontier.size === 0) break
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const hits = [...best.entries()]
|
|
337
|
+
.filter(([id]) => !seedSet.has(id))
|
|
338
|
+
// 只当图「胶水」的基础设施节点(会话锚点,payload 标了 `graph_role:'anchor'`)会被扩散经过,
|
|
339
|
+
// 但它们不是记忆:不能出现在命中里,否则每次召回都会往预算里塞一行 `session <id>`。
|
|
340
|
+
// 文本/向量臂的同一剔除在 `run()` 里做(那里才能拿到文本命中的 payload)。
|
|
341
|
+
.filter(([id]) => meta.get(id)?.graphRole !== 'anchor')
|
|
342
|
+
.map(([id, entry]) => ({
|
|
343
|
+
id,
|
|
344
|
+
score: entry.score,
|
|
345
|
+
why: { path: entry.path, edges: entry.edges, hop: entry.hop },
|
|
346
|
+
}))
|
|
347
|
+
.sort(byScoreThenId)
|
|
348
|
+
return {
|
|
349
|
+
hits: hits.slice(0, Math.max(1, arms.limit)),
|
|
350
|
+
degraded: hits.length === 0 ? await emptyGraphReason(store) : null,
|
|
351
|
+
meta,
|
|
352
|
+
traversed,
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** 种子的路径起点:`seeds` 是 Map<nodeId, {score, path?}>,显式种子自带 path。 */
|
|
357
|
+
function seedPath(seeds, id) {
|
|
358
|
+
const seed = seeds.get(id)
|
|
359
|
+
return seed !== undefined && Array.isArray(seed.path) ? seed.path : null
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* 应用层融合(纯函数,可单独测):**带分数归一化的加权 RRF** × 年龄衰减。
|
|
364
|
+
*
|
|
365
|
+
* score = exp(-ln2 × age / halfLifeMs) × Σ_arm w_arm × norm_arm(hit) / (k + rank_arm)
|
|
366
|
+
* norm_arm(hit) = score_arm(hit) / max(score_arm) (臂内最高分归一为 1)
|
|
367
|
+
*
|
|
368
|
+
* 为什么是「归一化 RRF」而不是纯 RRF:纯 RRF 丢掉「图臂是一次两跳扩张」这个信息,等权时图臂头名
|
|
369
|
+
* 会与文本头名同分并被 nodeId 并列规则排到前面(实测见 `DEFAULT_WEIGHTS` 注释)。加入 `norm_arm`
|
|
370
|
+
* 后,同一臂内两跳扩张(norm ≈ 0.4)自然落在它的一跳种子之后,而不同量纲的分数(BM25 / 余弦 / 图分)
|
|
371
|
+
* 仍不需要跨臂校准——只有排名与臂内相对强度进入融合。
|
|
372
|
+
*
|
|
373
|
+
* - `decay` 乘法作用在融合后的总分上(且只作用一次);`age = now - payload.ts`,负值按 0,缺 ts 则因子 1 并标注;
|
|
374
|
+
* - 排序 (score 降序, 参与臂数降序, nodeId 升序):同分时「更多臂同意的」先出,再按 id 稳定排序。
|
|
375
|
+
* 给了固定 `now` 时两次调用逐位相同(验收 f);用真实时钟时分数会随年龄连续漂移,这是衰减的本意。
|
|
376
|
+
*/
|
|
377
|
+
export function fuseArms(armHits, options = {}) {
|
|
378
|
+
const k = Number.isFinite(options.rrfK) && options.rrfK > 0 ? options.rrfK : RRF_K
|
|
379
|
+
const weights = { ...DEFAULT_WEIGHTS, ...(options.weights ?? {}) }
|
|
380
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now()
|
|
381
|
+
const halfLifeMs = Number.isFinite(options.halfLifeMs) && options.halfLifeMs > 0
|
|
382
|
+
? options.halfLifeMs
|
|
383
|
+
: DEFAULT_HALF_LIFE_MS
|
|
384
|
+
const metaOf = typeof options.metaOf === 'function' ? options.metaOf : () => undefined
|
|
385
|
+
const armMax = new Map()
|
|
386
|
+
for (const name of ARM_NAMES) {
|
|
387
|
+
const arm = armHits[name]
|
|
388
|
+
if (arm === undefined || arm === null || arm.enabled === false) continue
|
|
389
|
+
const max = arm.hits.reduce((best, hit) => Math.max(best, Number(hit.score) || 0), 0)
|
|
390
|
+
armMax.set(name, max)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const merged = new Map()
|
|
394
|
+
for (const name of ARM_NAMES) {
|
|
395
|
+
const arm = armHits[name]
|
|
396
|
+
if (arm === undefined || arm === null || arm.enabled === false) continue
|
|
397
|
+
const weight = Number(weights[name])
|
|
398
|
+
if (!Number.isFinite(weight) || weight <= 0) continue
|
|
399
|
+
const max = armMax.get(name) ?? 0
|
|
400
|
+
arm.hits.forEach((hit, index) => {
|
|
401
|
+
const entry = merged.get(hit.id) ?? { nodeId: hit.id, arms: [], graph: null }
|
|
402
|
+
const score = Number(hit.score) || 0
|
|
403
|
+
const norm = max > 0 ? Math.max(0, Math.min(1, score / max)) : 0
|
|
404
|
+
entry.arms.push({ arm: name, rank: index + 1, score, norm, weight })
|
|
405
|
+
if (name === 'graph' && hit.why !== undefined && entry.graph === null) {
|
|
406
|
+
entry.graph = {
|
|
407
|
+
path: Array.isArray(hit.why.path) ? [...hit.why.path] : [],
|
|
408
|
+
edges: Array.isArray(hit.why.edges) ? hit.why.edges.map((edge) => ({ ...edge })) : [],
|
|
409
|
+
hops: hit.why.hop ?? null,
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
merged.set(hit.id, entry)
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const fused = []
|
|
417
|
+
for (const entry of merged.values()) {
|
|
418
|
+
let rrf = 0
|
|
419
|
+
for (const arm of entry.arms) rrf += (arm.weight * arm.norm) / (k + arm.rank)
|
|
420
|
+
const meta = metaOf(entry.nodeId)
|
|
421
|
+
const ageMs = meta !== undefined && meta.ts !== null ? Math.max(0, now - meta.ts) : null
|
|
422
|
+
const factor = ageMs === null ? 1 : Math.exp((-Math.LN2 * ageMs) / halfLifeMs)
|
|
423
|
+
const arms = entry.arms.map((arm) => ({
|
|
424
|
+
...arm,
|
|
425
|
+
contribution: ((arm.weight * arm.norm) / (k + arm.rank)) * factor,
|
|
426
|
+
}))
|
|
427
|
+
fused.push({
|
|
428
|
+
id: meta?.key ?? String(entry.nodeId),
|
|
429
|
+
nodeId: entry.nodeId,
|
|
430
|
+
text: meta?.text ?? '',
|
|
431
|
+
ts: meta?.ts ?? null,
|
|
432
|
+
score: rrf * factor,
|
|
433
|
+
rrf,
|
|
434
|
+
why: {
|
|
435
|
+
summary: '',
|
|
436
|
+
arms,
|
|
437
|
+
rrf,
|
|
438
|
+
decay: { factor, ageMs, halfLifeMs },
|
|
439
|
+
graph: entry.graph,
|
|
440
|
+
},
|
|
441
|
+
})
|
|
442
|
+
}
|
|
443
|
+
fused.sort((a, b) => b.score - a.score || b.why.arms.length - a.why.arms.length || a.nodeId - b.nodeId)
|
|
444
|
+
for (const hit of fused) hit.why.summary = explain(hit)
|
|
445
|
+
return fused
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** 每条命中一句人话:哪些臂、各自排名/分数、图路径。这就是「为什么召回」的字符串形态。 */
|
|
449
|
+
export function explain(hit) {
|
|
450
|
+
const parts = hit.why.arms
|
|
451
|
+
.map((arm) => `${arm.arm}#${arm.rank}(${formatScore(arm.score)})`)
|
|
452
|
+
let text = `arms: ${parts.join(' + ')}`
|
|
453
|
+
if (hit.why.graph !== null && hit.why.graph.path.length > 1) {
|
|
454
|
+
const path = hit.why.graph.path.join('→')
|
|
455
|
+
const weights = hit.why.graph.edges.map((edge) => `${edge.label}:${formatScore(edge.weight)}`).join(',')
|
|
456
|
+
text += `; graph path ${path} (${weights}, hops=${hit.why.graph.hops})`
|
|
457
|
+
}
|
|
458
|
+
const decay = hit.why.decay
|
|
459
|
+
if (decay.ageMs !== null) {
|
|
460
|
+
text += `; age=${Math.round(decay.ageMs / 1000)}s → decay=${decay.factor.toFixed(3)} (halfLife=${Math.round(decay.halfLifeMs / 1000)}s)`
|
|
461
|
+
}
|
|
462
|
+
return text
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function formatScore(value) {
|
|
466
|
+
const number = Number(value)
|
|
467
|
+
if (!Number.isFinite(number)) return 'NaN'
|
|
468
|
+
return number >= 1 ? number.toFixed(3) : number.toFixed(4)
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* 预算装填(纯函数):按融合分从高到低贪心放入,放不下的进 `dropped`(带精确字符数),
|
|
473
|
+
* 绝不截半条、绝不偷偷少报。`used + remaining === total` 恒成立,`dropped` 的字符数与 `used` 之和
|
|
474
|
+
* 等于被考虑命中的总字符数——这就是验收 (c) 的求和校验。
|
|
475
|
+
*/
|
|
476
|
+
export function packByBudget(hits, budgetChars = DEFAULT_BUDGET_CHARS) {
|
|
477
|
+
const total = Math.max(0, Math.floor(Number.isFinite(budgetChars) ? budgetChars : DEFAULT_BUDGET_CHARS))
|
|
478
|
+
const packed = []
|
|
479
|
+
const dropped = []
|
|
480
|
+
let used = 0
|
|
481
|
+
for (const hit of Array.isArray(hits) ? hits : []) {
|
|
482
|
+
const chars = Number.isFinite(hit.chars) ? hit.chars : charCost(hit.text)
|
|
483
|
+
if (used + chars <= total) {
|
|
484
|
+
packed.push({ ...hit, chars })
|
|
485
|
+
used += chars
|
|
486
|
+
} else {
|
|
487
|
+
dropped.push({ id: hit.id, nodeId: hit.nodeId, chars, reason: 'budget' })
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
hits: packed,
|
|
492
|
+
dropped,
|
|
493
|
+
budget: { unit: 'chars', total, used, remaining: total - used },
|
|
494
|
+
truncated: dropped.length > 0,
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 一次召回要用的配置:默认值 + 调用方覆盖,并在构造时把不合法值夹到安全范围。 */
|
|
499
|
+
let DEFAULTS_RESOLVED = null
|
|
500
|
+
function defaultDim() {
|
|
501
|
+
try {
|
|
502
|
+
return activeEmbeddingDim()
|
|
503
|
+
} catch {
|
|
504
|
+
return EMBEDDING_DIM
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function defaultQueryPrefix() {
|
|
509
|
+
try {
|
|
510
|
+
return activeEmbeddingPrefixes().query
|
|
511
|
+
} catch {
|
|
512
|
+
return QUERY_PREFIX
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function normalizeOptions(input = {}) {
|
|
517
|
+
const graphInput = { ...DEFAULT_GRAPH, ...(input.graph ?? {}) }
|
|
518
|
+
return {
|
|
519
|
+
arms: { ...DEFAULT_ARMS, ...(input.arms ?? {}) },
|
|
520
|
+
limit: clampInt(input.limit, 12, 1, 200),
|
|
521
|
+
armLimit: clampInt(input.armLimit, Math.max(20, clampInt(input.limit, 12, 1, 200) * 4), 1, 200),
|
|
522
|
+
budgetChars: Math.max(0, Math.floor(Number.isFinite(input.budgetChars) ? input.budgetChars : DEFAULT_BUDGET_CHARS)),
|
|
523
|
+
rrfK: Number.isFinite(input.rrfK) && input.rrfK > 0 ? input.rrfK : RRF_K,
|
|
524
|
+
weights: { ...DEFAULT_WEIGHTS, ...(input.weights ?? {}) },
|
|
525
|
+
halfLifeMs: Number.isFinite(input.halfLifeMs) && input.halfLifeMs > 0 ? input.halfLifeMs : DEFAULT_HALF_LIFE_MS,
|
|
526
|
+
timeoutMs: Number.isFinite(input.timeoutMs) && input.timeoutMs > 0 ? input.timeoutMs : DEFAULT_TIMEOUT_MS,
|
|
527
|
+
queryPrefix: typeof input.queryPrefix === 'string' ? input.queryPrefix : defaultQueryPrefix(),
|
|
528
|
+
dim: clampInt(input.dim, defaultDim(), 1, 16384),
|
|
529
|
+
reranker: input.reranker ?? null,
|
|
530
|
+
judge: input.judge ?? null,
|
|
531
|
+
rerankMaxCandidates: clampInt(input.rerank?.maxCandidates ?? input.reranker?.maxCandidates, 24, 1, 200),
|
|
532
|
+
rerankWeight: Number.isFinite(input.rerank?.weight) ? Math.max(0, Math.min(1, input.rerank.weight)) : 0.6,
|
|
533
|
+
judgeMaxCandidates: clampInt(input.judgeOptions?.maxCandidates ?? input.judge?.maxCandidates, 12, 1, 200),
|
|
534
|
+
judgeMinProbability: Number.isFinite(input.judgeOptions?.minProbability) ? input.judgeOptions.minProbability : 0.2,
|
|
535
|
+
judgeKeepBest: input.judgeOptions?.keepBest !== false,
|
|
536
|
+
judgeRequired: input.judgeOptions?.required === true,
|
|
537
|
+
minVectorScore: Number.isFinite(input.minVectorScore) ? input.minVectorScore : 0,
|
|
538
|
+
exact: input.exact === true,
|
|
539
|
+
includeArmHits: input.includeArmHits === true,
|
|
540
|
+
seedIds: Array.isArray(input.seedIds) ? input.seedIds.slice(0, 64) : [],
|
|
541
|
+
graph: {
|
|
542
|
+
...graphInput,
|
|
543
|
+
maxHops: clampInt(graphInput.maxHops, 2, 1, 4),
|
|
544
|
+
seedsPerArm: clampInt(graphInput.seedsPerArm, 8, 1, 50),
|
|
545
|
+
frontierLimit: clampInt(graphInput.frontierLimit, 32, 1, 200),
|
|
546
|
+
rowLimit: clampInt(graphInput.rowLimit, 128, 16, 5000),
|
|
547
|
+
hopDecay: Number.isFinite(graphInput.hopDecay) && graphInput.hopDecay > 0 && graphInput.hopDecay <= 1
|
|
548
|
+
? graphInput.hopDecay
|
|
549
|
+
: 0.5,
|
|
550
|
+
minEdgeWeight: Number.isFinite(graphInput.minEdgeWeight) && graphInput.minEdgeWeight > 0
|
|
551
|
+
? graphInput.minEdgeWeight
|
|
552
|
+
: 0.01,
|
|
553
|
+
labels: Array.isArray(graphInput.labels) && graphInput.labels.length > 0
|
|
554
|
+
? graphInput.labels.filter((label) => EDGE_LABELS.includes(label))
|
|
555
|
+
: EDGE_LABELS,
|
|
556
|
+
limit: clampInt(graphInput.limit, Math.max(20, clampInt(input.limit, 12, 1, 200) * 2), 1, 200),
|
|
557
|
+
},
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function clampInt(value, fallback, min, max) {
|
|
562
|
+
const number = Number(value)
|
|
563
|
+
if (!Number.isFinite(number)) return fallback
|
|
564
|
+
return Math.min(max, Math.max(min, Math.floor(number)))
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 创建召回器。
|
|
569
|
+
*
|
|
570
|
+
* @param {object} options
|
|
571
|
+
* @param {object} [options.store] **已打开(或即将打开)的 TriviumDB 异步门面**;注入时本模块绝不 close 它。
|
|
572
|
+
* 不给则由本模块用 `createTriviumStore({ workspace, dir, dim: 384 })` 自建,并在 `close()` 时关闭。
|
|
573
|
+
* @param {string} [options.workspace] 分域键(`store.js` 的 `scopeOf` 口径);自建门面时必填。
|
|
574
|
+
* @param {string} [options.dir] 库目录(默认 `triviumDir()`,落在临时目录,绝不进仓库)。
|
|
575
|
+
* @param {object} [options.embedder] `embed.js` 的 `createEmbedder()`;缺省则向量臂恒为降级。
|
|
576
|
+
* @param {object} [options.arms] `{ text, vector, graph }` 三个布尔开关。
|
|
577
|
+
* @param {number} [options.dim] 期望的向量维度;默认取当前 profile(本地 384 / API 模型自己的宽度)。
|
|
578
|
+
*/
|
|
579
|
+
export function createTriviumRecall(options = {}) {
|
|
580
|
+
const dim = options.dim ?? defaultDim()
|
|
581
|
+
const embedder = options.embedder ?? null
|
|
582
|
+
if (embedder !== null && embedder.dim !== undefined && embedder.dim !== dim) {
|
|
583
|
+
throw recallError(
|
|
584
|
+
'KANABO_RECALL_DIMENSION',
|
|
585
|
+
`embedder 维度 ${embedder.dim} 与当前 profile 的 ${dim} 维不符。`,
|
|
586
|
+
{ details: { expected: dim, received: embedder.dim } })
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const ownsStore = options.store === undefined || options.store === null
|
|
590
|
+
let store = options.store ?? null
|
|
591
|
+
let opened = false
|
|
592
|
+
const counters = { recalls: 0, timeouts: 0, armFailures: 0, degradedRecalls: 0, closed: false }
|
|
593
|
+
|
|
594
|
+
function ensureStore() {
|
|
595
|
+
if (store !== null) return store
|
|
596
|
+
if (ownsStore) {
|
|
597
|
+
if (typeof options.workspace !== 'string' || options.workspace === '') {
|
|
598
|
+
throw recallError('KANABO_RECALL_WORKSPACE', '未注入 store 时必须提供非空的 workspace(分域键)。')
|
|
599
|
+
}
|
|
600
|
+
store = createTriviumStore({
|
|
601
|
+
workspace: options.workspace,
|
|
602
|
+
dir: options.dir,
|
|
603
|
+
dim,
|
|
604
|
+
idleMs: options.idleMs,
|
|
605
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
606
|
+
})
|
|
607
|
+
}
|
|
608
|
+
return store
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** 维度断言放在真正用到库之前:门面的 `stats().dim` 不需要拉起子进程就能读。 */
|
|
612
|
+
function assertStoreDim(handle) {
|
|
613
|
+
const actual = typeof handle?.stats === 'function' ? handle.stats().dim : undefined
|
|
614
|
+
if (actual !== undefined && actual !== dim) {
|
|
615
|
+
throw recallError(
|
|
616
|
+
'KANABO_RECALL_DIMENSION',
|
|
617
|
+
`TriviumDB 库的向量维度是 ${actual},当前 profile 要求 ${dim};`
|
|
618
|
+
+ '换向量模型必须换 profile(库文件名带模型后缀),不能拿旧库硬开。',
|
|
619
|
+
{ details: { expected: dim, received: actual } })
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async function open() {
|
|
624
|
+
const handle = ensureStore()
|
|
625
|
+
assertStoreDim(handle)
|
|
626
|
+
await handle.open()
|
|
627
|
+
opened = true
|
|
628
|
+
return handle
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** 显式种子(payload id)→ 节点 id;一条 TQL 就够,且用 JSON 字符串字面量,不拼裸文本。 */
|
|
632
|
+
async function resolveSeedIds(handle, seedIds) {
|
|
633
|
+
if (seedIds.length === 0) return []
|
|
634
|
+
const literals = seedIds.map((id) => JSON.stringify(String(id))).join(', ')
|
|
635
|
+
const rows = await handle.tql(`FIND {id: {$in: [${literals}]}} RETURN _.id AS nodeId, _ AS payload`)
|
|
636
|
+
const seeds = []
|
|
637
|
+
for (const row of Array.isArray(rows?.rows) ? rows.rows : []) {
|
|
638
|
+
const id = nodeIdOf(row?.nodeId)
|
|
639
|
+
const payload = unwrapNode(row?.payload)
|
|
640
|
+
if (id !== null) seeds.push({ id, meta: payload === null ? null : payloadMeta(payload, id) })
|
|
641
|
+
}
|
|
642
|
+
return seeds
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** 文本臂命中只有 id:缺元数据的一次性补齐(一条 TQL,用 OR 串,数字 id 绝不注入)。 */
|
|
646
|
+
async function fetchMeta(handle, nodeIds) {
|
|
647
|
+
const meta = new Map()
|
|
648
|
+
const ids = nodeIds.filter((id) => Number.isSafeInteger(id)).slice(0, 200)
|
|
649
|
+
if (ids.length === 0) return meta
|
|
650
|
+
const where = ids.map((id) => `n.id == ${id}`).join(' OR ')
|
|
651
|
+
const rows = await handle.tql(`MATCH (n) WHERE ${where} RETURN n.id AS nodeId, n AS payload`)
|
|
652
|
+
for (const row of Array.isArray(rows?.rows) ? rows.rows : []) {
|
|
653
|
+
const nodeId = nodeIdOf(row?.nodeId)
|
|
654
|
+
const payload = unwrapNode(row?.payload)
|
|
655
|
+
if (nodeId === null || payload === null) continue
|
|
656
|
+
meta.set(nodeId, payloadMeta(payload, nodeId))
|
|
657
|
+
}
|
|
658
|
+
return meta
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function seedMap(armHits, limit, explicit) {
|
|
662
|
+
const seeds = new Map()
|
|
663
|
+
for (const name of ['text', 'vector']) {
|
|
664
|
+
const arm = armHits[name]
|
|
665
|
+
if (arm === undefined || arm === null || arm.hits.length === 0) continue
|
|
666
|
+
const max = Math.max(...arm.hits.map((hit) => hit.score), Number.EPSILON)
|
|
667
|
+
for (const hit of arm.hits.slice(0, limit)) {
|
|
668
|
+
const normalized = Math.max(0, Math.min(1, hit.score / max))
|
|
669
|
+
const previous = seeds.get(hit.id)
|
|
670
|
+
if (previous === undefined || previous.score < normalized) seeds.set(hit.id, { score: normalized, path: null })
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
for (const seed of explicit) {
|
|
674
|
+
if (!seeds.has(seed.id)) seeds.set(seed.id, { score: 1, path: [seed.id] })
|
|
675
|
+
}
|
|
676
|
+
return seeds
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async function run(query, callOptions) {
|
|
680
|
+
const started = performance.now()
|
|
681
|
+
const config = normalizeOptions({ ...options, ...callOptions })
|
|
682
|
+
const handle = await open()
|
|
683
|
+
const armsEnabled = config.arms
|
|
684
|
+
const timings = { text: 0, vector: 0, graph: 0, fusion: 0, rerank: 0, judge: 0, pack: 0 }
|
|
685
|
+
const armSummary = {}
|
|
686
|
+
const armHits = {}
|
|
687
|
+
const meta = new Map()
|
|
688
|
+
|
|
689
|
+
function counterArmFailure(error, name, summary) {
|
|
690
|
+
summary[name] = {
|
|
691
|
+
ok: false,
|
|
692
|
+
count: 0,
|
|
693
|
+
degraded: null,
|
|
694
|
+
error: {
|
|
695
|
+
code: typeof error?.code === 'string' ? error.code : 'KANABO_RECALL_ARM',
|
|
696
|
+
message: String(error?.message ?? error),
|
|
697
|
+
},
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (armsEnabled.text === true) {
|
|
702
|
+
const at = performance.now()
|
|
703
|
+
try {
|
|
704
|
+
const arm = await textArm(handle, query, config.armLimit)
|
|
705
|
+
armHits.text = { hits: arm.hits, degraded: arm.degraded }
|
|
706
|
+
armSummary.text = { ok: true, count: arm.hits.length, degraded: arm.degraded }
|
|
707
|
+
} catch (error) {
|
|
708
|
+
counterArmFailure(error, 'text', armSummary)
|
|
709
|
+
}
|
|
710
|
+
timings.text = roundMs(performance.now() - at)
|
|
711
|
+
} else {
|
|
712
|
+
armSummary.text = { ok: true, enabled: false, count: 0 }
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
if (armsEnabled.vector === true) {
|
|
716
|
+
const at = performance.now()
|
|
717
|
+
try {
|
|
718
|
+
const arm = await vectorArm(handle, query, config.armLimit, embedder, config)
|
|
719
|
+
armHits.vector = { hits: arm.hits, degraded: arm.degraded }
|
|
720
|
+
armSummary.vector = { ok: true, count: arm.hits.length, degraded: arm.degraded }
|
|
721
|
+
for (const [id, entry] of arm.meta ?? []) meta.set(id, entry)
|
|
722
|
+
} catch (error) {
|
|
723
|
+
counterArmFailure(error, 'vector', armSummary)
|
|
724
|
+
}
|
|
725
|
+
timings.vector = roundMs(performance.now() - at)
|
|
726
|
+
} else {
|
|
727
|
+
armSummary.vector = { ok: true, enabled: false, count: 0 }
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// 锚点剔除(复核 N1)必须发生在建种子之前:文本/向量命中先补齐 payload,再统一丢掉
|
|
731
|
+
// `graph_role:'anchor'`。这样锚点既不会成为命中,也不会成为图臂的扩散起点。
|
|
732
|
+
const anchorCandidates = [...new Set([
|
|
733
|
+
...(armHits.text?.hits ?? []).map((hit) => hit.id),
|
|
734
|
+
...(armHits.vector?.hits ?? []).map((hit) => hit.id),
|
|
735
|
+
])].filter((id) => !meta.has(id))
|
|
736
|
+
// `fetchMeta` 一次只接受 200 个 id,而两臂最多各取 200 个命中,所以按 200 分段补齐。
|
|
737
|
+
for (let offset = 0; offset < anchorCandidates.length; offset += 200) {
|
|
738
|
+
for (const [id, entry] of await fetchMeta(handle, anchorCandidates.slice(offset, offset + 200))) meta.set(id, entry)
|
|
739
|
+
}
|
|
740
|
+
for (const name of ['text', 'vector']) {
|
|
741
|
+
const arm = armHits[name]
|
|
742
|
+
if (arm === undefined) continue
|
|
743
|
+
const kept = dropAnchors(arm.hits, meta)
|
|
744
|
+
const removed = arm.hits.length - kept.length
|
|
745
|
+
if (removed === 0) continue
|
|
746
|
+
arm.hits = kept
|
|
747
|
+
const summary = armSummary[name]
|
|
748
|
+
if (summary !== undefined) {
|
|
749
|
+
summary.count = kept.length
|
|
750
|
+
summary.anchorsFiltered = removed
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (armsEnabled.graph === true) {
|
|
755
|
+
const at = performance.now()
|
|
756
|
+
try {
|
|
757
|
+
const explicit = await resolveSeedIds(handle, config.seedIds)
|
|
758
|
+
for (const seed of explicit) {
|
|
759
|
+
if (seed.meta !== null && !meta.has(seed.id)) meta.set(seed.id, seed.meta)
|
|
760
|
+
}
|
|
761
|
+
const seeds = seedMap(armHits, config.graph.seedsPerArm, explicit)
|
|
762
|
+
const arm = await graphArm(handle, seeds, config.graph)
|
|
763
|
+
armHits.graph = { hits: arm.hits, degraded: arm.degraded }
|
|
764
|
+
armSummary.graph = {
|
|
765
|
+
ok: true,
|
|
766
|
+
count: arm.hits.length,
|
|
767
|
+
degraded: arm.degraded,
|
|
768
|
+
seeds: seeds.size,
|
|
769
|
+
traversed: arm.traversed ?? [],
|
|
770
|
+
}
|
|
771
|
+
for (const [id, entry] of arm.meta ?? []) if (!meta.has(id)) meta.set(id, entry)
|
|
772
|
+
} catch (error) {
|
|
773
|
+
counterArmFailure(error, 'graph', armSummary)
|
|
774
|
+
}
|
|
775
|
+
timings.graph = roundMs(performance.now() - at)
|
|
776
|
+
} else {
|
|
777
|
+
armSummary.graph = { ok: true, enabled: false, count: 0 }
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const fusedAt = performance.now()
|
|
781
|
+
const candidates = []
|
|
782
|
+
for (const name of ARM_NAMES) {
|
|
783
|
+
const arm = armHits[name]
|
|
784
|
+
if (arm === undefined) continue
|
|
785
|
+
for (const hit of arm.hits) candidates.push(hit.id)
|
|
786
|
+
}
|
|
787
|
+
const missing = [...new Set(candidates)].filter((id) => !meta.has(id))
|
|
788
|
+
for (const [id, entry] of await fetchMeta(handle, missing)) meta.set(id, entry)
|
|
789
|
+
|
|
790
|
+
const metaOf = (id) => meta.get(id)
|
|
791
|
+
const now = Number.isFinite(callOptions?.now) ? callOptions.now : options.now
|
|
792
|
+
const fused = fuseArms(armHits, { ...config, now, metaOf })
|
|
793
|
+
timings.fusion = roundMs(performance.now() - fusedAt)
|
|
794
|
+
if (fused.length === 0) {
|
|
795
|
+
// 一条都没召回是**正常结果**(等价于旧 recall 返回空);只有「所有启用的臂都失败」才是错误。
|
|
796
|
+
const enabled = ARM_NAMES.filter((name) => armsEnabled[name] === true)
|
|
797
|
+
const failed = enabled.filter((name) => armSummary[name]?.ok === false)
|
|
798
|
+
if (enabled.length > 0 && failed.length === enabled.length) {
|
|
799
|
+
throw recallError('KANABO_RECALL_ALL_ARMS_FAILED', '所有启用的召回臂都失败。', {
|
|
800
|
+
details: { arms: armSummary },
|
|
801
|
+
})
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const rerankAt = performance.now()
|
|
806
|
+
const reranked = await applyRerank(fused, query, {
|
|
807
|
+
client: config.reranker,
|
|
808
|
+
maxCandidates: config.rerankMaxCandidates,
|
|
809
|
+
weight: config.rerankWeight,
|
|
810
|
+
})
|
|
811
|
+
timings.rerank = roundMs(performance.now() - rerankAt)
|
|
812
|
+
const judgeAt = performance.now()
|
|
813
|
+
const judged = await applyJudge(reranked.list, query, {
|
|
814
|
+
client: config.judge,
|
|
815
|
+
maxCandidates: config.judgeMaxCandidates,
|
|
816
|
+
minProbability: config.judgeMinProbability,
|
|
817
|
+
keepBest: config.judgeKeepBest,
|
|
818
|
+
required: config.judgeRequired === true,
|
|
819
|
+
state: judgeState(query),
|
|
820
|
+
})
|
|
821
|
+
timings.judge = roundMs(performance.now() - judgeAt)
|
|
822
|
+
const ordered = judged.list
|
|
823
|
+
|
|
824
|
+
const ranked = ordered.slice(0, config.limit).map((hit) => ({ ...hit, chars: charCost(hit.text) }))
|
|
825
|
+
if (config.includeArmHits) {
|
|
826
|
+
for (const name of ARM_NAMES) {
|
|
827
|
+
const arm = armHits[name]
|
|
828
|
+
if (arm === undefined || armSummary[name] === undefined) continue
|
|
829
|
+
armSummary[name].hits = arm.hits.map((hit, index) => ({
|
|
830
|
+
id: hit.id,
|
|
831
|
+
score: hit.score,
|
|
832
|
+
why: name === 'graph'
|
|
833
|
+
? { arm: 'graph', rank: index + 1, score: hit.score, path: hit.why?.path ?? [], edges: hit.why?.edges ?? [] }
|
|
834
|
+
: { arm: name, rank: index + 1, score: hit.score },
|
|
835
|
+
}))
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const packAt = performance.now()
|
|
839
|
+
const packed = packByBudget(ranked, config.budgetChars)
|
|
840
|
+
timings.pack = roundMs(performance.now() - packAt)
|
|
841
|
+
|
|
842
|
+
counters.recalls += 1
|
|
843
|
+
if (Object.values(armSummary).some((arm) => arm.ok === false)) counters.armFailures += 1
|
|
844
|
+
if (Object.values(armSummary).some((arm) => typeof arm.degraded === 'string')) counters.degradedRecalls += 1
|
|
845
|
+
|
|
846
|
+
return {
|
|
847
|
+
query: { text: String(query ?? ''), arms: { ...armsEnabled } },
|
|
848
|
+
hits: packed.hits,
|
|
849
|
+
dropped: packed.dropped,
|
|
850
|
+
budget: packed.budget,
|
|
851
|
+
truncated: packed.truncated,
|
|
852
|
+
ranked: ranked.length,
|
|
853
|
+
candidates: fused.length,
|
|
854
|
+
arms: armSummary,
|
|
855
|
+
stages: { rerank: reranked.stage, judge: judged.stage },
|
|
856
|
+
timings: { ...timings, total: roundMs(performance.now() - started) },
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* 召回入口。`callOptions` 与构造参数同形,可逐次覆盖(`arms`、`limit`、`budgetChars`、`graph`、`now`…)。
|
|
862
|
+
* 总期限由 `timeoutMs` 兜底:超时以 `KANABO_RECALL_TIMEOUT` 拒绝,绝不挂起调用方。
|
|
863
|
+
*/
|
|
864
|
+
async function recall(query, callOptions = {}) {
|
|
865
|
+
if (counters.closed) throw recallError('KANABO_RECALL_CLOSED', '召回器已关闭。')
|
|
866
|
+
const timeoutMs = Number.isFinite(callOptions.timeoutMs) && callOptions.timeoutMs > 0
|
|
867
|
+
? callOptions.timeoutMs
|
|
868
|
+
: (Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_TIMEOUT_MS)
|
|
869
|
+
try {
|
|
870
|
+
return await withTimeout(run(query, callOptions), timeoutMs, 'recall()')
|
|
871
|
+
} catch (error) {
|
|
872
|
+
if (error?.code === 'KANABO_RECALL_TIMEOUT') counters.timeouts += 1
|
|
873
|
+
throw error
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
return {
|
|
878
|
+
recall,
|
|
879
|
+
open,
|
|
880
|
+
/** 已注入的门面由调用方负责关闭;自建的那一个在这里关(幂等)。 */
|
|
881
|
+
async close() {
|
|
882
|
+
counters.closed = true
|
|
883
|
+
if (!ownsStore || store === null) return { closed: true, owned: false }
|
|
884
|
+
const result = await store.close()
|
|
885
|
+
return { ...result, owned: true }
|
|
886
|
+
},
|
|
887
|
+
stats() {
|
|
888
|
+
return { ...counters, opened, ownsStore, dim }
|
|
889
|
+
},
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/** 毫秒取一位小数,便于把 p50/p95 直接写进证据。 */
|
|
894
|
+
function roundMs(value) {
|
|
895
|
+
return Math.round(value * 10) / 10
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* 分位数(最近秩法,无插值):`p50/p95` 直接可写进证据。
|
|
900
|
+
* 空数组返回 null,绝不返回 0 冒充测量值。
|
|
901
|
+
*/
|
|
902
|
+
export function percentiles(values, points = [50, 95]) {
|
|
903
|
+
const list = (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value)).sort((a, b) => a - b)
|
|
904
|
+
if (list.length === 0) return null
|
|
905
|
+
const out = {}
|
|
906
|
+
for (const point of points) {
|
|
907
|
+
const rank = Math.min(list.length - 1, Math.max(0, Math.ceil((point / 100) * list.length) - 1))
|
|
908
|
+
out[`p${point}`] = list[rank]
|
|
909
|
+
}
|
|
910
|
+
out.count = list.length
|
|
911
|
+
out.min = list[0]
|
|
912
|
+
out.max = list[list.length - 1]
|
|
913
|
+
return out
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
export default createTriviumRecall
|