@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,510 @@
1
+ /**
2
+ * TriviumDB 异步门面(P1 任务 10):数据库跑在**短命子进程**里,插件进程只发请求。
3
+ *
4
+ * 三条实测约束决定了这个形状(见 `docs/research/triviumdb.md`):
5
+ * 1. TriviumDB 0.9.3 是**文件级独占租约**:一个写者持有时,第二个句柄(含 readOnly)在 open 就抛
6
+ * `TDB_DATABASE_LOCKED`。所以「一个工作区 = 一个库 = 一个活句柄 = 一个子进程」,本文件**永不 import
7
+ * `triviumdb`**,也永不 open;它只写 NDJSON 到子进程的 stdin。
8
+ * 2. 库 API 全部同步阻塞,放进插件线程会卡住事件循环;关进子进程后阻塞只发生在那个短命进程里。
9
+ * 3. 冷启动约 210ms,进程退出后 RSS 归还给宿主(fork +0.3MB / worker_threads +17MB 实测对比)。
10
+ *
11
+ * 门面负责的四件事:
12
+ * - **复用**:一个活子进程服务所有请求;空闲 `idleMs` 后**由父进程**发 shutdown(父进程知道有没有在途
13
+ * 请求,因此不存在「刚发请求、子进程正好在退」的竞争),下次请求惰性重拉,数据由 WAL/flush 保住。
14
+ * - **期限**:每个请求有独立 deadline;超时即 SIGKILL 并拒绝该请求,下一请求重启一个新子进程(只重启一次,
15
+ * 不自动重试)。被超时杀掉的写**落盘结果未知**(与引擎的 TDB_WRITE_OUTCOME_UNKNOWN 同义),由调用方决定是否幂等重放。
16
+ * - **崩溃隔离**:子进程被外部杀掉时,在途请求以 `KANABO_TRIVIUM_CHILD_LOST` 拒绝,绝不挂起调用方。
17
+ * - **写串行**:`insert`/`batch`/`link`/`commit` 走同一条 promise 链,同一进程内的并发写按提交顺序落到同一子进程。
18
+ *
19
+ * 本文件刻意不做的:衰减排序与多路融合(任务 14)、Envelope 与观察 schema(任务 11)、
20
+ * 迁移与回滚(任务 13)、插件切换(任务 16)。
21
+ */
22
+ import { fork } from 'node:child_process'
23
+ import { existsSync } from 'node:fs'
24
+ import { tmpdir } from 'node:os'
25
+ import { dirname, join, resolve, sep } from 'node:path'
26
+ import { createInterface } from 'node:readline'
27
+ import { fileURLToPath } from 'node:url'
28
+ import { scopeOf, storeDir } from './store.js'
29
+
30
+ /** 向量维度默认值;任务 12 选定模型后由调用方显式传入。维度在创建时固定,写入后改维度只能走 migrate。 */
31
+ export const DEFAULT_DIM = 1536
32
+ export const DEFAULT_IDLE_MS = 15_000
33
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
34
+
35
+ const CHILD_SCRIPT = fileURLToPath(new URL('./store-trivium-child.js', import.meta.url))
36
+ const SYNC_MODES = new Set(['full', 'normal', 'off'])
37
+ const SHUTDOWN_GRACE_MS = 3_000
38
+
39
+ /** 带稳定 `code` 的错误,形状与 store.js 的 `storeError` 一致。 */
40
+ function triviumError(code, message, extra = {}) {
41
+ const error = new Error(message, extra.cause === undefined ? undefined : { cause: extra.cause })
42
+ error.code = code
43
+ if (extra.dbCode !== undefined) error.dbCode = extra.dbCode
44
+ if (extra.details !== undefined) error.details = extra.details
45
+ return error
46
+ }
47
+
48
+ /** TriviumDB 目录:默认落在系统临时目录下(`KANABO_MEMORY_DIR` 优先,与 JSON store 同一根),测试可用 `KANABO_TRIVIUM_DIR` 覆盖。 */
49
+ export function triviumDir() {
50
+ return resolve(process.env.KANABO_TRIVIUM_DIR ?? join(storeDir(), 'trivium'))
51
+ }
52
+
53
+ let repoRootCache
54
+
55
+ /** 模块所在的仓库根(向上找 `.git`);插件被装到 `~/.dsh/...` 时没有仓库,返回 null。 */
56
+ function repoRoot() {
57
+ if (repoRootCache !== undefined) return repoRootCache
58
+ let current = dirname(CHILD_SCRIPT)
59
+ for (;;) {
60
+ if (existsSync(join(current, '.git'))) {
61
+ repoRootCache = current
62
+ return current
63
+ }
64
+ const parent = dirname(current)
65
+ if (parent === current) {
66
+ repoRootCache = null
67
+ return null
68
+ }
69
+ current = parent
70
+ }
71
+ }
72
+
73
+ /** 库文件绝不允许落进仓库:`.tdb/.wal/.idx/.lock` 之类的产物一旦被提交就是脏工作区。 */
74
+ function assertOutsideRepo(dir) {
75
+ const root = repoRoot()
76
+ if (root === null) return
77
+ if (dir === root || dir.startsWith(`${root}${sep}`)) {
78
+ throw triviumError('KANABO_TRIVIUM_PATH', `TriviumDB 目录不得位于仓库内:${dir}(仓库根 ${root})`)
79
+ }
80
+ }
81
+
82
+ /** 工作区分域键 → 文件名;清洗规则与 `store.js` 的 `fileNameFor` 同口径,文件名永远是目录的直接子项。 */
83
+ function fileNameFor(workspace) {
84
+ const name = String(workspace)
85
+ .replace(/[^A-Za-z0-9._-]+/g, '_')
86
+ .replace(/^[_.]+|[_.]+$/g, '')
87
+ return name === '' || /^[.]+$/.test(name) ? 'workspace' : name
88
+ }
89
+
90
+ import { activeProfile, profileSuffix } from './providers.js'
91
+
92
+ /** 工作区分域键 → 绝对库路径(`.tdb` 主文件;`.wal/.idx/.vec/.pld/.lock` 由引擎同目录生成)。 */
93
+ export function dbPathFor(workspace, options = {}) {
94
+ if (typeof workspace !== 'string' || workspace.length === 0) {
95
+ throw triviumError('KANABO_TRIVIUM_WORKSPACE', 'dbPathFor 需要非空的 workspace 键')
96
+ }
97
+ const dir = resolve(options.dir ?? triviumDir())
98
+ assertOutsideRepo(dir)
99
+ const suffix = typeof options.suffix === 'string' ? options.suffix : profileSuffix(activeProfile())
100
+ const file = resolve(dir, `${fileNameFor(workspace)}${suffix}.tdb`)
101
+ if (dirname(file) !== dir) throw triviumError('KANABO_TRIVIUM_PATH', `库路径越界:${file}`)
102
+ return file
103
+ }
104
+
105
+ /** 会话 → 分域键:与 `store.js` 同一口径,避免两个存储对「同一工作区」有两种理解。 */
106
+ export function workspaceOf(session) {
107
+ return scopeOf(session)
108
+ }
109
+
110
+ /**
111
+ * 创建一个工作区门面。所有数据库调用返回 Promise;同一个门面的写按提交顺序串行。
112
+ *
113
+ * @param {object} options
114
+ * @param {string} options.workspace 分域键(通常 `scopeOf(session.header.cwd)`)
115
+ * @param {string} [options.dir] 库目录,默认 `triviumDir()`
116
+ * @param {number} [options.dim] 向量维度,默认 `DEFAULT_DIM`
117
+ * @param {number} [options.idleMs] 空闲退出阈值,默认 15s;测试可设 1s
118
+ * @param {number} [options.requestTimeoutMs] 单请求期限,默认 10s
119
+ * @param {'full'|'normal'|'off'} [options.syncMode] WAL 同步模式,默认 normal
120
+ */
121
+ export function createTriviumStore(options = {}) {
122
+ const workspace = options.workspace
123
+ if (typeof workspace !== 'string' || workspace.length === 0) {
124
+ throw triviumError(
125
+ 'KANABO_TRIVIUM_WORKSPACE',
126
+ 'createTriviumStore 需要非空的 workspace 键(分域口径见 store.js 的 scopeOf)',
127
+ )
128
+ }
129
+ const dim = Number.isInteger(options.dim) && options.dim > 0 ? options.dim : DEFAULT_DIM
130
+ const idleMs = Number.isFinite(options.idleMs) && options.idleMs > 0 ? options.idleMs : DEFAULT_IDLE_MS
131
+ const requestTimeoutMs =
132
+ Number.isFinite(options.requestTimeoutMs) && options.requestTimeoutMs > 0
133
+ ? options.requestTimeoutMs
134
+ : DEFAULT_REQUEST_TIMEOUT_MS
135
+ const syncMode = SYNC_MODES.has(options.syncMode) ? options.syncMode : 'normal'
136
+ const path = options.path ?? dbPathFor(workspace, { dir: options.dir, suffix: options.suffix })
137
+
138
+ let child = null
139
+ let retiring = null
140
+ const pending = new Map()
141
+ const counts = { spawn: 0, idleExits: 0, crashes: 0, timeouts: 0, requests: 0 }
142
+ let seq = 0
143
+ let idleTimer = null
144
+ let writeChain = Promise.resolve()
145
+ let closed = false
146
+ let lastExit = null
147
+
148
+ const closedError = () => triviumError('KANABO_TRIVIUM_CLOSED', '门面已关闭,不能再发请求')
149
+
150
+ function armIdle() {
151
+ clearTimeout(idleTimer)
152
+ idleTimer = null
153
+ if (closed || retiring !== null || child === null || pending.size > 0) return
154
+ idleTimer = setTimeout(() => {
155
+ void retire('idle')
156
+ }, idleMs)
157
+ idleTimer.unref?.()
158
+ }
159
+
160
+ function kill(proc, reason) {
161
+ if (proc === null || proc.__gone === true) return
162
+ proc.__reason = reason
163
+ // 立刻标记不可用:SIGKILL 到 `exit` 事件之间还有一个窗口,期间绝不能把新请求发给这个将死的进程。
164
+ proc.__killed = true
165
+ try {
166
+ proc.kill('SIGKILL')
167
+ } catch {
168
+ // 进程已经没了:exit 事件会走同一套清理。
169
+ }
170
+ }
171
+
172
+ function onLine(proc, line) {
173
+ const trimmed = line.trim()
174
+ if (trimmed === '') return
175
+ let message
176
+ try {
177
+ message = JSON.parse(trimmed)
178
+ } catch {
179
+ proc.__stderr = `${proc.__stderr ?? ''}[stdout 非 NDJSON] ${trimmed}\n`.slice(-4000)
180
+ return
181
+ }
182
+ if (message.type === 'idle-exit') {
183
+ proc.__ownIdleExit = true
184
+ return
185
+ }
186
+ if (message.type === 'fatal') {
187
+ proc.__fatal = message.error
188
+ return
189
+ }
190
+ const entry = pending.get(message.rid)
191
+ if (entry === undefined || entry.proc !== proc) return
192
+ pending.delete(message.rid)
193
+ clearTimeout(entry.timer)
194
+ if (message.ok === true) entry.resolve(message.value)
195
+ else {
196
+ const dbCode = message.error?.code
197
+ entry.reject(
198
+ triviumError('KANABO_TRIVIUM_CHILD', `${dbCode ?? 'TDB_ERROR'}: ${message.error?.message ?? '子进程返回错误'}`, {
199
+ dbCode,
200
+ details: message.error?.details,
201
+ }),
202
+ )
203
+ }
204
+ armIdle()
205
+ }
206
+
207
+ function onExit(proc, code, signal) {
208
+ proc.__gone = true
209
+ if (child === proc) child = null
210
+ const idle = proc.__reason === 'idle' || proc.__ownIdleExit === true
211
+ if (idle && proc.__countedIdle !== true) {
212
+ proc.__countedIdle = true
213
+ counts.idleExits += 1
214
+ } else if (!idle && proc.__reason !== 'close' && proc.__reason !== 'timeout') {
215
+ counts.crashes += 1
216
+ }
217
+ const reason = proc.__reason === 'running' ? (idle ? 'idle' : 'crash') : proc.__reason
218
+ lastExit = {
219
+ pid: proc.pid ?? null,
220
+ code,
221
+ signal,
222
+ reason,
223
+ stderr: proc.__stderr ?? '',
224
+ fatal: proc.__fatal ?? null,
225
+ at: Date.now(),
226
+ }
227
+ const lost = triviumError(
228
+ 'KANABO_TRIVIUM_CHILD_LOST',
229
+ `TriviumDB 子进程退出(code=${String(code)}, signal=${String(signal)}),在途请求已拒绝`,
230
+ { details: lastExit },
231
+ )
232
+ for (const [id, entry] of pending) {
233
+ if (entry.proc !== proc) continue
234
+ pending.delete(id)
235
+ clearTimeout(entry.timer)
236
+ entry.reject(lost)
237
+ }
238
+ proc.__resolveExit?.()
239
+ }
240
+
241
+ function spawn() {
242
+ const settings = { path, dim, syncMode, idleMs }
243
+ const proc = fork(CHILD_SCRIPT, [], {
244
+ // fork 必须带 ipc 通道;NDJSON 仍走 stdout(pipe),ipc 通道不使用。
245
+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
246
+ execArgv: [],
247
+ env: { ...process.env, KANABO_TRIVIUM_CHILD: JSON.stringify(settings) },
248
+ })
249
+ counts.spawn += 1
250
+ proc.__reason = 'running'
251
+ proc.__gone = false
252
+ proc.__exited = new Promise((resolveExit) => {
253
+ proc.__resolveExit = resolveExit
254
+ })
255
+ proc.stdout.setEncoding('utf8')
256
+ createInterface({ input: proc.stdout, crlfDelay: Infinity }).on('line', (line) => onLine(proc, line))
257
+ proc.stderr.setEncoding('utf8')
258
+ proc.stderr.on('data', (chunk) => {
259
+ proc.__stderr = `${proc.__stderr ?? ''}${chunk}`.slice(-4000)
260
+ })
261
+ // 子进程已死时写 stdin 会 EPIPE;在途请求由 exit 事件统一拒绝,这里只吞掉流错误。
262
+ proc.stdin.on('error', () => {})
263
+ proc.on('error', (error) => {
264
+ proc.__stderr = `${proc.__stderr ?? ''}fork failed: ${error?.message ?? String(error)}\n`
265
+ })
266
+ proc.on('exit', (code, signal) => onExit(proc, code, signal))
267
+ child = proc
268
+ return proc
269
+ }
270
+
271
+ async function ensureChild() {
272
+ for (;;) {
273
+ if (closed) throw closedError()
274
+ if (retiring !== null) {
275
+ await retiring.catch(() => {})
276
+ continue
277
+ }
278
+ if (child !== null && child.__gone !== true) {
279
+ if (child.__killed !== true) return child
280
+ // 已发 SIGKILL 但 `exit` 还没到:必须等它真的退出。内核在进程死亡时才释放文件租约,
281
+ // 立即重拉会让新子进程撞上 TDB_DATABASE_LOCKED(实测 SIGKILL 到退出 ~2ms,但这是竞态)。
282
+ await child.__exited
283
+ continue
284
+ }
285
+ try {
286
+ return spawn()
287
+ } catch (error) {
288
+ throw triviumError('KANABO_TRIVIUM_SPAWN', `无法启动 TriviumDB 子进程:${error?.message ?? String(error)}`, {
289
+ cause: error,
290
+ })
291
+ }
292
+ }
293
+ }
294
+
295
+ function onDeadline(proc, id, op, timeout) {
296
+ const entry = pending.get(id)
297
+ if (entry === undefined) return
298
+ pending.delete(id)
299
+ clearTimeout(entry.timer)
300
+ counts.timeouts += 1
301
+ entry.reject(
302
+ triviumError(
303
+ 'KANABO_TRIVIUM_TIMEOUT',
304
+ `TriviumDB 请求超时(op=${op}, ${timeout}ms):子进程已 SIGKILL,下一请求会重启;该写入落盘结果未知`,
305
+ { details: { op, timeoutMs: timeout, pid: proc.pid ?? null } },
306
+ ),
307
+ )
308
+ kill(proc, 'timeout')
309
+ }
310
+
311
+ async function call(op, args = {}, callOptions = {}) {
312
+ if (closed) throw closedError()
313
+ const timeout =
314
+ Number.isFinite(callOptions.timeoutMs) && callOptions.timeoutMs > 0 ? callOptions.timeoutMs : requestTimeoutMs
315
+ for (let attempt = 0; attempt < 2; attempt += 1) {
316
+ const proc = await ensureChild()
317
+ if (closed) throw closedError()
318
+ // 极窄的竞态:子进程在 `ensureChild` 返回后、请求写出前就死了(exit 已经处理完)。
319
+ // 这时请求根本没离开本进程,换一个新子进程重发是安全的;真正的在途请求由 exit 统一拒绝。
320
+ if (proc.__gone === true) continue
321
+ clearTimeout(idleTimer)
322
+ idleTimer = null
323
+ const id = seq + 1
324
+ seq = id
325
+ counts.requests += 1
326
+ return await new Promise((resolveCall, rejectCall) => {
327
+ const timer = setTimeout(() => onDeadline(proc, id, op, timeout), timeout)
328
+ timer.unref?.()
329
+ pending.set(id, { resolve: resolveCall, reject: rejectCall, timer, op, proc })
330
+ try {
331
+ // `...args` 在前:协议字段必须最后落值,否则一个参数名叫 rid/op 就能劫持帧头。
332
+ proc.stdin.write(`${JSON.stringify({ ...args, rid: id, op })}\n`)
333
+ } catch (error) {
334
+ pending.delete(id)
335
+ clearTimeout(timer)
336
+ rejectCall(
337
+ triviumError('KANABO_TRIVIUM_CHILD_LOST', `写入 TriviumDB 子进程失败:${error?.message ?? String(error)}`, {
338
+ cause: error,
339
+ }),
340
+ )
341
+ armIdle()
342
+ }
343
+ })
344
+ }
345
+ throw triviumError('KANABO_TRIVIUM_CHILD_LOST', 'TriviumDB 子进程连续两次在请求写出前退出')
346
+ }
347
+
348
+ function serializeWrite(task) {
349
+ const next = writeChain.then(task, task)
350
+ writeChain = next.then(
351
+ () => undefined,
352
+ () => undefined,
353
+ )
354
+ return next
355
+ }
356
+
357
+ async function shutdownChild(proc, reason) {
358
+ if (proc === null || proc.__gone === true) return
359
+ proc.__reason = reason
360
+ const hardStop = setTimeout(() => kill(proc, reason), SHUTDOWN_GRACE_MS)
361
+ hardStop.unref?.()
362
+ try {
363
+ proc.stdin.write(`${JSON.stringify({ op: 'shutdown', rid: seq + 1 })}\n`)
364
+ seq += 1
365
+ } catch {
366
+ kill(proc, reason)
367
+ }
368
+ try {
369
+ await proc.__exited
370
+ } finally {
371
+ clearTimeout(hardStop)
372
+ }
373
+ }
374
+
375
+ async function retire(reason) {
376
+ if (retiring !== null) return retiring
377
+ const proc = child
378
+ if (proc === null || pending.size > 0) return undefined
379
+ clearTimeout(idleTimer)
380
+ idleTimer = null
381
+ const done = shutdownChild(proc, reason)
382
+ retiring = done
383
+ try {
384
+ return await done
385
+ } finally {
386
+ if (retiring === done) retiring = null
387
+ }
388
+ }
389
+
390
+ async function open() {
391
+ return await call('open')
392
+ }
393
+
394
+ async function commit(callOptions) {
395
+ return await serializeWrite(() => call('commit', {}, callOptions))
396
+ }
397
+
398
+ async function insert(item, callOptions) {
399
+ return await serializeWrite(() => call('insert', item, callOptions))
400
+ }
401
+
402
+ async function batch(items, callOptions) {
403
+ return await serializeWrite(() => call('batch', { items }, callOptions))
404
+ }
405
+
406
+ /**
407
+ * 写边:`{ from, to, label, weight?, metadata? }`,`from`/`to` 是**节点 id**;也可以传一组边(数组)。
408
+ *
409
+ * 幂等:子进程用 (from, label, to) 的 upsert,同一组参数重放只会覆盖权重/元数据,
410
+ * 不会多出一条边——调用方(迁移)不需要自己去重就能重跑。标签由子进程按 `EDGE_LABELS` 校验。
411
+ * 一条边 = 一次 flush(回执即已落盘),所以迁移按批量(32 条)写,而不是逐条 flush。
412
+ */
413
+ async function link(edgeOrEdges, callOptions) {
414
+ const batch = Array.isArray(edgeOrEdges)
415
+ const edges = batch ? edgeOrEdges : [edgeOrEdges]
416
+ if (edges.length === 0 || edges.some((edge) => edge === null || typeof edge !== 'object')) {
417
+ throw triviumError('KANABO_TRIVIUM_LINK_EDGE', 'link 需要 { from, to, label, weight?, metadata? } 对象或其数组')
418
+ }
419
+ const result = await serializeWrite(() => call('link', { edges }, callOptions))
420
+ if (batch) return result
421
+ return { ...(result.edges?.[0] ?? {}), edgeCount: result.edgeCount }
422
+ }
423
+
424
+ /**
425
+ * 删除节点(GAP-9 按来源清除的基座)。引擎的 delete 是三层原子联删(向量 / payload / 全部边),
426
+ * 所以调用方不需要先拆边;返回实际删除数与删后节点数,便于调用方核对幂等。
427
+ */
428
+ async function deleteNodes(ids, callOptions) {
429
+ const list = Array.isArray(ids) ? ids : [ids]
430
+ if (list.length === 0) throw triviumError('KANABO_TRIVIUM_DELETE', 'deleteNodes 需要至少一个节点 id')
431
+ return await serializeWrite(() => call('delete', { ids: list }, callOptions))
432
+ }
433
+
434
+ /**
435
+ * 读边:`edges(from)` 读该节点的出边;`edges()`(不给 from)用一遍 TQL 扫全图(默认上限 1000,
436
+ * `options.limit` 可调)。两种形态都带 `graph`(节点数/边数/每标签边数),因此调用方要判断
437
+ * 「库里到底有没有边」不需要自己数行。
438
+ */
439
+ async function edges(from, callOptions = {}) {
440
+ const args = from === undefined || from === null
441
+ ? (callOptions.limit === undefined ? {} : { limit: callOptions.limit })
442
+ : { from }
443
+ return await call('edges', args, callOptions)
444
+ }
445
+
446
+ async function search(request, callOptions) {
447
+ return await call('search', request, callOptions)
448
+ }
449
+
450
+ async function tql(query, callOptions) {
451
+ return await call('tql', { query }, callOptions)
452
+ }
453
+
454
+ /**
455
+ * 建**有序属性索引**(幂等):时间窗查询的 `t0` 区间条件靠它从全扫变成 index scan
456
+ * (`EXPLAIN` 的访问路径从 `full_node_scan` 变成 `ordered_property_index (t0)`)。
457
+ * 建索引属于写入路径,所以放在门面;只支持 `ordered`,其它种类不在本任务范围。
458
+ */
459
+ async function createOrderedIndex(field, callOptions) {
460
+ if (typeof field !== 'string' || field.length === 0) {
461
+ throw triviumError('KANABO_TRIVIUM_INDEX', 'createOrderedIndex 需要非空的字段名')
462
+ }
463
+ return await serializeWrite(() => call('index', { field, kind: 'ordered' }, callOptions))
464
+ }
465
+
466
+ async function close() {
467
+ if (closed) return { closed: true, alreadyClosed: true, pid: null }
468
+ clearTimeout(idleTimer)
469
+ idleTimer = null
470
+ // 关闭顺序很重要:先让已排队的写跑完(它们是在 close 之前发出的,不能因为 close 而假失败),
471
+ // 再等在途请求(含只读)清空,最后才标记关闭并 shutdown。每个请求都有期限,等待有上界。
472
+ await writeChain
473
+ const drainDeadline = Date.now() + requestTimeoutMs + 500
474
+ while (pending.size > 0 && Date.now() < drainDeadline) {
475
+ await new Promise((resolve) => setTimeout(resolve, 10))
476
+ }
477
+ closed = true
478
+ if (retiring !== null) await retiring.catch(() => {})
479
+ const proc = child
480
+ if (proc === null) return { closed: true, pid: null }
481
+ await shutdownChild(proc, 'close')
482
+ return { closed: true, pid: null, lastExit }
483
+ }
484
+
485
+ /** 子进程状态快照;`pid === null` 表示当前没有子进程(从未启动或已退出),`usable === false` 表示它已不可再服务请求(正在被 SIGKILL 或已退出)。 */
486
+ function stats() {
487
+ const proc = child
488
+ return {
489
+ workspace,
490
+ path,
491
+ pid: proc !== null && proc.__gone !== true ? (proc.pid ?? null) : null,
492
+ usable: proc !== null && proc.__gone !== true && proc.__killed !== true,
493
+ dim,
494
+ idleMs,
495
+ requestTimeoutMs,
496
+ syncMode,
497
+ spawnCount: counts.spawn,
498
+ idleExits: counts.idleExits,
499
+ crashes: counts.crashes,
500
+ timeouts: counts.timeouts,
501
+ requests: counts.requests,
502
+ pending: pending.size,
503
+ lastExit,
504
+ }
505
+ }
506
+
507
+ return { workspace, path, open, close, insert, batch, link, edges, deleteNodes, createOrderedIndex, search, tql, commit, stats }
508
+ }
509
+
510
+ export default createTriviumStore