dsh-memu-memory 1.4.2 → 1.4.4
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/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
|
@@ -1,486 +1,529 @@
|
|
|
1
|
-
import test from 'node:test'
|
|
2
|
-
import assert from 'node:assert/strict'
|
|
3
|
-
import fs from 'node:fs'
|
|
4
|
-
import os from 'node:os'
|
|
5
|
-
import path from 'node:path'
|
|
6
|
-
import crypto from 'node:crypto'
|
|
7
|
-
import { Buffer } from 'node:buffer'
|
|
8
|
-
import { profileFingerprint, resolveEmbeddingSources } from '../lib/embedding-catalog.js'
|
|
9
|
-
import { createEmbeddingDownloadManager, verifyStagedArtifacts } from '../lib/embedding-download.js'
|
|
10
|
-
|
|
11
|
-
const REVISION = 'a'.repeat(40)
|
|
12
|
-
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-embed-dl-'))
|
|
13
|
-
test.after(() => fs.rmSync(scratch, { recursive: true, force: true }))
|
|
14
|
-
|
|
15
|
-
const sha256 = buffer => crypto.createHash('sha256').update(buffer).digest('hex')
|
|
16
|
-
|
|
17
|
-
function varint(value) {
|
|
18
|
-
const bytes = []
|
|
19
|
-
let rest = value
|
|
20
|
-
while (rest > 127) { bytes.push((rest & 0x7f) | 0x80); rest = Math.floor(rest / 128) }
|
|
21
|
-
bytes.push(rest)
|
|
22
|
-
return Buffer.from(bytes)
|
|
23
|
-
}
|
|
24
|
-
const tag = (field, wire) => varint((field << 3) | wire)
|
|
25
|
-
const bytesField = (field, buffer) => Buffer.concat([tag(field, 2), varint(buffer.length), buffer])
|
|
26
|
-
const textField = (field, text) => bytesField(field, Buffer.from(text, 'utf8'))
|
|
27
|
-
const intField = (field, value) => Buffer.concat([tag(field, 0), varint(value)])
|
|
28
|
-
const dimension = dim => (typeof dim === 'number' ? intField(1, dim) : textField(2, String(dim)))
|
|
29
|
-
function valueInfo(name, elemType, shape) {
|
|
30
|
-
const shapeMessage = Buffer.concat(shape.map(dim => bytesField(1, dimension(dim))))
|
|
31
|
-
const tensorType = Buffer.concat([intField(1, elemType), bytesField(2, shapeMessage)])
|
|
32
|
-
return Buffer.concat([textField(1, name), bytesField(2, bytesField(1, tensorType))])
|
|
33
|
-
}
|
|
34
|
-
function tinyOnnxGraph(outputDim = 8) {
|
|
35
|
-
const initializer = Buffer.concat([intField(1, 1), intField(2, 1), textField(8, 'w'), bytesField(9, Buffer.from('quantized-weights-fixture'))])
|
|
36
|
-
const graph = Buffer.concat([
|
|
37
|
-
bytesField(5, initializer),
|
|
38
|
-
bytesField(11, valueInfo('input_ids', 7, ['batch_size', 'sequence_length'])),
|
|
39
|
-
bytesField(11, valueInfo('attention_mask', 7, ['batch_size', 'sequence_length'])),
|
|
40
|
-
bytesField(11, valueInfo('token_type_ids', 7, ['batch_size', 'sequence_length'])),
|
|
41
|
-
bytesField(12, valueInfo('last_hidden_state', 1, ['batch_size', 'sequence_length', outputDim])),
|
|
42
|
-
])
|
|
43
|
-
return Buffer.concat([intField(1, 6), textField(2, 'onnx.quantize'), bytesField(7, graph), bytesField(8, Buffer.concat([textField(1, ''), intField(2, 11)]))])
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// fixture 目录:结构同真实 BGE 条目,但体积小、可在离线环境里跑完整个生命周期。
|
|
47
|
-
function fixtureManifest(overrides = {}) {
|
|
48
|
-
const payloads = {
|
|
49
|
-
'config.json': Buffer.from(JSON.stringify({ hidden_size: 8, max_position_embeddings: 32, vocab_size: 3, model_type: 'bert' })),
|
|
50
|
-
'vocab.txt': Buffer.from('[PAD]\n[UNK]\n[CLS]\n'),
|
|
51
|
-
'onnx/tiny.onnx': tinyOnnxGraph(8),
|
|
52
|
-
}
|
|
53
|
-
const files = Object.keys(payloads).map(filePath => ({
|
|
54
|
-
path: filePath,
|
|
55
|
-
role: filePath.endsWith('.onnx') ? 'graph' : filePath === 'config.json' ? 'config' : 'vocab',
|
|
56
|
-
bytes: payloads[filePath].length,
|
|
57
|
-
sha256: sha256(payloads[filePath]),
|
|
58
|
-
}))
|
|
59
|
-
const entry = {
|
|
60
|
-
id: 'fixture-tiny-int8',
|
|
61
|
-
displayName: 'Fixture tiny int8',
|
|
62
|
-
languages: ['zh'],
|
|
63
|
-
availability: 'available',
|
|
64
|
-
pendingReasons: [],
|
|
65
|
-
parameters: 1000,
|
|
66
|
-
dimension: 8,
|
|
67
|
-
maxTokens: 32,
|
|
68
|
-
pooling: 'cls',
|
|
69
|
-
normalization: 'l2',
|
|
70
|
-
prefixes: { query: '', document: '' },
|
|
71
|
-
quantization: { weights: 'qint8', scheme: 'dynamic-per-channel' },
|
|
72
|
-
runtime: { engine: 'onnxruntime-node', version: null, abi: 'napi-v6', os: 'win32', arch: 'x64', verified: false },
|
|
73
|
-
license: { base: { id: 'mit', source: 'fixture' }, onnxExport: { id: 'undeclared', source: 'fixture' } },
|
|
74
|
-
verification: { status: 'verified', method: 'sha256+onnx-header', checkedAt: '2026-10-30T00:00:00.000Z' },
|
|
75
|
-
sources: {
|
|
76
|
-
modelscope: { repo: 'fixture/tiny', revision: REVISION },
|
|
77
|
-
'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
|
|
78
|
-
huggingface: { repo: 'fixture/tiny', revision: REVISION },
|
|
79
|
-
},
|
|
80
|
-
graph: {
|
|
81
|
-
path: 'onnx/tiny.onnx',
|
|
82
|
-
opset: 11,
|
|
83
|
-
selfContained: true,
|
|
84
|
-
externalData: [],
|
|
85
|
-
inputs: [
|
|
86
|
-
{ name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
87
|
-
{ name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
88
|
-
{ name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
89
|
-
],
|
|
90
|
-
outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }],
|
|
91
|
-
},
|
|
92
|
-
files,
|
|
93
|
-
}
|
|
94
|
-
entry.totalBytes = files.reduce((sum, file) => sum + file.bytes, 0)
|
|
95
|
-
entry.profileFingerprint = profileFingerprint(entry)
|
|
96
|
-
return { entry: { ...entry, ...overrides.entry }, payloads: { ...payloads, ...(overrides.payloads || {}) } }
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function responseFor(bytes, options = {}) {
|
|
100
|
-
const status = options.status ?? 200
|
|
101
|
-
const split = options.chunk ?? 7
|
|
102
|
-
return {
|
|
103
|
-
ok: status >= 200 && status < 300,
|
|
104
|
-
status,
|
|
105
|
-
headers: { get: name => {
|
|
106
|
-
const lowered = String(name).toLowerCase()
|
|
107
|
-
if (lowered === 'content-length') return options.contentLength === undefined ? String(bytes.length) : options.contentLength
|
|
108
|
-
return null
|
|
109
|
-
} },
|
|
110
|
-
body: (async function* body() { for (let index = 0; index < bytes.length; index += split) yield bytes.subarray(index, index + split) })(),
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function makeFetch(entry, payloads, options = {}) {
|
|
115
|
-
const resolved = resolveEmbeddingSources(entry)
|
|
116
|
-
const routes = new Map(resolved.primary.files.map(file => [file.url, file.path]))
|
|
117
|
-
const calls = []
|
|
118
|
-
const fetchImpl = async (url, init) => {
|
|
119
|
-
calls.push({ url, init })
|
|
120
|
-
if (options.gate) await options.gate
|
|
121
|
-
if (init?.signal?.aborted) { const error = new Error('aborted'); error.name = 'AbortError'; throw error }
|
|
122
|
-
const filePath = routes.get(url)
|
|
123
|
-
if (!filePath) return { ok: false, status: 404, headers: { get: () => null }, body: null }
|
|
124
|
-
const payload = options.transform ? options.transform(filePath, payloads[filePath]) : payloads[filePath]
|
|
125
|
-
return responseFor(payload, options.responseFor ? options.responseFor(filePath) : {})
|
|
126
|
-
}
|
|
127
|
-
return { fetchImpl, calls, routes, resolved }
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function managerFor(entry, fetchImpl, extra = {}) {
|
|
131
|
-
const root = fs.mkdtempSync(path.join(scratch, 'root-'))
|
|
132
|
-
return { root, manager: createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl, ...extra }) }
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
test('没有明确确认就绝不下模型,也不发任何请求', async () => {
|
|
136
|
-
const { entry, payloads } = fixtureManifest()
|
|
137
|
-
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
138
|
-
const { manager } = managerFor(entry, fetchImpl)
|
|
139
|
-
await assert.rejects(manager.download(entry.id, {}), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
140
|
-
await assert.rejects(manager.download(entry.id, { confirmed: 'yes' }), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
141
|
-
assert.equal(calls.length, 0)
|
|
142
|
-
const status = manager.getStatus(entry.id)
|
|
143
|
-
assert.equal(status.state, 'absent')
|
|
144
|
-
assert.equal(status.installed, false)
|
|
145
|
-
assert.equal(status.active, false)
|
|
146
|
-
})
|
|
147
|
-
|
|
148
|
-
test('pending 模型与未知 id 都被拒绝,且不会联网', async () => {
|
|
149
|
-
const { entry, payloads } = fixtureManifest()
|
|
150
|
-
const pending = {
|
|
151
|
-
...entry,
|
|
152
|
-
id: 'fixture-pending-model',
|
|
153
|
-
availability: 'pending',
|
|
154
|
-
files: [],
|
|
155
|
-
totalBytes: 0,
|
|
156
|
-
pendingReasons: ['制品未核实:没有可比对的 bytes/sha256'],
|
|
157
|
-
verification: { ...entry.verification, status: 'unverified' },
|
|
158
|
-
}
|
|
159
|
-
pending.profileFingerprint = profileFingerprint(pending)
|
|
160
|
-
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
161
|
-
const { manager } = managerFor(pending, fetchImpl)
|
|
162
|
-
await assert.rejects(manager.download('fixture-pending-model', { confirmed: true }), error => {
|
|
163
|
-
assert.equal(error.code, 'EMBEDDING_MODEL_UNAVAILABLE')
|
|
164
|
-
assert.ok(error.pendingReasons.length > 0)
|
|
165
|
-
return true
|
|
166
|
-
})
|
|
167
|
-
await assert.rejects(manager.download('does-not-exist', { confirmed: true }), error => error.code === 'EMBEDDING_MODEL_UNKNOWN')
|
|
168
|
-
assert.equal(calls.length, 0)
|
|
169
|
-
assert.equal(manager.getStatus('does-not-exist').state, 'unknown')
|
|
170
|
-
})
|
|
171
|
-
|
|
172
|
-
// hf-mirror 对小文件用 chunked 传输(不发 content-length)。把「头缺失」当成 0 字节会
|
|
173
|
-
// 让每一个小文件都被误判成大小不符——真实装 Qwen3 时踩到的就是这个。
|
|
174
|
-
test('来源不发 content-length 时按下落的实际字节判断,不当成 0', async () => {
|
|
175
|
-
const { entry, payloads } = fixtureManifest()
|
|
176
|
-
const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: null } : {}) })
|
|
177
|
-
const { manager } = managerFor(entry, fetchImpl)
|
|
178
|
-
const status = await manager.download(entry.id, { confirmed: true })
|
|
179
|
-
assert.equal(status.state, 'installed')
|
|
180
|
-
assert.equal(status.installed, true)
|
|
181
|
-
})
|
|
182
|
-
|
|
183
|
-
// 多来源条目(Qwen3 卡片就是 hf-mirror + huggingface 同一个 commit):默认取目录顺序里
|
|
184
|
-
// 第一个,显式选源就只能用那一个,失败也不许回退到另一个源去下载。
|
|
185
|
-
test('显式选源只走那一个 provider,不回退到默认源', async () => {
|
|
186
|
-
const { entry, payloads } = fixtureManifest()
|
|
187
|
-
const mirrored = { ...entry, sources: {
|
|
188
|
-
'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
|
|
189
|
-
huggingface: { repo: 'fixture/tiny', revision: REVISION },
|
|
190
|
-
} }
|
|
191
|
-
const routes = new Map()
|
|
192
|
-
for (const provider of ['hf-mirror', 'huggingface']) {
|
|
193
|
-
for (const file of resolveEmbeddingSources(mirrored, { providers: [provider] }).primary.files) routes.set(file.url, { provider, path: file.path })
|
|
194
|
-
}
|
|
195
|
-
const calls = []
|
|
196
|
-
const fetchImpl = async (url, init) => {
|
|
197
|
-
calls.push(url)
|
|
198
|
-
const route = routes.get(url)
|
|
199
|
-
if (!route) return { ok: false, status: 404, headers: { get: () => null }, body: null }
|
|
200
|
-
return responseFor(payloads[route.path], {})
|
|
201
|
-
}
|
|
202
|
-
const { manager } = managerFor(mirrored, fetchImpl)
|
|
203
|
-
const byDefault = await manager.download(mirrored.id, { confirmed: true })
|
|
204
|
-
assert.equal(byDefault.provider, 'hf-mirror', '默认必须是镜像站')
|
|
205
|
-
assert.ok(calls[0].startsWith('https://hf-mirror.com/'), calls[0])
|
|
206
|
-
|
|
207
|
-
const { root } = managerFor(mirrored, fetchImpl)
|
|
208
|
-
const second = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
|
|
209
|
-
const chosen = await second.download(mirrored.id, { confirmed: true, provider: 'huggingface' })
|
|
210
|
-
assert.equal(chosen.provider, 'huggingface')
|
|
211
|
-
assert.ok(calls.some(url => url.startsWith('https://huggingface.co/')), '选源后要真的打到源站')
|
|
212
|
-
// 不存在的 provider 与「存在但这个条目没固定」是两种错,都要如实分开
|
|
213
|
-
await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'ollama' }), error => error.code === 'EMBEDDING_PROVIDER_UNKNOWN')
|
|
214
|
-
await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'modelscope' }), error => {
|
|
215
|
-
assert.equal(error.code, 'EMBEDDING_SOURCE_UNAVAILABLE')
|
|
216
|
-
assert.ok(String(error.message).includes('on modelscope'), error.message)
|
|
217
|
-
return true
|
|
218
|
-
})
|
|
219
|
-
// 换源之后默认源仍然可用(不许把条目卡在唯一来源上)
|
|
220
|
-
const third = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
|
|
221
|
-
assert.equal((await third.download(mirrored.id, { confirmed: true })).provider, 'hf-mirror')
|
|
222
|
-
})
|
|
223
|
-
|
|
224
|
-
test('verifyStagedArtifacts 核对 last-token pooling、float16 输出与窗口上限', async () => {
|
|
225
|
-
const dir = fs.mkdtempSync(path.join(scratch, 'last-'))
|
|
226
|
-
const graph = tinyOnnxGraph(8)
|
|
227
|
-
fs.mkdirSync(path.join(dir, '1_Pooling'), { recursive: true })
|
|
228
|
-
const base = {
|
|
229
|
-
id: 'fixture-last', dimension: 8, maxTokens: 32, pooling: 'last', normalization: 'l2',
|
|
230
|
-
graph: { path: 'onnx/tiny.onnx', opset: 11, inputs: [
|
|
231
|
-
{ name: 'input_ids', dtype: 'int64' }, { name: 'attention_mask', dtype: 'int64' }, { name: 'token_type_ids', dtype: 'int64' },
|
|
232
|
-
], outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }] },
|
|
233
|
-
files: [
|
|
234
|
-
{ path: 'config.json', role: 'config' },
|
|
235
|
-
{ path: 'onnx/tiny.onnx', role: 'graph' },
|
|
236
|
-
{ path: '1_Pooling/config.json', role: 'pooling-config' },
|
|
237
|
-
],
|
|
238
|
-
}
|
|
239
|
-
fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ hidden_size: 8, max_position_embeddings: 32 }), 'utf8')
|
|
240
|
-
fs.mkdirSync(path.join(dir, 'onnx'), { recursive: true })
|
|
241
|
-
fs.writeFileSync(path.join(dir, 'onnx/tiny.onnx'), graph)
|
|
242
|
-
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
|
|
243
|
-
const ok = await verifyStagedArtifacts({ entry: base, dir })
|
|
244
|
-
assert.ok(ok.checks.includes('pooling=last'), JSON.stringify(ok.checks))
|
|
245
|
-
|
|
246
|
-
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_mean_tokens: true }), 'utf8')
|
|
247
|
-
await assert.rejects(verifyStagedArtifacts({ entry: base, dir }), /not last-token pooling/)
|
|
248
|
-
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
|
|
249
|
-
|
|
250
|
-
// 窗口可以比制品小(刻意策略),但不能比制品大(必炸)
|
|
251
|
-
await assert.rejects(verifyStagedArtifacts({ entry: { ...base, maxTokens: 64 }, dir }), /exceeds the artifact's max_position_embeddings/)
|
|
252
|
-
// float16 图输出是可以接受的,但声明必须与图一致
|
|
253
|
-
const fp16 = { ...base, files: base.files.map(file => (file.role === 'graph' ? file : file)), graph: { ...base.graph, outputs: [{ name: 'last_hidden_state', dtype: 'float16', shape: ['batch_size', 'sequence_length', 8] }] } }
|
|
254
|
-
await assert.rejects(verifyStagedArtifacts({ entry: fp16, dir }), /output dtype/)
|
|
255
|
-
})
|
|
256
|
-
|
|
257
|
-
test('校验通过的制品原子安装:staging 清空、installed.json 记录 active:false', async () => {
|
|
258
|
-
const { entry, payloads } = fixtureManifest()
|
|
259
|
-
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
260
|
-
const { root, manager } = managerFor(entry, fetchImpl)
|
|
261
|
-
const status = await manager.download(entry.id, { confirmed: true })
|
|
262
|
-
assert.equal(status.state, 'installed')
|
|
263
|
-
assert.equal(status.installed, true)
|
|
264
|
-
assert.equal(status.active, false)
|
|
265
|
-
assert.equal(status.fingerprintMatches, true)
|
|
266
|
-
assert.equal(status.revision, REVISION)
|
|
267
|
-
assert.equal(status.provider, 'modelscope')
|
|
268
|
-
assert.ok(status.checks.includes('graph.opset=11'))
|
|
269
|
-
assert.equal(calls.length, entry.files.length)
|
|
270
|
-
assert.deepEqual(calls.map(call => call.url).sort(), resolveEmbeddingSources(entry).primary.files.map(file => file.url).sort())
|
|
271
|
-
for (const file of entry.files) {
|
|
272
|
-
const target = path.join(root, entry.id, ...file.path.split('/'))
|
|
273
|
-
assert.equal(fs.statSync(target).size, file.bytes)
|
|
274
|
-
assert.equal(sha256(fs.readFileSync(target)), file.sha256)
|
|
275
|
-
}
|
|
276
|
-
const record = JSON.parse(fs.readFileSync(path.join(root, entry.id, 'installed.json'), 'utf8'))
|
|
277
|
-
assert.equal(record.active, false)
|
|
278
|
-
assert.equal(record.fingerprint, entry.profileFingerprint)
|
|
279
|
-
assert.equal(record.verifiedBy, 'sha256+structural-smoke')
|
|
280
|
-
assert.deepEqual(fs.readdirSync(path.join(root, '.staging')), [])
|
|
281
|
-
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, true)
|
|
282
|
-
// 磁盘上不允许出现 active/profile 指针文件:激活是迁移模块的事。
|
|
283
|
-
const names = fs.readdirSync(path.join(root, entry.id))
|
|
284
|
-
assert.ok(names.every(name => !/active|profile/i.test(name)))
|
|
285
|
-
})
|
|
286
|
-
|
|
287
|
-
test('hash 不符立即失败,不安装,也不碰已有安装', async () => {
|
|
288
|
-
const { entry, payloads } = fixtureManifest()
|
|
289
|
-
const good = makeFetch(entry, payloads)
|
|
290
|
-
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
291
|
-
const first = await manager.download(entry.id, { confirmed: true })
|
|
292
|
-
assert.equal(first.state, 'installed')
|
|
293
|
-
const recordPath = path.join(root, entry.id, 'installed.json')
|
|
294
|
-
const before = fs.readFileSync(recordPath, 'utf8')
|
|
295
|
-
|
|
296
|
-
const tampered = makeFetch(entry, payloads, { transform: (filePath, buffer) => (filePath === 'onnx/tiny.onnx' ? Buffer.concat([buffer, Buffer.from('tampered')]) : buffer) })
|
|
297
|
-
const { manager: brokenManager } = managerFor(entry, tampered.fetchImpl, {})
|
|
298
|
-
const brokenRoot = brokenManager.root
|
|
299
|
-
await assert.rejects(brokenManager.download(entry.id, { confirmed: true }), error => {
|
|
300
|
-
assert.equal(error.code, 'EMBEDDING_SIZE_MISMATCH')
|
|
301
|
-
return true
|
|
302
|
-
})
|
|
303
|
-
assert.deepEqual(fs.readdirSync(path.join(brokenRoot, '.staging')), [])
|
|
304
|
-
assert.equal(fs.existsSync(path.join(brokenRoot, entry.id)), false)
|
|
305
|
-
|
|
306
|
-
const sameSizeTamper = makeFetch(entry, payloads, { transform: (filePath, buffer) => {
|
|
307
|
-
if (filePath !== 'onnx/tiny.onnx') return buffer
|
|
308
|
-
const copy = Buffer.from(buffer)
|
|
309
|
-
copy[copy.length - 1] = copy[copy.length - 1] ^ 0xff
|
|
310
|
-
return copy
|
|
311
|
-
} })
|
|
312
|
-
const { manager: sameSizeManager } = managerFor(entry, sameSizeTamper.fetchImpl, {})
|
|
313
|
-
await assert.rejects(sameSizeManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_HASH_MISMATCH')
|
|
314
|
-
assert.equal(fs.existsSync(path.join(sameSizeManager.root, entry.id)), false)
|
|
315
|
-
assert.deepEqual(fs.readdirSync(path.join(sameSizeManager.root, '.staging')), [])
|
|
316
|
-
|
|
317
|
-
// 原有安装一字未动。
|
|
318
|
-
assert.equal(fs.readFileSync(recordPath, 'utf8'), before)
|
|
319
|
-
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
320
|
-
})
|
|
321
|
-
|
|
322
|
-
test('content-length 与固定字节数不符时代理响应被拒绝', async () => {
|
|
323
|
-
const { entry, payloads } = fixtureManifest()
|
|
324
|
-
const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: '999' } : {}) })
|
|
325
|
-
const { root, manager } = managerFor(entry, fetchImpl)
|
|
326
|
-
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SIZE_MISMATCH')
|
|
327
|
-
assert.equal(manager.getStatus(entry.id).state, 'failed')
|
|
328
|
-
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
329
|
-
})
|
|
330
|
-
|
|
331
|
-
test('模型 smoke 不通过(结构或自定义 verifyModel)时同样不安装', async () => {
|
|
332
|
-
const { entry, payloads } = fixtureManifest()
|
|
333
|
-
const badGraph = Buffer.from(tinyOnnxGraph(16))
|
|
334
|
-
const wrongDim = fixtureManifest({ payloads: { 'onnx/tiny.onnx': badGraph }, entry: {} })
|
|
335
|
-
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').bytes = badGraph.length
|
|
336
|
-
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').sha256 = sha256(badGraph)
|
|
337
|
-
wrongDim.entry.totalBytes = wrongDim.entry.files.reduce((sum, file) => sum + file.bytes, 0)
|
|
338
|
-
wrongDim.entry.profileFingerprint = profileFingerprint(wrongDim.entry)
|
|
339
|
-
const structural = makeFetch(wrongDim.entry, wrongDim.payloads)
|
|
340
|
-
const { root, manager } = managerFor(wrongDim.entry, structural.fetchImpl)
|
|
341
|
-
await assert.rejects(manager.download(wrongDim.entry.id, { confirmed: true }), error => {
|
|
342
|
-
assert.equal(error.code, 'EMBEDDING_SMOKE_FAILED')
|
|
343
|
-
assert.match(error.message, /last dim 16/)
|
|
344
|
-
return true
|
|
345
|
-
})
|
|
346
|
-
assert.equal(fs.existsSync(path.join(root, wrongDim.entry.id)), false)
|
|
347
|
-
|
|
348
|
-
const custom = makeFetch(entry, payloads)
|
|
349
|
-
const { root: customRoot, manager: customManager } = managerFor(entry, custom.fetchImpl, { verifyModel: async () => { throw new Error('tokenizer smoke says no') } })
|
|
350
|
-
await assert.rejects(customManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SMOKE_FAILED')
|
|
351
|
-
assert.equal(customManager.getStatus(entry.id).state, 'failed')
|
|
352
|
-
assert.equal(fs.existsSync(path.join(customRoot, entry.id)), false)
|
|
353
|
-
})
|
|
354
|
-
|
|
355
|
-
test('verifyStagedArtifacts 直接核对图头、config 与词表', async () => {
|
|
356
|
-
const { entry, payloads } = fixtureManifest()
|
|
357
|
-
const dir = fs.mkdtempSync(path.join(scratch, 'staged-'))
|
|
358
|
-
for (const [filePath, buffer] of Object.entries(payloads)) {
|
|
359
|
-
fs.mkdirSync(path.dirname(path.join(dir, filePath)), { recursive: true })
|
|
360
|
-
fs.writeFileSync(path.join(dir, filePath), buffer)
|
|
361
|
-
}
|
|
362
|
-
const result = await verifyStagedArtifacts({ entry, dir })
|
|
363
|
-
assert.equal(result.ok, true)
|
|
364
|
-
assert.ok(result.checks.includes('graph.initializerBytes=' + Buffer.from('quantized-weights-fixture').length))
|
|
365
|
-
assert.ok(result.checks.includes('vocab.txt=3'))
|
|
366
|
-
fs.writeFileSync(path.join(dir, 'vocab.txt'), '[PAD]\n')
|
|
367
|
-
await assert.rejects(verifyStagedArtifacts({ entry, dir }), /vocab\.txt/)
|
|
368
|
-
})
|
|
369
|
-
|
|
370
|
-
test('取消下载:状态 cancelled、半成品不留在 staging、旧安装保留', async () => {
|
|
371
|
-
const { entry, payloads } = fixtureManifest()
|
|
372
|
-
const good = makeFetch(entry, payloads)
|
|
373
|
-
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
374
|
-
await manager.download(entry.id, { confirmed: true })
|
|
375
|
-
const before = manager.getStatus(entry.id)
|
|
376
|
-
|
|
377
|
-
let release
|
|
378
|
-
const gate = new Promise(resolve => { release = resolve })
|
|
379
|
-
const slow = makeFetch(entry, payloads, { gate })
|
|
380
|
-
const { manager: slowManager } = managerFor(entry, slow.fetchImpl, {})
|
|
381
|
-
const controller = new AbortController()
|
|
382
|
-
const pending = slowManager.download(entry.id, { confirmed: true, signal: controller.signal })
|
|
383
|
-
await new Promise(resolve => setTimeout(resolve, 20))
|
|
384
|
-
assert.equal(slowManager.getStatus(entry.id).state, 'downloading')
|
|
385
|
-
controller.abort()
|
|
386
|
-
release()
|
|
387
|
-
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
388
|
-
assert.equal(slowManager.getStatus(entry.id).state, 'cancelled')
|
|
389
|
-
assert.deepEqual(fs.readdirSync(path.join(slowManager.root, '.staging')), [])
|
|
390
|
-
assert.equal(fs.existsSync(path.join(slowManager.root, entry.id)), false)
|
|
391
|
-
assert.equal(manager.getStatus(entry.id).installedAt, before.installedAt)
|
|
392
|
-
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
393
|
-
})
|
|
394
|
-
|
|
395
|
-
test('同一模型并发下载被拒绝,进度可查', async () => {
|
|
396
|
-
const { entry, payloads } = fixtureManifest()
|
|
397
|
-
let release
|
|
398
|
-
const gate = new Promise(resolve => { release = resolve })
|
|
399
|
-
const slow = makeFetch(entry, payloads, { gate })
|
|
400
|
-
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
401
|
-
const first = manager.download(entry.id, { confirmed: true })
|
|
402
|
-
await new Promise(resolve => setTimeout(resolve, 20))
|
|
403
|
-
const progress = manager.getStatus(entry.id)
|
|
404
|
-
assert.equal(progress.state, 'downloading')
|
|
405
|
-
assert.equal(progress.progress.files, entry.files.length)
|
|
406
|
-
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_DOWNLOAD_BUSY')
|
|
407
|
-
release()
|
|
408
|
-
const status = await first
|
|
409
|
-
assert.equal(status.state, 'installed')
|
|
410
|
-
})
|
|
411
|
-
|
|
412
|
-
test('越界文件路径在 manifest 阶段就被拒绝,写不出 root', async () => {
|
|
413
|
-
for (const badPath of ['../escape.bin', 'nested/../../escape.bin', 'C:/windows/evil.bin', '/etc/passwd', 'onnx\\evil.onnx']) {
|
|
414
|
-
const { entry, payloads } = fixtureManifest()
|
|
415
|
-
entry.files = entry.files.map(file => (file.role === 'graph' ? { ...file, path: badPath } : file))
|
|
416
|
-
entry.graph = { ...entry.graph, path: badPath }
|
|
417
|
-
entry.profileFingerprint = profileFingerprint(entry)
|
|
418
|
-
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
419
|
-
const { root, manager } = managerFor(entry, fetchImpl)
|
|
420
|
-
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => {
|
|
421
|
-
assert.equal(error.code, 'EMBEDDING_MANIFEST_INVALID')
|
|
422
|
-
assert.ok(error.errors.some(item => item.code === 'FILE_PATH_UNSAFE'))
|
|
423
|
-
return true
|
|
424
|
-
})
|
|
425
|
-
assert.equal(calls.length, 0)
|
|
426
|
-
assert.deepEqual(fs.readdirSync(root), [])
|
|
427
|
-
assert.equal(fs.existsSync(path.join(scratch, 'escape.bin')), false)
|
|
428
|
-
}
|
|
429
|
-
})
|
|
430
|
-
|
|
431
|
-
test('重新下载同一模型时旧安装被替换,不留 trash 残渣', async () => {
|
|
432
|
-
const { entry, payloads } = fixtureManifest()
|
|
433
|
-
const good = makeFetch(entry, payloads)
|
|
434
|
-
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
435
|
-
const first = await manager.download(entry.id, { confirmed: true })
|
|
436
|
-
assert.equal(first.state, 'installed')
|
|
437
|
-
const nextRevision = 'd'.repeat(40)
|
|
438
|
-
const upgraded = { ...entry, sources: { modelscope: { repo: 'fixture/tiny', revision: nextRevision } } }
|
|
439
|
-
upgraded.profileFingerprint = profileFingerprint(upgraded)
|
|
440
|
-
const again = makeFetch(upgraded, payloads)
|
|
441
|
-
// 同一个 root:旧安装必须先被原子替换,而不是并存或半途丢失。
|
|
442
|
-
const freshManager = createEmbeddingDownloadManager({ root, catalog: [upgraded], fetchImpl: again.fetchImpl })
|
|
443
|
-
const second = await freshManager.download(entry.id, { confirmed: true })
|
|
444
|
-
assert.equal(second.revision, nextRevision)
|
|
445
|
-
assert.equal(second.state, 'installed')
|
|
446
|
-
assert.deepEqual(fs.readdirSync(path.join(freshManager.root, '.trash')), [])
|
|
447
|
-
assert.equal(JSON.parse(fs.readFileSync(path.join(freshManager.root, entry.id, 'installed.json'), 'utf8')).revision, nextRevision)
|
|
448
|
-
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
449
|
-
})
|
|
450
|
-
|
|
451
|
-
test('fetchImpl 失败时状态是 failed,错误码可展示且不伪造安装', async () => {
|
|
452
|
-
const { entry } = fixtureManifest()
|
|
453
|
-
const failing = async () => { throw new Error('ECONNRESET') }
|
|
454
|
-
const { root, manager } = managerFor(entry, failing)
|
|
455
|
-
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_NETWORK_ERROR')
|
|
456
|
-
const status = manager.getStatus(entry.id)
|
|
457
|
-
assert.equal(status.state, 'failed')
|
|
458
|
-
assert.equal(status.installed, false)
|
|
459
|
-
assert.equal(status.error.code, 'EMBEDDING_NETWORK_ERROR')
|
|
460
|
-
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
461
|
-
})
|
|
462
|
-
|
|
463
|
-
test('dispose 中止在途下载,不留下崩溃痕迹', async () => {
|
|
464
|
-
const { entry, payloads } = fixtureManifest()
|
|
465
|
-
let release
|
|
466
|
-
const gate = new Promise(resolve => { release = resolve })
|
|
467
|
-
const slow = makeFetch(entry, payloads, { gate })
|
|
468
|
-
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
469
|
-
const pending = manager.download(entry.id, { confirmed: true })
|
|
470
|
-
await new Promise(resolve => setTimeout(resolve, 20))
|
|
471
|
-
manager.dispose()
|
|
472
|
-
release()
|
|
473
|
-
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
474
|
-
assert.equal(manager.getStatus(entry.id).state, 'cancelled')
|
|
475
|
-
})
|
|
476
|
-
|
|
477
|
-
test('root 必须是显式目录;模型根目录之外的路径被拒绝', async () => {
|
|
478
|
-
assert.throws(() => createEmbeddingDownloadManager({}), TypeError)
|
|
479
|
-
assert.throws(() => createEmbeddingDownloadManager({ root: '' }), TypeError)
|
|
480
|
-
const { entry } = fixtureManifest()
|
|
481
|
-
const root = fs.mkdtempSync(path.join(scratch, 'root-guard-'))
|
|
482
|
-
const manager = createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl: async () => { throw new Error('unused') } })
|
|
483
|
-
assert.equal(manager.root, path.resolve(root))
|
|
484
|
-
assert.ok(manager.catalogIds.includes('bge-small-zh-v1.5-int8'))
|
|
485
|
-
assert.equal(manager.getStatus('bge-small-zh-v1.5-int8').state, 'absent')
|
|
486
|
-
})
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import crypto from 'node:crypto'
|
|
7
|
+
import { Buffer } from 'node:buffer'
|
|
8
|
+
import { profileFingerprint, resolveEmbeddingSources } from '../lib/embedding-catalog.js'
|
|
9
|
+
import { createEmbeddingDownloadManager, verifyStagedArtifacts } from '../lib/embedding-download.js'
|
|
10
|
+
|
|
11
|
+
const REVISION = 'a'.repeat(40)
|
|
12
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-embed-dl-'))
|
|
13
|
+
test.after(() => fs.rmSync(scratch, { recursive: true, force: true }))
|
|
14
|
+
|
|
15
|
+
const sha256 = buffer => crypto.createHash('sha256').update(buffer).digest('hex')
|
|
16
|
+
|
|
17
|
+
function varint(value) {
|
|
18
|
+
const bytes = []
|
|
19
|
+
let rest = value
|
|
20
|
+
while (rest > 127) { bytes.push((rest & 0x7f) | 0x80); rest = Math.floor(rest / 128) }
|
|
21
|
+
bytes.push(rest)
|
|
22
|
+
return Buffer.from(bytes)
|
|
23
|
+
}
|
|
24
|
+
const tag = (field, wire) => varint((field << 3) | wire)
|
|
25
|
+
const bytesField = (field, buffer) => Buffer.concat([tag(field, 2), varint(buffer.length), buffer])
|
|
26
|
+
const textField = (field, text) => bytesField(field, Buffer.from(text, 'utf8'))
|
|
27
|
+
const intField = (field, value) => Buffer.concat([tag(field, 0), varint(value)])
|
|
28
|
+
const dimension = dim => (typeof dim === 'number' ? intField(1, dim) : textField(2, String(dim)))
|
|
29
|
+
function valueInfo(name, elemType, shape) {
|
|
30
|
+
const shapeMessage = Buffer.concat(shape.map(dim => bytesField(1, dimension(dim))))
|
|
31
|
+
const tensorType = Buffer.concat([intField(1, elemType), bytesField(2, shapeMessage)])
|
|
32
|
+
return Buffer.concat([textField(1, name), bytesField(2, bytesField(1, tensorType))])
|
|
33
|
+
}
|
|
34
|
+
function tinyOnnxGraph(outputDim = 8) {
|
|
35
|
+
const initializer = Buffer.concat([intField(1, 1), intField(2, 1), textField(8, 'w'), bytesField(9, Buffer.from('quantized-weights-fixture'))])
|
|
36
|
+
const graph = Buffer.concat([
|
|
37
|
+
bytesField(5, initializer),
|
|
38
|
+
bytesField(11, valueInfo('input_ids', 7, ['batch_size', 'sequence_length'])),
|
|
39
|
+
bytesField(11, valueInfo('attention_mask', 7, ['batch_size', 'sequence_length'])),
|
|
40
|
+
bytesField(11, valueInfo('token_type_ids', 7, ['batch_size', 'sequence_length'])),
|
|
41
|
+
bytesField(12, valueInfo('last_hidden_state', 1, ['batch_size', 'sequence_length', outputDim])),
|
|
42
|
+
])
|
|
43
|
+
return Buffer.concat([intField(1, 6), textField(2, 'onnx.quantize'), bytesField(7, graph), bytesField(8, Buffer.concat([textField(1, ''), intField(2, 11)]))])
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// fixture 目录:结构同真实 BGE 条目,但体积小、可在离线环境里跑完整个生命周期。
|
|
47
|
+
function fixtureManifest(overrides = {}) {
|
|
48
|
+
const payloads = {
|
|
49
|
+
'config.json': Buffer.from(JSON.stringify({ hidden_size: 8, max_position_embeddings: 32, vocab_size: 3, model_type: 'bert' })),
|
|
50
|
+
'vocab.txt': Buffer.from('[PAD]\n[UNK]\n[CLS]\n'),
|
|
51
|
+
'onnx/tiny.onnx': tinyOnnxGraph(8),
|
|
52
|
+
}
|
|
53
|
+
const files = Object.keys(payloads).map(filePath => ({
|
|
54
|
+
path: filePath,
|
|
55
|
+
role: filePath.endsWith('.onnx') ? 'graph' : filePath === 'config.json' ? 'config' : 'vocab',
|
|
56
|
+
bytes: payloads[filePath].length,
|
|
57
|
+
sha256: sha256(payloads[filePath]),
|
|
58
|
+
}))
|
|
59
|
+
const entry = {
|
|
60
|
+
id: 'fixture-tiny-int8',
|
|
61
|
+
displayName: 'Fixture tiny int8',
|
|
62
|
+
languages: ['zh'],
|
|
63
|
+
availability: 'available',
|
|
64
|
+
pendingReasons: [],
|
|
65
|
+
parameters: 1000,
|
|
66
|
+
dimension: 8,
|
|
67
|
+
maxTokens: 32,
|
|
68
|
+
pooling: 'cls',
|
|
69
|
+
normalization: 'l2',
|
|
70
|
+
prefixes: { query: '', document: '' },
|
|
71
|
+
quantization: { weights: 'qint8', scheme: 'dynamic-per-channel' },
|
|
72
|
+
runtime: { engine: 'onnxruntime-node', version: null, abi: 'napi-v6', os: 'win32', arch: 'x64', verified: false },
|
|
73
|
+
license: { base: { id: 'mit', source: 'fixture' }, onnxExport: { id: 'undeclared', source: 'fixture' } },
|
|
74
|
+
verification: { status: 'verified', method: 'sha256+onnx-header', checkedAt: '2026-10-30T00:00:00.000Z' },
|
|
75
|
+
sources: {
|
|
76
|
+
modelscope: { repo: 'fixture/tiny', revision: REVISION },
|
|
77
|
+
'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
|
|
78
|
+
huggingface: { repo: 'fixture/tiny', revision: REVISION },
|
|
79
|
+
},
|
|
80
|
+
graph: {
|
|
81
|
+
path: 'onnx/tiny.onnx',
|
|
82
|
+
opset: 11,
|
|
83
|
+
selfContained: true,
|
|
84
|
+
externalData: [],
|
|
85
|
+
inputs: [
|
|
86
|
+
{ name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
87
|
+
{ name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
88
|
+
{ name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
89
|
+
],
|
|
90
|
+
outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }],
|
|
91
|
+
},
|
|
92
|
+
files,
|
|
93
|
+
}
|
|
94
|
+
entry.totalBytes = files.reduce((sum, file) => sum + file.bytes, 0)
|
|
95
|
+
entry.profileFingerprint = profileFingerprint(entry)
|
|
96
|
+
return { entry: { ...entry, ...overrides.entry }, payloads: { ...payloads, ...(overrides.payloads || {}) } }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function responseFor(bytes, options = {}) {
|
|
100
|
+
const status = options.status ?? 200
|
|
101
|
+
const split = options.chunk ?? 7
|
|
102
|
+
return {
|
|
103
|
+
ok: status >= 200 && status < 300,
|
|
104
|
+
status,
|
|
105
|
+
headers: { get: name => {
|
|
106
|
+
const lowered = String(name).toLowerCase()
|
|
107
|
+
if (lowered === 'content-length') return options.contentLength === undefined ? String(bytes.length) : options.contentLength
|
|
108
|
+
return null
|
|
109
|
+
} },
|
|
110
|
+
body: (async function* body() { for (let index = 0; index < bytes.length; index += split) yield bytes.subarray(index, index + split) })(),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function makeFetch(entry, payloads, options = {}) {
|
|
115
|
+
const resolved = resolveEmbeddingSources(entry)
|
|
116
|
+
const routes = new Map(resolved.primary.files.map(file => [file.url, file.path]))
|
|
117
|
+
const calls = []
|
|
118
|
+
const fetchImpl = async (url, init) => {
|
|
119
|
+
calls.push({ url, init })
|
|
120
|
+
if (options.gate) await options.gate
|
|
121
|
+
if (init?.signal?.aborted) { const error = new Error('aborted'); error.name = 'AbortError'; throw error }
|
|
122
|
+
const filePath = routes.get(url)
|
|
123
|
+
if (!filePath) return { ok: false, status: 404, headers: { get: () => null }, body: null }
|
|
124
|
+
const payload = options.transform ? options.transform(filePath, payloads[filePath]) : payloads[filePath]
|
|
125
|
+
return responseFor(payload, options.responseFor ? options.responseFor(filePath) : {})
|
|
126
|
+
}
|
|
127
|
+
return { fetchImpl, calls, routes, resolved }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function managerFor(entry, fetchImpl, extra = {}) {
|
|
131
|
+
const root = fs.mkdtempSync(path.join(scratch, 'root-'))
|
|
132
|
+
return { root, manager: createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl, ...extra }) }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
test('没有明确确认就绝不下模型,也不发任何请求', async () => {
|
|
136
|
+
const { entry, payloads } = fixtureManifest()
|
|
137
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
138
|
+
const { manager } = managerFor(entry, fetchImpl)
|
|
139
|
+
await assert.rejects(manager.download(entry.id, {}), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
140
|
+
await assert.rejects(manager.download(entry.id, { confirmed: 'yes' }), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
141
|
+
assert.equal(calls.length, 0)
|
|
142
|
+
const status = manager.getStatus(entry.id)
|
|
143
|
+
assert.equal(status.state, 'absent')
|
|
144
|
+
assert.equal(status.installed, false)
|
|
145
|
+
assert.equal(status.active, false)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('pending 模型与未知 id 都被拒绝,且不会联网', async () => {
|
|
149
|
+
const { entry, payloads } = fixtureManifest()
|
|
150
|
+
const pending = {
|
|
151
|
+
...entry,
|
|
152
|
+
id: 'fixture-pending-model',
|
|
153
|
+
availability: 'pending',
|
|
154
|
+
files: [],
|
|
155
|
+
totalBytes: 0,
|
|
156
|
+
pendingReasons: ['制品未核实:没有可比对的 bytes/sha256'],
|
|
157
|
+
verification: { ...entry.verification, status: 'unverified' },
|
|
158
|
+
}
|
|
159
|
+
pending.profileFingerprint = profileFingerprint(pending)
|
|
160
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
161
|
+
const { manager } = managerFor(pending, fetchImpl)
|
|
162
|
+
await assert.rejects(manager.download('fixture-pending-model', { confirmed: true }), error => {
|
|
163
|
+
assert.equal(error.code, 'EMBEDDING_MODEL_UNAVAILABLE')
|
|
164
|
+
assert.ok(error.pendingReasons.length > 0)
|
|
165
|
+
return true
|
|
166
|
+
})
|
|
167
|
+
await assert.rejects(manager.download('does-not-exist', { confirmed: true }), error => error.code === 'EMBEDDING_MODEL_UNKNOWN')
|
|
168
|
+
assert.equal(calls.length, 0)
|
|
169
|
+
assert.equal(manager.getStatus('does-not-exist').state, 'unknown')
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
// hf-mirror 对小文件用 chunked 传输(不发 content-length)。把「头缺失」当成 0 字节会
|
|
173
|
+
// 让每一个小文件都被误判成大小不符——真实装 Qwen3 时踩到的就是这个。
|
|
174
|
+
test('来源不发 content-length 时按下落的实际字节判断,不当成 0', async () => {
|
|
175
|
+
const { entry, payloads } = fixtureManifest()
|
|
176
|
+
const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: null } : {}) })
|
|
177
|
+
const { manager } = managerFor(entry, fetchImpl)
|
|
178
|
+
const status = await manager.download(entry.id, { confirmed: true })
|
|
179
|
+
assert.equal(status.state, 'installed')
|
|
180
|
+
assert.equal(status.installed, true)
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
// 多来源条目(Qwen3 卡片就是 hf-mirror + huggingface 同一个 commit):默认取目录顺序里
|
|
184
|
+
// 第一个,显式选源就只能用那一个,失败也不许回退到另一个源去下载。
|
|
185
|
+
test('显式选源只走那一个 provider,不回退到默认源', async () => {
|
|
186
|
+
const { entry, payloads } = fixtureManifest()
|
|
187
|
+
const mirrored = { ...entry, sources: {
|
|
188
|
+
'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
|
|
189
|
+
huggingface: { repo: 'fixture/tiny', revision: REVISION },
|
|
190
|
+
} }
|
|
191
|
+
const routes = new Map()
|
|
192
|
+
for (const provider of ['hf-mirror', 'huggingface']) {
|
|
193
|
+
for (const file of resolveEmbeddingSources(mirrored, { providers: [provider] }).primary.files) routes.set(file.url, { provider, path: file.path })
|
|
194
|
+
}
|
|
195
|
+
const calls = []
|
|
196
|
+
const fetchImpl = async (url, init) => {
|
|
197
|
+
calls.push(url)
|
|
198
|
+
const route = routes.get(url)
|
|
199
|
+
if (!route) return { ok: false, status: 404, headers: { get: () => null }, body: null }
|
|
200
|
+
return responseFor(payloads[route.path], {})
|
|
201
|
+
}
|
|
202
|
+
const { manager } = managerFor(mirrored, fetchImpl)
|
|
203
|
+
const byDefault = await manager.download(mirrored.id, { confirmed: true })
|
|
204
|
+
assert.equal(byDefault.provider, 'hf-mirror', '默认必须是镜像站')
|
|
205
|
+
assert.ok(calls[0].startsWith('https://hf-mirror.com/'), calls[0])
|
|
206
|
+
|
|
207
|
+
const { root } = managerFor(mirrored, fetchImpl)
|
|
208
|
+
const second = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
|
|
209
|
+
const chosen = await second.download(mirrored.id, { confirmed: true, provider: 'huggingface' })
|
|
210
|
+
assert.equal(chosen.provider, 'huggingface')
|
|
211
|
+
assert.ok(calls.some(url => url.startsWith('https://huggingface.co/')), '选源后要真的打到源站')
|
|
212
|
+
// 不存在的 provider 与「存在但这个条目没固定」是两种错,都要如实分开
|
|
213
|
+
await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'ollama' }), error => error.code === 'EMBEDDING_PROVIDER_UNKNOWN')
|
|
214
|
+
await assert.rejects(second.download(mirrored.id, { confirmed: true, provider: 'modelscope' }), error => {
|
|
215
|
+
assert.equal(error.code, 'EMBEDDING_SOURCE_UNAVAILABLE')
|
|
216
|
+
assert.ok(String(error.message).includes('on modelscope'), error.message)
|
|
217
|
+
return true
|
|
218
|
+
})
|
|
219
|
+
// 换源之后默认源仍然可用(不许把条目卡在唯一来源上)
|
|
220
|
+
const third = createEmbeddingDownloadManager({ root, catalog: [mirrored], fetchImpl })
|
|
221
|
+
assert.equal((await third.download(mirrored.id, { confirmed: true })).provider, 'hf-mirror')
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
test('verifyStagedArtifacts 核对 last-token pooling、float16 输出与窗口上限', async () => {
|
|
225
|
+
const dir = fs.mkdtempSync(path.join(scratch, 'last-'))
|
|
226
|
+
const graph = tinyOnnxGraph(8)
|
|
227
|
+
fs.mkdirSync(path.join(dir, '1_Pooling'), { recursive: true })
|
|
228
|
+
const base = {
|
|
229
|
+
id: 'fixture-last', dimension: 8, maxTokens: 32, pooling: 'last', normalization: 'l2',
|
|
230
|
+
graph: { path: 'onnx/tiny.onnx', opset: 11, inputs: [
|
|
231
|
+
{ name: 'input_ids', dtype: 'int64' }, { name: 'attention_mask', dtype: 'int64' }, { name: 'token_type_ids', dtype: 'int64' },
|
|
232
|
+
], outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }] },
|
|
233
|
+
files: [
|
|
234
|
+
{ path: 'config.json', role: 'config' },
|
|
235
|
+
{ path: 'onnx/tiny.onnx', role: 'graph' },
|
|
236
|
+
{ path: '1_Pooling/config.json', role: 'pooling-config' },
|
|
237
|
+
],
|
|
238
|
+
}
|
|
239
|
+
fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ hidden_size: 8, max_position_embeddings: 32 }), 'utf8')
|
|
240
|
+
fs.mkdirSync(path.join(dir, 'onnx'), { recursive: true })
|
|
241
|
+
fs.writeFileSync(path.join(dir, 'onnx/tiny.onnx'), graph)
|
|
242
|
+
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
|
|
243
|
+
const ok = await verifyStagedArtifacts({ entry: base, dir })
|
|
244
|
+
assert.ok(ok.checks.includes('pooling=last'), JSON.stringify(ok.checks))
|
|
245
|
+
|
|
246
|
+
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_mean_tokens: true }), 'utf8')
|
|
247
|
+
await assert.rejects(verifyStagedArtifacts({ entry: base, dir }), /not last-token pooling/)
|
|
248
|
+
fs.writeFileSync(path.join(dir, '1_Pooling', 'config.json'), JSON.stringify({ word_embedding_dimension: 8, pooling_mode_lasttoken: true }), 'utf8')
|
|
249
|
+
|
|
250
|
+
// 窗口可以比制品小(刻意策略),但不能比制品大(必炸)
|
|
251
|
+
await assert.rejects(verifyStagedArtifacts({ entry: { ...base, maxTokens: 64 }, dir }), /exceeds the artifact's max_position_embeddings/)
|
|
252
|
+
// float16 图输出是可以接受的,但声明必须与图一致
|
|
253
|
+
const fp16 = { ...base, files: base.files.map(file => (file.role === 'graph' ? file : file)), graph: { ...base.graph, outputs: [{ name: 'last_hidden_state', dtype: 'float16', shape: ['batch_size', 'sequence_length', 8] }] } }
|
|
254
|
+
await assert.rejects(verifyStagedArtifacts({ entry: fp16, dir }), /output dtype/)
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
test('校验通过的制品原子安装:staging 清空、installed.json 记录 active:false', async () => {
|
|
258
|
+
const { entry, payloads } = fixtureManifest()
|
|
259
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
260
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
261
|
+
const status = await manager.download(entry.id, { confirmed: true })
|
|
262
|
+
assert.equal(status.state, 'installed')
|
|
263
|
+
assert.equal(status.installed, true)
|
|
264
|
+
assert.equal(status.active, false)
|
|
265
|
+
assert.equal(status.fingerprintMatches, true)
|
|
266
|
+
assert.equal(status.revision, REVISION)
|
|
267
|
+
assert.equal(status.provider, 'modelscope')
|
|
268
|
+
assert.ok(status.checks.includes('graph.opset=11'))
|
|
269
|
+
assert.equal(calls.length, entry.files.length)
|
|
270
|
+
assert.deepEqual(calls.map(call => call.url).sort(), resolveEmbeddingSources(entry).primary.files.map(file => file.url).sort())
|
|
271
|
+
for (const file of entry.files) {
|
|
272
|
+
const target = path.join(root, entry.id, ...file.path.split('/'))
|
|
273
|
+
assert.equal(fs.statSync(target).size, file.bytes)
|
|
274
|
+
assert.equal(sha256(fs.readFileSync(target)), file.sha256)
|
|
275
|
+
}
|
|
276
|
+
const record = JSON.parse(fs.readFileSync(path.join(root, entry.id, 'installed.json'), 'utf8'))
|
|
277
|
+
assert.equal(record.active, false)
|
|
278
|
+
assert.equal(record.fingerprint, entry.profileFingerprint)
|
|
279
|
+
assert.equal(record.verifiedBy, 'sha256+structural-smoke')
|
|
280
|
+
assert.deepEqual(fs.readdirSync(path.join(root, '.staging')), [])
|
|
281
|
+
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, true)
|
|
282
|
+
// 磁盘上不允许出现 active/profile 指针文件:激活是迁移模块的事。
|
|
283
|
+
const names = fs.readdirSync(path.join(root, entry.id))
|
|
284
|
+
assert.ok(names.every(name => !/active|profile/i.test(name)))
|
|
285
|
+
})
|
|
286
|
+
|
|
287
|
+
test('hash 不符立即失败,不安装,也不碰已有安装', async () => {
|
|
288
|
+
const { entry, payloads } = fixtureManifest()
|
|
289
|
+
const good = makeFetch(entry, payloads)
|
|
290
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
291
|
+
const first = await manager.download(entry.id, { confirmed: true })
|
|
292
|
+
assert.equal(first.state, 'installed')
|
|
293
|
+
const recordPath = path.join(root, entry.id, 'installed.json')
|
|
294
|
+
const before = fs.readFileSync(recordPath, 'utf8')
|
|
295
|
+
|
|
296
|
+
const tampered = makeFetch(entry, payloads, { transform: (filePath, buffer) => (filePath === 'onnx/tiny.onnx' ? Buffer.concat([buffer, Buffer.from('tampered')]) : buffer) })
|
|
297
|
+
const { manager: brokenManager } = managerFor(entry, tampered.fetchImpl, {})
|
|
298
|
+
const brokenRoot = brokenManager.root
|
|
299
|
+
await assert.rejects(brokenManager.download(entry.id, { confirmed: true }), error => {
|
|
300
|
+
assert.equal(error.code, 'EMBEDDING_SIZE_MISMATCH')
|
|
301
|
+
return true
|
|
302
|
+
})
|
|
303
|
+
assert.deepEqual(fs.readdirSync(path.join(brokenRoot, '.staging')), [])
|
|
304
|
+
assert.equal(fs.existsSync(path.join(brokenRoot, entry.id)), false)
|
|
305
|
+
|
|
306
|
+
const sameSizeTamper = makeFetch(entry, payloads, { transform: (filePath, buffer) => {
|
|
307
|
+
if (filePath !== 'onnx/tiny.onnx') return buffer
|
|
308
|
+
const copy = Buffer.from(buffer)
|
|
309
|
+
copy[copy.length - 1] = copy[copy.length - 1] ^ 0xff
|
|
310
|
+
return copy
|
|
311
|
+
} })
|
|
312
|
+
const { manager: sameSizeManager } = managerFor(entry, sameSizeTamper.fetchImpl, {})
|
|
313
|
+
await assert.rejects(sameSizeManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_HASH_MISMATCH')
|
|
314
|
+
assert.equal(fs.existsSync(path.join(sameSizeManager.root, entry.id)), false)
|
|
315
|
+
assert.deepEqual(fs.readdirSync(path.join(sameSizeManager.root, '.staging')), [])
|
|
316
|
+
|
|
317
|
+
// 原有安装一字未动。
|
|
318
|
+
assert.equal(fs.readFileSync(recordPath, 'utf8'), before)
|
|
319
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
320
|
+
})
|
|
321
|
+
|
|
322
|
+
test('content-length 与固定字节数不符时代理响应被拒绝', async () => {
|
|
323
|
+
const { entry, payloads } = fixtureManifest()
|
|
324
|
+
const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: '999' } : {}) })
|
|
325
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
326
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SIZE_MISMATCH')
|
|
327
|
+
assert.equal(manager.getStatus(entry.id).state, 'failed')
|
|
328
|
+
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
test('模型 smoke 不通过(结构或自定义 verifyModel)时同样不安装', async () => {
|
|
332
|
+
const { entry, payloads } = fixtureManifest()
|
|
333
|
+
const badGraph = Buffer.from(tinyOnnxGraph(16))
|
|
334
|
+
const wrongDim = fixtureManifest({ payloads: { 'onnx/tiny.onnx': badGraph }, entry: {} })
|
|
335
|
+
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').bytes = badGraph.length
|
|
336
|
+
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').sha256 = sha256(badGraph)
|
|
337
|
+
wrongDim.entry.totalBytes = wrongDim.entry.files.reduce((sum, file) => sum + file.bytes, 0)
|
|
338
|
+
wrongDim.entry.profileFingerprint = profileFingerprint(wrongDim.entry)
|
|
339
|
+
const structural = makeFetch(wrongDim.entry, wrongDim.payloads)
|
|
340
|
+
const { root, manager } = managerFor(wrongDim.entry, structural.fetchImpl)
|
|
341
|
+
await assert.rejects(manager.download(wrongDim.entry.id, { confirmed: true }), error => {
|
|
342
|
+
assert.equal(error.code, 'EMBEDDING_SMOKE_FAILED')
|
|
343
|
+
assert.match(error.message, /last dim 16/)
|
|
344
|
+
return true
|
|
345
|
+
})
|
|
346
|
+
assert.equal(fs.existsSync(path.join(root, wrongDim.entry.id)), false)
|
|
347
|
+
|
|
348
|
+
const custom = makeFetch(entry, payloads)
|
|
349
|
+
const { root: customRoot, manager: customManager } = managerFor(entry, custom.fetchImpl, { verifyModel: async () => { throw new Error('tokenizer smoke says no') } })
|
|
350
|
+
await assert.rejects(customManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SMOKE_FAILED')
|
|
351
|
+
assert.equal(customManager.getStatus(entry.id).state, 'failed')
|
|
352
|
+
assert.equal(fs.existsSync(path.join(customRoot, entry.id)), false)
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
test('verifyStagedArtifacts 直接核对图头、config 与词表', async () => {
|
|
356
|
+
const { entry, payloads } = fixtureManifest()
|
|
357
|
+
const dir = fs.mkdtempSync(path.join(scratch, 'staged-'))
|
|
358
|
+
for (const [filePath, buffer] of Object.entries(payloads)) {
|
|
359
|
+
fs.mkdirSync(path.dirname(path.join(dir, filePath)), { recursive: true })
|
|
360
|
+
fs.writeFileSync(path.join(dir, filePath), buffer)
|
|
361
|
+
}
|
|
362
|
+
const result = await verifyStagedArtifacts({ entry, dir })
|
|
363
|
+
assert.equal(result.ok, true)
|
|
364
|
+
assert.ok(result.checks.includes('graph.initializerBytes=' + Buffer.from('quantized-weights-fixture').length))
|
|
365
|
+
assert.ok(result.checks.includes('vocab.txt=3'))
|
|
366
|
+
fs.writeFileSync(path.join(dir, 'vocab.txt'), '[PAD]\n')
|
|
367
|
+
await assert.rejects(verifyStagedArtifacts({ entry, dir }), /vocab\.txt/)
|
|
368
|
+
})
|
|
369
|
+
|
|
370
|
+
test('取消下载:状态 cancelled、半成品不留在 staging、旧安装保留', async () => {
|
|
371
|
+
const { entry, payloads } = fixtureManifest()
|
|
372
|
+
const good = makeFetch(entry, payloads)
|
|
373
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
374
|
+
await manager.download(entry.id, { confirmed: true })
|
|
375
|
+
const before = manager.getStatus(entry.id)
|
|
376
|
+
|
|
377
|
+
let release
|
|
378
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
379
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
380
|
+
const { manager: slowManager } = managerFor(entry, slow.fetchImpl, {})
|
|
381
|
+
const controller = new AbortController()
|
|
382
|
+
const pending = slowManager.download(entry.id, { confirmed: true, signal: controller.signal })
|
|
383
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
384
|
+
assert.equal(slowManager.getStatus(entry.id).state, 'downloading')
|
|
385
|
+
controller.abort()
|
|
386
|
+
release()
|
|
387
|
+
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
388
|
+
assert.equal(slowManager.getStatus(entry.id).state, 'cancelled')
|
|
389
|
+
assert.deepEqual(fs.readdirSync(path.join(slowManager.root, '.staging')), [])
|
|
390
|
+
assert.equal(fs.existsSync(path.join(slowManager.root, entry.id)), false)
|
|
391
|
+
assert.equal(manager.getStatus(entry.id).installedAt, before.installedAt)
|
|
392
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
test('同一模型并发下载被拒绝,进度可查', async () => {
|
|
396
|
+
const { entry, payloads } = fixtureManifest()
|
|
397
|
+
let release
|
|
398
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
399
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
400
|
+
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
401
|
+
const first = manager.download(entry.id, { confirmed: true })
|
|
402
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
403
|
+
const progress = manager.getStatus(entry.id)
|
|
404
|
+
assert.equal(progress.state, 'downloading')
|
|
405
|
+
assert.equal(progress.progress.files, entry.files.length)
|
|
406
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_DOWNLOAD_BUSY')
|
|
407
|
+
release()
|
|
408
|
+
const status = await first
|
|
409
|
+
assert.equal(status.state, 'installed')
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
test('越界文件路径在 manifest 阶段就被拒绝,写不出 root', async () => {
|
|
413
|
+
for (const badPath of ['../escape.bin', 'nested/../../escape.bin', 'C:/windows/evil.bin', '/etc/passwd', 'onnx\\evil.onnx']) {
|
|
414
|
+
const { entry, payloads } = fixtureManifest()
|
|
415
|
+
entry.files = entry.files.map(file => (file.role === 'graph' ? { ...file, path: badPath } : file))
|
|
416
|
+
entry.graph = { ...entry.graph, path: badPath }
|
|
417
|
+
entry.profileFingerprint = profileFingerprint(entry)
|
|
418
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
419
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
420
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => {
|
|
421
|
+
assert.equal(error.code, 'EMBEDDING_MANIFEST_INVALID')
|
|
422
|
+
assert.ok(error.errors.some(item => item.code === 'FILE_PATH_UNSAFE'))
|
|
423
|
+
return true
|
|
424
|
+
})
|
|
425
|
+
assert.equal(calls.length, 0)
|
|
426
|
+
assert.deepEqual(fs.readdirSync(root), [])
|
|
427
|
+
assert.equal(fs.existsSync(path.join(scratch, 'escape.bin')), false)
|
|
428
|
+
}
|
|
429
|
+
})
|
|
430
|
+
|
|
431
|
+
test('重新下载同一模型时旧安装被替换,不留 trash 残渣', async () => {
|
|
432
|
+
const { entry, payloads } = fixtureManifest()
|
|
433
|
+
const good = makeFetch(entry, payloads)
|
|
434
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
435
|
+
const first = await manager.download(entry.id, { confirmed: true })
|
|
436
|
+
assert.equal(first.state, 'installed')
|
|
437
|
+
const nextRevision = 'd'.repeat(40)
|
|
438
|
+
const upgraded = { ...entry, sources: { modelscope: { repo: 'fixture/tiny', revision: nextRevision } } }
|
|
439
|
+
upgraded.profileFingerprint = profileFingerprint(upgraded)
|
|
440
|
+
const again = makeFetch(upgraded, payloads)
|
|
441
|
+
// 同一个 root:旧安装必须先被原子替换,而不是并存或半途丢失。
|
|
442
|
+
const freshManager = createEmbeddingDownloadManager({ root, catalog: [upgraded], fetchImpl: again.fetchImpl })
|
|
443
|
+
const second = await freshManager.download(entry.id, { confirmed: true })
|
|
444
|
+
assert.equal(second.revision, nextRevision)
|
|
445
|
+
assert.equal(second.state, 'installed')
|
|
446
|
+
assert.deepEqual(fs.readdirSync(path.join(freshManager.root, '.trash')), [])
|
|
447
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(freshManager.root, entry.id, 'installed.json'), 'utf8')).revision, nextRevision)
|
|
448
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
449
|
+
})
|
|
450
|
+
|
|
451
|
+
test('fetchImpl 失败时状态是 failed,错误码可展示且不伪造安装', async () => {
|
|
452
|
+
const { entry } = fixtureManifest()
|
|
453
|
+
const failing = async () => { throw new Error('ECONNRESET') }
|
|
454
|
+
const { root, manager } = managerFor(entry, failing)
|
|
455
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_NETWORK_ERROR')
|
|
456
|
+
const status = manager.getStatus(entry.id)
|
|
457
|
+
assert.equal(status.state, 'failed')
|
|
458
|
+
assert.equal(status.installed, false)
|
|
459
|
+
assert.equal(status.error.code, 'EMBEDDING_NETWORK_ERROR')
|
|
460
|
+
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
461
|
+
})
|
|
462
|
+
|
|
463
|
+
test('dispose 中止在途下载,不留下崩溃痕迹', async () => {
|
|
464
|
+
const { entry, payloads } = fixtureManifest()
|
|
465
|
+
let release
|
|
466
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
467
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
468
|
+
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
469
|
+
const pending = manager.download(entry.id, { confirmed: true })
|
|
470
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
471
|
+
manager.dispose()
|
|
472
|
+
release()
|
|
473
|
+
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
474
|
+
assert.equal(manager.getStatus(entry.id).state, 'cancelled')
|
|
475
|
+
})
|
|
476
|
+
|
|
477
|
+
test('root 必须是显式目录;模型根目录之外的路径被拒绝', async () => {
|
|
478
|
+
assert.throws(() => createEmbeddingDownloadManager({}), TypeError)
|
|
479
|
+
assert.throws(() => createEmbeddingDownloadManager({ root: '' }), TypeError)
|
|
480
|
+
const { entry } = fixtureManifest()
|
|
481
|
+
const root = fs.mkdtempSync(path.join(scratch, 'root-guard-'))
|
|
482
|
+
const manager = createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl: async () => { throw new Error('unused') } })
|
|
483
|
+
assert.equal(manager.root, path.resolve(root))
|
|
484
|
+
assert.ok(manager.catalogIds.includes('bge-small-zh-v1.5-int8'))
|
|
485
|
+
assert.equal(manager.getStatus('bge-small-zh-v1.5-int8').state, 'absent')
|
|
486
|
+
})
|
|
487
|
+
|
|
488
|
+
// 深校验需要读取模型文件并计算 sha256,因此按文件指纹缓存结论。
|
|
489
|
+
// 196ms),而设置页每打开一次都会问一次。现在按文件指纹缓存结论——这条用例钉住
|
|
490
|
+
// 「缓存不能把磁盘上的改动藏起来」:同尺寸改写也必须重新判定。
|
|
491
|
+
test('深校验结论按文件指纹缓存,但磁盘被改过就必须重新判定', async () => {
|
|
492
|
+
const { entry, payloads } = fixtureManifest()
|
|
493
|
+
const { fetchImpl } = makeFetch(entry, payloads)
|
|
494
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
495
|
+
await manager.download(entry.id, { confirmed: true })
|
|
496
|
+
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, true, 'first deep check passes')
|
|
497
|
+
|
|
498
|
+
// 同尺寸改写:readInstall 的 size 检查照样通过,只有 sha256 能看出差别。
|
|
499
|
+
const target = path.join(root, entry.id, 'onnx', 'tiny.onnx')
|
|
500
|
+
const original = fs.readFileSync(target)
|
|
501
|
+
const flipped = Buffer.from(original)
|
|
502
|
+
flipped[Math.floor(flipped.length / 2)] ^= 0xff
|
|
503
|
+
fs.writeFileSync(target, flipped)
|
|
504
|
+
assert.equal(fs.statSync(target).size, original.length, 'same-size tamper on purpose')
|
|
505
|
+
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, false, 'the cached verdict must not hide a changed file')
|
|
506
|
+
|
|
507
|
+
fs.writeFileSync(target, original)
|
|
508
|
+
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, true, 'restoring the bytes restores the verdict')
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
test('a transient deep-verification read failure retries without changing model files', async () => {
|
|
512
|
+
const { entry, payloads } = fixtureManifest()
|
|
513
|
+
const { fetchImpl } = makeFetch(entry, payloads)
|
|
514
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
515
|
+
await manager.download(entry.id, { confirmed: true })
|
|
516
|
+
const probe = createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl })
|
|
517
|
+
const target = path.join(root, entry.id, 'onnx', 'tiny.onnx')
|
|
518
|
+
const before = fs.statSync(target)
|
|
519
|
+
const originalRead = fs.readFileSync
|
|
520
|
+
fs.readFileSync = function (file, ...args) {
|
|
521
|
+
if (file === target) throw Object.assign(new Error('temporary file contention'), { code: 'EBUSY' })
|
|
522
|
+
return originalRead.call(this, file, ...args)
|
|
523
|
+
}
|
|
524
|
+
try {
|
|
525
|
+
assert.equal(probe.getStatus(entry.id, { deep: true }).verified, false)
|
|
526
|
+
} finally { fs.readFileSync = originalRead }
|
|
527
|
+
assert.equal(probe.getStatus(entry.id, { deep: true }).verified, true, 'an I/O error must not be cached as permanent corruption')
|
|
528
|
+
assert.equal(fs.statSync(target).mtimeMs, before.mtimeMs, 'recovery does not require touching the files')
|
|
529
|
+
})
|