@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.0
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 +304 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cursor.js +116 -0
- package/egress.js +788 -0
- package/embed-child.js +142 -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 +153 -0
- package/migrate.js +1722 -0
- package/package.json +48 -3
- package/persona.js +949 -0
- package/query-window.js +561 -0
- package/recall-trivium.js +873 -0
- package/recall.js +113 -0
- package/remove-legacy.mjs +720 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +507 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +423 -0
- package/trivium-runtime.js +1794 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1794 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆运行时的单一 TriviumDB 门面(平台计划 todo 16):注册表 + 活写入路径 + 配额 + 快照 + 两阶段关闭。
|
|
3
|
+
*
|
|
4
|
+
* 为什么必须是一个进程级注册表(实测,见 `docs/research/triviumdb.md` §3、`gate-memory.md` §4):
|
|
5
|
+
* TriviumDB 0.9.3 是**文件级独占租约**——同一库路径在同一个进程里开第二个门面(含 readOnly)
|
|
6
|
+
* 会在 open 阶段抛 `TDB_DATABASE_LOCKED`,没有重试。所以 tools / extract / sweep / recall provider /
|
|
7
|
+
* 时间窗查询**共用**本文件的注册表:一个库路径一个门面、一个子进程,按路径引用计数。
|
|
8
|
+
*
|
|
9
|
+
* 本文件只做四件事:
|
|
10
|
+
* 1. **注册表**:`acquireFacade(scope)` 按库路径复用门面并计数;`release()` 只减计数,**不关**门面
|
|
11
|
+
* (子进程按门面自己的 idleMs 空闲退出,租约随之释放;下次请求惰性重拉)。终态关闭只由
|
|
12
|
+
* `requestShutdown()` / `close()` 触发。
|
|
13
|
+
* 2. **活写入路径的共用原语**:信封 → payload(含平铺镜像字段)、文本索引、工作区扫描、按会话统计
|
|
14
|
+
* 已保留轮次。TQL 不能过滤嵌套路径,所以时间窗要用的 `source_type`/`id`/`ts`/`video_id`/`t0`/`t1`
|
|
15
|
+
* 必须是 payload 顶层字段(与 migrate.js 的 `payloadFor` 同一口径;探针断言两边常量一致)。
|
|
16
|
+
* 3. **配额**:条目数与总字节数两个维度,超限抛带 `code`/`details` 的结构化错误。引擎与门面
|
|
17
|
+
* 都**没有删除原语**(`db.delete` 存在,但门面只暴露 insert/batch/link/edges/tql/commit),
|
|
18
|
+
* 所以配额是**准入控制**而不是 FIFO 淘汰:达到上限后新写入被拒(结构化错误),已有条目不动。
|
|
19
|
+
* 默认值给足(条目 10000、正文 64 MiB),让它是安全带而不是日常行为。
|
|
20
|
+
* 4. **快照与两阶段关闭**:`createSnapshot/verifySnapshot/restoreSnapshot` 是引擎的独占操作,
|
|
21
|
+
* 必须在持有租约的进程里做。本文件的插件进程**从不 import `triviumdb`**:先把门面关到租约释放,
|
|
22
|
+
* 再 fork 一个短命 helper(本文件自己的 `--trivium-helper` 模式)开库/校验/恢复,做完即退。
|
|
23
|
+
*
|
|
24
|
+
* ## 快照与校验的口径
|
|
25
|
+
*
|
|
26
|
+
* - `createSnapshot` 产出引擎的原生快照目录(清单含每文件 crc32/sha256)。目标目录已存在即失败
|
|
27
|
+
* (与引擎的 `TDB_SNAPSHOT_EXISTS` 同义),绝不覆盖旧快照。
|
|
28
|
+
* - `verifySnapshotArtifacts` 做两件事:① 引擎的 `verifySnapshot(dir)` 校验制品完整性;② 与**活库
|
|
29
|
+
* 当前字节**逐文件比对 sha256——这一步才是「快照之后库又变了」的漂移检测(引擎的 verify 只校验
|
|
30
|
+
* 快照自身,不知道活库)。多出的数据文件(如 `.wal`、新的 `.pld.N`)同样计为漂移。
|
|
31
|
+
* - `restoreSnapshot` 把快照恢复到临时目录 → 用引擎再校验一次 → 把活库文件移到 `.backup-<ts>` →
|
|
32
|
+
* 把恢复出来的文件按活库基名搬回。恢复后活库的字节与快照清单一致。
|
|
33
|
+
*
|
|
34
|
+
* 已知边界(不由本文件解决):门面不暴露 `delete`,所以旧 JSON store 的 200 条 FIFO 淘汰不再存在;
|
|
35
|
+
* 只是条目/字节配额在超限时拒绝新写入。
|
|
36
|
+
*/
|
|
37
|
+
import { spawn } from 'node:child_process'
|
|
38
|
+
import { createHash } from 'node:crypto'
|
|
39
|
+
import {
|
|
40
|
+
existsSync,
|
|
41
|
+
mkdirSync,
|
|
42
|
+
readFileSync,
|
|
43
|
+
readdirSync,
|
|
44
|
+
renameSync,
|
|
45
|
+
rmSync,
|
|
46
|
+
statSync,
|
|
47
|
+
writeFileSync,
|
|
48
|
+
} from 'node:fs'
|
|
49
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
50
|
+
import { realpathSync } from 'node:fs'
|
|
51
|
+
import { fileURLToPath } from 'node:url'
|
|
52
|
+
|
|
53
|
+
import { EMBEDDING_DIM } from './contract.js'
|
|
54
|
+
import { MAX_ENTRY_BYTES, scopeOf } from './store.js'
|
|
55
|
+
import { createTriviumStore, dbPathFor, triviumDir } from './store-trivium.js'
|
|
56
|
+
|
|
57
|
+
/** 与 `migrate.js` 的 `MIGRATION_KIND` 同一字面量:两个写入方必须写同一种节点,召回/校验才认得。 */
|
|
58
|
+
export const MEMORY_KIND = 'kanabo-envelope'
|
|
59
|
+
/** 会话锚点节点的 kind:与 migrate.js 的 `SESSION_NODE_KIND` 一致(图臂经过但不返回)。 */
|
|
60
|
+
export const SESSION_NODE_KIND = 'kanabo-session'
|
|
61
|
+
/**
|
|
62
|
+
* 锚点的图标记:与 `migrate.js#anchorPayload` 同一字面量,召回侧(`recall-trivium.js`)按它把锚点
|
|
63
|
+
* 从每个臂的命中里剔除。它是节点 payload 的约定而不是跨包字段,因此不进 `contract.js`。
|
|
64
|
+
*/
|
|
65
|
+
export const ANCHOR_GRAPH_ROLE = 'anchor'
|
|
66
|
+
/** 锚点 legacy_id 的前缀:与 `migrate.js#SESSION_KEY_PREFIX` 一致,两个写入方指向同一个节点。 */
|
|
67
|
+
export const SESSION_KEY_PREFIX = 'session:'
|
|
68
|
+
/**
|
|
69
|
+
* 一批写多少条边:`link` 每调用一次就 flush 一次,而 flush 的代价几乎与边数无关
|
|
70
|
+
* (实测一个 10k 库:`link(32)` ≈ 140ms、`link(512)` ≈ 164ms,都是「一次 flush」的价钱)。
|
|
71
|
+
* 所以批量要大:1040 条边(128 条条目 × 双向 + 余量)两三次 link 就写完,而不是 32 次。
|
|
72
|
+
*/
|
|
73
|
+
export const MAX_EDGE_BATCH = 1024
|
|
74
|
+
/** 单页行数:分页的**粒度**,不是总额上限(总上限见 `SCAN_MAX_ROWS`)。 */
|
|
75
|
+
export const SCAN_LIMIT = 5000
|
|
76
|
+
/** 全量扫描的硬上限:超过即失败关闭——配额绝不拿部分和做准入。 */
|
|
77
|
+
export const SCAN_MAX_ROWS = 100_000
|
|
78
|
+
/** 配额默认值:条目数与正文总字节数(每 workspace)。可用环境变量覆盖(探针与运维用)。 */
|
|
79
|
+
export const QUOTA_DEFAULTS = Object.freeze({ entries: 10_000, bytes: 64 * 1024 * 1024 })
|
|
80
|
+
/** 快照 helper 的期限:开库 + 快照 + 关闭都在这个窗口内完成。 */
|
|
81
|
+
export const SNAPSHOT_TIMEOUT_MS = 30_000
|
|
82
|
+
/**
|
|
83
|
+
* 向量回填 worker 的默认期限:开库 + 加载模型(约 1.2GB)+ 一批嵌入 + 一次 flush 都在窗口内。
|
|
84
|
+
* 超时由父进程 SIGTERM → SIGKILL,已 flush 的批次保留,剩余节点下次重试。
|
|
85
|
+
*/
|
|
86
|
+
export const BACKFILL_TIMEOUT_MS = 120_000
|
|
87
|
+
/**
|
|
88
|
+
* 回填给回合让步的期限:先 SIGTERM,超过它再 SIGKILL——这是回填能给一个请求增加的最长等待。
|
|
89
|
+
* 给得短是有意的:子进程按批 flush,所以「在批与批之间被杀」最多丢当前一批(节点仍是完整零向量,
|
|
90
|
+
* 下次重试),而回合延迟是用户能感知的成本。这个界限由探针 (d)/(e) 分别测量:回合最多多等这么久,
|
|
91
|
+
* 且真被杀后库里只有「完整零向量」或「完整真实向量」,没有半个向量。
|
|
92
|
+
*/
|
|
93
|
+
export const BACKFILL_PREEMPT_GRACE_MS = 150
|
|
94
|
+
/** 一次回填最多补多少节点:剩下的留给下一次运行,保证单次时长与内存都是有界的。 */
|
|
95
|
+
export const BACKFILL_MAX_NODES = 200
|
|
96
|
+
/** 回填进度文件(只作遥测,绝不作为「已回填」的真相来源):落在库目录旁,不进仓库。 */
|
|
97
|
+
export const BACKFILL_STATE_FILE = 'backfill-state.json'
|
|
98
|
+
/**
|
|
99
|
+
* 单次向量请求的硬期限:冷启动要加载模型(实测 2.4–2.8s),所以给足;超时即杀服务并降级,绝不挂起工具调用。
|
|
100
|
+
* 这是「工具路径的嵌入预算」——remember 与 recall 都受它约束。
|
|
101
|
+
*/
|
|
102
|
+
export const EMBED_SERVICE_TIMEOUT_MS = 6_000
|
|
103
|
+
/** 向量服务空闲多久退出:模型常驻约 1.2GB,闲着不该一直占;退出后下次请求再拉。 */
|
|
104
|
+
export const EMBED_SERVICE_IDLE_MS = 60_000
|
|
105
|
+
|
|
106
|
+
const MODULE_PATH = fileURLToPath(import.meta.url)
|
|
107
|
+
/** 回填子进程的入口:本文件把租约关掉后才拉起它,它自己直接 open 引擎(插件进程永不 open)。 */
|
|
108
|
+
const BACKFILL_CHILD = fileURLToPath(new URL('./backfill-child.js', import.meta.url))
|
|
109
|
+
/** 常驻向量服务子进程的入口:只加载嵌入模型,不碰引擎、不碰库文件(任务 52)。 */
|
|
110
|
+
const EMBED_CHILD = fileURLToPath(new URL('./embed-child.js', import.meta.url))
|
|
111
|
+
/**
|
|
112
|
+
* 引擎自己维护、且**不进快照清单**的旁文件:它们存不存在不是数据漂移。
|
|
113
|
+
* `.wal` 是尚未合并的日志(快照只收已 flush 的主文件);`.lock` 是租约;`.manifest.json` 是引擎写在库旁的代际清单。
|
|
114
|
+
* 真正的数据文件(无后缀主文件、`.vec`、`.pld.N`、`.idx`、`.flush_ok`)都在清单里,缺/改/多都算漂移。
|
|
115
|
+
*/
|
|
116
|
+
const ENGINE_SIDECARS = new Set(['.wal', '.lock', '.manifest.json'])
|
|
117
|
+
const RETENTION_ORIGINS = new Set(['live', 'sweep', 'on-demand'])
|
|
118
|
+
const RESTORE_NAME = 'database.tdb'
|
|
119
|
+
|
|
120
|
+
/** 带稳定 `code` 的错误,形状与 store.js / store-trivium.js 的 `KANABO_*` 约定一致。 */
|
|
121
|
+
export function memoryError(code, message, details) {
|
|
122
|
+
const error = new Error(message)
|
|
123
|
+
error.code = code
|
|
124
|
+
if (details !== undefined) error.details = details
|
|
125
|
+
return error
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function sha256(buffer) {
|
|
129
|
+
return createHash('sha256').update(buffer).digest('hex')
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function positiveInt(value, fallback) {
|
|
133
|
+
const number = Number(value)
|
|
134
|
+
return Number.isInteger(number) && number > 0 ? number : fallback
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 配额从环境读(每次调用重读,探针可以在同一进程里改),非法值退回默认。 */
|
|
138
|
+
export function quotaLimits() {
|
|
139
|
+
return {
|
|
140
|
+
entries: positiveInt(process.env.KANABO_MEMORY_MAX_ENTRIES, QUOTA_DEFAULTS.entries),
|
|
141
|
+
bytes: positiveInt(process.env.KANABO_MEMORY_MAX_BYTES, QUOTA_DEFAULTS.bytes),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
// 路径、payload 与文本
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
/** 分域键 → 绝对库路径;与 `store-trivium.js` 的 `dbPathFor` 完全同一实现(含「不得进仓库」断言)。 */
|
|
150
|
+
export function dbPathOf(scope, options = {}) {
|
|
151
|
+
return dbPathFor(scope, { dir: options.dir })
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 节点 payload 可嵌入的文本:与召回命中行同口径(先剥 `envelope`,再取 text / scene_description /
|
|
156
|
+
* topic / tool_name)。回填 worker 用本函数决定「嵌入什么」,因此向量臂看到的文本与文本臂一致。
|
|
157
|
+
*/
|
|
158
|
+
export function embedTextOf(payload) {
|
|
159
|
+
const envelope = payload !== null && typeof payload === 'object'
|
|
160
|
+
&& payload.envelope !== null && typeof payload.envelope === 'object' ? payload.envelope : null
|
|
161
|
+
const fromEnvelope = envelope === null ? '' : envelopeTextOf(envelope)
|
|
162
|
+
if (fromEnvelope !== '') return fromEnvelope
|
|
163
|
+
if (payload === null || typeof payload !== 'object') return ''
|
|
164
|
+
for (const key of ['text', 'scene_description', 'topic', 'tool_name']) {
|
|
165
|
+
const value = payload[key]
|
|
166
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
167
|
+
}
|
|
168
|
+
return ''
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 条目的可读正文:`text` 优先,空则退回 topic——与 `store.js#textOf` 同口径。 */
|
|
172
|
+
export function envelopeTextOf(envelope) {
|
|
173
|
+
const text = typeof envelope?.text === 'string' ? envelope.text.trim() : ''
|
|
174
|
+
if (text === '') return typeof envelope?.topic === 'string' ? envelope.topic.trim() : ''
|
|
175
|
+
return text
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 文本索引的内容:`topic` + 正文。旧实现 `searchEntries` 打分时同时看正文与 topic,
|
|
180
|
+
* 只索引正文会让「只有 topic 沾边」的条目从文本臂上凭空消失。正文已含 topic 时不重复加。
|
|
181
|
+
* (与 `migrate.js#indexTextFor` 同一规则;探针断言两边行为一致。)
|
|
182
|
+
*/
|
|
183
|
+
export function indexTextFor(topic, text) {
|
|
184
|
+
const body = String(text ?? '')
|
|
185
|
+
const head = typeof topic === 'string' ? topic.trim() : ''
|
|
186
|
+
if (head === '' || body.includes(head)) return body
|
|
187
|
+
return `${head} ${body}`
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 平铺镜像的字段:TQL 不能过滤嵌套路径,时间窗(query-window.js)只认 payload 顶层字段。 */
|
|
191
|
+
const MIRROR_TYPE_FIELDS = Object.freeze({
|
|
192
|
+
VIDEO_CLIP: Object.freeze(['video_id', 't0', 't1', 'frame_id', 'app', 'activity', 'scene_description', 'keyframe_path']),
|
|
193
|
+
AUDIO_SEGMENT: Object.freeze(['audio_id', 't0', 't1', 'text', 'speaker', 'stem']),
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 信封 → 节点 payload。形状与 `migrate.js#payloadFor` 对齐(kind/workspace/id/legacy_id/source_type/
|
|
198
|
+
* session_id/turn/ts/evidence_trace/text_sha256/envelope + 类型字段平铺),并多记两个活写入路径
|
|
199
|
+
* 自己要用的顶层键:`origin`(保留来源,sweep 账本与 extract 去重用)与 `topic`(recall 工具补全用)。
|
|
200
|
+
*/
|
|
201
|
+
export function payloadFor(scope, envelope) {
|
|
202
|
+
const payload = {
|
|
203
|
+
kind: MEMORY_KIND,
|
|
204
|
+
workspace: scope,
|
|
205
|
+
id: envelope.id,
|
|
206
|
+
legacy_id: envelope.id,
|
|
207
|
+
source_type: envelope.source_type,
|
|
208
|
+
session_id: envelope.session.id,
|
|
209
|
+
session_scope: typeof envelope.session.scope === 'string' ? envelope.session.scope : null,
|
|
210
|
+
turn: envelope.turn,
|
|
211
|
+
ts: envelope.ts,
|
|
212
|
+
origin: typeof envelope.origin === 'string' && envelope.origin.length > 0 ? envelope.origin : null,
|
|
213
|
+
topic: typeof envelope.topic === 'string'
|
|
214
|
+
? envelope.topic
|
|
215
|
+
: (typeof envelope.node_metadata?.topic === 'string' ? envelope.node_metadata.topic : ''),
|
|
216
|
+
// 顶层 `bytes` 镜像:配额的全量字节数可以一次 `sum(n.bytes)` 聚合得到(不需要拉全库 payload);
|
|
217
|
+
// 迁移写入的行没有这个镜像,所以 `scanWorkspace` 保留逐行求和的路径并交叉校验两者。
|
|
218
|
+
bytes: Buffer.byteLength(envelopeTextOf(envelope), 'utf8'),
|
|
219
|
+
evidence_trace: envelope.evidence_trace,
|
|
220
|
+
text_sha256: sha256(Buffer.from(envelopeTextOf(envelope), 'utf8')),
|
|
221
|
+
envelope,
|
|
222
|
+
}
|
|
223
|
+
for (const field of MIRROR_TYPE_FIELDS[envelope.source_type] ?? []) {
|
|
224
|
+
if (envelope[field] !== undefined) payload[field] = envelope[field]
|
|
225
|
+
}
|
|
226
|
+
// 扩展字段一律走契约允许的 `node_metadata`,再平铺到 payload 顶层供查询使用:
|
|
227
|
+
// `job_id` 是「按来源清除」(任务 27)的过滤键,`graph_role` 是读侧解释层级的键。
|
|
228
|
+
// 直接给信封加顶层键会被 `validateEnvelope` 拒绝(那正是契约该做的事)。
|
|
229
|
+
const metadata = envelope.node_metadata !== null && typeof envelope.node_metadata === 'object' && !Array.isArray(envelope.node_metadata)
|
|
230
|
+
? envelope.node_metadata
|
|
231
|
+
: null
|
|
232
|
+
if (metadata !== null) {
|
|
233
|
+
for (const key of ['job_id', 'graph_role']) {
|
|
234
|
+
if (typeof metadata[key] === 'string' && metadata[key].length > 0) payload[key] = metadata[key]
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return payload
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 条目 id:沿用旧 store 的 `mem-` 前缀与形状(`migrate.js` 以它为稳定身份)。 */
|
|
241
|
+
export function entryId() {
|
|
242
|
+
return `mem-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** TQL 字符串字面量(只用于 workspace / id 之类的短字符串;正文绝不拼进 TQL)。 */
|
|
246
|
+
function tqlString(value) {
|
|
247
|
+
return JSON.stringify(String(value))
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function nodeIdOf(value) {
|
|
251
|
+
const id = typeof value === 'number' ? value : Number(value)
|
|
252
|
+
return Number.isSafeInteger(id) && id >= 0 ? id : null
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** `X AS node` / `RETURN *` 投影的都是节点包装 `{ id, numEdges, payload }`。 */
|
|
256
|
+
function nodeOf(row) {
|
|
257
|
+
const node = row?._ ?? row?.node ?? null
|
|
258
|
+
if (node === null || typeof node !== 'object') return null
|
|
259
|
+
const id = nodeIdOf(node.id)
|
|
260
|
+
const payload = node.payload !== null && typeof node.payload === 'object' ? node.payload : null
|
|
261
|
+
return id === null ? null : { nodeId: id, payload }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function rowsOf(result) {
|
|
265
|
+
return Array.isArray(result?.rows) ? result.rows : []
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** payload → 可读条目(工具输出与账本共用;绝不猜缺失字段)。 */
|
|
269
|
+
export function entryOf(row) {
|
|
270
|
+
const payload = row?.payload ?? null
|
|
271
|
+
if (payload === null) return null
|
|
272
|
+
const envelope = payload.envelope !== null && typeof payload.envelope === 'object' ? payload.envelope : null
|
|
273
|
+
const id = typeof envelope?.id === 'string' && envelope.id.length > 0
|
|
274
|
+
? envelope.id
|
|
275
|
+
: (typeof payload.id === 'string' ? payload.id : String(row.nodeId))
|
|
276
|
+
const topic = typeof payload.topic === 'string' && payload.topic.length > 0
|
|
277
|
+
? payload.topic
|
|
278
|
+
: (typeof envelope?.topic === 'string' ? envelope.topic : (typeof envelope?.node_metadata?.topic === 'string' ? envelope.node_metadata.topic : ''))
|
|
279
|
+
const ts = Number.isSafeInteger(Number(envelope?.ts ?? payload.ts)) ? Number(envelope?.ts ?? payload.ts) : 0
|
|
280
|
+
return {
|
|
281
|
+
nodeId: row.nodeId,
|
|
282
|
+
id,
|
|
283
|
+
topic,
|
|
284
|
+
text: envelope === null ? '' : envelopeTextOf(envelope),
|
|
285
|
+
ts,
|
|
286
|
+
origin: typeof envelope?.origin === 'string' && envelope.origin.length > 0
|
|
287
|
+
? envelope.origin
|
|
288
|
+
: (typeof payload.origin === 'string' && payload.origin.length > 0 ? payload.origin : null),
|
|
289
|
+
turn: Number.isSafeInteger(Number(envelope?.turn ?? payload.turn)) ? Number(envelope?.turn ?? payload.turn) : null,
|
|
290
|
+
sessionId: typeof envelope?.session?.id === 'string' ? envelope.session.id : (typeof payload.session_id === 'string' ? payload.session_id : null),
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 配额:先算后写,超限抛结构化错误,绝不写半截。`incoming` 是本批要新增的条目数/正文字节数。
|
|
295
|
+
* `used` 必须是**全量**账本:两个计数都得是安全非负整数,否则以 `KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE`
|
|
296
|
+
* 失败关闭(部分和放行是“配额被空翻”的根源,见 task-16 门评审 B1)。 */
|
|
297
|
+
export function assertQuota(used, incoming) {
|
|
298
|
+
const limits = quotaLimits()
|
|
299
|
+
const usedCount = exactCounter(used?.count, 'count')
|
|
300
|
+
const usedBytes = exactCounter(used?.bytes, 'bytes')
|
|
301
|
+
const incomingEntries = exactCounter(incoming?.entries, 'entries')
|
|
302
|
+
const incomingBytes = exactCounter(incoming?.bytes, 'bytes')
|
|
303
|
+
if (used?.bytesExact === false) {
|
|
304
|
+
throw memoryError('KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE',
|
|
305
|
+
'配额需要全量账本,但调用方给的 bytes 不是全量结果;拒绝放行。', { field: 'bytesExact' })
|
|
306
|
+
}
|
|
307
|
+
const exact = {
|
|
308
|
+
entries: { limit: limits.entries, used: usedCount, incoming: incomingEntries },
|
|
309
|
+
bytes: { limit: limits.bytes, used: usedBytes, incoming: incomingBytes },
|
|
310
|
+
}
|
|
311
|
+
if (usedCount + incomingEntries > limits.entries) {
|
|
312
|
+
throw memoryError(
|
|
313
|
+
'KANABO_MEMORY_QUOTA_ENTRIES',
|
|
314
|
+
`记忆条目数超限:已有 ${usedCount} 条,本次要写 ${incomingEntries} 条,上限 ${limits.entries}(workspace 配额)。`
|
|
315
|
+
+ ' 已有条目不会被删除;请清理旧条目或调高 KANABO_MEMORY_MAX_ENTRIES。',
|
|
316
|
+
exact.entries)
|
|
317
|
+
}
|
|
318
|
+
if (usedBytes + incomingBytes > limits.bytes) {
|
|
319
|
+
throw memoryError(
|
|
320
|
+
'KANABO_MEMORY_QUOTA_BYTES',
|
|
321
|
+
`记忆正文总字节超限:已有 ${usedBytes} 字节,本次要写 ${incomingBytes} 字节,上限 ${limits.bytes}。`
|
|
322
|
+
+ ' 已有条目不会被删除;请调高 KANABO_MEMORY_MAX_BYTES。',
|
|
323
|
+
exact.bytes)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 配额的两个计数必须来自全量账本;任何非安全整数的值都不能当成 0 放行。 */
|
|
328
|
+
function exactCounter(value, field) {
|
|
329
|
+
const number = typeof value === 'number' ? value : NaN
|
|
330
|
+
if (!Number.isSafeInteger(number) || number < 0) {
|
|
331
|
+
throw memoryError('KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE',
|
|
332
|
+
`配额需要全量账本,但 ${field} 不是安全非负整数(收到 ${String(value)});拒绝放行。`,
|
|
333
|
+
{ field, received: String(value) })
|
|
334
|
+
}
|
|
335
|
+
return number
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ---------------------------------------------------------------------------
|
|
339
|
+
// 进程级注册表
|
|
340
|
+
// ---------------------------------------------------------------------------
|
|
341
|
+
|
|
342
|
+
/** @type {Map<string, object>} 库路径 → 记录(真正的单例边界)。 */
|
|
343
|
+
const REGISTRY = new Map()
|
|
344
|
+
/** @type {{requestedAt: number, promise: Promise<object>|null, result: object|null}|null} */
|
|
345
|
+
let SHUTDOWN = null
|
|
346
|
+
|
|
347
|
+
function recordFor(scope, options) {
|
|
348
|
+
const dir = options?.dir
|
|
349
|
+
const path = dbPathOf(scope, { dir })
|
|
350
|
+
const existing = REGISTRY.get(path)
|
|
351
|
+
if (existing !== undefined) return existing
|
|
352
|
+
const dim = positiveInt(options?.dim, EMBEDDING_DIM)
|
|
353
|
+
const facade = createTriviumStore({
|
|
354
|
+
workspace: scope,
|
|
355
|
+
dir,
|
|
356
|
+
dim,
|
|
357
|
+
idleMs: options?.idleMs,
|
|
358
|
+
requestTimeoutMs: options?.requestTimeoutMs,
|
|
359
|
+
})
|
|
360
|
+
const record = {
|
|
361
|
+
path,
|
|
362
|
+
workspace: scope,
|
|
363
|
+
dim,
|
|
364
|
+
facade,
|
|
365
|
+
refs: 0,
|
|
366
|
+
active: 0,
|
|
367
|
+
closed: false,
|
|
368
|
+
chain: Promise.resolve(),
|
|
369
|
+
ready: null,
|
|
370
|
+
createdAt: Date.now(),
|
|
371
|
+
}
|
|
372
|
+
REGISTRY.set(path, record)
|
|
373
|
+
return record
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function ensureOpen(record) {
|
|
377
|
+
if (record.ready === null) {
|
|
378
|
+
record.ready = (async () => {
|
|
379
|
+
// 回填子进程持有同一个库路径的租约:新请求必须先让它让步(SIGTERM → 限时 SIGKILL),
|
|
380
|
+
// 否则这里 open 会直接撞上 TDB_DATABASE_LOCKED。让步有界,见 BACKFILL_PREEMPT_GRACE_MS。
|
|
381
|
+
await preemptBackfill(record.path)
|
|
382
|
+
return await record.facade.open()
|
|
383
|
+
})().catch((error) => {
|
|
384
|
+
record.ready = null
|
|
385
|
+
throw error
|
|
386
|
+
})
|
|
387
|
+
}
|
|
388
|
+
return record.ready
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* 取一个工作区的门面(引用计数 +1)。`release()` 必须与它成对调用;release **不关**门面。
|
|
393
|
+
* 关闭中的注册表拒绝新请求(`KANABO_MEMORY_SHUTDOWN`),这是两阶段关闭的第一阶段语义。
|
|
394
|
+
*/
|
|
395
|
+
export function acquireFacade(scope, options = {}) {
|
|
396
|
+
if (SHUTDOWN !== null) {
|
|
397
|
+
throw memoryError('KANABO_MEMORY_SHUTDOWN', '记忆运行时正在关闭,不再接受新的 TriviumDB 请求。')
|
|
398
|
+
}
|
|
399
|
+
if (typeof scope !== 'string' || scope.length === 0) {
|
|
400
|
+
throw memoryError('KANABO_MEMORY_WORKSPACE', 'acquireFacade 需要非空的 workspace 键(分域口径见 store.js 的 scopeOf)')
|
|
401
|
+
}
|
|
402
|
+
const record = recordFor(scope, options)
|
|
403
|
+
record.refs += 1
|
|
404
|
+
record.active += 1
|
|
405
|
+
let released = false
|
|
406
|
+
const release = () => {
|
|
407
|
+
if (released) return
|
|
408
|
+
released = true
|
|
409
|
+
record.active -= 1
|
|
410
|
+
record.refs -= 1
|
|
411
|
+
}
|
|
412
|
+
return { record, key: record.path, path: record.path, facade: record.facade, release }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** 取门面 → 执行 → 无论成败都释放引用。 */
|
|
416
|
+
export async function withFacade(scope, run, options = {}) {
|
|
417
|
+
const handle = acquireFacade(scope, options)
|
|
418
|
+
try {
|
|
419
|
+
await ensureOpen(handle.record)
|
|
420
|
+
return await run(handle.facade, handle.record)
|
|
421
|
+
} finally {
|
|
422
|
+
handle.release()
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* 同一库路径的读-改-写串行链。extract 的「读去重键 → 插入」与 remember 的「查配额 → 插入」
|
|
428
|
+
* 必须原子:两个会话并发保留时,各自读到旧账本再各写一条,会让同一条记忆出现两次。
|
|
429
|
+
*/
|
|
430
|
+
export async function withLock(scope, run, options = {}) {
|
|
431
|
+
const record = recordFor(scope, options)
|
|
432
|
+
const next = record.chain.then(run, run)
|
|
433
|
+
record.chain = next.then(() => undefined, () => undefined)
|
|
434
|
+
return await next
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** 注册表快照(测试与 SLO 用):每个库路径一个门面、一个子进程计数。 */
|
|
438
|
+
export function stats() {
|
|
439
|
+
return {
|
|
440
|
+
shuttingDown: SHUTDOWN !== null,
|
|
441
|
+
embedService: embedServiceStatsOf(),
|
|
442
|
+
facades: [...REGISTRY.values()].map((record) => {
|
|
443
|
+
const facadeStats = typeof record.facade.stats === 'function' ? record.facade.stats() : {}
|
|
444
|
+
return {
|
|
445
|
+
path: record.path,
|
|
446
|
+
workspace: record.workspace,
|
|
447
|
+
dim: record.dim,
|
|
448
|
+
refs: record.refs,
|
|
449
|
+
active: record.active,
|
|
450
|
+
closed: record.closed,
|
|
451
|
+
spawnCount: Number(facadeStats.spawnCount ?? 0),
|
|
452
|
+
pid: facadeStats.pid ?? null,
|
|
453
|
+
requests: Number(facadeStats.requests ?? 0),
|
|
454
|
+
}
|
|
455
|
+
}),
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ---------------------------------------------------------------------------
|
|
460
|
+
// 活写入路径的共用原语
|
|
461
|
+
// ---------------------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
/** 全量扫描的硬上限:`options.maxRows` 或 `KANABO_MEMORY_SCAN_MAX_ROWS` 可以调低(探针用它证明失败关闭)。 */
|
|
464
|
+
function scanMaxRows(options = {}) {
|
|
465
|
+
return positiveInt(options.maxRows, positiveInt(process.env.KANABO_MEMORY_SCAN_MAX_ROWS, SCAN_MAX_ROWS))
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function workspaceWhere(scope) {
|
|
469
|
+
return `n.kind == ${tqlString(MEMORY_KIND)} AND n.workspace == ${tqlString(scope)}`
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function scanIncomplete(scope, detail) {
|
|
473
|
+
return memoryError('KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE',
|
|
474
|
+
`无法完整扫描 workspace ${scope}(已读 ${detail.read} 行,上限 ${detail.maxRows},原因 ${detail.reason});`
|
|
475
|
+
+ '配额必须按全量判定,拒绝按部分和放行。',
|
|
476
|
+
{ scope, ...detail })
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* 引擎侧一次聚合:`count(*)` 是权威条数;`count(n.bytes)`/`sum(n.bytes)` 只看带顶层 `bytes` 镜像的行。
|
|
481
|
+
* `withBytes === count` 时 `known` 就是全量字节数;否则调用方必须分页逐行补齐(迁移/视觉旧行没有这个镜像)。
|
|
482
|
+
*/
|
|
483
|
+
async function aggregateWorkspace(facade, scope) {
|
|
484
|
+
const rows = rowsOf(await facade.tql(
|
|
485
|
+
`MATCH (n) WHERE ${workspaceWhere(scope)} RETURN count(*) AS total, count(n.bytes) AS withBytes, sum(n.bytes) AS known`))
|
|
486
|
+
const count = Number(rows[0]?.total)
|
|
487
|
+
const withBytes = Number(rows[0]?.withBytes)
|
|
488
|
+
const known = rows[0]?.known === null || rows[0]?.known === undefined ? null : Number(rows[0].known)
|
|
489
|
+
return {
|
|
490
|
+
count: Number.isSafeInteger(count) && count >= 0 ? count : null,
|
|
491
|
+
withBytes: Number.isSafeInteger(withBytes) && withBytes >= 0 ? withBytes : null,
|
|
492
|
+
known: Number.isFinite(known) ? known : null,
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* keyset 分页(按节点 id 升序;TQL 没有 SKIP/OFFSET,`n.id > lastId` 是唯一可用的稳定游标)。
|
|
498
|
+
* 超过硬上限、id 不前进、或读到超过上限的行数,一律抛失败关闭错误——绝不返回部分行假装全部。
|
|
499
|
+
*/
|
|
500
|
+
async function listAllNodes(facade, scope, options = {}) {
|
|
501
|
+
const pageSize = positiveInt(options.pageSize, SCAN_LIMIT)
|
|
502
|
+
const maxRows = scanMaxRows(options)
|
|
503
|
+
const expected = Number.isSafeInteger(options.expected) && options.expected >= 0 ? options.expected : null
|
|
504
|
+
const nodes = []
|
|
505
|
+
let pages = 0
|
|
506
|
+
let lastId = 0
|
|
507
|
+
for (;;) {
|
|
508
|
+
pages += 1
|
|
509
|
+
const page = rowsOf(await facade.tql(
|
|
510
|
+
`MATCH (n) WHERE ${workspaceWhere(scope)} AND n.id > ${lastId} `
|
|
511
|
+
+ `RETURN n.id AS nodeId, n AS node ORDER BY n.id ASC LIMIT ${pageSize}`))
|
|
512
|
+
if (page.length === 0) break
|
|
513
|
+
for (const row of page) {
|
|
514
|
+
const node = nodeOf(row)
|
|
515
|
+
if (node === null) continue
|
|
516
|
+
if (node.nodeId <= lastId) throw scanIncomplete(scope, { maxRows, read: nodes.length, pages, reason: 'non-monotonic-id' })
|
|
517
|
+
nodes.push(node)
|
|
518
|
+
lastId = node.nodeId
|
|
519
|
+
if (nodes.length > maxRows) throw scanIncomplete(scope, { maxRows, read: nodes.length, pages, reason: 'row-cap' })
|
|
520
|
+
}
|
|
521
|
+
if (expected !== null && nodes.length >= expected) break
|
|
522
|
+
if (page.length < pageSize) break
|
|
523
|
+
}
|
|
524
|
+
return { nodes, pages }
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* 扫描一个 workspace 的**全部**记忆节点:条数取引擎 `count(*)`,字节数按全量逐行求和
|
|
529
|
+
* (两条路径互相交叉校验:带上 `bytes` 镜像的行数等于总条数时,引擎的 `sum(n.bytes)` 必须与逐行和相等)。
|
|
530
|
+
*
|
|
531
|
+
* 行数超过 `SCAN_MAX_ROWS`(或 `KANABO_MEMORY_SCAN_MAX_ROWS`)时抛 `KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE`:
|
|
532
|
+
* 配额必须失败关闭,不能拿“新 N 条”的和去放行一条新写入。
|
|
533
|
+
* 条目按 `nodeId` 升序返回;需要「最新在前」的调用方自己按 ts 排序(工具都这么做)。
|
|
534
|
+
*/
|
|
535
|
+
export async function scanWorkspace(scope, options = {}) {
|
|
536
|
+
return await withFacade(scope, async (facade) => {
|
|
537
|
+
const aggregate = await aggregateWorkspace(facade, scope)
|
|
538
|
+
if (aggregate.count === null) {
|
|
539
|
+
throw memoryError('KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE',
|
|
540
|
+
`无法读取 workspace ${scope} 的条目总数(count(*) 未返回安全整数);拒绝按不确定的账本放行。`, { scope })
|
|
541
|
+
}
|
|
542
|
+
const listed = await listAllNodes(facade, scope, { ...options, expected: aggregate.count })
|
|
543
|
+
if (listed.nodes.length !== aggregate.count) {
|
|
544
|
+
throw scanIncomplete(scope, {
|
|
545
|
+
maxRows: scanMaxRows(options), read: listed.nodes.length, pages: listed.pages,
|
|
546
|
+
reason: 'count-mismatch', counted: aggregate.count,
|
|
547
|
+
})
|
|
548
|
+
}
|
|
549
|
+
const entries = []
|
|
550
|
+
let bytes = 0
|
|
551
|
+
for (const node of listed.nodes) {
|
|
552
|
+
const entry = entryOf(node)
|
|
553
|
+
if (entry === null) continue
|
|
554
|
+
entries.push(entry)
|
|
555
|
+
bytes += Buffer.byteLength(entry.text, 'utf8')
|
|
556
|
+
}
|
|
557
|
+
if (aggregate.withBytes === aggregate.count && aggregate.known !== null && aggregate.known !== bytes) {
|
|
558
|
+
throw memoryError('KANABO_MEMORY_QUOTA_SCAN_INCOMPLETE',
|
|
559
|
+
`workspace ${scope} 的字节和自相矛盾:引擎聚合 ${aggregate.known},逐行求和 ${bytes};拒绝按不确定的账本放行。`,
|
|
560
|
+
{ scope, aggregate: aggregate.known, summed: bytes })
|
|
561
|
+
}
|
|
562
|
+
return {
|
|
563
|
+
count: aggregate.count,
|
|
564
|
+
bytes,
|
|
565
|
+
bytesExact: true,
|
|
566
|
+
pages: listed.pages,
|
|
567
|
+
rows: listed.nodes,
|
|
568
|
+
entries,
|
|
569
|
+
countTruncated: false,
|
|
570
|
+
}
|
|
571
|
+
}, options)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** 一个会话已保留的轮次(带 origin 的条目):sweep 的账本口径,与 extract 的 `seen` 完全一致。
|
|
575
|
+
* 同样用 keyset 分页扫完(会话超过一页时不能少算),超过硬上限即失败关闭。 */
|
|
576
|
+
export async function countRetained(scope, sessionId, options = {}) {
|
|
577
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return 0
|
|
578
|
+
return await withFacade(scope, async (facade) => {
|
|
579
|
+
const pageSize = positiveInt(options.pageSize, SCAN_LIMIT)
|
|
580
|
+
const maxRows = scanMaxRows(options)
|
|
581
|
+
let retained = 0
|
|
582
|
+
let read = 0
|
|
583
|
+
let pages = 0
|
|
584
|
+
let lastId = 0
|
|
585
|
+
for (;;) {
|
|
586
|
+
pages += 1
|
|
587
|
+
const page = rowsOf(await facade.tql(
|
|
588
|
+
`MATCH (n) WHERE ${workspaceWhere(scope)} AND n.session_id == ${tqlString(sessionId)} AND n.id > ${lastId} `
|
|
589
|
+
+ `RETURN n.id AS nodeId, n AS node ORDER BY n.id ASC LIMIT ${pageSize}`))
|
|
590
|
+
if (page.length === 0) break
|
|
591
|
+
for (const row of page) {
|
|
592
|
+
const node = nodeOf(row)
|
|
593
|
+
if (node === null) continue
|
|
594
|
+
if (node.nodeId <= lastId) throw scanIncomplete(scope, { maxRows, read, pages, reason: 'non-monotonic-id' })
|
|
595
|
+
lastId = node.nodeId
|
|
596
|
+
read += 1
|
|
597
|
+
if (read > maxRows) throw scanIncomplete(scope, { maxRows, read, pages, reason: 'row-cap' })
|
|
598
|
+
const origin = node.payload?.envelope?.origin ?? node.payload?.origin
|
|
599
|
+
if (typeof origin === 'string' && RETENTION_ORIGINS.has(origin)) retained += 1
|
|
600
|
+
}
|
|
601
|
+
if (page.length < pageSize) break
|
|
602
|
+
}
|
|
603
|
+
return retained
|
|
604
|
+
}, options)
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** 按节点 id 读 payload(recall 工具补 topic 等工具输出字段用;只拼数字 id)。 */
|
|
608
|
+
export async function readByNodeIds(scope, nodeIds, options = {}) {
|
|
609
|
+
const ids = [...new Set((Array.isArray(nodeIds) ? nodeIds : []).filter((id) => Number.isSafeInteger(id)).slice(0, 200))]
|
|
610
|
+
if (ids.length === 0) return new Map()
|
|
611
|
+
return await withFacade(scope, async (facade) => {
|
|
612
|
+
const where = ids.map((id) => `n.id == ${id}`).join(' OR ')
|
|
613
|
+
const rows = rowsOf(await facade.tql(`MATCH (n) WHERE ${where} RETURN n.id AS nodeId, n AS node`))
|
|
614
|
+
const byId = new Map()
|
|
615
|
+
for (const row of rows) {
|
|
616
|
+
const node = nodeOf(row)
|
|
617
|
+
if (node === null) continue
|
|
618
|
+
const entry = entryOf(node)
|
|
619
|
+
if (entry !== null) byId.set(node.nodeId, entry)
|
|
620
|
+
}
|
|
621
|
+
return byId
|
|
622
|
+
}, options)
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// ---------------------------------------------------------------------------
|
|
626
|
+
// 活写入的会话边(任务 50):条目 ↔ 会话锚点,与 migrate.js 同构、幂等、批量
|
|
627
|
+
// ---------------------------------------------------------------------------
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* 每个库路径已知的锚点(sessionId → 节点 id)。锚点只被 insert、永不被删除(门面不暴露 delete),
|
|
631
|
+
* 所以同进程内缓存不会漂;唯一会让它失效的是快照恢复(`restoreSnapshot` 会清掉该路径的条目)。
|
|
632
|
+
* 作用:把「每条活写入都做一次全锚点 TQL」降到「稳态下每条活写入只写一批边」。
|
|
633
|
+
*
|
|
634
|
+
* @type {Map<string, Map<string, number>>}
|
|
635
|
+
*/
|
|
636
|
+
const ANCHOR_CACHE = new Map()
|
|
637
|
+
|
|
638
|
+
function anchorCacheOf(path) {
|
|
639
|
+
let cache = ANCHOR_CACHE.get(path)
|
|
640
|
+
if (cache === undefined) {
|
|
641
|
+
cache = new Map()
|
|
642
|
+
ANCHOR_CACHE.set(path, cache)
|
|
643
|
+
}
|
|
644
|
+
return cache
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* 读已有锚点(一次 TQL)并补插缺的(一次 `batch`,一次 flush)。返回该路径的锚点缓存。
|
|
649
|
+
* 锚点 payload 与 `migrate.js#anchorPayload` 逐字段一致:同 kind、同 `graph_role`、同 legacy_id 前缀,
|
|
650
|
+
* 因此迁移库与活写入库里的会话锚点是同一类节点,召回侧不需要两套规则。
|
|
651
|
+
*/
|
|
652
|
+
async function ensureSessionAnchors(facade, path, scope, sessionIds, ts) {
|
|
653
|
+
const cache = anchorCacheOf(path)
|
|
654
|
+
const missing = [...sessionIds].filter((sessionId) => !cache.has(sessionId))
|
|
655
|
+
if (missing.length === 0) return { cache, created: 0 }
|
|
656
|
+
const rows = rowsOf(await facade.tql(
|
|
657
|
+
`FIND {kind: ${tqlString(SESSION_NODE_KIND)}, workspace: ${tqlString(scope)}} RETURN *`))
|
|
658
|
+
for (const row of rows) {
|
|
659
|
+
// `FIND … RETURN *` 的每一行是 `{_: {id, payload}}`:必须走 nodeOf 解包,否则永远看不到已有锚点,
|
|
660
|
+
// 每次写入都会重复插入一个新锚点。
|
|
661
|
+
const node = nodeOf(row)
|
|
662
|
+
if (node === null) continue
|
|
663
|
+
const key = node.payload?.legacy_id
|
|
664
|
+
const sessionId = node.payload?.session_id
|
|
665
|
+
if (typeof key === 'string' && key.startsWith(SESSION_KEY_PREFIX)) {
|
|
666
|
+
cache.set(key.slice(SESSION_KEY_PREFIX.length), node.nodeId)
|
|
667
|
+
} else if (typeof sessionId === 'string' && !cache.has(sessionId)) {
|
|
668
|
+
cache.set(sessionId, node.nodeId)
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
const zero = new Array(EMBEDDING_DIM).fill(0)
|
|
672
|
+
const inserts = []
|
|
673
|
+
const insertedFor = []
|
|
674
|
+
for (const sessionId of missing) {
|
|
675
|
+
if (cache.has(sessionId)) continue
|
|
676
|
+
const payload = {
|
|
677
|
+
kind: SESSION_NODE_KIND,
|
|
678
|
+
// 图「胶水」标记:召回侧把锚点从命中里剔除,但图臂仍会经过它扩散。
|
|
679
|
+
graph_role: ANCHOR_GRAPH_ROLE,
|
|
680
|
+
workspace: scope,
|
|
681
|
+
legacy_id: `${SESSION_KEY_PREFIX}${sessionId}`,
|
|
682
|
+
session_id: sessionId,
|
|
683
|
+
ts,
|
|
684
|
+
text: `session ${sessionId}`,
|
|
685
|
+
}
|
|
686
|
+
inserts.push({ vector: zero, payload, text: payload.text })
|
|
687
|
+
insertedFor.push(sessionId)
|
|
688
|
+
}
|
|
689
|
+
if (inserts.length > 0) {
|
|
690
|
+
const result = await facade.batch(inserts)
|
|
691
|
+
const ids = Array.isArray(result?.ids) ? result.ids.map(Number) : []
|
|
692
|
+
for (let index = 0; index < insertedFor.length; index += 1) {
|
|
693
|
+
const id = nodeIdOf(ids[index])
|
|
694
|
+
if (id !== null) cache.set(insertedFor[index], id)
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
return { cache, created: inserts.length }
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** 边写入失败时的结构化回执:节点已经落盘,边写失败不能把整次写入反向标成失败。 */
|
|
701
|
+
function edgeFailure(error) {
|
|
702
|
+
return {
|
|
703
|
+
written: 0,
|
|
704
|
+
created: 0,
|
|
705
|
+
anchors: 0,
|
|
706
|
+
sessions: 0,
|
|
707
|
+
error: {
|
|
708
|
+
code: typeof error?.code === 'string' ? error.code : 'KANABO_MEMORY_EDGE',
|
|
709
|
+
message: String(error?.message ?? error),
|
|
710
|
+
},
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* 活写入的成员关系:条目 ↔ 会话锚点,`belongs_to_session` **双向**写(与 `migrate.js` 的双写同构)。
|
|
716
|
+
*
|
|
717
|
+
* TriviumDB 的边有向、图臂只走出边:只写「条目 → 锚点」时,从锚点出发永远走不到同会话的记忆,
|
|
718
|
+
* 也就无法证明「新记忆距自己的会话锚点 1 跳」。幂等由引擎的 (from,label,to) upsert 保证,
|
|
719
|
+
* 重放不会多出边——所以第二次写同一会话不会重复建锚点,也不会重复建边。
|
|
720
|
+
*
|
|
721
|
+
* 成本:一批条目只多一次 `link`(一次 flush)、稳态下 0 次 TQL 与 0 次锚点插入。
|
|
722
|
+
*/
|
|
723
|
+
async function writeSessionEdges(facade, path, scope, envelopes, ids) {
|
|
724
|
+
const pairs = []
|
|
725
|
+
const sessionIds = new Set()
|
|
726
|
+
let ts = 0
|
|
727
|
+
envelopes.forEach((envelope, index) => {
|
|
728
|
+
const nodeId = nodeIdOf(ids[index])
|
|
729
|
+
const sessionId = typeof envelope?.session?.id === 'string' ? envelope.session.id : ''
|
|
730
|
+
if (nodeId === null || sessionId === '') return
|
|
731
|
+
pairs.push({ nodeId, sessionId })
|
|
732
|
+
sessionIds.add(sessionId)
|
|
733
|
+
const stamp = Number(envelope?.ts)
|
|
734
|
+
if (Number.isSafeInteger(stamp) && stamp > ts) ts = stamp
|
|
735
|
+
})
|
|
736
|
+
if (pairs.length === 0) return { written: 0, created: 0, anchors: 0, sessions: 0 }
|
|
737
|
+
const ensured = await ensureSessionAnchors(facade, path, scope, sessionIds, ts)
|
|
738
|
+
const edges = []
|
|
739
|
+
for (const pair of pairs) {
|
|
740
|
+
const anchorId = ensured.cache.get(pair.sessionId)
|
|
741
|
+
if (anchorId === undefined) continue
|
|
742
|
+
edges.push({ from: pair.nodeId, to: anchorId, label: 'belongs_to_session', weight: 1 })
|
|
743
|
+
edges.push({ from: anchorId, to: pair.nodeId, label: 'belongs_to_session', weight: 1 })
|
|
744
|
+
}
|
|
745
|
+
if (edges.length === 0) {
|
|
746
|
+
return { written: 0, created: 0, anchors: ensured.created, sessions: sessionIds.size, error: { code: 'KANABO_MEMORY_ANCHOR', message: '会话锚点没有解析出节点 id' } }
|
|
747
|
+
}
|
|
748
|
+
let created = 0
|
|
749
|
+
for (let start = 0; start < edges.length; start += MAX_EDGE_BATCH) {
|
|
750
|
+
const result = await facade.link(edges.slice(start, start + MAX_EDGE_BATCH))
|
|
751
|
+
created += Number(result?.created ?? 0)
|
|
752
|
+
}
|
|
753
|
+
return { written: edges.length, created, anchors: ensured.created, sessions: sessionIds.size }
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* 追加一批信封:一次 `batch`(子进程内逐条插入、一次 flush),返回节点 id 与会话边回执。
|
|
758
|
+
* 向量写零向量(`vector` 缺省):活路径不加载 470MB 的嵌入模型,零向量被向量臂的
|
|
759
|
+
* `score <= minVectorScore` 过滤掉,文本臂照常命中——这是刻意的成本取舍,不是静默错误;
|
|
760
|
+
* 缺的向量由 `backfillVectors`(短命子进程)机会式补上(任务 50)。
|
|
761
|
+
*
|
|
762
|
+
* 会话边在节点落盘之后写:边写失败不会推翻已经成功保留的条目(`edges.error` 如实返回,
|
|
763
|
+
* 下一次同会话写入会把缺的边 upsert 回来)。锚点缓存失效(快照恢复过)时清缓存重试一次。
|
|
764
|
+
*/
|
|
765
|
+
export async function appendEnvelopes(scope, envelopes, options = {}) {
|
|
766
|
+
const list = (Array.isArray(envelopes) ? envelopes : []).filter((envelope) => envelope !== null && typeof envelope === 'object')
|
|
767
|
+
if (list.length === 0) return { ids: [], count: 0, edges: null }
|
|
768
|
+
const vectors = Array.isArray(options?.vectors) ? options.vectors : null
|
|
769
|
+
// 契约必须在入口强制:`appendEnvelopes` 是活写入的唯一入口,不校验就等于「契约只写在文档里」。
|
|
770
|
+
// 非法 source_type / 缺必填字段在这里就拒绝,绝不让它落库后被读侧当成合法数据。
|
|
771
|
+
const { validateEnvelope } = await import('./envelope.js')
|
|
772
|
+
const validated = list.map((envelope) => validateEnvelope(envelope))
|
|
773
|
+
const items = validated.map((envelope, index) => {
|
|
774
|
+
const payload = payloadFor(scope, envelope)
|
|
775
|
+
const item = { payload, text: indexTextFor(payload.topic, envelopeTextOf(envelope)) }
|
|
776
|
+
const vector = vectors === null ? null : realVectorOrNull(vectors[index])
|
|
777
|
+
if (vector !== null) item.vector = vector
|
|
778
|
+
return item
|
|
779
|
+
})
|
|
780
|
+
return await withFacade(scope, async (facade, record) => {
|
|
781
|
+
const result = await facade.batch(items)
|
|
782
|
+
const ids = Array.isArray(result?.ids) ? result.ids.map(Number) : []
|
|
783
|
+
let edges
|
|
784
|
+
try {
|
|
785
|
+
edges = await writeSessionEdges(facade, record.path, scope, list, ids)
|
|
786
|
+
} catch (error) {
|
|
787
|
+
// 只在「锚点缓存指向的节点已不存在」(快照恢复)时清缓存重试一次;其它错误如实返回。
|
|
788
|
+
if (String(error?.dbCode ?? '') === 'KANABO_TRIVIUM_NODE_NOT_FOUND' || /NODE_NOT_FOUND/.test(String(error?.message ?? ''))) {
|
|
789
|
+
ANCHOR_CACHE.delete(record.path)
|
|
790
|
+
try {
|
|
791
|
+
edges = await writeSessionEdges(facade, record.path, scope, list, ids)
|
|
792
|
+
} catch (again) {
|
|
793
|
+
edges = edgeFailure(again)
|
|
794
|
+
}
|
|
795
|
+
} else {
|
|
796
|
+
edges = edgeFailure(error)
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return { ids, count: Number(result?.count ?? ids.length), edges }
|
|
800
|
+
}, options)
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** 窗口查询专用索引:0.9.3 的 t0 区间条件要 ordered index 才走索引;幂等,写路径负责建。 */
|
|
804
|
+
export async function ensureWindowIndex(scope, options = {}) {
|
|
805
|
+
return await withFacade(scope, async (facade) => await facade.createOrderedIndex('t0'), options)
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* 时间窗查询(query-window.js 注入本门面):先窗后语义仍由调用方给 `semanticQuery`。
|
|
810
|
+
* 这里只为「同一个门面」服务——本函数绝不新建门面。
|
|
811
|
+
*/
|
|
812
|
+
export async function windowQuery(scope, params = {}, options = {}) {
|
|
813
|
+
const { createWindowQuery } = await import('./query-window.js')
|
|
814
|
+
return await withFacade(scope, async (facade) => {
|
|
815
|
+
const query = createWindowQuery({ store: facade })
|
|
816
|
+
try {
|
|
817
|
+
return await query.windowQuery(params)
|
|
818
|
+
} finally {
|
|
819
|
+
await query.close()
|
|
820
|
+
}
|
|
821
|
+
}, options)
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// ---------------------------------------------------------------------------
|
|
825
|
+
// 快照:关到租约释放 → fork 短命 helper 用引擎原生 API → 结果回传
|
|
826
|
+
// ---------------------------------------------------------------------------
|
|
827
|
+
|
|
828
|
+
function snapshotRoot(options = {}) {
|
|
829
|
+
return options.snapshotRoot ?? join(options.dir ?? triviumDir(), 'snapshots')
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function fileBase(dbPath) {
|
|
833
|
+
return basename(dbPath)
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
function liveSuffixes(dbPath) {
|
|
837
|
+
const dir = dirname(dbPath)
|
|
838
|
+
const base = fileBase(dbPath)
|
|
839
|
+
if (!existsSync(dir)) return []
|
|
840
|
+
return readdirSync(dir)
|
|
841
|
+
.filter((name) => name === base || name.startsWith(`${base}.`))
|
|
842
|
+
.map((name) => (name === base ? '' : name.slice(base.length)))
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function digestOf(path) {
|
|
846
|
+
return { size: statSync(path).size, sha256: sha256(readFileSync(path)) }
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/** 关掉并移出注册表里的一个记录(快照/恢复的独占前提)。 */
|
|
850
|
+
async function closePath(path) {
|
|
851
|
+
const record = REGISTRY.get(path)
|
|
852
|
+
if (record === undefined) return { closed: false, pid: null }
|
|
853
|
+
REGISTRY.delete(path)
|
|
854
|
+
record.closed = true
|
|
855
|
+
const result = await record.facade.close()
|
|
856
|
+
return { closed: true, pid: result?.lastExit?.pid ?? null, lastExit: result?.lastExit ?? null }
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** 等待该路径上没有在途请求(两阶段关闭的第一阶段:停止接新 + 排空旧)。 */
|
|
860
|
+
async function waitIdle(record, timeoutMs) {
|
|
861
|
+
const deadline = Date.now() + timeoutMs
|
|
862
|
+
while (record.active > 0 && Date.now() < deadline) {
|
|
863
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 10))
|
|
864
|
+
}
|
|
865
|
+
return record.active === 0
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** 两阶段关闭的第一阶段:拒绝新请求,启动排空 + 关闭,返回请求回执而不阻塞。 */
|
|
869
|
+
export function requestShutdown() {
|
|
870
|
+
if (SHUTDOWN === null) {
|
|
871
|
+
const facades = REGISTRY.size
|
|
872
|
+
SHUTDOWN = { requestedAt: Date.now(), promise: null, result: null }
|
|
873
|
+
SHUTDOWN.promise = drainAndCloseAll()
|
|
874
|
+
return { requested: true, requestedAt: SHUTDOWN.requestedAt, facades }
|
|
875
|
+
}
|
|
876
|
+
if (SHUTDOWN.promise === null) SHUTDOWN.promise = drainAndCloseAll()
|
|
877
|
+
return { requested: true, requestedAt: SHUTDOWN.requestedAt, facades: 0 }
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
async function drainAndCloseAll() {
|
|
881
|
+
// 回填子进程先退:它持有的是同一个库路径的租约,关门面之前不先拿回去,facade.close() 会等一个
|
|
882
|
+
// 它自己不会释放的租约。取消走 SIGTERM → 限时 SIGKILL,与回合抢占同一套边界。
|
|
883
|
+
const backfills = await cancelBackfills('shutdown')
|
|
884
|
+
const embedService = await closeEmbedService(2_000)
|
|
885
|
+
const records = [...REGISTRY.values()]
|
|
886
|
+
REGISTRY.clear()
|
|
887
|
+
const closed = []
|
|
888
|
+
for (const record of records) {
|
|
889
|
+
record.closed = true
|
|
890
|
+
const drained = await waitIdle(record, 5000)
|
|
891
|
+
let outcome = null
|
|
892
|
+
try {
|
|
893
|
+
outcome = await record.facade.close()
|
|
894
|
+
} catch (error) {
|
|
895
|
+
outcome = { closed: false, error: typeof error?.code === 'string' ? error.code : String(error) }
|
|
896
|
+
}
|
|
897
|
+
closed.push({
|
|
898
|
+
path: record.path,
|
|
899
|
+
workspace: record.workspace,
|
|
900
|
+
drained,
|
|
901
|
+
closed: outcome?.closed === true,
|
|
902
|
+
pid: outcome?.lastExit?.pid ?? null,
|
|
903
|
+
lastExit: outcome?.lastExit ?? null,
|
|
904
|
+
error: outcome?.error ?? null,
|
|
905
|
+
})
|
|
906
|
+
}
|
|
907
|
+
const leftoverPids = []
|
|
908
|
+
for (const row of closed) {
|
|
909
|
+
const pid = row.lastExit?.pid
|
|
910
|
+
if (!Number.isInteger(pid) || pid <= 0) continue
|
|
911
|
+
try {
|
|
912
|
+
process.kill(pid, 0)
|
|
913
|
+
leftoverPids.push(pid)
|
|
914
|
+
} catch {
|
|
915
|
+
// ESRCH:进程已消失(租约由内核释放)。
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return { closed: closed.every((row) => row.closed), facades: closed, leftoverPids, backfills, embedService, closedAt: Date.now() }
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** 两阶段关闭的第二阶段:在期限内等第一阶段完成;超时如实返回(不假装已关)。 */
|
|
922
|
+
export async function close(options = {}) {
|
|
923
|
+
const timeoutMs = positiveInt(options.timeoutMs, 15_000)
|
|
924
|
+
requestShutdown()
|
|
925
|
+
let timer
|
|
926
|
+
const expiry = new Promise((resolveExpiry) => {
|
|
927
|
+
timer = setTimeout(() => resolveExpiry({ timedOut: true }), timeoutMs)
|
|
928
|
+
timer.unref?.()
|
|
929
|
+
})
|
|
930
|
+
let outcome
|
|
931
|
+
try {
|
|
932
|
+
outcome = await Promise.race([SHUTDOWN.promise.then((value) => ({ timedOut: false, value })), expiry])
|
|
933
|
+
} finally {
|
|
934
|
+
clearTimeout(timer)
|
|
935
|
+
}
|
|
936
|
+
if (outcome.timedOut === true) {
|
|
937
|
+
return { closed: false, timedOut: true, facades: [], leftoverPids: [], timeoutMs }
|
|
938
|
+
}
|
|
939
|
+
SHUTDOWN.result = outcome.value
|
|
940
|
+
return { ...outcome.value, timedOut: false, timeoutMs }
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** 重置关闭状态:只给同进程内的多轮探针用(生产里关闭是终态)。 */
|
|
944
|
+
export function resetShutdownForTest() {
|
|
945
|
+
SHUTDOWN = null
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function runHelper(args, options = {}) {
|
|
949
|
+
const timeoutMs = positiveInt(options.timeoutMs, SNAPSHOT_TIMEOUT_MS)
|
|
950
|
+
return new Promise((resolveRun, rejectRun) => {
|
|
951
|
+
let child
|
|
952
|
+
try {
|
|
953
|
+
child = spawn(process.execPath, [MODULE_PATH, '--trivium-helper', ...args], {
|
|
954
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
955
|
+
env: { ...process.env },
|
|
956
|
+
})
|
|
957
|
+
} catch (error) {
|
|
958
|
+
rejectRun(memoryError('KANABO_MEMORY_HELPER', `无法启动快照 helper:${error?.message ?? String(error)}`))
|
|
959
|
+
return
|
|
960
|
+
}
|
|
961
|
+
let stdout = ''
|
|
962
|
+
let stderr = ''
|
|
963
|
+
let settled = false
|
|
964
|
+
const finish = (error, value) => {
|
|
965
|
+
if (settled) return
|
|
966
|
+
settled = true
|
|
967
|
+
clearTimeout(timer)
|
|
968
|
+
if (error) rejectRun(error)
|
|
969
|
+
else resolveRun(value)
|
|
970
|
+
}
|
|
971
|
+
const timer = setTimeout(() => {
|
|
972
|
+
try {
|
|
973
|
+
child.kill('SIGKILL')
|
|
974
|
+
} catch {
|
|
975
|
+
// 已经退出。
|
|
976
|
+
}
|
|
977
|
+
finish(memoryError('KANABO_MEMORY_HELPER_TIMEOUT', `快照 helper(${args[0]})超过 ${timeoutMs}ms 未完成,已 SIGKILL。`))
|
|
978
|
+
}, timeoutMs)
|
|
979
|
+
child.stdout.setEncoding('utf8')
|
|
980
|
+
child.stdout.on('data', (chunk) => { stdout += chunk })
|
|
981
|
+
child.stderr.setEncoding('utf8')
|
|
982
|
+
child.stderr.on('data', (chunk) => { stderr += chunk })
|
|
983
|
+
child.on('error', (error) => finish(memoryError('KANABO_MEMORY_HELPER', `快照 helper 启动失败:${error?.message ?? String(error)}`)))
|
|
984
|
+
child.on('exit', (code, signal) => {
|
|
985
|
+
const lines = stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '')
|
|
986
|
+
let parsed = null
|
|
987
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
988
|
+
try {
|
|
989
|
+
parsed = JSON.parse(lines[index])
|
|
990
|
+
break
|
|
991
|
+
} catch {
|
|
992
|
+
// 不是 JSON 行,继续往前找。
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
if (parsed === null) {
|
|
996
|
+
finish(memoryError('KANABO_MEMORY_HELPER',
|
|
997
|
+
`快照 helper(${args[0]})没有输出 JSON(exit=${String(code)}, signal=${String(signal)}):${stderr.slice(-800)}`))
|
|
998
|
+
return
|
|
999
|
+
}
|
|
1000
|
+
if (parsed.ok !== true) {
|
|
1001
|
+
finish(memoryError(parsed.error?.code ?? 'KANABO_MEMORY_HELPER', parsed.error?.message ?? '快照 helper 失败', parsed.error?.details))
|
|
1002
|
+
return
|
|
1003
|
+
}
|
|
1004
|
+
finish(null, parsed.value)
|
|
1005
|
+
})
|
|
1006
|
+
})
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* 创建快照:先释放租约,再让 helper 用引擎原生 `createSnapshot` 抓整个库目录。
|
|
1011
|
+
* `destination` 缺省为 `<triviumDir>/snapshots/<workspace 文件基名>/<generationId>`;已存在即失败,绝不覆盖。
|
|
1012
|
+
*/
|
|
1013
|
+
export async function createSnapshot(scopeOrOptions = {}, options = {}) {
|
|
1014
|
+
const settings = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions, ...options } : { ...scopeOrOptions }
|
|
1015
|
+
const scope = settings.scope
|
|
1016
|
+
const path = dbPathOf(scope, { dir: settings.dir })
|
|
1017
|
+
const generationId = typeof settings.generationId === 'string' && settings.generationId.length > 0
|
|
1018
|
+
? settings.generationId
|
|
1019
|
+
: `gen-${new Date().toISOString().replace(/[:.]/g, '-')}-${Math.random().toString(36).slice(2, 8)}`
|
|
1020
|
+
const destination = resolve(settings.destination
|
|
1021
|
+
?? join(snapshotRoot(settings), fileBase(path).replace(/\.tdb$/, ''), generationId))
|
|
1022
|
+
if (existsSync(destination)) {
|
|
1023
|
+
throw memoryError('KANABO_MEMORY_SNAPSHOT_EXISTS', `快照目录已存在,拒绝覆盖:${destination}`, { destination, generationId })
|
|
1024
|
+
}
|
|
1025
|
+
const closed = await closePath(path)
|
|
1026
|
+
const value = await runHelper(['create', path, destination, generationId],
|
|
1027
|
+
{ timeoutMs: settings.timeoutMs })
|
|
1028
|
+
return {
|
|
1029
|
+
ok: true,
|
|
1030
|
+
scope,
|
|
1031
|
+
dbPath: path,
|
|
1032
|
+
generationId,
|
|
1033
|
+
destination,
|
|
1034
|
+
manifest: value?.manifest ?? null,
|
|
1035
|
+
nodeCount: value?.nodeCount ?? null,
|
|
1036
|
+
closedFacade: closed.closed,
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* 校验快照:① 引擎的制品完整性;② 与活库当前字节逐文件比对(漂移检测)。
|
|
1042
|
+
* 只读:不关任何门面(读文件不需要租约)。
|
|
1043
|
+
*/
|
|
1044
|
+
export async function verifySnapshotArtifacts(scopeOrOptions = {}, options = {}) {
|
|
1045
|
+
const settings = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions, ...options } : { ...scopeOrOptions }
|
|
1046
|
+
const snapshotDir = resolve(settings.snapshotDir ?? settings.destination
|
|
1047
|
+
?? (() => { throw memoryError('KANABO_MEMORY_SNAPSHOT', 'verifySnapshotArtifacts 需要 snapshotDir(或 destination)') })())
|
|
1048
|
+
const manifest = await runHelper(['verify', snapshotDir], { timeoutMs: settings.timeoutMs })
|
|
1049
|
+
const result = { ok: true, snapshotDir, manifest, drift: [], extra: [], sidecars: [], live: null }
|
|
1050
|
+
if (typeof settings.scope !== 'string' || settings.scope.length === 0) return result
|
|
1051
|
+
const dbPath = dbPathOf(settings.scope, { dir: settings.dir })
|
|
1052
|
+
result.live = { path: dbPath, exists: existsSync(dbPath) }
|
|
1053
|
+
if (!existsSync(dbPath)) return result
|
|
1054
|
+
const declared = new Set()
|
|
1055
|
+
for (const file of Array.isArray(manifest?.files) ? manifest.files : []) {
|
|
1056
|
+
const suffix = String(file?.suffix ?? '')
|
|
1057
|
+
declared.add(suffix)
|
|
1058
|
+
const livePath = `${dbPath}${suffix}`
|
|
1059
|
+
if (!existsSync(livePath)) {
|
|
1060
|
+
result.drift.push({ suffix: suffix === '' ? '(base)' : suffix, reason: 'missing' })
|
|
1061
|
+
continue
|
|
1062
|
+
}
|
|
1063
|
+
const live = digestOf(livePath)
|
|
1064
|
+
const sameSize = Number(file?.size) === live.size
|
|
1065
|
+
const sameHash = typeof file?.sha256 === 'string' ? file.sha256 === live.sha256 : true
|
|
1066
|
+
if (!sameSize || !sameHash) {
|
|
1067
|
+
result.drift.push({
|
|
1068
|
+
suffix: suffix === '' ? '(base)' : suffix,
|
|
1069
|
+
reason: sameSize ? 'content' : 'size',
|
|
1070
|
+
expected: { size: file?.size ?? null, sha256: file?.sha256 ?? null },
|
|
1071
|
+
actual: live,
|
|
1072
|
+
})
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
for (const suffix of liveSuffixes(dbPath)) {
|
|
1076
|
+
if (declared.has(suffix)) continue
|
|
1077
|
+
if (ENGINE_SIDECARS.has(suffix)) {
|
|
1078
|
+
result.sidecars.push(suffix)
|
|
1079
|
+
continue
|
|
1080
|
+
}
|
|
1081
|
+
result.extra.push({ suffix, reason: 'not-in-snapshot' })
|
|
1082
|
+
}
|
|
1083
|
+
result.ok = result.drift.length === 0 && result.extra.length === 0
|
|
1084
|
+
return result
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* 恢复快照:恢复到临时目录 → 引擎再校验 → 活库文件移到 `.backup-<ts>` → 恢复文件按活库基名搬回。
|
|
1089
|
+
* 返回恢复后的清单、备份目录与搬动明细;调用方(或下一次请求)会惰性重开一个新门面。
|
|
1090
|
+
*/
|
|
1091
|
+
export async function restoreSnapshot(scopeOrOptions = {}, options = {}) {
|
|
1092
|
+
const settings = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions, ...options } : { ...scopeOrOptions }
|
|
1093
|
+
const scope = settings.scope
|
|
1094
|
+
const path = dbPathOf(scope, { dir: settings.dir })
|
|
1095
|
+
const snapshotDir = resolve(settings.snapshotDir ?? settings.destination
|
|
1096
|
+
?? (() => { throw memoryError('KANABO_MEMORY_SNAPSHOT', 'restoreSnapshot 需要 snapshotDir(或 destination)') })())
|
|
1097
|
+
const closed = await closePath(path)
|
|
1098
|
+
const result = await runHelper(['restore', snapshotDir, path], { timeoutMs: settings.timeoutMs })
|
|
1099
|
+
// 快照会换掉整个库目录:进程内所有「该路径下已知锚点」的缓存随机失效,必须清掉。
|
|
1100
|
+
ANCHOR_CACHE.delete(path)
|
|
1101
|
+
return { ok: true, scope, dbPath: path, snapshotDir, ...result, closedFacade: closed.closed }
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// ---------------------------------------------------------------------------
|
|
1105
|
+
// 向量回填:关掉租约 → 短命子进程 open/嵌入/写回/flush/退出(任务 50)
|
|
1106
|
+
// ---------------------------------------------------------------------------
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* 运行中的回填预留(每库路径一条)。`exited` 永远会 settle:子进程退出、启动失败或被抢占取消都会落值,
|
|
1110
|
+
* 所以 `preemptBackfill` 可以无期限地 await 它(取消本身带 SIGTERM → 限时 SIGKILL)。
|
|
1111
|
+
*
|
|
1112
|
+
* @type {Map<string, {startedAt:number, aborted:boolean, exited:Promise<object>, cancel:(reason?:string)=>void}>}
|
|
1113
|
+
*/
|
|
1114
|
+
const BACKFILL = new Map()
|
|
1115
|
+
/** 同一时刻只允许一个回填子进程:模型约 1.2GB,两个就逼近 4GB 包络。 */
|
|
1116
|
+
let ACTIVE_BACKFILL = null
|
|
1117
|
+
|
|
1118
|
+
/** 当前回填状态(测试/运维用):运行中的库路径、是否已有全局槽位被占。 */
|
|
1119
|
+
export function backfillStats() {
|
|
1120
|
+
return {
|
|
1121
|
+
running: [...BACKFILL.keys()],
|
|
1122
|
+
active: ACTIVE_BACKFILL,
|
|
1123
|
+
anchorsCached: [...ANCHOR_CACHE.values()].reduce((total, cache) => total + cache.size, 0),
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* 让该路径上的回填让步。返回是否确实抢占了一个在跑/待跑的回填。
|
|
1129
|
+
*
|
|
1130
|
+
* 为什么要抢占而不是排队:回填加载模型要秒级、写回要秒级,排到回合前面就是把回合延迟
|
|
1131
|
+
* 变成回填时长;而排队等回填结束再放行同样不行。所以回合优先,回填最多再跑当前这一批。
|
|
1132
|
+
*/
|
|
1133
|
+
async function preemptBackfill(path) {
|
|
1134
|
+
const reservation = BACKFILL.get(path)
|
|
1135
|
+
if (reservation === undefined) return false
|
|
1136
|
+
BACKFILL.delete(path)
|
|
1137
|
+
reservation.cancel('preempted')
|
|
1138
|
+
await reservation.exited
|
|
1139
|
+
return true
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/** 关闭前取消所有回填(两阶段关闭的第一阶段):回填不得继续持有库租约。 */
|
|
1143
|
+
async function cancelBackfills(reason) {
|
|
1144
|
+
const reservations = [...BACKFILL.entries()]
|
|
1145
|
+
BACKFILL.clear()
|
|
1146
|
+
for (const [, reservation] of reservations) reservation.cancel(reason)
|
|
1147
|
+
if (reservations.length > 0) {
|
|
1148
|
+
const grace = new Promise((resolveGrace) => {
|
|
1149
|
+
const timer = setTimeout(resolveGrace, BACKFILL_PREEMPT_GRACE_MS + 1_000)
|
|
1150
|
+
timer.unref?.()
|
|
1151
|
+
})
|
|
1152
|
+
await Promise.race([Promise.all(reservations.map(([, reservation]) => reservation.exited)), grace])
|
|
1153
|
+
}
|
|
1154
|
+
return reservations.length
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* 回填预留:一个 promise 收敛「子进程退出/启动失败/被取消」三种结局,stdout 只认最后一条非进度 JSON。
|
|
1159
|
+
* 超时上限是父进程侧的硬期限:到点 SIGTERM,再过 grace 仍不退则 SIGKILL——已 flush 的批次保留。
|
|
1160
|
+
*/
|
|
1161
|
+
function createBackfillReservation(timeoutMs) {
|
|
1162
|
+
let settle
|
|
1163
|
+
const exited = new Promise((resolveExit) => { settle = resolveExit })
|
|
1164
|
+
let done = false
|
|
1165
|
+
let timer = null
|
|
1166
|
+
let child = null
|
|
1167
|
+
let stdout = ''
|
|
1168
|
+
let stderr = ''
|
|
1169
|
+
const finish = (value) => {
|
|
1170
|
+
if (done) return
|
|
1171
|
+
done = true
|
|
1172
|
+
clearTimeout(timer)
|
|
1173
|
+
settle(value)
|
|
1174
|
+
}
|
|
1175
|
+
const killSoon = (proc) => {
|
|
1176
|
+
try {
|
|
1177
|
+
proc.kill('SIGTERM')
|
|
1178
|
+
} catch {
|
|
1179
|
+
// 已经退出。
|
|
1180
|
+
}
|
|
1181
|
+
const hard = setTimeout(() => {
|
|
1182
|
+
try {
|
|
1183
|
+
proc.kill('SIGKILL')
|
|
1184
|
+
} catch {
|
|
1185
|
+
// 同上。
|
|
1186
|
+
}
|
|
1187
|
+
}, BACKFILL_PREEMPT_GRACE_MS)
|
|
1188
|
+
hard.unref?.()
|
|
1189
|
+
}
|
|
1190
|
+
const reservation = {
|
|
1191
|
+
startedAt: Date.now(),
|
|
1192
|
+
aborted: false,
|
|
1193
|
+
timedOut: false,
|
|
1194
|
+
exited,
|
|
1195
|
+
cancel(reason) {
|
|
1196
|
+
reservation.aborted = true
|
|
1197
|
+
if (child === null) {
|
|
1198
|
+
finish({ exited: true, killed: false, reason: reason ?? 'preempted', summary: null, stderr: '' })
|
|
1199
|
+
return
|
|
1200
|
+
}
|
|
1201
|
+
killSoon(child)
|
|
1202
|
+
},
|
|
1203
|
+
attach(proc) {
|
|
1204
|
+
child = proc
|
|
1205
|
+
timer = setTimeout(() => {
|
|
1206
|
+
reservation.timedOut = true
|
|
1207
|
+
killSoon(proc)
|
|
1208
|
+
}, timeoutMs)
|
|
1209
|
+
timer.unref?.()
|
|
1210
|
+
proc.stdout.setEncoding('utf8')
|
|
1211
|
+
proc.stdout.on('data', (chunk) => { stdout += chunk })
|
|
1212
|
+
proc.stderr.setEncoding('utf8')
|
|
1213
|
+
proc.stderr.on('data', (chunk) => { stderr = `${stderr}${chunk}`.slice(-4000) })
|
|
1214
|
+
proc.on('error', (error) => {
|
|
1215
|
+
finish({ exited: true, killed: false, spawnError: String(error?.message ?? error), summary: null, stderr })
|
|
1216
|
+
})
|
|
1217
|
+
proc.on('exit', (code, signal) => {
|
|
1218
|
+
const lines = stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '')
|
|
1219
|
+
let summary = null
|
|
1220
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
1221
|
+
try {
|
|
1222
|
+
const parsed = JSON.parse(lines[index])
|
|
1223
|
+
if (parsed !== null && typeof parsed === 'object' && parsed.type !== 'progress') {
|
|
1224
|
+
summary = parsed
|
|
1225
|
+
break
|
|
1226
|
+
}
|
|
1227
|
+
} catch {
|
|
1228
|
+
// 不是 JSON 行,继续往前找。
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
finish({
|
|
1232
|
+
exited: true,
|
|
1233
|
+
killed: signal !== null,
|
|
1234
|
+
code,
|
|
1235
|
+
signal,
|
|
1236
|
+
summary,
|
|
1237
|
+
stderr,
|
|
1238
|
+
timedOut: reservation.timedOut === true,
|
|
1239
|
+
aborted: reservation.aborted === true,
|
|
1240
|
+
})
|
|
1241
|
+
})
|
|
1242
|
+
},
|
|
1243
|
+
}
|
|
1244
|
+
return reservation
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/** 回填遥测文件:只记「上一次运行做了什么」,绝不作为「哪些节点已回填」的真相来源。 */
|
|
1248
|
+
function writeBackfillState(options, result) {
|
|
1249
|
+
if (options.state === false) return
|
|
1250
|
+
try {
|
|
1251
|
+
const dir = resolve(options.dir ?? triviumDir())
|
|
1252
|
+
mkdirSync(dir, { recursive: true })
|
|
1253
|
+
const file = join(dir, BACKFILL_STATE_FILE)
|
|
1254
|
+
let previous = null
|
|
1255
|
+
try {
|
|
1256
|
+
previous = JSON.parse(readFileSync(file, 'utf8'))
|
|
1257
|
+
} catch {
|
|
1258
|
+
previous = null
|
|
1259
|
+
}
|
|
1260
|
+
const runs = Number.isSafeInteger(previous?.runs) ? previous.runs : 0
|
|
1261
|
+
writeFileSync(file, `${JSON.stringify({ version: 1, updatedAt: Date.now(), runs: runs + (result.ran === true ? 1 : 0), last: result }, null, 2)}\n`)
|
|
1262
|
+
} catch {
|
|
1263
|
+
// 遥测写不进去不影响回填结果本身。
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* 向量回填入口:把「零向量的记忆节点」用 `embed.js` 补成真实嵌入,节点不动、边不动、锚点不碰。
|
|
1269
|
+
*
|
|
1270
|
+
* 前提与顺序(与快照同一模式,见文件头 §4):
|
|
1271
|
+
* 1. 该路径没有在途请求、全局没有其它回填在跑;否则本次不动(`why:'busy'|'already-running'`)。
|
|
1272
|
+
* 2. 先把库路径上的门面关掉——插件进程从不 open 库,租约必须由回填子进程独占。
|
|
1273
|
+
* 3. fork `backfill-child.js`:它扫零向量节点、分批 `passage: ` 嵌入、`updateVector` + `flush`、退出。
|
|
1274
|
+
* 4. 任何时刻有回合请求进来,`ensureOpen` 会抢占(SIGTERM → 限时 SIGKILL),下一次写入重新开门面。
|
|
1275
|
+
*
|
|
1276
|
+
* 失败语义:子进程崩溃/超时只意味着「这批没写完」——已写的是完整向量,没写的保持零向量并在下一次
|
|
1277
|
+
* 运行重试;绝不把降级结果(`degraded`、全零、非有限数)写成「已回填」。
|
|
1278
|
+
*/
|
|
1279
|
+
export async function backfillVectors(scopeOrOptions = {}, options = {}) {
|
|
1280
|
+
const settings = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions, ...options } : { ...scopeOrOptions }
|
|
1281
|
+
const scope = settings.scope
|
|
1282
|
+
const path = dbPathOf(scope, { dir: settings.dir })
|
|
1283
|
+
const base = { scope, dbPath: path }
|
|
1284
|
+
if (SHUTDOWN !== null) return { ran: false, why: 'shutting-down', ...base }
|
|
1285
|
+
if (BACKFILL.has(path)) return { ran: false, why: 'already-running', ...base }
|
|
1286
|
+
if (ACTIVE_BACKFILL !== null) return { ran: false, why: 'already-running', activePath: ACTIVE_BACKFILL, ...base }
|
|
1287
|
+
const record = REGISTRY.get(path)
|
|
1288
|
+
if (record !== undefined && record.active > 0) return { ran: false, why: 'busy', ...base }
|
|
1289
|
+
// 不存在的库不建空文件:回填只补「已经有记忆」的库(engine 在 open 时会为一个新路径建库)。
|
|
1290
|
+
if (!existsSync(path)) return { ran: false, why: 'no-database', ...base }
|
|
1291
|
+
|
|
1292
|
+
const timeoutMs = positiveInt(settings.timeoutMs, BACKFILL_TIMEOUT_MS)
|
|
1293
|
+
const reservation = createBackfillReservation(timeoutMs)
|
|
1294
|
+
BACKFILL.set(path, reservation)
|
|
1295
|
+
ACTIVE_BACKFILL = path
|
|
1296
|
+
let closedFacade = false
|
|
1297
|
+
try {
|
|
1298
|
+
// 同一时刻只驻留一个模型:常驻向量服务(约 1.2GB)让位给回填子进程(约 1.2GB),两者不叠加。
|
|
1299
|
+
// 必须放在预留之后:并发的两个回填由同一个预留挡住,而不是在关服务那一格各自过关。
|
|
1300
|
+
await closeEmbedService(BACKFILL_PREEMPT_GRACE_MS + 850)
|
|
1301
|
+
const closed = await closePath(path)
|
|
1302
|
+
closedFacade = closed.closed
|
|
1303
|
+
// 关租约的间隙里可能已经有回合请求进来(它会在 ensureOpen 里抢占我们)。
|
|
1304
|
+
if (reservation.aborted || BACKFILL.get(path) !== reservation) {
|
|
1305
|
+
return { ran: false, why: 'preempted', ...base, closedFacade }
|
|
1306
|
+
}
|
|
1307
|
+
const config = {
|
|
1308
|
+
path,
|
|
1309
|
+
scope,
|
|
1310
|
+
dim: positiveInt(record?.dim, positiveInt(settings.dim, EMBEDDING_DIM)),
|
|
1311
|
+
batchSize: positiveInt(settings.batchSize, 16),
|
|
1312
|
+
maxNodes: positiveInt(settings.maxNodes, BACKFILL_MAX_NODES),
|
|
1313
|
+
pageSize: positiveInt(settings.pageSize, 500),
|
|
1314
|
+
quiet: settings.quiet !== false,
|
|
1315
|
+
deadline: Date.now() + Math.max(1_000, timeoutMs - 5_000),
|
|
1316
|
+
stateFile: BACKFILL_STATE_FILE,
|
|
1317
|
+
}
|
|
1318
|
+
let child
|
|
1319
|
+
try {
|
|
1320
|
+
child = spawn(process.execPath, [BACKFILL_CHILD], {
|
|
1321
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1322
|
+
env: { ...process.env, KANABO_BACKFILL_CHILD: JSON.stringify(config) },
|
|
1323
|
+
})
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
const result = { ran: false, why: 'spawn-failed', ...base, closedFacade, error: String(error?.message ?? error) }
|
|
1326
|
+
writeBackfillState(settings, result)
|
|
1327
|
+
return result
|
|
1328
|
+
}
|
|
1329
|
+
reservation.attach(child)
|
|
1330
|
+
const outcome = await reservation.exited
|
|
1331
|
+
if (outcome.spawnError !== undefined) {
|
|
1332
|
+
const result = { ran: false, why: 'spawn-failed', ...base, closedFacade, error: outcome.spawnError }
|
|
1333
|
+
writeBackfillState(settings, result)
|
|
1334
|
+
return result
|
|
1335
|
+
}
|
|
1336
|
+
const tookMs = Date.now() - reservation.startedAt
|
|
1337
|
+
if (outcome.aborted === true) return { ran: false, why: 'preempted', ...base, closedFacade, ms: tookMs }
|
|
1338
|
+
if (outcome.timedOut === true) {
|
|
1339
|
+
const result = {
|
|
1340
|
+
ran: false,
|
|
1341
|
+
why: 'timeout',
|
|
1342
|
+
...base,
|
|
1343
|
+
closedFacade,
|
|
1344
|
+
ms: tookMs,
|
|
1345
|
+
timeoutMs,
|
|
1346
|
+
error: { code: 'KANABO_MEMORY_BACKFILL_TIMEOUT', message: `回填子进程超过 ${timeoutMs}ms,已 SIGTERM/SIGKILL;已 flush 的批次保留。` },
|
|
1347
|
+
stderr: outcome.stderr ?? '',
|
|
1348
|
+
}
|
|
1349
|
+
writeBackfillState(settings, result)
|
|
1350
|
+
return result
|
|
1351
|
+
}
|
|
1352
|
+
const summary = outcome.summary
|
|
1353
|
+
if (summary === null || summary.ok !== true) {
|
|
1354
|
+
const error = summary?.ok === false ? summary.error : null
|
|
1355
|
+
const result = {
|
|
1356
|
+
ran: false,
|
|
1357
|
+
why: 'child-failed',
|
|
1358
|
+
...base,
|
|
1359
|
+
closedFacade,
|
|
1360
|
+
ms: tookMs,
|
|
1361
|
+
exitCode: outcome.code ?? null,
|
|
1362
|
+
signal: outcome.signal ?? null,
|
|
1363
|
+
error: error ?? { code: 'KANABO_MEMORY_BACKFILL_CHILD', message: (outcome.stderr ?? '').slice(-800) || '回填子进程没有输出摘要' },
|
|
1364
|
+
}
|
|
1365
|
+
writeBackfillState(settings, result)
|
|
1366
|
+
return result
|
|
1367
|
+
}
|
|
1368
|
+
const result = { ran: true, ...base, closedFacade, ms: tookMs, ...summary.value }
|
|
1369
|
+
writeBackfillState(settings, result)
|
|
1370
|
+
return result
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
const result = {
|
|
1373
|
+
ran: false,
|
|
1374
|
+
why: 'threw',
|
|
1375
|
+
...base,
|
|
1376
|
+
closedFacade,
|
|
1377
|
+
error: { code: typeof error?.code === 'string' ? error.code : 'KANABO_MEMORY_BACKFILL', message: String(error?.message ?? error) },
|
|
1378
|
+
}
|
|
1379
|
+
writeBackfillState(settings, result)
|
|
1380
|
+
return result
|
|
1381
|
+
} finally {
|
|
1382
|
+
if (BACKFILL.get(path) === reservation) BACKFILL.delete(path)
|
|
1383
|
+
if (ACTIVE_BACKFILL === path) ACTIVE_BACKFILL = null
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// ---------------------------------------------------------------------------
|
|
1388
|
+
// 常驻向量服务:模型只在子进程里,插件进程按需要一条查询/写入向量(任务 52)
|
|
1389
|
+
// ---------------------------------------------------------------------------
|
|
1390
|
+
|
|
1391
|
+
/**
|
|
1392
|
+
* 零向量守卫(唯一实现):只有 384 维、全部有限、非全零的数组才算真实嵌入。
|
|
1393
|
+
* 召回入参、写入向量、服务回包三处都走它——全零向量永远不能冒充嵌入。
|
|
1394
|
+
*/
|
|
1395
|
+
export function realVectorOrNull(vector) {
|
|
1396
|
+
if (!Array.isArray(vector) || vector.length !== EMBEDDING_DIM) return null
|
|
1397
|
+
let nonZero = false
|
|
1398
|
+
for (const value of vector) {
|
|
1399
|
+
const number = Number(value)
|
|
1400
|
+
if (!Number.isFinite(number)) return null
|
|
1401
|
+
if (number !== 0) nonZero = true
|
|
1402
|
+
}
|
|
1403
|
+
return nonZero ? vector.map((value) => Number(value)) : null
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
function embedTimeoutOf(options) {
|
|
1407
|
+
return positiveInt(options?.timeoutMs ?? process.env.KANABO_MEMORY_EMBED_TIMEOUT_MS, EMBED_SERVICE_TIMEOUT_MS)
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
function embedIdleOf(options) {
|
|
1411
|
+
const raw = options?.idleMs ?? process.env.KANABO_MEMORY_EMBED_IDLE_MS
|
|
1412
|
+
const number = Number(raw)
|
|
1413
|
+
return Number.isFinite(number) && number >= 0 ? Math.floor(number) : EMBED_SERVICE_IDLE_MS
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/**
|
|
1417
|
+
* 进程内唯一的向量服务句柄:`{ child, pending, rid, idleTimer, requests, startedAt, lastError, peakRssMb, stderr }`。
|
|
1418
|
+
* 一个插件进程只允许一个(一个模型约 1.2GB);请求按 `rid` 配对,超时即杀。
|
|
1419
|
+
*/
|
|
1420
|
+
let EMBED_SERVICE = null
|
|
1421
|
+
|
|
1422
|
+
function embedServiceStatsOf() {
|
|
1423
|
+
const service = EMBED_SERVICE
|
|
1424
|
+
return {
|
|
1425
|
+
running: service !== null,
|
|
1426
|
+
pid: service?.child?.pid ?? null,
|
|
1427
|
+
requests: service?.requests ?? 0,
|
|
1428
|
+
uptimeMs: service === null ? 0 : Date.now() - service.startedAt,
|
|
1429
|
+
peakRssMb: service?.peakRssMb ?? null,
|
|
1430
|
+
provider: service?.provider ?? null,
|
|
1431
|
+
lastError: service?.lastError ?? null,
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
/** 向量服务状态(运维/探针用):运行中、pid、请求数、峰值 RSS 与最近一次错误。 */
|
|
1436
|
+
export function embedServiceStats() {
|
|
1437
|
+
return { ...embedServiceStatsOf(), timeoutMs: EMBED_SERVICE_TIMEOUT_MS, idleMs: EMBED_SERVICE_IDLE_MS }
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
function failPending(service, error) {
|
|
1441
|
+
service.lastError = error
|
|
1442
|
+
for (const [rid, pending] of service.pending) {
|
|
1443
|
+
clearTimeout(pending.timer)
|
|
1444
|
+
service.pending.delete(rid)
|
|
1445
|
+
pending.resolve({ ok: false, error })
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
function spawnEmbedService() {
|
|
1450
|
+
const child = spawn(process.execPath, [EMBED_CHILD], {
|
|
1451
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1452
|
+
env: { ...process.env, KANABO_EMBED_CHILD: JSON.stringify({ dim: EMBEDDING_DIM }) },
|
|
1453
|
+
})
|
|
1454
|
+
const service = {
|
|
1455
|
+
child,
|
|
1456
|
+
pending: new Map(),
|
|
1457
|
+
rid: 0,
|
|
1458
|
+
idleTimer: null,
|
|
1459
|
+
requests: 0,
|
|
1460
|
+
startedAt: Date.now(),
|
|
1461
|
+
lastError: null,
|
|
1462
|
+
peakRssMb: null,
|
|
1463
|
+
provider: null,
|
|
1464
|
+
stderr: '',
|
|
1465
|
+
}
|
|
1466
|
+
let buffer = ''
|
|
1467
|
+
child.stdout.setEncoding('utf8')
|
|
1468
|
+
child.stdout.on('data', (chunk) => {
|
|
1469
|
+
buffer += chunk
|
|
1470
|
+
let index = buffer.indexOf('\n')
|
|
1471
|
+
while (index >= 0) {
|
|
1472
|
+
const line = buffer.slice(0, index).trim()
|
|
1473
|
+
buffer = buffer.slice(index + 1)
|
|
1474
|
+
index = buffer.indexOf('\n')
|
|
1475
|
+
if (line === '') continue
|
|
1476
|
+
let reply
|
|
1477
|
+
try {
|
|
1478
|
+
reply = JSON.parse(line)
|
|
1479
|
+
} catch {
|
|
1480
|
+
continue
|
|
1481
|
+
}
|
|
1482
|
+
const pending = service.pending.get(reply?.rid)
|
|
1483
|
+
if (pending === undefined) continue
|
|
1484
|
+
service.pending.delete(reply.rid)
|
|
1485
|
+
clearTimeout(pending.timer)
|
|
1486
|
+
if (Number.isFinite(reply?.peakRssMb)) service.peakRssMb = Number(reply.peakRssMb)
|
|
1487
|
+
if (typeof reply?.provider === 'string') service.provider = reply.provider
|
|
1488
|
+
pending.resolve(reply)
|
|
1489
|
+
}
|
|
1490
|
+
})
|
|
1491
|
+
child.stderr.setEncoding('utf8')
|
|
1492
|
+
child.stderr.on('data', (chunk) => { service.stderr = `${service.stderr}${chunk}`.slice(-4000) })
|
|
1493
|
+
child.stdin.on('error', () => {
|
|
1494
|
+
// 写入时子进程已死:`exit` 会统一收尾。
|
|
1495
|
+
})
|
|
1496
|
+
child.on('error', (error) => {
|
|
1497
|
+
failPending(service, { code: 'KANABO_MEMORY_EMBED_SPAWN', message: String(error?.message ?? error) })
|
|
1498
|
+
if (EMBED_SERVICE === service) EMBED_SERVICE = null
|
|
1499
|
+
})
|
|
1500
|
+
child.on('exit', (code, signal) => {
|
|
1501
|
+
failPending(service, {
|
|
1502
|
+
code: 'KANABO_MEMORY_EMBED_EXIT',
|
|
1503
|
+
message: `向量服务退出(code=${String(code)} signal=${String(signal)})${service.stderr.slice(-400)}`,
|
|
1504
|
+
})
|
|
1505
|
+
if (service.idleTimer !== null) clearTimeout(service.idleTimer)
|
|
1506
|
+
service.idleTimer = null
|
|
1507
|
+
if (EMBED_SERVICE === service) EMBED_SERVICE = null
|
|
1508
|
+
})
|
|
1509
|
+
// 子进程与管道保持 ref:在途请求期间进程不能被「无事可做」地退出(那会让 await 悬空)。
|
|
1510
|
+
// 退出靠三条确定性路径:空闲计时器、closeEmbedService、父进程死时 stdin 结束。
|
|
1511
|
+
EMBED_SERVICE = service
|
|
1512
|
+
return service
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
function requestEmbed(service, texts, prefix, timeoutMs) {
|
|
1516
|
+
return new Promise((resolve) => {
|
|
1517
|
+
const rid = ++service.rid
|
|
1518
|
+
service.requests += 1
|
|
1519
|
+
const timer = setTimeout(() => {
|
|
1520
|
+
service.pending.delete(rid)
|
|
1521
|
+
const error = { code: 'KANABO_MEMORY_EMBED_TIMEOUT', message: `向量服务超过 ${timeoutMs}ms 未响应;已杀进程并在下次重新拉起。` }
|
|
1522
|
+
resolve({ ok: false, error, timedOut: true })
|
|
1523
|
+
// 挂住的模型进程不可信(可能卡在加载或推理):杀掉并在下一次重新拉起;其它在途请求由关闭流程统一收尾。
|
|
1524
|
+
void closeEmbedService(BACKFILL_PREEMPT_GRACE_MS)
|
|
1525
|
+
}, timeoutMs)
|
|
1526
|
+
timer.unref?.()
|
|
1527
|
+
service.pending.set(rid, { resolve, timer })
|
|
1528
|
+
try {
|
|
1529
|
+
service.child.stdin.write(`${JSON.stringify({ rid, texts, prefix })}\n`)
|
|
1530
|
+
} catch (error) {
|
|
1531
|
+
service.pending.delete(rid)
|
|
1532
|
+
clearTimeout(timer)
|
|
1533
|
+
resolve({ ok: false, error: { code: 'KANABO_MEMORY_EMBED_WRITE', message: String(error?.message ?? error) } })
|
|
1534
|
+
}
|
|
1535
|
+
})
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
function armEmbedIdle(service, idleMs) {
|
|
1539
|
+
if (service.idleTimer !== null) clearTimeout(service.idleTimer)
|
|
1540
|
+
service.idleTimer = null
|
|
1541
|
+
if (idleMs <= 0) {
|
|
1542
|
+
void closeEmbedService(BACKFILL_PREEMPT_GRACE_MS)
|
|
1543
|
+
return
|
|
1544
|
+
}
|
|
1545
|
+
service.idleTimer = setTimeout(() => {
|
|
1546
|
+
service.idleTimer = null
|
|
1547
|
+
if (EMBED_SERVICE === service) void closeEmbedService(BACKFILL_PREEMPT_GRACE_MS)
|
|
1548
|
+
}, idleMs)
|
|
1549
|
+
service.idleTimer.unref?.()
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
function killEmbedService(service, timeoutMs) {
|
|
1553
|
+
const child = service.child
|
|
1554
|
+
const exited = new Promise((resolveExit) => {
|
|
1555
|
+
let settled = false
|
|
1556
|
+
child.once('exit', () => {
|
|
1557
|
+
if (!settled) {
|
|
1558
|
+
settled = true
|
|
1559
|
+
resolveExit(true)
|
|
1560
|
+
}
|
|
1561
|
+
})
|
|
1562
|
+
const timer = setTimeout(() => {
|
|
1563
|
+
if (!settled) {
|
|
1564
|
+
settled = true
|
|
1565
|
+
resolveExit(false)
|
|
1566
|
+
}
|
|
1567
|
+
}, Math.max(1, timeoutMs))
|
|
1568
|
+
timer.unref?.()
|
|
1569
|
+
})
|
|
1570
|
+
try {
|
|
1571
|
+
child.kill('SIGTERM')
|
|
1572
|
+
} catch {
|
|
1573
|
+
// 已经退出。
|
|
1574
|
+
}
|
|
1575
|
+
return exited.then((ok) => {
|
|
1576
|
+
if (ok) return true
|
|
1577
|
+
try {
|
|
1578
|
+
child.kill('SIGKILL')
|
|
1579
|
+
} catch {
|
|
1580
|
+
// 同上。
|
|
1581
|
+
}
|
|
1582
|
+
return false
|
|
1583
|
+
})
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
/** 关闭向量服务(幂等):先拒新请求、把在途请求收成失败,再 SIGTERM → 限时 SIGKILL。 */
|
|
1587
|
+
export async function closeEmbedService(timeoutMs = 1_000) {
|
|
1588
|
+
const service = EMBED_SERVICE
|
|
1589
|
+
if (service === null) return { closed: true, running: false, pid: null }
|
|
1590
|
+
EMBED_SERVICE = null
|
|
1591
|
+
if (service.idleTimer !== null) clearTimeout(service.idleTimer)
|
|
1592
|
+
service.idleTimer = null
|
|
1593
|
+
failPending(service, { code: 'KANABO_MEMORY_EMBED_CLOSED', message: '向量服务已关闭;本次请求降级。' })
|
|
1594
|
+
const graceful = await killEmbedService(service, timeoutMs)
|
|
1595
|
+
return { closed: graceful, running: false, pid: service.child.pid ?? null }
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
/**
|
|
1599
|
+
* 把一批文本变成向量(文本层唯一入口:remember 的入库向量与 recall 的查询向量都走这里)。
|
|
1600
|
+
*
|
|
1601
|
+
* 契约(与 `embed.js` 同形):**绝不抛错**。失败统一折成 `{ vectors: [null…], degraded: true, reason }`,
|
|
1602
|
+
* 调用方据此降级(remember 写零向量等回填、recall 少一条臂),工具调用永远拿得到结果。
|
|
1603
|
+
* 超时/失败会杀掉服务进程(挂住的模型不可信);空闲超过 `idleMs` 也会退出,插件 RSS 随即回基线。
|
|
1604
|
+
*/
|
|
1605
|
+
export async function embedTexts(texts, options = {}) {
|
|
1606
|
+
const started = Date.now()
|
|
1607
|
+
const list = (Array.isArray(texts) ? texts : [texts]).map((text) => String(text ?? ''))
|
|
1608
|
+
const prefix = typeof options.prefix === 'string' ? options.prefix : ''
|
|
1609
|
+
const timeoutMs = embedTimeoutOf(options)
|
|
1610
|
+
const empty = (reason, message = null) => ({
|
|
1611
|
+
vectors: list.map(() => null),
|
|
1612
|
+
degraded: true,
|
|
1613
|
+
reason,
|
|
1614
|
+
error: message === null ? null : { code: reason, message },
|
|
1615
|
+
ms: Date.now() - started,
|
|
1616
|
+
peakRssMb: null,
|
|
1617
|
+
provider: null,
|
|
1618
|
+
})
|
|
1619
|
+
if (list.length === 0) return { vectors: [], degraded: false, reason: null, error: null, ms: 0, peakRssMb: null, provider: null }
|
|
1620
|
+
if (SHUTDOWN !== null) return empty('shutting_down', '记忆运行时正在关闭,不再接受向量请求。')
|
|
1621
|
+
if (list.some((text) => text.trim() === '')) return empty('empty_text')
|
|
1622
|
+
// 回合优先:回填正在跑时先让它收尾,模型进程不叠加(与 `ensureOpen` 的抢占同一策略)。
|
|
1623
|
+
if (ACTIVE_BACKFILL !== null) await cancelBackfills('embed-request')
|
|
1624
|
+
let service
|
|
1625
|
+
try {
|
|
1626
|
+
service = EMBED_SERVICE ?? spawnEmbedService()
|
|
1627
|
+
} catch (error) {
|
|
1628
|
+
return empty('KANABO_MEMORY_EMBED_SPAWN', String(error?.message ?? error))
|
|
1629
|
+
}
|
|
1630
|
+
const reply = await requestEmbed(service, list, prefix, timeoutMs)
|
|
1631
|
+
if (reply?.ok !== true) {
|
|
1632
|
+
const code = typeof reply?.error?.code === 'string' ? reply.error.code : 'KANABO_MEMORY_EMBED'
|
|
1633
|
+
return empty(code, String(reply?.error?.message ?? '向量服务请求失败'))
|
|
1634
|
+
}
|
|
1635
|
+
const results = Array.isArray(reply.results) ? reply.results : []
|
|
1636
|
+
const vectors = list.map((_, index) => realVectorOrNull(results[index]?.vector))
|
|
1637
|
+
const reasons = []
|
|
1638
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
1639
|
+
if (vectors[index] !== null) continue
|
|
1640
|
+
const reason = typeof results[index]?.reason === 'string' ? results[index].reason : 'zero_vector'
|
|
1641
|
+
reasons.push(reason)
|
|
1642
|
+
}
|
|
1643
|
+
armEmbedIdle(service, embedIdleOf(options))
|
|
1644
|
+
return {
|
|
1645
|
+
vectors,
|
|
1646
|
+
degraded: reasons.length > 0,
|
|
1647
|
+
reason: reasons[0] ?? null,
|
|
1648
|
+
error: null,
|
|
1649
|
+
ms: Date.now() - started,
|
|
1650
|
+
peakRssMb: service.peakRssMb,
|
|
1651
|
+
provider: service.provider ?? (typeof reply.provider === 'string' ? reply.provider : null),
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
/** `recall-trivium.js` 的 `embedder` 形状(`{ dim, embed(text, {prefix}) }`),背后是上面的服务。 */
|
|
1656
|
+
export function createServiceEmbedder(options = {}) {
|
|
1657
|
+
return {
|
|
1658
|
+
dim: EMBEDDING_DIM,
|
|
1659
|
+
async embed(text, callOptions = {}) {
|
|
1660
|
+
const prefix = typeof callOptions.prefix === 'string' ? callOptions.prefix : ''
|
|
1661
|
+
const result = await embedTexts([text], { prefix, timeoutMs: options.timeoutMs, idleMs: options.idleMs })
|
|
1662
|
+
const vector = result.vectors[0] ?? null
|
|
1663
|
+
if (vector === null) return { vector: null, degraded: true, reason: result.reason ?? 'vector_unavailable' }
|
|
1664
|
+
return { vector, degraded: false, reason: null, cached: false }
|
|
1665
|
+
},
|
|
1666
|
+
stats() {
|
|
1667
|
+
return embedServiceStatsOf()
|
|
1668
|
+
},
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
// ---------------------------------------------------------------------------
|
|
1673
|
+
// helper 子进程:只有这里才 import 原生引擎(插件进程永不加载它)
|
|
1674
|
+
// ---------------------------------------------------------------------------
|
|
1675
|
+
|
|
1676
|
+
async function helperMain(argv) {
|
|
1677
|
+
const [mode, ...rest] = argv
|
|
1678
|
+
const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`)
|
|
1679
|
+
try {
|
|
1680
|
+
const trivium = await import('triviumdb')
|
|
1681
|
+
if (mode === 'create') {
|
|
1682
|
+
const [path, destination, generationId] = rest
|
|
1683
|
+
if (existsSync(destination)) {
|
|
1684
|
+
send({ ok: false, error: { code: 'KANABO_MEMORY_SNAPSHOT_EXISTS', message: `快照目录已存在:${destination}` } })
|
|
1685
|
+
return 1
|
|
1686
|
+
}
|
|
1687
|
+
mkdirSync(dirname(destination), { recursive: true })
|
|
1688
|
+
const db = new trivium.TriviumDB(path, {
|
|
1689
|
+
dim: EMBEDDING_DIM,
|
|
1690
|
+
loadTextIndex: true,
|
|
1691
|
+
storageMode: 'mmap',
|
|
1692
|
+
syncMode: 'normal',
|
|
1693
|
+
})
|
|
1694
|
+
let manifest
|
|
1695
|
+
try {
|
|
1696
|
+
db.flush()
|
|
1697
|
+
manifest = db.createSnapshot(destination, generationId)
|
|
1698
|
+
} finally {
|
|
1699
|
+
closeEngine(db)
|
|
1700
|
+
}
|
|
1701
|
+
send({ ok: true, value: { manifest, nodeCount: manifest?.node_count ?? null } })
|
|
1702
|
+
return 0
|
|
1703
|
+
}
|
|
1704
|
+
if (mode === 'verify') {
|
|
1705
|
+
const [directory] = rest
|
|
1706
|
+
const manifest = trivium.verifySnapshot(directory)
|
|
1707
|
+
send({ ok: true, value: manifest })
|
|
1708
|
+
return 0
|
|
1709
|
+
}
|
|
1710
|
+
if (mode === 'restore') {
|
|
1711
|
+
const [snapshotDir, dbPath] = rest
|
|
1712
|
+
const dir = dirname(dbPath)
|
|
1713
|
+
const base = basename(dbPath)
|
|
1714
|
+
mkdirSync(dir, { recursive: true })
|
|
1715
|
+
const staging = join(dir, `.restore-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
|
|
1716
|
+
let manifest
|
|
1717
|
+
try {
|
|
1718
|
+
manifest = trivium.restoreSnapshot(snapshotDir, staging)
|
|
1719
|
+
trivium.verifySnapshot(staging)
|
|
1720
|
+
const backupDir = join(dir, `.backup-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
|
|
1721
|
+
const moved = []
|
|
1722
|
+
const restored = []
|
|
1723
|
+
mkdirSync(backupDir, { recursive: true })
|
|
1724
|
+
for (const name of readdirSync(dir)) {
|
|
1725
|
+
if (name === base || name.startsWith(`${base}.`)) {
|
|
1726
|
+
renameSync(join(dir, name), join(backupDir, name))
|
|
1727
|
+
moved.push(name)
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
for (const name of readdirSync(staging)) {
|
|
1731
|
+
if (name !== RESTORE_NAME && !name.startsWith(`${RESTORE_NAME}.`)) continue
|
|
1732
|
+
const target = `${base}${name.slice(RESTORE_NAME.length)}`
|
|
1733
|
+
renameSync(join(staging, name), join(dir, target))
|
|
1734
|
+
restored.push(target)
|
|
1735
|
+
}
|
|
1736
|
+
const after = {}
|
|
1737
|
+
for (const file of Array.isArray(manifest?.files) ? manifest.files : []) {
|
|
1738
|
+
const livePath = `${dbPath}${String(file?.suffix ?? '')}`
|
|
1739
|
+
if (!existsSync(livePath)) throw new Error(`恢复后缺少文件:${livePath}`)
|
|
1740
|
+
after[String(file?.suffix ?? '')] = digestOf(livePath)
|
|
1741
|
+
}
|
|
1742
|
+
send({ ok: true, value: { manifest, backupDir, moved, restored, after } })
|
|
1743
|
+
return 0
|
|
1744
|
+
} finally {
|
|
1745
|
+
rmSync(staging, { recursive: true, force: true })
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
send({ ok: false, error: { code: 'KANABO_MEMORY_HELPER', message: `未知 helper 模式:${String(mode)}` } })
|
|
1749
|
+
return 2
|
|
1750
|
+
} catch (error) {
|
|
1751
|
+
send({ ok: false, error: { code: typeof error?.code === 'string' ? error.code : 'KANABO_MEMORY_HELPER', message: String(error?.message ?? error) } })
|
|
1752
|
+
return 1
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/** 两阶段关闭:先请求(停止接收新操作、排空),再限时等待真正释放;失败也不假装成功。 */
|
|
1757
|
+
function closeEngine(db) {
|
|
1758
|
+
let released = false
|
|
1759
|
+
try {
|
|
1760
|
+
db.requestShutdown()
|
|
1761
|
+
released = db.closeTimeout(3000) === true
|
|
1762
|
+
} catch {
|
|
1763
|
+
released = false
|
|
1764
|
+
}
|
|
1765
|
+
if (!released) {
|
|
1766
|
+
try {
|
|
1767
|
+
db.close()
|
|
1768
|
+
} catch {
|
|
1769
|
+
// 进程即将退出:内核对 mmap/WAL 的回收等同 close。
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
function isEntryPoint() {
|
|
1775
|
+
const script = process.argv[1]
|
|
1776
|
+
if (typeof script !== 'string' || script.length === 0) return false
|
|
1777
|
+
try {
|
|
1778
|
+
return realpathSync(script) === realpathSync(MODULE_PATH)
|
|
1779
|
+
} catch {
|
|
1780
|
+
return false
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
if (isEntryPoint() && process.argv[2] === '--trivium-helper') {
|
|
1785
|
+
helperMain(process.argv.slice(3)).then((code) => {
|
|
1786
|
+
process.exitCode = code
|
|
1787
|
+
}, (error) => {
|
|
1788
|
+
process.stdout.write(`${JSON.stringify({ ok: false, error: { code: 'KANABO_MEMORY_HELPER', message: String(error?.stack ?? error) } })}\n`)
|
|
1789
|
+
process.exitCode = 1
|
|
1790
|
+
})
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
/** `scopeOf` 从 store.js 再导出:调用方(extract/sweep)不必同时 import 两个模块。 */
|
|
1794
|
+
export { scopeOf, MAX_ENTRY_BYTES, triviumDir }
|