dsh-memu-memory 1.2.8 → 1.2.9
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/CHANGELOG.md +472 -0
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/lib/backup.js +154 -25
- package/lib/binding-diagnostics.js +1 -2
- package/lib/budget.js +0 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +3 -3
- package/lib/consolidation-ledger.js +5 -2
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +2 -2
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +50 -7
- package/lib/lexicon.js +61 -16
- package/lib/local-vector-service.js +21 -1
- package/lib/media.js +49 -12
- package/lib/memory.js +662 -116
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +45 -7
- package/lib/prompts.js +0 -7
- package/lib/rpc.js +95 -17
- package/lib/snippet.js +18 -2
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +19 -0
- package/lib/text-retrieval.js +120 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +83 -83
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +18 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/inject-conflict.test.mjs +18 -0
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +16 -0
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/recall-intent.test.mjs +23 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
package/lib/commitment.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// open → 还没兑现;done → 已兑现;cancelled → 明确取消;expired → 过期未完成。
|
|
5
5
|
// due_at 接受 YYYY-MM-DD 或 ISO 时间;比较按“到期那一天”算,不按时分秒。
|
|
6
6
|
|
|
7
|
+
import { localCalendarDay } from './temporal.js'
|
|
8
|
+
|
|
7
9
|
export const COMMITMENT_STATUSES = ['open', 'done', 'cancelled', 'expired']
|
|
8
10
|
|
|
9
11
|
const DAY_MS = 86_400_000
|
|
@@ -46,9 +48,7 @@ function dueDateText(value) {
|
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
function localDateKey(now) {
|
|
49
|
-
|
|
50
|
-
const safe = Number.isFinite(at.getTime()) ? at : new Date()
|
|
51
|
-
return `${safe.getFullYear()}-${String(safe.getMonth() + 1).padStart(2, '0')}-${String(safe.getDate()).padStart(2, '0')}`
|
|
51
|
+
return localCalendarDay(now)
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
function daysBetween(fromKey, toKey) {
|
|
@@ -268,8 +268,11 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
|
|
|
268
268
|
entry.attempts = (Number(entry.attempts) || 0) + 1
|
|
269
269
|
entry.retryAt = retryAtFrom(now, entry.attempts)
|
|
270
270
|
} else {
|
|
271
|
-
//
|
|
272
|
-
|
|
271
|
+
// 重试也不会变好(父授权变了、工具面不存在)。这里仍然要写一个退避,只是
|
|
272
|
+
// 取上限而不是从 1 分钟起:null 在 cycle 的读侧等于「随时可以再试」,于是
|
|
273
|
+
// 「不要每小时再试一次」变成了「每 5 分钟再试一次」。一小时是同一个上界,
|
|
274
|
+
// 语义却是真的「别再急着试」。
|
|
275
|
+
entry.retryAt = retryAtFrom(now, 6)
|
|
273
276
|
}
|
|
274
277
|
entry.lastReasonCode = reasonCode
|
|
275
278
|
entry.lastError = clampText(error || reasonCode)
|
package/lib/curator-policy.js
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
// gate already owns the value (DUP_DICE / DUP_REJECT_DICE / TOPIC_DICE), so
|
|
9
9
|
// the write-side duplicate ruler and the curator pair bands can never
|
|
10
10
|
// drift apart.
|
|
11
|
+
// 3. 相似度尺度的阈值(Dice 分带、长度剪枝比、包含探针下限)在
|
|
12
|
+
// lib/text-similarity.js 的 SIMILARITY_THRESHOLDS 里集中定义;本文件的常量
|
|
13
|
+
// 是「策展策略」——即哪些相似度分带触发 absorb/link/duplicate——而不是
|
|
14
|
+
// 相似度尺度本身。两处文档的分工以此为准。
|
|
11
15
|
import { DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
12
16
|
// 刻意的双向依赖(仅函数体内使用):computeRRFWeights 的近期语义检测要用
|
|
13
17
|
// 「当前生效的 tokenize」,而分词开关(TOKENIZER_V2)就定义在本表,实际实现
|
|
@@ -38,6 +42,11 @@ export const CLUSTER_MIN_PAIR = 0.55
|
|
|
38
42
|
export const CLUSTER_BLOCK_MIN_SHARED = 2
|
|
39
43
|
export const CLUSTER_EXACT_PAIR_LIMIT = 300
|
|
40
44
|
export const CLUSTER_RECENT_LIMIT = 2000
|
|
45
|
+
// 倒排 blocking 的硬上限(防御性,不是主要剪枝):df 剪枝之后仍可能留下大量
|
|
46
|
+
// 共享对(例如每条都含一批中等频率的专有词)。超过这个数量就停止收集新对,
|
|
47
|
+
// 只保留已累积的计数——排序/切片必须有界,簇构建不能退化成 N²。
|
|
48
|
+
// 主要剪枝是 BLOCK_DF_RATIO 的 posting 上限:高频词在倒排层就被跳过。
|
|
49
|
+
export const CLUSTER_MAX_PAIRS = 50000
|
|
41
50
|
|
|
42
51
|
// —— 成对特征(§4.2)——
|
|
43
52
|
export const PAIR_SCAN_LIMIT = 20
|
|
@@ -53,6 +62,20 @@ export const PAIR_W_ENTITY = 0.15
|
|
|
53
62
|
export const BM25_K1 = 1.2
|
|
54
63
|
export const BM25_B = 0.75
|
|
55
64
|
export const BM25_MAX_QUERY_TERMS = 64
|
|
65
|
+
// query 侧的高频词闸(A-2):df 超过 dfCap 的 term 整条不参与打分,dfCap 取
|
|
66
|
+
// 「占比」与「候选池下限」中较大的那个:
|
|
67
|
+
// dfCap = max(BM25_DF_MIN_POOL, ceil(BM25_DF_RATIO × N))
|
|
68
|
+
// 只有占比是不够的:N=12 时 0.3N=3.6,任何被共享的查询词都会被剔光,12 条记忆
|
|
69
|
+
// 都提到「会议」的那次召回直接返回 0 条(实测回归)。下限的意思是「这条 posting
|
|
70
|
+
// 装得进一次召回所用过的最小候选池,就谈不上淹掉谁」。而 N=21 里 df=21 的「版本」
|
|
71
|
+
// 越过下限、被剔掉,decoy 才不会被一个恒正的小分拉进候选池——这正是要修的。
|
|
72
|
+
// 被剔除的是整个 term,不是把分数清零后保留条目(那只是换了个 0 分候选)。
|
|
73
|
+
// idf 下限曾经也有一道闸,但它可触及的条件(df > 0.9N)必然先被 df 闸命中,
|
|
74
|
+
// 剩下的只有 N<9 的极小语料——那正是绝不能剪的那一档,所以删掉。
|
|
75
|
+
export const BM25_DF_RATIO = 0.3
|
|
76
|
+
// 与 memory.js 的 HYBRID_CANDIDATE_MIN 同一口径:任何一次召回至少会看这么多条。
|
|
77
|
+
// posting 不超过它就淹不掉任何东西,剪枝只会白丢召回。
|
|
78
|
+
export const BM25_DF_MIN_POOL = 12
|
|
56
79
|
export const BLOCK_DF_RATIO = 0.3
|
|
57
80
|
export const RRF_K = 60 // 与 memory.js 的 HYBRID_RRF_K 同一口径
|
|
58
81
|
export const RRF_W_BM25 = 0.5
|
package/lib/cycle.js
CHANGED
|
@@ -92,6 +92,11 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
92
92
|
const idle = now - activeAt >= idleMs
|
|
93
93
|
const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
|
|
94
94
|
const state = ledger ? sessionState(binding.sessionId, ledger) : null
|
|
95
|
+
// The ledger's backoff used to be write-only: failJob stored retryAt and nothing
|
|
96
|
+
// ever read it, so a session that failed three times was retried on the very next
|
|
97
|
+
// sweep, five minutes later, forever. `sleepRetryAt` below is a different clock —
|
|
98
|
+
// that one delays the next *window*, this one delays the retry after a *failure*.
|
|
99
|
+
if ((Date.parse(state?.retryAt || '') || 0) > now) continue
|
|
95
100
|
const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
|
|
96
101
|
? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
|
|
97
102
|
: 0
|
|
@@ -157,10 +162,9 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
157
162
|
// 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
|
|
158
163
|
// 或后续证据变多再检查。否则这句话会被永久跳过。
|
|
159
164
|
if (result.settled === false) {
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
165
|
+
// 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
|
|
166
|
+
// 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
|
|
167
|
+
setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
|
|
164
168
|
log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
|
|
165
169
|
continue
|
|
166
170
|
}
|
|
@@ -17,16 +17,19 @@ import {
|
|
|
17
17
|
// 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
|
|
18
18
|
// 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
|
|
19
19
|
// 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
|
|
20
|
-
// 4.
|
|
21
|
-
|
|
22
|
-
export const DOWNLOAD_STATES = Object.freeze(['unknown', 'absent', 'downloading', 'verifying', 'installed', 'failed', 'cancelled'])
|
|
20
|
+
// 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
|
|
21
|
+
// 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
|
|
23
22
|
|
|
24
23
|
const INSTALL_RECORD = 'installed.json'
|
|
25
24
|
const STAGING_DIR = '.staging'
|
|
26
25
|
const TRASH_DIR = '.trash'
|
|
26
|
+
const CACHE_DIR = '.cache'
|
|
27
27
|
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
28
|
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
29
|
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
30
|
+
// S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
|
|
31
|
+
const DEFAULT_FETCH_TIMEOUT_MS = 600_000
|
|
32
|
+
const DEFAULT_STALL_TIMEOUT_MS = 30_000
|
|
30
33
|
|
|
31
34
|
function fail(code, message, extra) {
|
|
32
35
|
const error = new Error(message)
|
|
@@ -35,6 +38,37 @@ function fail(code, message, extra) {
|
|
|
35
38
|
return error
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
function sha256FileSync(file) {
|
|
42
|
+
const hash = crypto.createHash('sha256')
|
|
43
|
+
const fd = fs.openSync(file, 'r')
|
|
44
|
+
try {
|
|
45
|
+
const buffer = Buffer.allocUnsafe(64 * 1024)
|
|
46
|
+
let read
|
|
47
|
+
while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
|
|
48
|
+
} finally {
|
|
49
|
+
fs.closeSync(fd)
|
|
50
|
+
}
|
|
51
|
+
return hash.digest('hex')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
|
|
55
|
+
// 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
|
|
56
|
+
function ensureFreeSpace(dir, requiredBytes) {
|
|
57
|
+
if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
|
|
58
|
+
let available = null
|
|
59
|
+
try {
|
|
60
|
+
const stat = fs.statfsSync(dir)
|
|
61
|
+
available = Number(stat.bavail) * Number(stat.bsize)
|
|
62
|
+
} catch {
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
if (!Number.isFinite(available) || available <= 0) return
|
|
66
|
+
// 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
|
|
67
|
+
if (available < requiredBytes * 2) {
|
|
68
|
+
throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
38
72
|
function isAbort(error, signal) {
|
|
39
73
|
return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
|
|
40
74
|
}
|
|
@@ -186,6 +220,8 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
186
220
|
const { root, fetchImpl = fetch, verifyModel, maxFileBytes = DEFAULT_MAX_FILE_BYTES, now = () => new Date().toISOString() } = options
|
|
187
221
|
if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingDownloadManager requires a root directory')
|
|
188
222
|
const baseDir = path.resolve(root)
|
|
223
|
+
const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
|
|
224
|
+
const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
|
|
189
225
|
const extraCatalog = Array.isArray(options.catalog) ? options.catalog : []
|
|
190
226
|
const jobs = new Map()
|
|
191
227
|
// 失败/取消结果单独记账:jobs 只表示「在途」,所以重试不会被误判成 BUSY,
|
|
@@ -204,6 +240,12 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
204
240
|
|
|
205
241
|
const modelDir = id => insideRoot(path.join(baseDir, id))
|
|
206
242
|
const recordPath = id => path.join(modelDir(id), INSTALL_RECORD)
|
|
243
|
+
// S-16:续传用的稳定 .part 放在独立 .cache,与 .staging 隔离(staging 仍保持
|
|
244
|
+
// 「安装成功后必须为空」的既有语义)。文件名带 sha256,换源/换版本不会误复用。
|
|
245
|
+
const partPathFor = file => {
|
|
246
|
+
const safe = String(file.path).split('/').pop().replace(/[^A-Za-z0-9._-]+/g, '-')
|
|
247
|
+
return path.join(insideRoot(path.join(baseDir, CACHE_DIR)), `${safe}-${file.sha256}.part`)
|
|
248
|
+
}
|
|
207
249
|
|
|
208
250
|
function readInstall(entry) {
|
|
209
251
|
const dir = modelDir(entry.id)
|
|
@@ -328,7 +370,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
328
370
|
outcomes.delete(entry.id)
|
|
329
371
|
let staging = null
|
|
330
372
|
let installed = false
|
|
373
|
+
const parts = []
|
|
331
374
|
try {
|
|
375
|
+
// S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
|
|
376
|
+
fs.mkdirSync(baseDir, { recursive: true })
|
|
377
|
+
ensureFreeSpace(baseDir, entry.totalBytes)
|
|
332
378
|
const stagingRoot = insideRoot(path.join(baseDir, STAGING_DIR))
|
|
333
379
|
fs.mkdirSync(stagingRoot, { recursive: true })
|
|
334
380
|
staging = fs.mkdtempSync(path.join(stagingRoot, `${entry.id}-`))
|
|
@@ -340,51 +386,138 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
340
386
|
if (!path.resolve(target).startsWith(path.resolve(staging) + path.sep)) throw fail('EMBEDDING_PATH_ESCAPE', `file ${file.path} escapes the staging directory`)
|
|
341
387
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
342
388
|
job.progress.current = file.path
|
|
389
|
+
|
|
390
|
+
// S-16:稳定 .part 缓存(独立于 .staging)+ Range 续传。半成品只进 .cache,
|
|
391
|
+
// 保持 staging「安装成功后必须为空」的既有语义。
|
|
392
|
+
const part = partPathFor(file)
|
|
393
|
+
parts.push(part)
|
|
394
|
+
fs.mkdirSync(path.dirname(part), { recursive: true })
|
|
395
|
+
let existing = 0
|
|
396
|
+
try { existing = fs.statSync(part).size } catch {}
|
|
397
|
+
if (existing > file.bytes) {
|
|
398
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
399
|
+
existing = 0
|
|
400
|
+
}
|
|
401
|
+
if (existing > 0 && existing === file.bytes) {
|
|
402
|
+
let reusable = false
|
|
403
|
+
try { reusable = sha256FileSync(part) === file.sha256 } catch { reusable = false }
|
|
404
|
+
if (reusable) {
|
|
405
|
+
fs.copyFileSync(part, target)
|
|
406
|
+
job.progress.bytes += file.bytes
|
|
407
|
+
job.progress.done += 1
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
// 长度对但 hash 不符:这份半成品不可信,从头下。
|
|
411
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
412
|
+
existing = 0
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// S-1:总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
|
|
416
|
+
// 连接让 for-await 永久 pending;超时单独记账,别被误判成用户取消。
|
|
417
|
+
let timedOut = false
|
|
418
|
+
const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
|
|
419
|
+
totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
420
|
+
const stallController = new AbortController()
|
|
421
|
+
let stallTimer = null
|
|
422
|
+
const armStall = () => {
|
|
423
|
+
if (stallTimer) clearTimeout(stallTimer)
|
|
424
|
+
stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
|
|
425
|
+
stallTimer.unref?.()
|
|
426
|
+
}
|
|
427
|
+
const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
|
|
428
|
+
const timeoutFailure = cause => fail('EMBEDDING_DOWNLOAD_TIMEOUT', `download of ${file.path} timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
|
|
429
|
+
const abortedFailure = cause => fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause })
|
|
430
|
+
// 磁盘写失败清 .part;超时/取消保留 .part 供下次 Range 续传。
|
|
431
|
+
let removePart = false
|
|
432
|
+
const streamFailure = error => {
|
|
433
|
+
if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
|
|
434
|
+
if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
|
|
435
|
+
if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
|
|
436
|
+
removePart = true
|
|
437
|
+
return fail('EMBEDDING_DISK_FULL', `cannot write ${file.path}: ${error.code}; partial download removed`, { cause: error })
|
|
438
|
+
}
|
|
439
|
+
return error
|
|
440
|
+
}
|
|
441
|
+
armStall()
|
|
442
|
+
const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
|
|
443
|
+
const headers = { 'accept-encoding': 'identity' }
|
|
444
|
+
if (existing > 0) headers.Range = `bytes=${existing}-`
|
|
343
445
|
let response
|
|
344
446
|
try {
|
|
345
|
-
response = await fetchImpl(file.url, { signal
|
|
447
|
+
response = await fetchImpl(file.url, { signal, redirect: 'follow', headers })
|
|
346
448
|
} catch (error) {
|
|
347
|
-
if (
|
|
449
|
+
if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
|
|
450
|
+
if (isAbort(error, controller.signal)) throw abortedFailure(error)
|
|
348
451
|
throw fail('EMBEDDING_NETWORK_ERROR', `cannot fetch ${file.path} from ${source.provider}: ${error?.message || error}`, { cause: error })
|
|
349
452
|
}
|
|
350
453
|
if (!response || !response.ok) {
|
|
351
454
|
throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
|
|
352
455
|
}
|
|
456
|
+
let append = existing > 0
|
|
457
|
+
if (append && response.status === 200) {
|
|
458
|
+
// 源忽略了 Range,丢弃 .part 从头下,避免把整段内容追加到半成品后面。
|
|
459
|
+
job.progress.bytes = Math.max(0, job.progress.bytes - existing)
|
|
460
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
461
|
+
append = false
|
|
462
|
+
existing = 0
|
|
463
|
+
} else if (append) {
|
|
464
|
+
const contentRange = String(response.headers?.get?.('content-range') || '')
|
|
465
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
|
|
466
|
+
if (response.status !== 206 || !match || Number(match[1]) !== existing || Number(match[3]) !== file.bytes) {
|
|
467
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} returned an unexpected Content-Range for resume: ${contentRange || '(missing)'}`)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
353
470
|
// 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
|
|
354
471
|
// 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
|
|
355
472
|
const declaredHeader = response.headers?.get?.('content-length')
|
|
356
473
|
const declaredLength = Number(declaredHeader)
|
|
357
|
-
|
|
358
|
-
|
|
474
|
+
const expectedLength = file.bytes - existing
|
|
475
|
+
if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== expectedLength) {
|
|
476
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the expected ${expectedLength} bytes`)
|
|
359
477
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const fd = fs.openSync(target, 'wx', 0o600)
|
|
478
|
+
let size = existing
|
|
479
|
+
const fd = fs.openSync(part, append ? 'a' : 'w', 0o600)
|
|
363
480
|
try {
|
|
364
481
|
const body = response.body
|
|
365
482
|
if (body && typeof body[Symbol.asyncIterator] === 'function') {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
483
|
+
try {
|
|
484
|
+
for await (const chunk of body) {
|
|
485
|
+
if (controller.signal.aborted) throw abortedFailure(null)
|
|
486
|
+
armStall()
|
|
487
|
+
size += chunk.length
|
|
488
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
489
|
+
fs.writeSync(fd, chunk)
|
|
490
|
+
job.progress.bytes += chunk.length
|
|
491
|
+
}
|
|
492
|
+
} catch (error) { throw streamFailure(error) }
|
|
374
493
|
} else {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
494
|
+
try {
|
|
495
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
496
|
+
size += buffer.length
|
|
497
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
498
|
+
fs.writeSync(fd, buffer)
|
|
499
|
+
job.progress.bytes += buffer.length
|
|
500
|
+
} catch (error) { throw streamFailure(error) }
|
|
381
501
|
}
|
|
382
502
|
} finally {
|
|
383
|
-
|
|
503
|
+
clearStall()
|
|
504
|
+
try { fs.closeSync(fd) } catch {}
|
|
505
|
+
if (removePart) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
506
|
+
}
|
|
507
|
+
if (size !== file.bytes) {
|
|
508
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
509
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
|
|
510
|
+
}
|
|
511
|
+
const digest = sha256FileSync(part)
|
|
512
|
+
if (digest !== file.sha256) {
|
|
513
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
514
|
+
throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
fs.copyFileSync(part, target)
|
|
518
|
+
} catch (error) {
|
|
519
|
+
throw fail('EMBEDDING_INSTALL_FAILED', `cannot stage ${file.path}: ${error?.code || error?.message || error}; partial download removed`, { cause: error })
|
|
384
520
|
}
|
|
385
|
-
if (size !== file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
|
|
386
|
-
const digest = hash.digest('hex')
|
|
387
|
-
if (digest !== file.sha256) throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
|
|
388
521
|
job.progress.done += 1
|
|
389
522
|
}
|
|
390
523
|
job.state = 'verifying'
|
|
@@ -441,6 +574,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
441
574
|
const aborted = isAbort(error, controller.signal)
|
|
442
575
|
const code = aborted ? 'EMBEDDING_DOWNLOAD_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('EMBEDDING_') ? error.code : 'EMBEDDING_DOWNLOAD_FAILED')
|
|
443
576
|
const failed = code === error?.code ? error : fail(code, `download of ${entry.id} failed: ${error?.message || error}`, { cause: error })
|
|
577
|
+
// S-16:非可续传类失败清掉 .part,别让半成品占空间;网络错误/超时/取消
|
|
578
|
+
// 保留 .part 供下次 Range 续传(S-1)。
|
|
579
|
+
if (!['EMBEDDING_DOWNLOAD_ABORTED', 'EMBEDDING_NETWORK_ERROR', 'EMBEDDING_DOWNLOAD_TIMEOUT'].includes(code)) {
|
|
580
|
+
for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
581
|
+
}
|
|
444
582
|
job.state = aborted ? 'cancelled' : 'failed'
|
|
445
583
|
job.error = { code, message: String(failed.message || error) }
|
|
446
584
|
jobs.delete(entry.id)
|
|
@@ -449,6 +587,8 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
449
587
|
} finally {
|
|
450
588
|
signal?.removeEventListener('abort', onAbort)
|
|
451
589
|
if (staging && !installed) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
|
|
590
|
+
// 安装成功后本次的 .part 已完成使命,清掉避免长期占空间。
|
|
591
|
+
if (installed) { for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} } }
|
|
452
592
|
}
|
|
453
593
|
}
|
|
454
594
|
|
package/lib/embedding-runtime.js
CHANGED
|
@@ -26,14 +26,14 @@ export const RUNTIME_RECORD = 'installed.json'
|
|
|
26
26
|
export const RUNTIME_ACTIVE = 'active.json'
|
|
27
27
|
export const RUNTIME_STAGING = '.staging'
|
|
28
28
|
export const RUNTIME_CACHE = '.cache'
|
|
29
|
-
export const RUNTIME_TRASH = '.trash'
|
|
30
29
|
export const RUNTIME_LAYOUT = 'node_modules'
|
|
31
|
-
export const RUNTIME_STATES = Object.freeze(['unknown', 'unsupported', 'absent', 'downloading', 'verifying', 'installing', 'installed', 'failed', 'cancelled'])
|
|
32
30
|
|
|
33
31
|
const DEFAULT_MAX_ARTIFACT_BYTES = 256 * 1024 * 1024
|
|
34
32
|
const DEFAULT_MAX_FILE_BYTES = 128 * 1024 * 1024
|
|
35
33
|
const DEFAULT_SMOKE_TIMEOUT_MS = 120_000
|
|
36
34
|
const DEFAULT_FETCH_TIMEOUT_MS = 600_000
|
|
35
|
+
// 分块 stall 超时:连续这么久没收到任何 chunk 就判定连接半开并 abort(S-1)。
|
|
36
|
+
const DEFAULT_STALL_TIMEOUT_MS = 30_000
|
|
37
37
|
const READY_LIMIT = 8_192
|
|
38
38
|
|
|
39
39
|
// The child smoke process needs the OS basics and nothing else: an inherited proxy
|
|
@@ -49,6 +49,25 @@ function failure(code, message, extra) {
|
|
|
49
49
|
return error
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
// S-16:下载前预检目标盘剩余空间,避免下到一半 ENOSPC 留下 .part 占空间。
|
|
53
|
+
// statfsSync 在部分平台/挂载点会抛错或回报 0,此时不拦(fail-open),让写入
|
|
54
|
+
// 路径自己报错,别因为一个探针就挡住本来能装成功的下载。
|
|
55
|
+
function ensureFreeSpace(dir, requiredBytes) {
|
|
56
|
+
if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
|
|
57
|
+
let available = null
|
|
58
|
+
try {
|
|
59
|
+
const stat = fs.statfsSync(dir)
|
|
60
|
+
available = Number(stat.bavail) * Number(stat.bsize)
|
|
61
|
+
} catch {
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
if (!Number.isFinite(available) || available <= 0) return
|
|
65
|
+
// 留一倍余量给解包与安装副本,别把盘压到 0。
|
|
66
|
+
if (available < requiredBytes * 2) {
|
|
67
|
+
throw failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `not enough free space for the managed runtime: need ~${requiredBytes * 2} bytes, only ${available} available`)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
52
71
|
function isPlainObject(value) {
|
|
53
72
|
return !!value && typeof value === 'object' && !Array.isArray(value)
|
|
54
73
|
}
|
|
@@ -248,6 +267,7 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
|
|
|
248
267
|
const maxFileBytes = Number.isInteger(options.maxFileBytes) ? options.maxFileBytes : DEFAULT_MAX_FILE_BYTES
|
|
249
268
|
const smokeTimeoutMs = Number.isInteger(options.smokeTimeoutMs) ? options.smokeTimeoutMs : DEFAULT_SMOKE_TIMEOUT_MS
|
|
250
269
|
const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
|
|
270
|
+
const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
|
|
251
271
|
const extract = typeof options.extract === 'function' ? options.extract : defaultExtract
|
|
252
272
|
const smoke = typeof options.smoke === 'function' ? options.smoke : defaultSmoke
|
|
253
273
|
const resolveEntry = typeof options.resolveEntry === 'function' ? options.resolveEntry : id => (id ? getEmbeddingModel(String(id)) : null)
|
|
@@ -516,11 +536,41 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
|
|
|
516
536
|
}
|
|
517
537
|
const headers = { 'accept-encoding': 'identity' }
|
|
518
538
|
if (existing > 0) headers.Range = `bytes=${existing}-`
|
|
539
|
+
// S-1:fetch 总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
|
|
540
|
+
// 连接让 for-await 永久 pending;超时单独记账,别被 install() 误判成用户取消。
|
|
541
|
+
let timedOut = false
|
|
542
|
+
const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
|
|
543
|
+
totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
544
|
+
const stallController = new AbortController()
|
|
545
|
+
let stallTimer = null
|
|
546
|
+
const armStall = () => {
|
|
547
|
+
if (stallTimer) clearTimeout(stallTimer)
|
|
548
|
+
stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
|
|
549
|
+
stallTimer.unref?.()
|
|
550
|
+
}
|
|
551
|
+
const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
|
|
552
|
+
const timeoutFailure = cause => failure('LOCAL_VECTOR_RUNTIME_DOWNLOAD_TIMEOUT', `${artifact.name} download timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
|
|
553
|
+
const abortedFailure = cause => failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause })
|
|
554
|
+
// for-await 被 signal 中断时抛原生 AbortError,按来源还原成明确失败码;
|
|
555
|
+
// 磁盘写失败(ENOSPC/EIO/...)清掉 .part,别让半成品占着空间(S-16)。
|
|
556
|
+
let removePart = false
|
|
557
|
+
const streamFailure = error => {
|
|
558
|
+
if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
|
|
559
|
+
if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
|
|
560
|
+
if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
|
|
561
|
+
removePart = true
|
|
562
|
+
return failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `${artifact.name} download failed with ${error.code}; partial download removed`, { cause: error })
|
|
563
|
+
}
|
|
564
|
+
return error
|
|
565
|
+
}
|
|
566
|
+
armStall()
|
|
567
|
+
const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
|
|
519
568
|
let response
|
|
520
569
|
try {
|
|
521
|
-
response = await fetchImpl(url, { signal
|
|
570
|
+
response = await fetchImpl(url, { signal, redirect: 'follow', headers })
|
|
522
571
|
} catch (error) {
|
|
523
|
-
if (
|
|
572
|
+
if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
|
|
573
|
+
if (isAbort(error, controller.signal)) throw abortedFailure(error)
|
|
524
574
|
throw failure('LOCAL_VECTOR_RUNTIME_NETWORK_ERROR', `cannot fetch ${artifact.name}: ${error?.message || error}`, { cause: error })
|
|
525
575
|
}
|
|
526
576
|
if (!response || !response.ok) throw failure('LOCAL_VECTOR_RUNTIME_HTTP_ERROR', `registry returned ${response?.status ?? 'no response'} for ${artifact.name}`)
|
|
@@ -552,22 +602,29 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
|
|
|
552
602
|
try {
|
|
553
603
|
const body = response.body
|
|
554
604
|
if (body && typeof body[Symbol.asyncIterator] === 'function') {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
605
|
+
try {
|
|
606
|
+
for await (const chunk of body) {
|
|
607
|
+
if (controller.signal.aborted) throw abortedFailure(null)
|
|
608
|
+
armStall()
|
|
609
|
+
size += chunk.length
|
|
610
|
+
if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
|
|
611
|
+
fs.writeSync(fd, chunk)
|
|
612
|
+
bump(chunk.length)
|
|
613
|
+
}
|
|
614
|
+
} catch (error) { throw streamFailure(error) }
|
|
562
615
|
} else {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
616
|
+
try {
|
|
617
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
618
|
+
size += buffer.length
|
|
619
|
+
if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
|
|
620
|
+
fs.writeSync(fd, buffer)
|
|
621
|
+
bump(buffer.length)
|
|
622
|
+
} catch (error) { throw streamFailure(error) }
|
|
568
623
|
}
|
|
569
624
|
} finally {
|
|
570
|
-
|
|
625
|
+
clearStall()
|
|
626
|
+
try { fs.closeSync(fd) } catch {}
|
|
627
|
+
if (removePart) { try { fs.rmSync(paths.part, { force: true }) } catch {} }
|
|
571
628
|
}
|
|
572
629
|
if (size !== artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} is ${size} bytes, expected ${artifact.bytes}`)
|
|
573
630
|
const digest = await sha256File(paths.part)
|
|
@@ -643,6 +700,8 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
|
|
|
643
700
|
job = null
|
|
644
701
|
return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
|
|
645
702
|
}
|
|
703
|
+
// S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
|
|
704
|
+
ensureFreeSpace(baseDir, totalBytes)
|
|
646
705
|
// Pick up a partial download from an interrupted process. Old installers kept
|
|
647
706
|
// the tarball inside their own staging dir; this stable cache is what makes a
|
|
648
707
|
// restart resume instead of re-downloading 115 MB.
|
package/lib/engine.js
CHANGED
|
@@ -973,9 +973,3 @@ export async function ensureEngine({ force = false, log = null, beforeSwitch = n
|
|
|
973
973
|
return installEngine({ force: true, log, beforeSwitch })
|
|
974
974
|
}
|
|
975
975
|
|
|
976
|
-
export function startBackgroundInstall({ log = null } = {}) {
|
|
977
|
-
const status = engineStatus()
|
|
978
|
-
if (status.status === 'installing') return status
|
|
979
|
-
void ensureEngine({ log }).catch(() => {})
|
|
980
|
-
return engineStatus()
|
|
981
|
-
}
|
package/lib/freshness.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// The word list is fixed on purpose — exposing it as a setting would create a second
|
|
12
12
|
// vocabulary system, and this is a nudge, not a filter.
|
|
13
13
|
|
|
14
|
+
import { localCalendarDay } from './temporal.js'
|
|
14
15
|
const DAY_MS = 86_400_000
|
|
15
16
|
const DEFAULT_FRESHNESS_DAYS = 30
|
|
16
17
|
// Fixed first-version vocabulary (plan D.2). Keep it separate from the lexicon.
|
|
@@ -52,8 +53,7 @@ function timestampMs(value) {
|
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
function localDateKey(now) {
|
|
55
|
-
|
|
56
|
-
return `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`
|
|
56
|
+
return localCalendarDay(baseTime(now))
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
/**
|