@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/embed-child.js ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 向量服务子进程(任务 52):常驻、只做「文本 → 384 维向量」,**插件进程永不加载模型**。
4
+ *
5
+ * 为什么需要一个常驻子进程,而不是每次召回 fork 一个(实测,见 `.omo/evidence/dsh-kanabo-platform/task-52.log`):
6
+ * - 本地 e5 模型加载约 2.4–2.8s、常驻约 1.2GB;每次召回都付一次加载,工具路径单次召回就从 ~50ms
7
+ * 变成 ~2.6s,且每调一次就是一个新进程。常驻子进程把加载摊到「每个进程一次」,之后单条嵌入
8
+ * 是毫秒级;模型仍然不在插件进程里(资源包络:插件 RSS 不因召回上涨)。
9
+ * - 本进程**不碰引擎、不碰库文件**:没有租约,所以它和门面子进程、回填子进程互不干扰;
10
+ * 父进程空闲即杀(默认 60s),关闭时随两阶段关闭一起退。
11
+ *
12
+ * 协议:stdin 每行一个 JSON 请求,stdout 每行一个 JSON 响应(父进程按 `rid` 配对):
13
+ * 请求 { "rid": 7, "texts": ["…"], "prefix": "query: " }
14
+ * 响应 { "rid": 7, "ok": true, "results": [{ "vector": [...384] | null, "degraded": bool, "reason": null|"…" }],
15
+ * "peakRssMb": 1024.5 }
16
+ * 嵌入失败(模型缺失/超时/维度不符/超内存)**不是本进程的错误**:`embed.js` 把它们折成
17
+ * `degraded` 结果逐条返回,父进程据此让向量臂降级、其余两臂照常工作。
18
+ *
19
+ * 退出:stdin 结束(父进程死了)或 SIGTERM/SIGINT → dispose 模型、退出 0。
20
+ * 零向量守卫在两侧都做:`embed.js` 只在维度/有限性上把关,本进程与父进程都不接受全零向量当嵌入。
21
+ */
22
+ import { EMBEDDING_DIM } from './contract.js'
23
+ import { createEmbedder, peakRssMb } from './embed.js'
24
+ import { createEmbeddingProvider } from './providers.js'
25
+
26
+ const CONFIG_ENV = 'KANABO_EMBED_CHILD'
27
+
28
+ function readConfig() {
29
+ const raw = process.env[CONFIG_ENV]
30
+ if (raw === undefined || raw === '') return {}
31
+ try {
32
+ const parsed = JSON.parse(raw)
33
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
34
+ } catch {
35
+ return {}
36
+ }
37
+ }
38
+
39
+ const config = readConfig()
40
+ const dim = Number.isInteger(config.dim) && config.dim > 0 ? config.dim : EMBEDDING_DIM
41
+
42
+ function send(message) {
43
+ try {
44
+ process.stdout.write(`${JSON.stringify(message)}\n`)
45
+ } catch {
46
+ // 父进程已关管道:下一次 stdin 结束会带我们退出。
47
+ }
48
+ }
49
+
50
+ function isRealEmbedding(vector) {
51
+ if (vector === null || vector === undefined || typeof vector.length !== 'number') return false
52
+ if (vector.length !== dim) return false
53
+ let nonZero = false
54
+ for (const value of vector) {
55
+ const number = Number(value)
56
+ if (!Number.isFinite(number)) return false
57
+ if (number !== 0) nonZero = true
58
+ }
59
+ return nonZero
60
+ }
61
+
62
+ let embedder = null
63
+
64
+ function embedderOf() {
65
+ if (embedder === null) {
66
+ const api = config.provider !== null && typeof config.provider === 'object' && config.provider.kind === 'api'
67
+ ? createEmbeddingProvider(config.provider, { apiKey: config.provider.apiKey })
68
+ : null
69
+ embedder = createEmbedder({
70
+ dim,
71
+ timeoutMs: Number.isInteger(config.timeoutMs) ? config.timeoutMs : undefined,
72
+ ...(api === null ? {} : { provider: api }),
73
+ })
74
+ }
75
+ return embedder
76
+ }
77
+
78
+ async function handle(request) {
79
+ if (request === null || typeof request !== 'object') return
80
+ const rid = request.rid
81
+ const texts = Array.isArray(request.texts) ? request.texts.map((text) => String(text ?? '')) : null
82
+ if (texts === null || texts.length === 0) {
83
+ send({ rid, ok: false, error: { code: 'KANABO_EMBED_CHILD_REQUEST', message: '请求需要非空的 texts 数组' } })
84
+ return
85
+ }
86
+ const prefix = typeof request.prefix === 'string' ? request.prefix : ''
87
+ try {
88
+ const results = await embedderOf().embedBatch(texts, { prefix })
89
+ send({
90
+ rid,
91
+ ok: true,
92
+ results: results.map((result) => {
93
+ if (result?.degraded === true || !isRealEmbedding(result?.vector)) {
94
+ const reason = result?.reason ?? (result?.degraded === true ? 'provider_unavailable' : 'zero_vector')
95
+ return { vector: null, degraded: true, reason }
96
+ }
97
+ // 契约要求普通 Array(不是 Float32Array):JSON 序列化后父进程拿到的就是 number[]。
98
+ return { vector: Array.from(result.vector, (value) => Number(value)), degraded: false, reason: null }
99
+ }),
100
+ peakRssMb: peakRssMb(),
101
+ provider: embedderOf().providerId ?? null,
102
+ })
103
+ } catch (error) {
104
+ // embed.js 按理不抛;真抛了也只回一条失败,不让整个服务死掉。
105
+ send({
106
+ rid,
107
+ ok: false,
108
+ error: {
109
+ code: typeof error?.code === 'string' ? error.code : 'KANABO_EMBED_CHILD',
110
+ message: String(error?.message ?? error),
111
+ },
112
+ })
113
+ }
114
+ }
115
+
116
+ /** 请求串行处理:模型不是并发安全的入口,而且并发只会把峰值内存推高。 */
117
+ let chain = Promise.resolve()
118
+ let buffer = ''
119
+
120
+ process.stdin.setEncoding('utf8')
121
+ process.stdin.on('data', (chunk) => {
122
+ buffer += chunk
123
+ let index = buffer.indexOf('\n')
124
+ while (index >= 0) {
125
+ const line = buffer.slice(0, index).trim()
126
+ buffer = buffer.slice(index + 1)
127
+ index = buffer.indexOf('\n')
128
+ if (line === '') continue
129
+ let request
130
+ try {
131
+ request = JSON.parse(line)
132
+ } catch {
133
+ send({ rid: null, ok: false, error: { code: 'KANABO_EMBED_CHILD_REQUEST', message: '请求不是合法 JSON' } })
134
+ continue
135
+ }
136
+ chain = chain.then(() => handle(request), () => handle(request))
137
+ }
138
+ })
139
+
140
+ function shutdown(code = 0) {
141
+ try {
142
+ embedder?.close?.()
143
+ } catch {
144
+ // 进程即将退出:内核回收即可。
145
+ }
146
+ embedder = null
147
+ process.exit(code)
148
+ }
149
+
150
+ process.stdin.on('end', () => shutdown(0))
151
+ process.stdin.on('close', () => shutdown(0))
152
+ for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => shutdown(0))
package/embed.js ADDED
@@ -0,0 +1,475 @@
1
+ /**
2
+ * 可插拔向量提供者(任务 12):把「把文本变成定长浮点向量」收敛到一个不抛错的门面上。
3
+ *
4
+ * 形状(为什么不是直接返回 Float32Array):
5
+ * - 向量维度是契约值 `EMBEDDING_DIM`(`contract.js`);模型给的维度不符时**加载即失败**,
6
+ * 绝不 pad/截断——补零的向量会让余弦相似度整个失真。
7
+ * - 模型不可用(没下到、依赖缺失、超时、内存超预算)时,热路径**不抛错**,返回
8
+ * `{ vector: null, degraded: true, reason }`;调用方(任务 14 的召回)据此退化为纯文本 BM25。
9
+ * 绝不返回全零向量冒充嵌入。
10
+ *
11
+ * 三个必须守住的数字:
12
+ * 1. `EMBEDDING_DIM = 384`:加载时用一条探针文本实测,不符就抛 `KANABO_EMBED_DIMENSION_MISMATCH`。
13
+ * 2. `MAX_RSS_MB = 4096`:加载后与每批之后读 `/proc/self/status` 的 `VmHWM`;越界即卸载并降级。
14
+ * 3. `BATCH_TIMEOUT_MS`:每批是硬期限,超时的那批标记 `provider_timeout`,下一批照常可用。
15
+ *
16
+ * 选型(证据见 `.omo/evidence/dsh-kanabo-platform/task-12.log`):`Xenova/multilingual-e5-small`
17
+ * 的 **fp32** ONNX(384 维,470MB,加载后峰值 RSS ≈1.2–1.3GB)。量化导出(q8)不可用:它的
18
+ * attention mask 在 padding 上失真,同一文本单条与批量相差 ~0.017,违反确定性;fp32 导出逐位一致。
19
+ * 英文 MiniLM(90MB)被否:中文文本约 45% 词元落到 `[UNK]`,对本项目的中文记忆没有区分度。
20
+ *
21
+ * 模型文件只从本地目录加载(默认 `$TMPDIR/dsh-kanabo-models`)。首次部署可从
22
+ * `https://hf-mirror.com` 拉取(`huggingface.co` 在本机不可达):URL、大小与 sha256 记录在证据日志里,
23
+ * 用 `KANABO_EMBED_OFFLINE=1` 可强制离线(缺失即降级),`KANABO_EMBED_MODEL_SHA256` 可钉住权重的哈希。
24
+ */
25
+ import { createHash } from 'node:crypto'
26
+ import { createReadStream } from 'node:fs'
27
+ import { existsSync, statSync } from 'node:fs'
28
+ import { readFileSync } from 'node:fs'
29
+ import { tmpdir } from 'node:os'
30
+ import { join } from 'node:path'
31
+
32
+ import { EMBEDDING_DIM, EMBEDDING_MODEL_ID } from './contract.js'
33
+
34
+ /** 内存缓存条数上限(LRU):384 维 Float32 每条约 1.5KB,512 条≈0.8MB。 */
35
+ export const CACHE_CAPACITY = 512
36
+ /** 单次模型调用的文本条数上限;超过自动切块。 */
37
+ export const BATCH_SIZE = 16
38
+ /** 每批的硬期限(毫秒):超时即标记该批降级,不重试、不阻塞下一批。 */
39
+ export const BATCH_TIMEOUT_MS = 5_000
40
+ /** 可重试的加载失败(模型缺失、镜像不通)在多长时间内不重试,避免每次调用都打网络。 */
41
+ export const LOAD_RETRY_MS = 30_000
42
+ /** 单个 ONNX 文件的大小上限:超过 1GiB 视为会突破 4GB 预算的模型,拒绝加载。 */
43
+ export const MAX_MODEL_BYTES = 1024 ** 3
44
+ /** 进程峰值 RSS 上限(MiB):与平台计划的 4GB 上限对齐。 */
45
+ export const MAX_RSS_MB = 4096
46
+
47
+ /** 降级原因码:稳定的字符串,供调用方与日志分类(不随文案变化)。 */
48
+ export const DEGRADED_REASONS = Object.freeze({
49
+ UNAVAILABLE: 'provider_unavailable',
50
+ TIMEOUT: 'provider_timeout',
51
+ ERROR: 'provider_error',
52
+ DIMENSION_MISMATCH: 'dimension_mismatch',
53
+ MODEL_TOO_LARGE: 'model_too_large',
54
+ MODEL_HASH_MISMATCH: 'model_hash_mismatch',
55
+ MEMORY_OVER_BUDGET: 'memory_over_budget',
56
+ })
57
+
58
+ function embedError(code, message, extra = {}) {
59
+ const error = new Error(message, extra.cause === undefined ? undefined : { cause: extra.cause })
60
+ error.code = code
61
+ if (extra.expected !== undefined) error.expected = extra.expected
62
+ if (extra.received !== undefined) error.received = extra.received
63
+ return error
64
+ }
65
+
66
+ /** 把任意抛出物折成稳定的原因码:只有我们自己打的码可信,其余一律归为 `provider_error`。 */
67
+ function reasonOf(error) {
68
+ const code = typeof error?.code === 'string' ? error.code : ''
69
+ switch (code) {
70
+ case 'KANABO_EMBED_PROVIDER_UNAVAILABLE':
71
+ return DEGRADED_REASONS.UNAVAILABLE
72
+ case 'KANABO_EMBED_TIMEOUT':
73
+ return DEGRADED_REASONS.TIMEOUT
74
+ case 'KANABO_EMBED_DIMENSION_MISMATCH':
75
+ return DEGRADED_REASONS.DIMENSION_MISMATCH
76
+ case 'KANABO_EMBED_MODEL_TOO_LARGE':
77
+ return DEGRADED_REASONS.MODEL_TOO_LARGE
78
+ case 'KANABO_EMBED_MODEL_HASH_MISMATCH':
79
+ return DEGRADED_REASONS.MODEL_HASH_MISMATCH
80
+ case 'KANABO_EMBED_MEMORY_OVER_BUDGET':
81
+ return DEGRADED_REASONS.MEMORY_OVER_BUDGET
82
+ default:
83
+ return DEGRADED_REASONS.ERROR
84
+ }
85
+ }
86
+
87
+ /** 进程峰值常驻内存(MiB,`VmHWM`);非 Linux 或不可读时为 null(不猜数字)。 */
88
+ export function peakRssMb() {
89
+ try {
90
+ const status = readFileSync('/proc/self/status', 'utf8')
91
+ const match = /^VmHWM:\s+(\d+) kB$/m.exec(status)
92
+ return match === null ? null : Number(match[1]) / 1024
93
+ } catch {
94
+ return null
95
+ }
96
+ }
97
+
98
+ /** 文件 sha256(流式,避免把 470MB 权重整块读进内存)。 */
99
+ async function sha256File(path) {
100
+ const hash = createHash('sha256')
101
+ for await (const chunk of createReadStream(path)) hash.update(chunk)
102
+ return hash.digest('hex')
103
+ }
104
+
105
+ /** 带硬期限的等待:超时以 `KANABO_EMBED_TIMEOUT` 拒绝;原 promise 的迟到结果被吞掉。 */
106
+ function withTimeout(promise, timeoutMs, label) {
107
+ let timer
108
+ const expiry = new Promise((_, reject) => {
109
+ timer = setTimeout(() => {
110
+ reject(embedError('KANABO_EMBED_TIMEOUT', `${label} 超过 ${timeoutMs}ms 期限。`))
111
+ }, timeoutMs)
112
+ })
113
+ promise.catch(() => {}) // 超时后原 promise 仍会 settle,必须消费掉,否则 unhandledRejection。
114
+ return Promise.race([promise, expiry]).finally(() => clearTimeout(timer))
115
+ }
116
+
117
+ /** 定容 LRU:`get` 命中后刷新最近使用;`set` 溢出时淘汰最久未用的一条。 */
118
+ /** 定容 LRU:`get` 命中后刷新最近使用;`set` 溢出时淘汰最久未用的一条。 */
119
+ class LruCache {
120
+ constructor(capacity) {
121
+ this.capacity = Math.max(1, capacity | 0)
122
+ this.map = new Map()
123
+ this.hits = 0
124
+ this.misses = 0
125
+ }
126
+
127
+ get(key) {
128
+ const value = this.map.get(key)
129
+ if (value === undefined) {
130
+ this.misses += 1
131
+ return undefined
132
+ }
133
+ this.map.delete(key)
134
+ this.map.set(key, value)
135
+ this.hits += 1
136
+ return value
137
+ }
138
+
139
+ set(key, value) {
140
+ if (this.map.has(key)) this.map.delete(key)
141
+ this.map.set(key, value)
142
+ while (this.map.size > this.capacity) this.map.delete(this.map.keys().next().value)
143
+ }
144
+
145
+ clear() {
146
+ this.map.clear()
147
+ }
148
+ }
149
+
150
+ /** 校验并防御性拷贝一条向量:维度必须等于 `dim`,非有限数即拒(NaN 会污染余弦)。 */
151
+ function checkVector(vector, dim, providerId) {
152
+ const data = vector instanceof Float32Array ? vector : Float32Array.from(vector ?? [])
153
+ if (data.length !== dim) {
154
+ throw embedError(
155
+ 'KANABO_EMBED_DIMENSION_MISMATCH',
156
+ `provider ${providerId} 返回的向量维度是 ${data.length},契约维度是 ${dim};拒绝 pad/截断。`,
157
+ { expected: dim, received: data.length })
158
+ }
159
+ for (const value of data) {
160
+ if (!Number.isFinite(value)) {
161
+ throw embedError(
162
+ 'KANABO_EMBED_PROVIDER_ERROR',
163
+ `provider ${providerId} 返回了非有限数(NaN/Infinity),拒绝写入向量。`)
164
+ }
165
+ }
166
+ return data
167
+ }
168
+
169
+ /**
170
+ * 本地 ONNX provider(默认):`@huggingface/transformers` 懒加载,模型文件只从 `modelDir` 读。
171
+ * `load()` 会做三件事:大小守卫 → 可选哈希钉住 → 用一条探针文本断言维度。
172
+ */
173
+ export function createLocalProvider(options = {}) {
174
+ const modelId = options.modelId ?? process.env.KANABO_EMBED_MODEL ?? EMBEDDING_MODEL_ID
175
+ const dtype = options.dtype ?? process.env.KANABO_EMBED_DTYPE ?? 'fp32'
176
+ const modelDir = options.modelDir ?? process.env.KANABO_EMBED_MODEL_DIR ?? join(tmpdir(), 'dsh-kanabo-models')
177
+ const offline = options.offline ?? process.env.KANABO_EMBED_OFFLINE === '1'
178
+ const remoteHost = options.remoteHost ?? process.env.KANABO_EMBED_REMOTE_HOST ?? 'https://hf-mirror.com'
179
+ const maxModelBytes = options.maxModelBytes ?? MAX_MODEL_BYTES
180
+ const expectedSha = options.modelSha256 ?? process.env.KANABO_EMBED_MODEL_SHA256
181
+ const onnxFile = dtype === 'fp32' ? 'model.onnx' : `model_${dtype}.onnx`
182
+
183
+ let extractor = null
184
+ const provider = {
185
+ id: `local:${modelId}@${dtype}`,
186
+ dim: EMBEDDING_DIM,
187
+ modelId,
188
+ modelPath: join(modelDir, modelId, 'onnx', onnxFile),
189
+ modelSha256: null,
190
+ async load() {
191
+ if (extractor !== null) return
192
+ const { env, pipeline } = await import('@huggingface/transformers').catch((cause) => {
193
+ throw embedError(
194
+ 'KANABO_EMBED_PROVIDER_UNAVAILABLE',
195
+ '本地向量依赖 @huggingface/transformers 不可用(未安装或加载失败)。',
196
+ { cause })
197
+ })
198
+ if (existsSync(provider.modelPath)) {
199
+ const size = statSync(provider.modelPath).size
200
+ if (size > maxModelBytes) {
201
+ throw embedError(
202
+ 'KANABO_EMBED_MODEL_TOO_LARGE',
203
+ `模型文件 ${provider.modelPath} 为 ${size} 字节,超过上限 ${maxModelBytes};拒绝加载(可能突破 ${MAX_RSS_MB}MB)。`)
204
+ }
205
+ provider.modelSha256 = await sha256File(provider.modelPath)
206
+ if (typeof expectedSha === 'string' && expectedSha !== '' && provider.modelSha256 !== expectedSha) {
207
+ throw embedError(
208
+ 'KANABO_EMBED_MODEL_HASH_MISMATCH',
209
+ `模型文件 ${provider.modelPath} 的 sha256 是 ${provider.modelSha256},与钉住值 ${expectedSha} 不符;拒绝使用可疑权重。`)
210
+ }
211
+ } else if (offline) {
212
+ throw embedError(
213
+ 'KANABO_EMBED_PROVIDER_UNAVAILABLE',
214
+ `离线模式且本地模型缺失:${provider.modelPath}。`)
215
+ }
216
+ env.localModelPath = modelDir.endsWith('/') ? modelDir : `${modelDir}/`
217
+ env.allowLocalModels = true
218
+ env.allowRemoteModels = !offline
219
+ env.remoteHost = remoteHost
220
+ extractor = await pipeline('feature-extraction', modelId, { dtype }).catch((cause) => {
221
+ throw embedError(
222
+ 'KANABO_EMBED_PROVIDER_UNAVAILABLE',
223
+ `加载向量模型 ${modelId} 失败(本地缺失且镜像不可用?):${cause?.message ?? String(cause)}`,
224
+ { cause })
225
+ })
226
+ // 加载即断言:模型真实返回的维度必须等于契约值(这是唯一能证明「契约没漂」的时刻)。
227
+ const probe = await extractor('dimension probe', { pooling: 'mean', normalize: true })
228
+ const received = probe?.data?.length
229
+ if (received !== provider.dim) {
230
+ extractor = null
231
+ throw embedError(
232
+ 'KANABO_EMBED_DIMENSION_MISMATCH',
233
+ `模型 ${modelId} 返回 ${received} 维,契约 EMBEDDING_DIM 是 ${provider.dim};拒绝加载。`,
234
+ { expected: provider.dim, received })
235
+ }
236
+ },
237
+ async embed(texts) {
238
+ if (extractor === null) {
239
+ throw embedError('KANABO_EMBED_PROVIDER_UNAVAILABLE', '本地向量模型尚未加载。')
240
+ }
241
+ const output = await extractor(texts, { pooling: 'mean', normalize: true })
242
+ if (texts.length === 1) return [Float32Array.from(output.data)]
243
+ return texts.map((_, index) => Float32Array.from(output[index].data))
244
+ },
245
+ close() {
246
+ extractor?.dispose?.()
247
+ extractor = null
248
+ },
249
+ }
250
+ return provider
251
+ }
252
+
253
+ /**
254
+ * 可注入的 API provider:与本地 provider 完全同构,只是把推理换成一次 HTTP 调用。
255
+ * 它是「装不下/拿不到本地模型」时的答案,绝不做默认路径——调用方显式注入才会用。
256
+ * `dim` 必须与契约一致(OpenAI 的 `text-embedding-3-*` 支持 `dimensions` 参数降到 384)。
257
+ */
258
+ export function createApiProvider(options = {}) {
259
+ const url = options.url ?? process.env.KANABO_EMBED_API_URL ?? 'https://api.openai.com/v1/embeddings'
260
+ const apiKey = options.apiKey ?? process.env.KANABO_EMBED_API_KEY ?? ''
261
+ const model = options.model ?? process.env.KANABO_EMBED_API_MODEL ?? 'text-embedding-3-small'
262
+ const dim = options.dim ?? EMBEDDING_DIM
263
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
264
+ return {
265
+ id: `api:${model}`,
266
+ dim,
267
+ async load() {
268
+ if (typeof fetchImpl !== 'function') {
269
+ throw embedError('KANABO_EMBED_PROVIDER_UNAVAILABLE', 'API provider 缺少 fetch 实现。')
270
+ }
271
+ if (apiKey === '') {
272
+ throw embedError('KANABO_EMBED_PROVIDER_UNAVAILABLE', 'API provider 缺少 KANABO_EMBED_API_KEY。')
273
+ }
274
+ },
275
+ async embed(texts) {
276
+ const response = await fetchImpl(url, {
277
+ method: 'POST',
278
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
279
+ body: JSON.stringify({ model, input: texts, dimensions: dim }),
280
+ })
281
+ if (!response.ok) {
282
+ throw embedError('KANABO_EMBED_PROVIDER_UNAVAILABLE', `向量 API 返回 HTTP ${response.status}。`)
283
+ }
284
+ const payload = await response.json()
285
+ const rows = Array.isArray(payload?.data) ? payload.data : []
286
+ return texts.map((_, index) => Float32Array.from(rows[index]?.embedding ?? []))
287
+ },
288
+ close() {},
289
+ }
290
+ }
291
+
292
+ /**
293
+ * 门面:缓存 + 切块 + 期限 + 降级。
294
+ *
295
+ * `provider` 可注入(测试或 API 路径);缺省时构造本地 ONNX provider,且**不会**在构造期加载模型——
296
+ * 第一次 `embed()` 才懒加载。加载失败被记住:致命的(维度/体积/哈希/内存)永不重试,其余每
297
+ * `LOAD_RETRY_MS` 才重试一次,热路径始终只返回降级结果、不抛错。
298
+ */
299
+ export function createEmbedder(options = {}) {
300
+ const provider = options.provider ?? createLocalProvider(options)
301
+ const dim = options.dim ?? provider.dim ?? EMBEDDING_DIM
302
+ const cache = new LruCache(options.cacheCapacity ?? CACHE_CAPACITY)
303
+ const batchSize = Math.max(1, options.batchSize ?? BATCH_SIZE)
304
+ const timeoutMs = Math.max(1, options.timeoutMs ?? BATCH_TIMEOUT_MS)
305
+ const maxRssMb = options.maxRssMb ?? MAX_RSS_MB
306
+ const defaultPrefix = options.prefix ?? ''
307
+
308
+ const stats = {
309
+ calls: 0, // 实际打到 provider 的调用次数(缓存命中不计)
310
+ batches: 0,
311
+ timeouts: 0,
312
+ degraded: 0,
313
+ peakRssMb: null,
314
+ }
315
+ let loadFailure = null
316
+ let loaded = false
317
+ let closed = false
318
+
319
+ /** 「重试也不会变好」的加载失败:维度、体积、权重哈希、内存预算。 */
320
+ const FATAL_LOAD_REASONS = new Set([
321
+ DEGRADED_REASONS.DIMENSION_MISMATCH,
322
+ DEGRADED_REASONS.MODEL_TOO_LARGE,
323
+ DEGRADED_REASONS.MODEL_HASH_MISMATCH,
324
+ DEGRADED_REASONS.MEMORY_OVER_BUDGET,
325
+ ])
326
+
327
+ function rememberLoadFailure(error) {
328
+ const fatal = FATAL_LOAD_REASONS.has(reasonOf(error))
329
+ loadFailure = { error, fatal, retryAt: Date.now() + LOAD_RETRY_MS }
330
+ return error
331
+ }
332
+
333
+ /** 批后采样峰值 RSS;越界则卸载并返回致命的 `KANABO_EMBED_MEMORY_OVER_BUDGET`。 */
334
+ function sampleMemory() {
335
+ const peak = peakRssMb()
336
+ if (peak !== null) stats.peakRssMb = peak
337
+ if (peak !== null && peak > maxRssMb) {
338
+ provider.close?.()
339
+ loaded = false
340
+ return embedError(
341
+ 'KANABO_EMBED_MEMORY_OVER_BUDGET',
342
+ `向量模型峰值 RSS ${peak.toFixed(0)}MB 超过上限 ${maxRssMb}MB;已卸载并降级。`)
343
+ }
344
+ return null
345
+ }
346
+
347
+ async function ensureLoaded() {
348
+ if (loadFailure !== null && (loadFailure.fatal || Date.now() < loadFailure.retryAt)) {
349
+ throw loadFailure.error
350
+ }
351
+ if (loaded) return
352
+ try {
353
+ await provider.load?.()
354
+ } catch (error) {
355
+ throw rememberLoadFailure(error)
356
+ }
357
+ loaded = true
358
+ loadFailure = null
359
+ const overBudget = sampleMemory()
360
+ if (overBudget !== null) throw rememberLoadFailure(overBudget)
361
+ }
362
+
363
+ /** 降级结果:没有向量、有原因码;调用方据此退化为纯文本召回。 */
364
+ function degraded(reason) {
365
+ stats.degraded += 1
366
+ return { vector: null, degraded: true, reason, cached: false }
367
+ }
368
+
369
+ /** 一次 provider 调用(已切好块):超时/异常都折成原因码,绝不外抛。 */
370
+ async function callProvider(inputs) {
371
+ stats.calls += 1
372
+ stats.batches += 1
373
+ try {
374
+ const vectors = await withTimeout(provider.embed(inputs), timeoutMs, `embed(${inputs.length})`)
375
+ const checked = vectors.map((vector) => checkVector(vector, dim, provider.id))
376
+ const overBudget = sampleMemory()
377
+ if (overBudget !== null) throw rememberLoadFailure(overBudget)
378
+ return checked
379
+ } catch (error) {
380
+ const reason = reasonOf(error)
381
+ if (reason === DEGRADED_REASONS.TIMEOUT) stats.timeouts += 1
382
+ // 已加载的模型给出错维度同样是配置错误:记为致命,之后每次调用都直接降级。
383
+ if (reason === DEGRADED_REASONS.DIMENSION_MISMATCH) rememberLoadFailure(error)
384
+ throw error
385
+ }
386
+ }
387
+
388
+ function keyOf(text, prefix) {
389
+ return `${prefix}\u0000${text}`
390
+ }
391
+
392
+ /**
393
+ * 批量嵌入:命中缓存的文本不再进模型;未命中的按 `batchSize` 切块、每块一个硬期限。
394
+ * 返回与 `texts` 等长的结果数组,元素形状同 `embed()`。
395
+ */
396
+ async function embedBatch(texts, callOptions = {}) {
397
+ const list = Array.isArray(texts) ? texts : [texts]
398
+ const prefix = callOptions.prefix ?? defaultPrefix
399
+ const results = new Array(list.length)
400
+ const pending = []
401
+ for (let index = 0; index < list.length; index += 1) {
402
+ const text = list[index]
403
+ if (typeof text !== 'string') {
404
+ results[index] = degraded(DEGRADED_REASONS.ERROR)
405
+ continue
406
+ }
407
+ const hit = cache.get(keyOf(text, prefix))
408
+ if (hit !== undefined) {
409
+ results[index] = { vector: Float32Array.from(hit), degraded: false, reason: null, cached: true }
410
+ } else {
411
+ pending.push({ index, key: keyOf(text, prefix), input: `${prefix}${text}` })
412
+ }
413
+ }
414
+ if (pending.length === 0) return results
415
+ try {
416
+ await ensureLoaded()
417
+ } catch (error) {
418
+ const reason = reasonOf(error)
419
+ for (const item of pending) results[item.index] = degraded(reason)
420
+ return results
421
+ }
422
+ for (let start = 0; start < pending.length; start += batchSize) {
423
+ const chunk = pending.slice(start, start + batchSize)
424
+ try {
425
+ const vectors = await callProvider(chunk.map((item) => item.input))
426
+ for (let offset = 0; offset < chunk.length; offset += 1) {
427
+ const item = chunk[offset]
428
+ const vector = vectors[offset]
429
+ cache.set(item.key, vector)
430
+ results[item.index] = { vector: Float32Array.from(vector), degraded: false, reason: null, cached: false }
431
+ }
432
+ } catch (error) {
433
+ const reason = reasonOf(error)
434
+ for (const item of chunk) results[item.index] = degraded(reason)
435
+ }
436
+ }
437
+ return results
438
+ }
439
+
440
+ return {
441
+ dim,
442
+ providerId: provider.id,
443
+ modelId: provider.modelId ?? null,
444
+ async load() {
445
+ await ensureLoaded() // 显式 `load()` 保留「响亮失败」语义,供测试与启动自检使用。
446
+ return { dim, modelId: provider.modelId ?? null, sha256: provider.modelSha256 ?? null }
447
+ },
448
+ async embed(text, callOptions = {}) {
449
+ const [result] = await embedBatch([text], callOptions)
450
+ return result
451
+ },
452
+ embedBatch,
453
+ /** 缓存与计数快照:`fatal` 非 null 说明加载已永久失败(致命类),`lastLoadFailure` 记最近一次加载失败。 */
454
+ stats() {
455
+ return {
456
+ ...stats,
457
+ cacheSize: cache.map.size,
458
+ cacheCapacity: cache.capacity,
459
+ cacheHits: cache.hits,
460
+ cacheMisses: cache.misses,
461
+ loaded,
462
+ fatal: loadFailure?.fatal === true ? reasonOf(loadFailure.error) : null,
463
+ lastLoadFailure: loadFailure === null ? null : reasonOf(loadFailure.error),
464
+ }
465
+ },
466
+ close() {
467
+ if (closed) return
468
+ closed = true
469
+ loaded = false
470
+ loadFailure = null
471
+ provider.close?.()
472
+ cache.clear()
473
+ },
474
+ }
475
+ }