@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.
@@ -0,0 +1,447 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * TriviumDB 子进程 worker:`store-trivium.js` 的**唯一**数据库持有者。
4
+ *
5
+ * 为什么必须是独立进程(实测,见 `docs/research/triviumdb.md` §二/§三):
6
+ * TriviumDB 0.9.3 的并发模型是**文件级独占租约**——一个写者持有时,第二个句柄(含 `readOnly`)
7
+ * 在 open 阶段就抛 `TDB_DATABASE_LOCKED`。所以插件进程永远不 open,只通过本文件间接读写;
8
+ * 又因为库是同步阻塞的原生 addon,把它关在子进程里也顺带把事件循环让给插件。
9
+ *
10
+ * 协议:**NDJSON over stdin/stdout**(一行一个 JSON)。
11
+ * - 父进程 → 本进程:`{ rid, op, ...参数 }`;子进程 → 父进程:`{ rid, ok, value }` 或 `{ rid, ok: false, error }`。
12
+ * 请求号必须叫 `rid` 而不是 `id`:`insert` 的参数自带 `id`(显式节点 id),同一个名字会让响应落到
13
+ * 错误的请求号上,调用方会一直等到超时(已实测:重复显式 id 时每次必挂)。
14
+ * - 请求由单线程按到达顺序处理,因此同一子进程内的写天然串行;`rid` 由父进程单调递增。
15
+ * - 选管道而不是 IPC:帧边界明确(stdout 只允许 NDJSON),且**父进程消失时 stdin EOF 立刻可知**,
16
+ * 孤儿进程不会带着数据库租约常驻。
17
+ * - 退出前的最后一行是 `{ type: 'idle-exit' }` 或 `{ type: 'fatal', error }`,两者都不带 id。
18
+ *
19
+ * 两条不能错过的语义:
20
+ * 1. `loadTextIndex` 必须显式 true——0.9.3 的默认值是 false,且**不带 flag 时 `TEXT` 查询静默返回 0 行**。
21
+ * 本文件把开库选项冻结成常量,并在唯一开库入口断言,任何调用方都无法把它关掉(行为证明见证据 (f))。
22
+ * 2. 写成功回执前必须 `flush()`——父进程只在收到回执后向调用方确认,所以回执即「已落 WAL + flush_ok」。
23
+ *
24
+ * 空闲退出:主计时器归父进程(它知道有没有在途请求,不存在「刚发请求子进程正好在退」的竞争);
25
+ * 本文件只保留一个 2 倍空闲期的**兜底**计时器,用于父进程异常消失但管道未关的极端情况。
26
+ */
27
+ import { createInterface } from 'node:readline'
28
+ import { TriviumDB } from 'triviumdb'
29
+ import { EDGE_LABELS } from './contract.js'
30
+
31
+ const CONFIG_ENV = 'KANABO_TRIVIUM_CHILD'
32
+
33
+ /**
34
+ * 开库选项:`loadTextIndex` 只能为 true。
35
+ * 引擎没有「读回该 flag」的 getter,所以这里做结构性断言(冻结常量 + 唯一入口检查),
36
+ * 行为证明(TEXT 有行 / 关掉 flag 后 0 行)放在任务 10 的证据 (f) 里。
37
+ */
38
+ const OPEN_OPTIONS = Object.freeze({ loadTextIndex: true, storageMode: 'mmap' })
39
+ const SYNC_MODES = new Set(['full', 'normal', 'off'])
40
+
41
+ const config = readConfig()
42
+ const dim = Number.isInteger(config?.dim) && config.dim > 0 ? config.dim : Number(config?.dim ?? 0) || 1536
43
+ const syncMode = SYNC_MODES.has(config?.syncMode) ? config.syncMode : 'normal'
44
+ const idleMs = Number.isFinite(config?.idleMs) && config.idleMs > 0 ? config.idleMs : 15000
45
+
46
+ let db = null
47
+ let openMs = 0
48
+ let served = 0
49
+ let idleTimer = null
50
+
51
+ function readConfig() {
52
+ try {
53
+ const parsed = JSON.parse(process.env[CONFIG_ENV] ?? '')
54
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+
60
+ function send(message) {
61
+ process.stdout.write(`${JSON.stringify(message)}\n`)
62
+ }
63
+
64
+ /** 带稳定 `code` 的错误,形状与 store.js 的 `storeError` 一致。 */
65
+ function coded(code, message, details) {
66
+ const error = new Error(message)
67
+ error.code = code
68
+ if (details !== undefined) error.details = details
69
+ return error
70
+ }
71
+
72
+ function errorInfo(error) {
73
+ return {
74
+ code: typeof error?.code === 'string' ? error.code : 'KANABO_TRIVIUM_CHILD',
75
+ message: String(error?.message ?? error),
76
+ details: error?.details ?? null,
77
+ }
78
+ }
79
+
80
+ function failFast(message, code) {
81
+ send({ type: 'fatal', error: { code, message } })
82
+ process.exit(2)
83
+ }
84
+
85
+ if (config === null || typeof config.path !== 'string' || config.path.length === 0) {
86
+ failFast(`${CONFIG_ENV} 缺失或不是合法 JSON(需要 { path, dim, syncMode, idleMs })`, 'KANABO_TRIVIUM_CONFIG')
87
+ }
88
+ if (config.loadTextIndex === false) {
89
+ // 唯一能走到这里的路径是「有人显式传了 false」:拒绝,而不是让全文检索静默失效。
90
+ failFast('子进程拒绝在 loadTextIndex:false 下开库(TEXT 会静默返回 0 行)', 'KANABO_TRIVIUM_TEXT_INDEX')
91
+ }
92
+
93
+ function openDb() {
94
+ if (db !== null) return
95
+ const options = { dim, syncMode, ...OPEN_OPTIONS }
96
+ if (options.loadTextIndex !== true || !Object.isFrozen(OPEN_OPTIONS)) {
97
+ throw coded('KANABO_TRIVIUM_TEXT_INDEX', '开库必须 loadTextIndex:true')
98
+ }
99
+ const startedAt = performance.now()
100
+ db = new TriviumDB(config.path, options)
101
+ openMs = Math.round((performance.now() - startedAt) * 10) / 10
102
+ }
103
+
104
+ function vectorOf(vector) {
105
+ if (vector === undefined || vector === null) return new Array(dim).fill(0)
106
+ if (!Array.isArray(vector)) throw coded('KANABO_TRIVIUM_VECTOR', 'vector 必须是数组')
107
+ if (vector.length !== dim) {
108
+ throw coded('KANABO_TRIVIUM_VECTOR', `vector 维度应为 ${dim},实际 ${vector.length}`, { dim, got: vector.length })
109
+ }
110
+ return vector
111
+ }
112
+
113
+ function insertOne(item) {
114
+ const vector = vectorOf(item?.vector)
115
+ const payload = item?.payload ?? null
116
+ let id
117
+ if (item?.id === undefined || item.id === null) {
118
+ id = db.insert(vector, payload)
119
+ } else {
120
+ id = Number(item.id)
121
+ if (!Number.isSafeInteger(id) || id < 0) {
122
+ throw coded('KANABO_TRIVIUM_ID', `显式 id 必须是 JavaScript 安全非负整数:${item.id}`)
123
+ }
124
+ db.insertWithId(id, vector, payload)
125
+ }
126
+ if (typeof item?.text === 'string' && item.text.length > 0) db.indexText(id, item.text)
127
+ return id
128
+ }
129
+
130
+ /** 边标签只认契约里的三个:写进库的标签若不在枚举内,图臂按标签遍历时就永远查不到它。 */
131
+ const EDGE_LABELS_SET = new Set(EDGE_LABELS)
132
+
133
+ function nodeIdArg(value, field) {
134
+ if (value === undefined || value === null) {
135
+ throw coded('KANABO_TRIVIUM_LINK_NODE', `link/edges 缺少 ${field}(需要节点 id)`)
136
+ }
137
+ const id = typeof value === 'number' ? value : Number(value)
138
+ if (!Number.isSafeInteger(id) || id < 0) {
139
+ throw coded('KANABO_TRIVIUM_LINK_NODE', `${field} 必须是 JavaScript 安全非负整数节点 id:${String(value)}`)
140
+ }
141
+ return id
142
+ }
143
+
144
+ /**
145
+ * 建边:**幂等 upsert**。唯一键是 (from, label, to),重放同一组参数只会覆盖权重/元数据,
146
+ * 不会多出一条边——迁移的「重跑不重复建边」就落在这个原语上,而不是调用方的去重逻辑。
147
+ * 两个端点都必须已存在:悬空边会让图臂在扩散时拿到不存在的目标,引擎也会立刻拒绝。
148
+ */
149
+ /**
150
+ * 建边:**幂等 upsert**。唯一键是 (from, label, to),重放同一组参数只会覆盖权重/元数据,
151
+ * 不会多出一条边——迁移的「重跑不重复建边」就落在这个原语上,而不是调用方的去重逻辑。
152
+ * 两个端点都必须已存在:悬空边会让图臂在扩散时拿到不存在的目标,引擎也会立刻拒绝。
153
+ *
154
+ * 支持批量形(`edges: [...]`):一次请求写一组边、一次 flush。实测 flush 约 130ms,
155
+ * 逐条 flush 会让 2000 条边变成 4 分钟;批量写把边写成本压到与 `batch` 插节点同一量级。
156
+ */
157
+ function linkEdges(message) {
158
+ const list = Array.isArray(message.edges) ? message.edges : [message]
159
+ if (list.length === 0) throw coded('KANABO_TRIVIUM_LINK_EDGE', 'link 至少要有一条边')
160
+ for (const edge of list) {
161
+ if (edge === null || typeof edge !== 'object' || Array.isArray(edge)) {
162
+ throw coded('KANABO_TRIVIUM_LINK_EDGE', '每条边必须是 { from, to, label, weight?, metadata? } 对象')
163
+ }
164
+ }
165
+ const results = list.map(linkEdge)
166
+ db.flush()
167
+ return {
168
+ edges: results,
169
+ count: results.length,
170
+ created: results.filter((edge) => edge.created).length,
171
+ edgeCount: graphSummary().edgeCount,
172
+ }
173
+ }
174
+
175
+ function linkEdge(message) {
176
+ const from = nodeIdArg(message.from, 'from')
177
+ const to = nodeIdArg(message.to, 'to')
178
+ const label = message.label
179
+ if (typeof label !== 'string' || !EDGE_LABELS_SET.has(label)) {
180
+ throw coded('KANABO_TRIVIUM_LINK_LABEL', `label 必须是 [${EDGE_LABELS.join(', ')}] 之一(收到 ${String(label)})`, {
181
+ labels: [...EDGE_LABELS],
182
+ received: label ?? null,
183
+ })
184
+ }
185
+ const weight = message.weight === undefined || message.weight === null ? 1 : message.weight
186
+ if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0 || weight > 1) {
187
+ throw coded('KANABO_TRIVIUM_LINK_WEIGHT', `weight 必须是 0..1 之间的有限数(收到 ${String(weight)})`)
188
+ }
189
+ const metadata = message.metadata === undefined ? null : message.metadata
190
+ if (metadata !== null && (typeof metadata !== 'object' || Array.isArray(metadata))) {
191
+ throw coded('KANABO_TRIVIUM_LINK_METADATA', 'metadata 只能是 JSON 对象或 null')
192
+ }
193
+ if (!db.contains(from)) throw coded('KANABO_TRIVIUM_NODE_NOT_FOUND', `link 的 from 节点不存在:${from}`, { id: from })
194
+ if (!db.contains(to)) throw coded('KANABO_TRIVIUM_NODE_NOT_FOUND', `link 的 to 节点不存在:${to}`, { id: to })
195
+ const existed = db.getEdge(from, to, label) !== null
196
+ db.upsertEdge(from, to, label, weight, metadata)
197
+ return { from, to, label, weight, metadata, created: !existed }
198
+ }
199
+
200
+ /** 图规模摘要:`edge_count` 是权威的边数,`label_stats` 直接给出每个标签的边数(无需扫全表)。 */
201
+ function graphSummary() {
202
+ const stats = db.graphStats()
203
+ const labels = {}
204
+ for (const [label, value] of Object.entries(stats?.label_stats ?? {})) {
205
+ labels[label] = Number(value?.edge_count ?? 0)
206
+ }
207
+ return {
208
+ nodeCount: Number(stats?.node_count ?? db.nodeCount()),
209
+ edgeCount: Number(stats?.edge_count ?? 0),
210
+ isolatedNodeCount: Number(stats?.isolated_node_count ?? 0),
211
+ labelCount: Number(stats?.label_count ?? Object.keys(labels).length),
212
+ labels,
213
+ }
214
+ }
215
+
216
+ function edgeRow(row) {
217
+ const metadata = row?.m === undefined ? null : row.m
218
+ return { from: Number(row.s), to: Number(row.t), label: String(row.l), weight: Number(row.w), metadata }
219
+ }
220
+
221
+ /** 读边:给 `from` 时读该节点的出边(引擎的邻接表),不给时用一遍 TQL 扫全图(有上限)。 */
222
+ function readEdges(message) {
223
+ if (message.from === undefined || message.from === null) {
224
+ const limit = Number.isSafeInteger(message.limit) && message.limit > 0 ? Math.min(message.limit, 200_000) : 1000
225
+ const rows = db.tql(
226
+ `MATCH (a)-[r]->(b) RETURN a.id AS s, b.id AS t, r.label AS l, r.weight AS w, r.metadata AS m LIMIT ${limit}`)
227
+ return { from: null, edges: (Array.isArray(rows) ? rows : []).map(edgeRow), graph: graphSummary() }
228
+ }
229
+ const from = nodeIdArg(message.from, 'from')
230
+ if (!db.contains(from)) {
231
+ throw coded('KANABO_TRIVIUM_NODE_NOT_FOUND', `edges 的 from 节点不存在:${from}`, { id: from })
232
+ }
233
+ const edges = db.getEdges(from).map((edge) => ({
234
+ from,
235
+ to: Number(edge?.targetId),
236
+ label: String(edge?.label),
237
+ weight: Number(edge?.weight),
238
+ metadata: edge?.metadata === undefined ? null : edge.metadata,
239
+ }))
240
+ return { from, edges, graph: graphSummary() }
241
+ }
242
+
243
+ function batchInsert(items) {
244
+ if (!Array.isArray(items)) throw coded('KANABO_TRIVIUM_BATCH', 'batch 的 items 必须是数组')
245
+ const ids = []
246
+ // 全部自带 id 时才走引擎的批量写;否则逐条插入(混合 id 语义由 insert 统一处理)。
247
+ const explicit = items.every((item) => item?.id !== undefined && item?.id !== null)
248
+ if (!explicit) {
249
+ for (const item of items) ids.push(insertOne(item))
250
+ } else {
251
+ const numeric = items.map((item) => {
252
+ const id = Number(item.id)
253
+ if (!Number.isSafeInteger(id) || id < 0) {
254
+ throw coded('KANABO_TRIVIUM_ID', `显式 id 必须是 JavaScript 安全非负整数:${item.id}`)
255
+ }
256
+ return id
257
+ })
258
+ db.batchInsertWithIds(numeric, items.map((item) => vectorOf(item.vector)), items.map((item) => item.payload ?? null))
259
+ for (let index = 0; index < items.length; index += 1) {
260
+ const text = items[index]?.text
261
+ if (typeof text === 'string' && text.length > 0) db.indexText(numeric[index], text)
262
+ }
263
+ ids.push(...numeric)
264
+ }
265
+ return ids
266
+ }
267
+
268
+ function handle(message) {
269
+ switch (message.op) {
270
+ case 'ping':
271
+ return { pid: process.pid, nodeCount: db === null ? 0 : db.nodeCount() }
272
+ case 'open': {
273
+ openDb()
274
+ return {
275
+ pid: process.pid,
276
+ path: config.path,
277
+ dim: db.dim(),
278
+ nodeCount: db.nodeCount(),
279
+ openMs,
280
+ loadTextIndex: OPEN_OPTIONS.loadTextIndex,
281
+ storageMode: OPEN_OPTIONS.storageMode,
282
+ }
283
+ }
284
+ case 'insert': {
285
+ openDb()
286
+ const id = insertOne(message)
287
+ db.flush()
288
+ return { id, nodeCount: db.nodeCount() }
289
+ }
290
+ case 'batch': {
291
+ openDb()
292
+ const ids = batchInsert(message.items)
293
+ db.flush()
294
+ return { ids, count: ids.length, nodeCount: db.nodeCount() }
295
+ }
296
+ case 'search': {
297
+ openDb()
298
+ const hits = db.search(
299
+ vectorOf(message.vector),
300
+ message.topK ?? 5,
301
+ message.expandDepth ?? 0,
302
+ message.minScore ?? 0,
303
+ message.payloadFilter ?? null,
304
+ message.exact ?? false,
305
+ )
306
+ return { hits }
307
+ }
308
+ case 'tql': {
309
+ openDb()
310
+ return { rows: db.tql(String(message.query ?? '')) }
311
+ }
312
+ case 'link': {
313
+ openDb()
314
+ return linkEdges(message)
315
+ }
316
+ case 'edges': {
317
+ openDb()
318
+ return readEdges(message)
319
+ }
320
+ case 'index': {
321
+ openDb()
322
+ const field = message.field
323
+ if (typeof field !== 'string' || field.length === 0) {
324
+ throw coded('KANABO_TRIVIUM_INDEX', 'index 需要非空字符串 field')
325
+ }
326
+ const kind = message.kind ?? 'ordered'
327
+ if (kind !== 'ordered') {
328
+ throw coded('KANABO_TRIVIUM_INDEX', `只支持 kind:'ordered'(收到 ${String(kind)})`)
329
+ }
330
+ db.createOrderedIndex(field)
331
+ db.flush()
332
+ return { field, kind, indexes: db.indexInfo() }
333
+ }
334
+ case 'commit': {
335
+ openDb()
336
+ db.flush()
337
+ return { flushed: true, nodeCount: db.nodeCount(), graph: graphSummary() }
338
+ }
339
+ // 删除节点。引擎的 `delete` 是**三层原子联删**(向量 / payload / 全部关联边),
340
+ // 所以调用方不需要自己先拆边,也不会有孤立边。这是 GAP-9「按来源清除」的基座。
341
+ case 'delete': {
342
+ openDb()
343
+ const ids = Array.isArray(message.ids) ? message.ids.map((id) => Number(id)).filter((id) => Number.isSafeInteger(id) && id > 0) : []
344
+ if (ids.length === 0) throw coded('KANABO_TRIVIUM_DELETE', 'delete 需要非空的节点 id 数组')
345
+ const before = ids.filter((id) => db.contains(id)).length
346
+ const removed = typeof db.deleteManyAtomic === 'function' ? db.deleteManyAtomic(ids) : (() => {
347
+ let count = 0
348
+ for (const id of ids) if (db.contains(id)) { db.delete(id); count += 1 }
349
+ return count
350
+ })()
351
+ db.flush()
352
+ return { requested: ids.length, present: before, removed, nodeCount: db.nodeCount(), graph: graphSummary() }
353
+ }
354
+ case 'stats':
355
+ return {
356
+ pid: process.pid,
357
+ openMs,
358
+ served,
359
+ nodeCount: db === null ? 0 : db.nodeCount(),
360
+ loadTextIndex: OPEN_OPTIONS.loadTextIndex,
361
+ }
362
+ default:
363
+ throw coded('KANABO_TRIVIUM_OP', `未知操作:${String(message.op)}`)
364
+ }
365
+ }
366
+
367
+ /** 关闭并返回摘要;重复调用安全。 */
368
+ function closeDb() {
369
+ if (db === null) return { nodeCount: 0, openMs }
370
+ const nodeCount = db.nodeCount()
371
+ try {
372
+ db.flush()
373
+ } catch {
374
+ // 兜底:flush 失败也要 close,close 自己还会再 flush 一次。
375
+ }
376
+ try {
377
+ db.close()
378
+ } catch {
379
+ // 关闭失败时进程即将退出,内核对 mmap/WAL 的回收等同 close。
380
+ }
381
+ db = null
382
+ return { nodeCount, openMs }
383
+ }
384
+
385
+ function armIdle() {
386
+ clearTimeout(idleTimer)
387
+ // 兜底计时器:正常路径由父进程的 shutdown 请求触发,这里只在父进程消失时救人。
388
+ idleTimer = setTimeout(() => {
389
+ const summary = closeDb()
390
+ process.stdout.write(`${JSON.stringify({ type: 'idle-exit', by: 'child-backstop', pid: process.pid, ...summary })}\n`, () => {
391
+ process.exit(0)
392
+ })
393
+ }, Math.max(idleMs * 2, idleMs + 5000))
394
+ idleTimer.unref?.()
395
+ }
396
+
397
+ function shutdown(message) {
398
+ const summary = closeDb()
399
+ const line = `${JSON.stringify({
400
+ id: message.rid,
401
+ ok: true,
402
+ value: { closed: true, pid: process.pid, ...summary },
403
+ })}\n`
404
+ // 回执必须在退出前真正写进管道,否则父进程会看到「子进程没了、请求也没回」。
405
+ process.stdout.write(line, () => process.exit(0))
406
+ }
407
+
408
+ const reader = createInterface({ input: process.stdin, crlfDelay: Infinity })
409
+
410
+ reader.on('line', (line) => {
411
+ const trimmed = line.trim()
412
+ if (trimmed === '') return
413
+ let message
414
+ try {
415
+ message = JSON.parse(trimmed)
416
+ } catch {
417
+ send({ type: 'fatal', error: { code: 'KANABO_TRIVIUM_FRAME', message: '父进程发来的不是合法 NDJSON' } })
418
+ return
419
+ }
420
+ if (message?.op === 'shutdown') {
421
+ shutdown(message)
422
+ return
423
+ }
424
+ try {
425
+ const value = handle(message)
426
+ served += 1
427
+ send({ rid: message.rid, ok: true, value })
428
+ } catch (error) {
429
+ send({ rid: message.rid, ok: false, error: errorInfo(error) })
430
+ }
431
+ armIdle()
432
+ })
433
+
434
+ // 父进程退出或关闭管道:孤儿进程不得继续持有数据库租约。
435
+ reader.on('close', () => {
436
+ closeDb()
437
+ process.exit(0)
438
+ })
439
+
440
+ for (const signal of ['SIGTERM', 'SIGINT']) {
441
+ process.on(signal, () => {
442
+ closeDb()
443
+ process.exit(0)
444
+ })
445
+ }
446
+
447
+ armIdle()