@delali/narsil 0.2.4-next.59 → 0.3.1-next.101
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/README.md +9 -8
- package/dist/adapters/filesystem.d.ts +1 -1
- package/dist/adapters/filesystem.mjs +1 -1
- package/dist/adapters/indexeddb.d.ts +1 -1
- package/dist/adapters/indexeddb.mjs +1 -1
- package/dist/adapters/memory.d.ts +1 -1
- package/dist/{adapters-79OIa4xm.d.ts → adapters-BQFQ4PRz.d.ts} +27 -1
- package/dist/browser/chunk-BDOSMEEP.mjs +493 -0
- package/dist/browser/chunk-EJDUFWSO.mjs +602 -0
- package/dist/browser/chunk-HOZW3PKP.mjs +9 -0
- package/dist/browser/chunk-JOVZ6HMT.mjs +4358 -0
- package/dist/browser/chunk-JPTQZWJQ.mjs +10 -0
- package/dist/browser/chunk-KPJMDPHG.mjs +24558 -0
- package/dist/browser/chunk-PGIM3HIM.mjs +2743 -0
- package/dist/browser/chunk-RHG4O77A.mjs +206 -0
- package/dist/browser/chunk-RIJSLY2I.mjs +360 -0
- package/dist/browser/durability-wiring-SRUYT3VV.mjs +3875 -0
- package/dist/browser/module-CBB2ETYP.mjs +3111 -0
- package/dist/browser/release-76MXRPGV.mjs +33 -0
- package/dist/browser/replace-RURXTGVG.mjs +57 -0
- package/dist/browser/restore-queue-EEZQO6RF.mjs +35 -0
- package/dist/browser/runtime-7ZAHCHWR.mjs +557 -0
- package/dist/browser/snapshot-OAAA5UJ7.mjs +1210 -0
- package/dist/browser/write-7D6VIK6O.mjs +208 -0
- package/dist/{capabilities-DSsOGz6F.d.ts → capabilities-DiGlB6Sr.d.ts} +68 -7
- package/dist/chunk-2RIRGOUL.mjs +113 -0
- package/dist/chunk-37CD3OKS.mjs +87 -0
- package/dist/chunk-44W3CBNG.mjs +7 -0
- package/dist/chunk-46D6JQIG.mjs +426 -0
- package/dist/{chunk-VMRR3DQU.mjs → chunk-5JNA5SKS.mjs} +546 -35
- package/dist/chunk-747OHOUA.mjs +11 -0
- package/dist/chunk-75XIEF6H.mjs +126 -0
- package/dist/chunk-7X5JST5L.mjs +114 -0
- package/dist/chunk-BOFBLJFZ.mjs +209 -0
- package/dist/{chunk-USKFU7J5.mjs → chunk-BWJVNZPR.mjs} +8 -1
- package/dist/chunk-C7SLA6CM.mjs +19 -0
- package/dist/{chunk-POWOTUKJ.mjs → chunk-CQUMNIIG.mjs} +3 -6
- package/dist/chunk-CVXLLEQ3.mjs +1011 -0
- package/dist/chunk-DJHHF2L5.mjs +17 -0
- package/dist/chunk-E74YLAIG.mjs +24 -0
- package/dist/{chunk-UXNWQZST.mjs → chunk-EMRMGYRE.mjs} +236 -18
- package/dist/chunk-EWZLIYHV.mjs +57 -0
- package/dist/chunk-GBEEG5AN.mjs +35 -0
- package/dist/chunk-GES7U2PM.mjs +68 -0
- package/dist/chunk-HJSN7UYG.mjs +10 -0
- package/dist/chunk-HLPRHOSO.mjs +17 -0
- package/dist/chunk-HMFNFVP7.mjs +14 -0
- package/dist/chunk-J5QP52HA.mjs +1751 -0
- package/dist/{chunk-YNVIUGF5.mjs → chunk-JZVARCRZ.mjs} +3 -28
- package/dist/chunk-KOKM4PQN.mjs +52 -0
- package/dist/{chunk-B2TFROFX.mjs → chunk-KWTW6VTG.mjs} +465 -250
- package/dist/chunk-KZ3NX2P7.mjs +21 -0
- package/dist/chunk-L5ORED7V.mjs +25 -0
- package/dist/{chunk-THYRHHO2.mjs → chunk-LGAMKHA2.mjs} +2009 -2351
- package/dist/chunk-LKOB5COA.mjs +117 -0
- package/dist/chunk-LPQOEU5M.mjs +96 -0
- package/dist/{chunk-3LHGNRYE.mjs → chunk-LXWDQLTW.mjs} +7 -2
- package/dist/{chunk-L6TNPLAR.mjs → chunk-OEYI3KRB.mjs} +270 -108
- package/dist/chunk-OM362BRO.mjs +948 -0
- package/dist/chunk-OZDFA4WC.mjs +67 -0
- package/dist/chunk-P36MUFEJ.mjs +10 -0
- package/dist/chunk-PC2G76VW.mjs +2540 -0
- package/dist/{chunk-GCM3JFVA.mjs → chunk-PNEYIHA4.mjs} +11 -2
- package/dist/chunk-PNFKUCG3.mjs +1130 -0
- package/dist/chunk-Q6XWVUZX.mjs +44 -0
- package/dist/chunk-R27EMH5M.mjs +617 -0
- package/dist/{chunk-YMZCMH5M.mjs → chunk-R6A773WK.mjs} +19 -24
- package/dist/chunk-RF7PLG43.mjs +106 -0
- package/dist/chunk-RFBLQLLZ.mjs +16 -0
- package/dist/{chunk-Y3L5MDRV.mjs → chunk-RFVUDM5E.mjs} +17 -2
- package/dist/chunk-S7FL6UAH.mjs +521 -0
- package/dist/chunk-S7GNDRPS.mjs +651 -0
- package/dist/chunk-SP3NM3ZG.mjs +3537 -0
- package/dist/chunk-U476IXKQ.mjs +10 -0
- package/dist/chunk-UA3AUGNV.mjs +462 -0
- package/dist/chunk-UTG5YNXV.mjs +507 -0
- package/dist/chunk-VI4R6W25.mjs +8484 -0
- package/dist/chunk-WQBCBKY3.mjs +8 -0
- package/dist/{chunk-24RXHMEL.mjs → chunk-WVCOCKBU.mjs} +3794 -7570
- package/dist/chunk-X5CV2E2B.mjs +1 -0
- package/dist/chunk-XADZPPZI.mjs +614 -0
- package/dist/chunk-YEEQHT4V.mjs +212 -0
- package/dist/chunk-YTJCGKM4.mjs +56 -0
- package/dist/chunk-YYQIODMF.mjs +275 -0
- package/dist/chunk-ZI34TVOA.mjs +144 -0
- package/dist/{chunk-OOSIDHA3.mjs → chunk-ZKWYWW4Y.mjs} +1 -1
- package/dist/chunk-ZM7KU4YW.mjs +35 -0
- package/dist/{client-BQK6Tf6A.d.ts → client-BOStAkc5.d.ts} +160 -37
- package/dist/client.d.ts +11 -10
- package/dist/client.mjs +209 -45
- package/dist/{config-DmXULPa-.d.ts → config-Cjvzbs_j.d.ts} +51 -3
- package/dist/config-DffQlmRq.d.ts +421 -0
- package/dist/direct-executor-ZD64PPEZ.mjs +24 -0
- package/dist/distribution/coordinator/etcd.d.ts +79 -18
- package/dist/distribution/coordinator/etcd.mjs +553 -109
- package/dist/distribution/coordinator/in-memory.d.ts +4 -3
- package/dist/distribution/coordinator/in-memory.mjs +22 -3
- package/dist/distribution/transport/grpc.d.ts +2 -2
- package/dist/distribution/transport/grpc.mjs +79 -14
- package/dist/distribution/transport/in-memory.d.ts +2 -2
- package/dist/distribution/transport/in-memory.mjs +12 -7
- package/dist/distribution/transport/tcp.d.ts +2 -2
- package/dist/distribution/transport/tcp.mjs +50 -28
- package/dist/distribution.d.ts +144 -23
- package/dist/distribution.mjs +14479 -8173
- package/dist/durability-wiring-FEUBR5BT.mjs +3330 -0
- package/dist/embeddings/openai.d.ts +2 -2
- package/dist/embeddings/openai.mjs +22 -133
- package/dist/{engine-CIOyFozK.d.ts → engine-rC0vjjY-.d.ts} +165 -141
- package/dist/{memory-yFaVn2xZ.d.ts → events-DqOIg5xa.d.ts} +645 -136
- package/dist/{types-DAK7mnUZ.d.ts → index-Bkdt8nDw.d.ts} +182 -45
- package/dist/index.browser.mjs +4 -32180
- package/dist/index.d.ts +91 -20
- package/dist/index.mjs +33 -16
- package/dist/invalidation/broadcast-channel.d.ts +1 -1
- package/dist/invalidation/filesystem.d.ts +1 -1
- package/dist/invalidation/filesystem.mjs +2 -1
- package/dist/invalidation/noop.d.ts +1 -1
- package/dist/module-3S65MVCM.mjs +2151 -0
- package/dist/partial-words-DTIHO8G4.d.ts +19 -0
- package/dist/partial-words.d.ts +22 -0
- package/dist/partial-words.mjs +17 -0
- package/dist/pattern-Cledccbl.d.ts +18 -0
- package/dist/pattern.d.ts +22 -0
- package/dist/pattern.mjs +12 -0
- package/dist/persistence/durability/checkpoint-worker.d.ts +119 -72
- package/dist/persistence/durability/checkpoint-worker.mjs +51 -18
- package/dist/react.d.ts +279 -183
- package/dist/react.mjs +201 -48
- package/dist/release-BH3DKW3T.mjs +33 -0
- package/dist/replace-CEO5KJJ3.mjs +57 -0
- package/dist/rerank-K7C4WZFG.mjs +60 -0
- package/dist/rerankers/http.d.ts +50 -0
- package/dist/rerankers/http.mjs +104 -0
- package/dist/restore-queue-KQHA7ZV2.mjs +35 -0
- package/dist/runtime-6Y4ZYXOG.mjs +177 -0
- package/dist/{schema-d5Afu03A.d.ts → schema-4W_7tk1f.d.ts} +81 -11
- package/dist/server.d.ts +13 -12
- package/dist/server.mjs +611 -80
- package/dist/snapshot-QGZPODM5.mjs +799 -0
- package/dist/synonyms-CpOAHPa-.d.ts +52 -0
- package/dist/synonyms.d.ts +22 -0
- package/dist/synonyms.mjs +12 -0
- package/dist/{tasks-CH2Dod8w.d.ts → tasks-CwPTz-tP.d.ts} +10 -3
- package/dist/thread-N3IUGUS3.mjs +697 -0
- package/dist/{types-BQDlIvfS.d.ts → types-2qoitTXg.d.ts} +1 -1
- package/dist/{types-D5OwhtsQ.d.ts → types-Cz5okLml.d.ts} +2 -2
- package/dist/vector/search-worker.d.ts +46 -4
- package/dist/vector/search-worker.mjs +21 -11
- package/dist/workers/entry.mjs +9 -6
- package/dist/write-U5RI7MAX.mjs +241 -0
- package/package.json +55 -9
- package/dist/chunk-3L4U6EJQ.mjs +0 -49
- package/dist/chunk-IFBKLBGB.mjs +0 -7
- package/dist/chunk-ORBLD3EL.mjs +0 -6
- package/dist/chunk-U7KYW4BA.mjs +0 -135
- package/dist/chunk-ZJ4CSAB2.mjs +0 -13
- package/dist/chunk-ZNZBXMP5.mjs +0 -2117
- package/dist/chunk-ZZT3EAUC.mjs +0 -11168
- package/dist/config-BhldZgaK.d.ts +0 -194
- package/dist/direct-executor-ALAVE7FC.mjs +0 -12
- package/dist/serialization/crc32-worker.d.ts +0 -20
- package/dist/serialization/crc32-worker.mjs +0 -62
- package/dist/simd-DW5AtJ6B.d.ts +0 -41
- package/dist/thread-DYHEQRVY.mjs +0 -402
|
@@ -0,0 +1,1210 @@
|
|
|
1
|
+
import { vectorsPerFile } from './chunk-JOVZ6HMT.mjs';
|
|
2
|
+
import { indexMetadataOf, writeCheckpointSegments, DEFAULT_COMPACTION_THRESHOLD, writeLiveVectors, commitCheckpointManifest, manifestKey, decodeSegmentManifest, SINGLE_NODE_PRIMARY_TERM, partitionContentsOf, manifestFileRefs, unpackIndexSnapshotEnvelope, encodeSegmentManifest, loadSegmentedCheckpoint, writeMetadataEnvelope, openManifestPayload, listedKeysOf, decodeManifestPayload, readSegmentFile, readVectorFile, readGraphParts, documentsOfPayloadV2, deserializePayloadV1 } from './chunk-PGIM3HIM.mjs';
|
|
3
|
+
import './chunk-EJDUFWSO.mjs';
|
|
4
|
+
import { encodeIndexConfiguration, createByteReader, hasNrslMagic, HEADER_SIZE, readHeader, raiseEarlierReleaseGraphSetting, restoredConfigFields, restoredEmbedding, getLanguage, validateSchema, validatePatternValueLimit, requireSurfaceFormsForPartialFields, validateVectorPromotion, validateVectorStorage, validateRequiredFieldsInSchema, resolveIndexAnalysis, validateEmbeddingConfig, prepareStoredSynonyms, rejectSnapshot, readHeapStatistics, readResidentMemory, extractVectorFieldsFromSchema, loadVectorCodeFor, decodeEveryStoredDocument, parseVectorDimension, insertDocumentVectors, decodeIndexConfiguration, flattenSchema } from './chunk-KPJMDPHG.mjs';
|
|
5
|
+
import { decodeVectorIndexParts, vectorsToBytes, VECTOR_FILE_PAYLOAD_VERSION, bytesToVectors } from './chunk-RIJSLY2I.mjs';
|
|
6
|
+
import { MAX_FILE_BYTES } from './chunk-BDOSMEEP.mjs';
|
|
7
|
+
import './chunk-JPTQZWJQ.mjs';
|
|
8
|
+
import { NarsilError, ErrorCodes } from './chunk-RHG4O77A.mjs';
|
|
9
|
+
import { decode } from '@msgpack/msgpack';
|
|
10
|
+
|
|
11
|
+
// src/persistence/archive/memory-store.ts
|
|
12
|
+
function joined(chunks) {
|
|
13
|
+
let total = 0;
|
|
14
|
+
for (const chunk of chunks) total += chunk.byteLength;
|
|
15
|
+
const bytes = new Uint8Array(total);
|
|
16
|
+
let offset = 0;
|
|
17
|
+
for (const chunk of chunks) {
|
|
18
|
+
bytes.set(chunk, offset);
|
|
19
|
+
offset += chunk.byteLength;
|
|
20
|
+
}
|
|
21
|
+
return bytes;
|
|
22
|
+
}
|
|
23
|
+
function memoryCheckpointStore() {
|
|
24
|
+
const files = /* @__PURE__ */ new Map();
|
|
25
|
+
return {
|
|
26
|
+
files,
|
|
27
|
+
read: async (key) => files.get(key) ?? null,
|
|
28
|
+
write: async (key, chunks) => {
|
|
29
|
+
files.set(key, joined(chunks));
|
|
30
|
+
},
|
|
31
|
+
remove: async (key) => {
|
|
32
|
+
files.delete(key);
|
|
33
|
+
},
|
|
34
|
+
list: async (prefix) => [...files.keys()].filter((key) => key.startsWith(prefix)).sort(),
|
|
35
|
+
byteLength: async (key) => files.get(key)?.byteLength ?? null
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/persistence/archive/from-memory.ts
|
|
40
|
+
function frozenPlan(plan) {
|
|
41
|
+
const files = [];
|
|
42
|
+
for (let index = 0; index < plan.newFiles; index++) files.push(plan.readNewFile(index));
|
|
43
|
+
return { ...plan, readNewFile: (index) => files[index] };
|
|
44
|
+
}
|
|
45
|
+
function partitionVectorPlan(vectorIndex, docIds) {
|
|
46
|
+
const held = [];
|
|
47
|
+
const vectors = [];
|
|
48
|
+
for (const docId of docIds) {
|
|
49
|
+
const vector = vectorIndex.getVector(docId);
|
|
50
|
+
if (vector === null) continue;
|
|
51
|
+
held.push(docId);
|
|
52
|
+
vectors.push(Float32Array.from(vector));
|
|
53
|
+
}
|
|
54
|
+
const capacity = vectorsPerFile(vectorIndex.dimension, null);
|
|
55
|
+
const files = [];
|
|
56
|
+
for (let start = 0; start < held.length; start += capacity) {
|
|
57
|
+
const slice = held.slice(start, start + capacity);
|
|
58
|
+
const packed = new Float32Array(slice.length * vectorIndex.dimension);
|
|
59
|
+
for (let i = 0; i < slice.length; i++) packed.set(vectors[start + i], i * vectorIndex.dimension);
|
|
60
|
+
const payload = {
|
|
61
|
+
v: VECTOR_FILE_PAYLOAD_VERSION,
|
|
62
|
+
fieldName: vectorIndex.fieldName,
|
|
63
|
+
dimension: vectorIndex.dimension,
|
|
64
|
+
docIds: slice,
|
|
65
|
+
codes: null,
|
|
66
|
+
vectors: vectorsToBytes(packed)
|
|
67
|
+
};
|
|
68
|
+
files.push({ payload, ordinals: new Int32Array(slice.length), dead: null });
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
unchanged: false,
|
|
72
|
+
kept: [],
|
|
73
|
+
keptFiles: [],
|
|
74
|
+
newFiles: files.length,
|
|
75
|
+
graphParts: null,
|
|
76
|
+
signature: { revision: 0, graphSize: -1, calibration: null },
|
|
77
|
+
readNewFile: (index) => files[index]
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function capture(input) {
|
|
81
|
+
const partitionIds = input.partitionId === null ? Array.from({ length: input.manager.partitionCount }, (_, partitionId) => partitionId) : [input.partitionId];
|
|
82
|
+
const targets = partitionIds.map((partitionId) => ({
|
|
83
|
+
partitionId,
|
|
84
|
+
lastSeqNo: input.appliedSeqNo(partitionId),
|
|
85
|
+
primaryTerm: SINGLE_NODE_PRIMARY_TERM
|
|
86
|
+
}));
|
|
87
|
+
const contents = partitionIds.map((partitionId) => partitionContentsOf(input.manager, partitionId));
|
|
88
|
+
const plans = /* @__PURE__ */ new Map();
|
|
89
|
+
const partitionDocIds = input.partitionId === null ? null : [...input.manager.getPartition(input.partitionId).docIds()];
|
|
90
|
+
for (const [fieldPath, vectorIndex] of input.vectorIndexes) {
|
|
91
|
+
plans.set(
|
|
92
|
+
fieldPath,
|
|
93
|
+
partitionDocIds === null ? frozenPlan(vectorIndex.planCheckpoint(null)) : partitionVectorPlan(vectorIndex, partitionDocIds)
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return { targets, contents, plans };
|
|
97
|
+
}
|
|
98
|
+
async function buildArchiveFromMemory(input) {
|
|
99
|
+
if (input.partitionId === null) {
|
|
100
|
+
for (const vectorIndex of input.vectorIndexes.values()) await vectorIndex.completeGraph();
|
|
101
|
+
}
|
|
102
|
+
const captured = capture(input);
|
|
103
|
+
const store = memoryCheckpointStore();
|
|
104
|
+
const written = await writeCheckpointSegments({
|
|
105
|
+
store,
|
|
106
|
+
metadata: input.metadata,
|
|
107
|
+
targets: captured.targets,
|
|
108
|
+
compactionThreshold: DEFAULT_COMPACTION_THRESHOLD,
|
|
109
|
+
prior: null,
|
|
110
|
+
wholePartitions: captured.contents
|
|
111
|
+
});
|
|
112
|
+
const vectors = await writeLiveVectors({ store, indexName: input.indexName, plans: captured.plans, priorVectors: [] });
|
|
113
|
+
const refs = vectors.refs;
|
|
114
|
+
await commitCheckpointManifest(store, input.metadata, written, refs);
|
|
115
|
+
const manifestBytes = store.files.get(manifestKey(input.indexName));
|
|
116
|
+
const decoded = manifestBytes === void 0 ? null : await decodeSegmentManifest(manifestBytes, input.indexName);
|
|
117
|
+
if (manifestBytes === void 0 || decoded === null || decoded.kind !== "current") {
|
|
118
|
+
throw new NarsilError(
|
|
119
|
+
ErrorCodes.PERSISTENCE_SAVE_FAILED,
|
|
120
|
+
`The archive of index "${input.indexName}" holds no manifest`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
manifestBytes,
|
|
125
|
+
manifest: decoded.manifest,
|
|
126
|
+
readFile: async (ref) => {
|
|
127
|
+
const bytes = store.files.get(ref.key);
|
|
128
|
+
if (bytes === void 0) {
|
|
129
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_SAVE_FAILED, `The archive file "${ref.key}" is missing`, {
|
|
130
|
+
key: ref.key
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return bytes;
|
|
134
|
+
},
|
|
135
|
+
readRange: async (ref, offset, length) => {
|
|
136
|
+
const bytes = store.files.get(ref.key);
|
|
137
|
+
if (bytes === void 0 || offset + length > bytes.byteLength) {
|
|
138
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The archive file "${ref.key}" is missing`, {
|
|
139
|
+
key: ref.key
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return bytes.subarray(offset, offset + length);
|
|
143
|
+
},
|
|
144
|
+
release: () => store.files.clear()
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/persistence/archive/constants.ts
|
|
149
|
+
var MAX_PAX_HEADER_BYTES = 65536;
|
|
150
|
+
|
|
151
|
+
// src/persistence/archive/tar.ts
|
|
152
|
+
var TAR_BLOCK_BYTES = 512;
|
|
153
|
+
var NAME_OFFSET = 0;
|
|
154
|
+
var NAME_BYTES = 100;
|
|
155
|
+
var MODE_OFFSET = 100;
|
|
156
|
+
var OWNER_OFFSET = 108;
|
|
157
|
+
var GROUP_OFFSET = 116;
|
|
158
|
+
var ID_FIELD_BYTES = 8;
|
|
159
|
+
var SIZE_OFFSET = 124;
|
|
160
|
+
var SIZE_FIELD_BYTES = 12;
|
|
161
|
+
var SIZE_FIELD_DIGITS = 11;
|
|
162
|
+
var MTIME_OFFSET = 136;
|
|
163
|
+
var MTIME_FIELD_BYTES = 12;
|
|
164
|
+
var CHECKSUM_FIELD_OFFSET = 148;
|
|
165
|
+
var CHECKSUM_FIELD_BYTES = 8;
|
|
166
|
+
var CHECKSUM_DIGITS = 6;
|
|
167
|
+
var TYPEFLAG_OFFSET = 156;
|
|
168
|
+
var MAGIC_OFFSET = 257;
|
|
169
|
+
var MAGIC_BYTES = 6;
|
|
170
|
+
var VERSION_OFFSET = 263;
|
|
171
|
+
var VERSION_BYTES = 2;
|
|
172
|
+
var PREFIX_OFFSET = 345;
|
|
173
|
+
var PREFIX_BYTES = 155;
|
|
174
|
+
var MODE_OCTAL = "0000644";
|
|
175
|
+
var ZERO_OCTAL_7 = "0000000";
|
|
176
|
+
var ZERO_OCTAL_11 = "00000000000";
|
|
177
|
+
var REGULAR_FILE = 48;
|
|
178
|
+
var OLD_REGULAR_FILE = 0;
|
|
179
|
+
var PAX_EXTENDED_HEADER = 120;
|
|
180
|
+
var PAX_HEADER_NAME = "PaxHeader";
|
|
181
|
+
var encoder = new TextEncoder();
|
|
182
|
+
var decoder = new TextDecoder("utf-8", { fatal: true });
|
|
183
|
+
function writeString(block, offset, length, value) {
|
|
184
|
+
const bytes = encoder.encode(value);
|
|
185
|
+
block.set(bytes.subarray(0, length), offset);
|
|
186
|
+
}
|
|
187
|
+
function writeOctal(block, offset, digits, value) {
|
|
188
|
+
writeString(block, offset, digits, value.toString(8).padStart(digits, "0"));
|
|
189
|
+
}
|
|
190
|
+
function headerChecksum(block) {
|
|
191
|
+
let sum = 0;
|
|
192
|
+
const checksumEnd = CHECKSUM_FIELD_OFFSET + CHECKSUM_FIELD_BYTES;
|
|
193
|
+
for (let at = 0; at < TAR_BLOCK_BYTES; at++) {
|
|
194
|
+
sum += at >= CHECKSUM_FIELD_OFFSET && at < checksumEnd ? 32 : block[at];
|
|
195
|
+
}
|
|
196
|
+
return sum;
|
|
197
|
+
}
|
|
198
|
+
function ustarBlock(name, prefix, size, typeflag) {
|
|
199
|
+
const block = new Uint8Array(TAR_BLOCK_BYTES);
|
|
200
|
+
writeString(block, NAME_OFFSET, NAME_BYTES, name);
|
|
201
|
+
writeString(block, MODE_OFFSET, ID_FIELD_BYTES, MODE_OCTAL);
|
|
202
|
+
writeString(block, OWNER_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
|
|
203
|
+
writeString(block, GROUP_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
|
|
204
|
+
writeOctal(block, SIZE_OFFSET, SIZE_FIELD_DIGITS, size);
|
|
205
|
+
writeString(block, MTIME_OFFSET, MTIME_FIELD_BYTES, ZERO_OCTAL_11);
|
|
206
|
+
block[TYPEFLAG_OFFSET] = typeflag;
|
|
207
|
+
writeString(block, MAGIC_OFFSET, MAGIC_BYTES, "ustar");
|
|
208
|
+
writeString(block, VERSION_OFFSET, VERSION_BYTES, "00");
|
|
209
|
+
writeString(block, PREFIX_OFFSET, PREFIX_BYTES, prefix);
|
|
210
|
+
const checksum = headerChecksum(block);
|
|
211
|
+
writeString(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_DIGITS, checksum.toString(8).padStart(CHECKSUM_DIGITS, "0"));
|
|
212
|
+
block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS] = 0;
|
|
213
|
+
block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS + 1] = 32;
|
|
214
|
+
return block;
|
|
215
|
+
}
|
|
216
|
+
function splitForUstar(name) {
|
|
217
|
+
if (encoder.encode(name).byteLength <= NAME_BYTES) return { name, prefix: "" };
|
|
218
|
+
for (let slash = name.indexOf("/"); slash >= 0; slash = name.indexOf("/", slash + 1)) {
|
|
219
|
+
const prefix = name.slice(0, slash);
|
|
220
|
+
const rest = name.slice(slash + 1);
|
|
221
|
+
if (encoder.encode(prefix).byteLength <= PREFIX_BYTES && encoder.encode(rest).byteLength <= NAME_BYTES) {
|
|
222
|
+
return { name: rest, prefix };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
function paxRecord(key, value) {
|
|
228
|
+
const body = ` ${key}=${value}
|
|
229
|
+
`;
|
|
230
|
+
const bodyBytes = encoder.encode(body).byteLength;
|
|
231
|
+
let digits = 1;
|
|
232
|
+
while (String(bodyBytes + digits).length !== digits) digits += 1;
|
|
233
|
+
return `${bodyBytes + digits}${body}`;
|
|
234
|
+
}
|
|
235
|
+
function tarPadding(size) {
|
|
236
|
+
const remainder = size % TAR_BLOCK_BYTES;
|
|
237
|
+
return new Uint8Array(remainder === 0 ? 0 : TAR_BLOCK_BYTES - remainder);
|
|
238
|
+
}
|
|
239
|
+
function tarEntryHeaders(name, size) {
|
|
240
|
+
const split = splitForUstar(name);
|
|
241
|
+
if (split !== null) return [ustarBlock(split.name, split.prefix, size, REGULAR_FILE)];
|
|
242
|
+
const record = encoder.encode(paxRecord("path", name));
|
|
243
|
+
return [
|
|
244
|
+
ustarBlock(PAX_HEADER_NAME, "", record.byteLength, PAX_EXTENDED_HEADER),
|
|
245
|
+
record,
|
|
246
|
+
tarPadding(record.byteLength),
|
|
247
|
+
ustarBlock(name.slice(-NAME_BYTES).replace(/^[^/]*\//, ""), "", size, REGULAR_FILE)
|
|
248
|
+
];
|
|
249
|
+
}
|
|
250
|
+
function tarEnd() {
|
|
251
|
+
return new Uint8Array(TAR_BLOCK_BYTES * 2);
|
|
252
|
+
}
|
|
253
|
+
function invalidArchive(message, details) {
|
|
254
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `Invalid snapshot archive: ${message}`, details);
|
|
255
|
+
}
|
|
256
|
+
function readString(block, offset, length) {
|
|
257
|
+
let end = offset;
|
|
258
|
+
while (end < offset + length && block[end] !== 0) end++;
|
|
259
|
+
try {
|
|
260
|
+
return decoder.decode(block.subarray(offset, end));
|
|
261
|
+
} catch {
|
|
262
|
+
invalidArchive("an entry header holds a name that is not UTF-8");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function readOctal(block, offset, length, what) {
|
|
266
|
+
const text = readString(block, offset, length).trim();
|
|
267
|
+
if (!/^[0-7]+$/.test(text)) invalidArchive(`an entry header holds an invalid ${what}`);
|
|
268
|
+
const value = Number.parseInt(text, 8);
|
|
269
|
+
if (!Number.isSafeInteger(value)) invalidArchive(`an entry header holds an invalid ${what}`);
|
|
270
|
+
return value;
|
|
271
|
+
}
|
|
272
|
+
function isZeroBlock(block) {
|
|
273
|
+
for (let at = 0; at < block.length; at++) if (block[at] !== 0) return false;
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
function parseTarHeader(block) {
|
|
277
|
+
if (readOctal(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_FIELD_BYTES, "checksum") !== headerChecksum(block)) {
|
|
278
|
+
invalidArchive("an entry header fails its checksum");
|
|
279
|
+
}
|
|
280
|
+
const typeflag = block[TYPEFLAG_OFFSET];
|
|
281
|
+
if (typeflag !== REGULAR_FILE && typeflag !== OLD_REGULAR_FILE && typeflag !== PAX_EXTENDED_HEADER) {
|
|
282
|
+
invalidArchive(`an entry has type ${String.fromCharCode(typeflag)}, while an archive holds regular files alone`);
|
|
283
|
+
}
|
|
284
|
+
const name = readString(block, NAME_OFFSET, NAME_BYTES);
|
|
285
|
+
const prefix = readString(block, PREFIX_OFFSET, PREFIX_BYTES);
|
|
286
|
+
return {
|
|
287
|
+
name: prefix.length > 0 ? `${prefix}/${name}` : name,
|
|
288
|
+
size: readOctal(block, SIZE_OFFSET, SIZE_FIELD_BYTES, "size"),
|
|
289
|
+
isPaxHeader: typeflag === PAX_EXTENDED_HEADER
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
var SPACE = 32;
|
|
293
|
+
var EQUALS = 61;
|
|
294
|
+
var NEWLINE = 10;
|
|
295
|
+
function decodeRecordText(bytes) {
|
|
296
|
+
try {
|
|
297
|
+
return decoder.decode(bytes);
|
|
298
|
+
} catch {
|
|
299
|
+
invalidArchive("a pax extended header is not UTF-8");
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function parsePaxRecords(body) {
|
|
303
|
+
const records = /* @__PURE__ */ new Map();
|
|
304
|
+
let at = 0;
|
|
305
|
+
while (at < body.length) {
|
|
306
|
+
const space = body.indexOf(SPACE, at);
|
|
307
|
+
if (space < 0) invalidArchive("a pax extended header holds a malformed record");
|
|
308
|
+
const length = Number.parseInt(decodeRecordText(body.subarray(at, space)), 10);
|
|
309
|
+
if (!Number.isSafeInteger(length) || length <= space - at || at + length > body.length) {
|
|
310
|
+
invalidArchive("a pax extended header holds a malformed record");
|
|
311
|
+
}
|
|
312
|
+
const record = body.subarray(space + 1, at + length);
|
|
313
|
+
const equals = record.indexOf(EQUALS);
|
|
314
|
+
if (equals < 0 || record[record.length - 1] !== NEWLINE) {
|
|
315
|
+
invalidArchive("a pax extended header holds a record without a value");
|
|
316
|
+
}
|
|
317
|
+
records.set(decodeRecordText(record.subarray(0, equals)), decodeRecordText(record.subarray(equals + 1, -1)));
|
|
318
|
+
at += length;
|
|
319
|
+
}
|
|
320
|
+
return records;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/persistence/archive/read.ts
|
|
324
|
+
var ARCHIVE_CONFIG_ENTRY = "config";
|
|
325
|
+
var ARCHIVE_MANIFEST_ENTRY = "manifest";
|
|
326
|
+
var SEGMENTS_MARKER = "/segments/";
|
|
327
|
+
var CHECKSUM_OFFSET = 14;
|
|
328
|
+
async function readBlock(reader) {
|
|
329
|
+
const block = await reader.readExactly(TAR_BLOCK_BYTES);
|
|
330
|
+
if (block === null) return null;
|
|
331
|
+
if (block.byteLength < TAR_BLOCK_BYTES) invalidArchive("the archive ends inside an entry header");
|
|
332
|
+
return block;
|
|
333
|
+
}
|
|
334
|
+
async function readPadded(reader, size) {
|
|
335
|
+
const body = await reader.readExactly(size) ?? new Uint8Array(0);
|
|
336
|
+
if (body.byteLength < size) invalidArchive("the archive ends inside an entry");
|
|
337
|
+
const remainder = size % TAR_BLOCK_BYTES;
|
|
338
|
+
if (remainder !== 0) {
|
|
339
|
+
const padding = await reader.readExactly(TAR_BLOCK_BYTES - remainder);
|
|
340
|
+
if (padding === null || padding.byteLength < TAR_BLOCK_BYTES - remainder) {
|
|
341
|
+
invalidArchive("the archive ends inside the padding of an entry");
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return body;
|
|
345
|
+
}
|
|
346
|
+
async function nextEntryHeader(reader) {
|
|
347
|
+
const block = await readBlock(reader);
|
|
348
|
+
if (block === null || isZeroBlock(block)) return null;
|
|
349
|
+
const header = parseTarHeader(block);
|
|
350
|
+
if (!header.isPaxHeader) return { name: header.name, size: header.size };
|
|
351
|
+
if (header.size > MAX_PAX_HEADER_BYTES) invalidArchive("a pax extended header is too long");
|
|
352
|
+
const records = parsePaxRecords(await readPadded(reader, header.size));
|
|
353
|
+
const next = await readBlock(reader);
|
|
354
|
+
if (next === null || isZeroBlock(next)) invalidArchive("a pax extended header precedes no entry");
|
|
355
|
+
const entry = parseTarHeader(next);
|
|
356
|
+
if (entry.isPaxHeader) invalidArchive("a pax extended header follows another");
|
|
357
|
+
const path = records.get("path");
|
|
358
|
+
const size = records.get("size");
|
|
359
|
+
const parsedSize = size === void 0 ? entry.size : Number.parseInt(size, 10);
|
|
360
|
+
if (!Number.isSafeInteger(parsedSize) || parsedSize < 0) invalidArchive("a pax extended header holds an invalid size");
|
|
361
|
+
return { name: path ?? entry.name, size: parsedSize };
|
|
362
|
+
}
|
|
363
|
+
async function readNamedEntry(reader, expected) {
|
|
364
|
+
const header = await nextEntryHeader(reader);
|
|
365
|
+
if (header === null) invalidArchive(`the archive ends before its ${expected} entry`);
|
|
366
|
+
if (header.name !== expected) invalidArchive(`the archive holds "${header.name}" where its ${expected} entry belongs`);
|
|
367
|
+
if (header.size > MAX_FILE_BYTES) invalidArchive(`the ${expected} entry passes the file size limit`);
|
|
368
|
+
return readPadded(reader, header.size);
|
|
369
|
+
}
|
|
370
|
+
function sourceIndexNameOf(keys) {
|
|
371
|
+
const first = keys[0];
|
|
372
|
+
if (first === void 0) return "archive";
|
|
373
|
+
const at = first.indexOf(SEGMENTS_MARKER);
|
|
374
|
+
if (at <= 0) invalidArchive(`the manifest lists the key "${first}" outside any index`);
|
|
375
|
+
return first.slice(0, at);
|
|
376
|
+
}
|
|
377
|
+
function headerChecksumOf(bytes) {
|
|
378
|
+
if (bytes.byteLength < HEADER_SIZE) return -1;
|
|
379
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(CHECKSUM_OFFSET, false);
|
|
380
|
+
}
|
|
381
|
+
async function readSnapshotArchive(reader, handlers) {
|
|
382
|
+
await handlers.config(await readNamedEntry(reader, ARCHIVE_CONFIG_ENTRY));
|
|
383
|
+
const raw = await openManifestPayload(await readNamedEntry(reader, ARCHIVE_MANIFEST_ENTRY));
|
|
384
|
+
const sourceIndexName = sourceIndexNameOf(listedKeysOf(raw));
|
|
385
|
+
const decoded = decodeManifestPayload(raw, sourceIndexName);
|
|
386
|
+
if (decoded.kind !== "current") invalidArchive("the manifest holds the layout of an earlier release");
|
|
387
|
+
const manifest = decoded.manifest;
|
|
388
|
+
await handlers.manifest(manifest, sourceIndexName);
|
|
389
|
+
const files = manifestFileRefs(manifest);
|
|
390
|
+
const prefix = `${sourceIndexName}/`;
|
|
391
|
+
const listedNames = new Set(files.map((file) => file.key.slice(prefix.length)));
|
|
392
|
+
const seen = /* @__PURE__ */ new Set();
|
|
393
|
+
for (const ref of files) {
|
|
394
|
+
const expected = ref.key.slice(prefix.length);
|
|
395
|
+
const header = await nextEntryHeader(reader);
|
|
396
|
+
if (header === null) invalidArchive(`the archive ends before it holds "${expected}"`);
|
|
397
|
+
if (header.name !== expected) {
|
|
398
|
+
const why = !listedNames.has(header.name) ? "that the manifest does not list" : seen.has(header.name) ? "twice" : "out of order";
|
|
399
|
+
invalidArchive(`the archive holds the entry "${header.name}" ${why}`, { entry: header.name });
|
|
400
|
+
}
|
|
401
|
+
if (header.size !== ref.bytes) {
|
|
402
|
+
invalidArchive(`the entry "${expected}" holds ${header.size} bytes where the manifest lists ${ref.bytes}`);
|
|
403
|
+
}
|
|
404
|
+
const bytes = await readPadded(reader, header.size);
|
|
405
|
+
if (headerChecksumOf(bytes) !== ref.checksum) {
|
|
406
|
+
invalidArchive(`the entry "${expected}" carries a checksum other than the manifest lists`, { entry: expected });
|
|
407
|
+
}
|
|
408
|
+
seen.add(expected);
|
|
409
|
+
await handlers.file(expected, ref, bytes);
|
|
410
|
+
}
|
|
411
|
+
const trailing = await nextEntryHeader(reader);
|
|
412
|
+
if (trailing !== null) {
|
|
413
|
+
invalidArchive(`the archive holds the entry "${trailing.name}" that the manifest does not list`, {
|
|
414
|
+
entry: trailing.name
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// src/persistence/archive/write.ts
|
|
420
|
+
function entryChunks(name, bytes) {
|
|
421
|
+
return [...tarEntryHeaders(name, bytes.byteLength), bytes, tarPadding(bytes.byteLength)].filter(
|
|
422
|
+
(chunk) => chunk.byteLength > 0
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
async function* archiveChunks(source) {
|
|
426
|
+
yield* entryChunks(ARCHIVE_CONFIG_ENTRY, source.config);
|
|
427
|
+
yield* entryChunks(ARCHIVE_MANIFEST_ENTRY, source.manifestBytes);
|
|
428
|
+
const prefix = `${source.sourceIndexName}/`;
|
|
429
|
+
for (const ref of manifestFileRefs(source.manifest)) {
|
|
430
|
+
yield* entryChunks(ref.key.slice(prefix.length), await source.readFile(ref));
|
|
431
|
+
}
|
|
432
|
+
yield tarEnd();
|
|
433
|
+
}
|
|
434
|
+
function archiveStream(source) {
|
|
435
|
+
const chunks = archiveChunks(source);
|
|
436
|
+
let released = false;
|
|
437
|
+
const release = () => {
|
|
438
|
+
if (released) return;
|
|
439
|
+
released = true;
|
|
440
|
+
source.release();
|
|
441
|
+
};
|
|
442
|
+
return new ReadableStream({
|
|
443
|
+
async pull(controller) {
|
|
444
|
+
try {
|
|
445
|
+
const step = await chunks.next();
|
|
446
|
+
if (step.done) {
|
|
447
|
+
release();
|
|
448
|
+
controller.close();
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
controller.enqueue(step.value);
|
|
452
|
+
} catch (error) {
|
|
453
|
+
release();
|
|
454
|
+
controller.error(error);
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
async cancel() {
|
|
458
|
+
release();
|
|
459
|
+
await chunks.return(void 0);
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// src/persistence/archive/validate.ts
|
|
465
|
+
function requireDimension(key, found, expected) {
|
|
466
|
+
if (expected === found) return;
|
|
467
|
+
throw new NarsilError(
|
|
468
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
469
|
+
`The vector file "${key}" holds vectors of ${found} dimensions where the schema gives ${String(expected)}`,
|
|
470
|
+
{ key, found, expected }
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
function requireSchemaOfManifest(key, schema, manifest) {
|
|
474
|
+
for (const [field, type] of Object.entries(schema)) {
|
|
475
|
+
const listed = manifest.schema[field];
|
|
476
|
+
if (listed === void 0 || listed === type) continue;
|
|
477
|
+
throw new NarsilError(
|
|
478
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
479
|
+
`The segment "${key}" gives field "${field}" the type "${type}", while the manifest gives it "${listed}"`,
|
|
480
|
+
{ key, field }
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
async function validateStagedCheckpoint(store, manifest) {
|
|
485
|
+
for (const partition of manifest.partitions) {
|
|
486
|
+
for (const ref of partition.segments) {
|
|
487
|
+
const contents = await readSegmentFile(store, ref);
|
|
488
|
+
requireSchemaOfManifest(ref.key, contents.schema, manifest);
|
|
489
|
+
decodeEveryStoredDocument(contents.arrays.documentTable);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
for (const field of manifest.vectors) {
|
|
493
|
+
const fieldType = manifest.schema[field.fieldPath];
|
|
494
|
+
const dimension = fieldType === void 0 ? null : parseVectorDimension(fieldType);
|
|
495
|
+
for (const file of field.files) {
|
|
496
|
+
const { payload } = await readVectorFile(store, file, field.fieldPath);
|
|
497
|
+
requireDimension(file.key, payload.dimension, dimension);
|
|
498
|
+
}
|
|
499
|
+
await readGraphParts(store, field);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/engine/snapshot/constants.ts
|
|
504
|
+
var RESTORE_WORST_HEAP_BYTES_PER_STORED_BYTE = 0.2;
|
|
505
|
+
var RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_BYTE = 7.86;
|
|
506
|
+
var RESTORE_WORST_HEAP_BYTES_PER_VECTOR = 264;
|
|
507
|
+
var RESTORE_WORST_HEAP_BYTES_PER_VECTOR_DIMENSION = 0.24;
|
|
508
|
+
var RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR = 738;
|
|
509
|
+
var RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION = 0.2;
|
|
510
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_STORED_BYTE = 4.06;
|
|
511
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_BYTE = 14.5;
|
|
512
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_VECTOR = 1482;
|
|
513
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_VECTOR_DIMENSION = 9.29;
|
|
514
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR = 2141;
|
|
515
|
+
var RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION = 24.15;
|
|
516
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_STORED_BYTE = 0.16;
|
|
517
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_BYTE = 6.16;
|
|
518
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_VECTOR = 204;
|
|
519
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_VECTOR_DIMENSION = 0.17;
|
|
520
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR = 695;
|
|
521
|
+
var RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION = 0.04;
|
|
522
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_STORED_BYTE = 2.14;
|
|
523
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_BYTE = 5.05;
|
|
524
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_VECTOR = 1080;
|
|
525
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_VECTOR_DIMENSION = 0.72;
|
|
526
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR = 1744;
|
|
527
|
+
var RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION = 20.05;
|
|
528
|
+
var RESTORE_ESTIMATE_MARGIN = 1.25;
|
|
529
|
+
|
|
530
|
+
// src/engine/snapshot/memory-budget.ts
|
|
531
|
+
var MEGABYTE_BYTES = 1048576;
|
|
532
|
+
var ARCHIVE_RATES = {
|
|
533
|
+
worst: {
|
|
534
|
+
heap: {
|
|
535
|
+
perStoredByte: RESTORE_WORST_HEAP_BYTES_PER_STORED_BYTE,
|
|
536
|
+
perVector: RESTORE_WORST_HEAP_BYTES_PER_VECTOR,
|
|
537
|
+
perVectorDimension: RESTORE_WORST_HEAP_BYTES_PER_VECTOR_DIMENSION
|
|
538
|
+
},
|
|
539
|
+
external: {
|
|
540
|
+
perStoredByte: RESTORE_WORST_EXTERNAL_BYTES_PER_STORED_BYTE,
|
|
541
|
+
perVector: RESTORE_WORST_EXTERNAL_BYTES_PER_VECTOR,
|
|
542
|
+
perVectorDimension: RESTORE_WORST_EXTERNAL_BYTES_PER_VECTOR_DIMENSION
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
floor: {
|
|
546
|
+
heap: {
|
|
547
|
+
perStoredByte: RESTORE_FLOOR_HEAP_BYTES_PER_STORED_BYTE,
|
|
548
|
+
perVector: RESTORE_FLOOR_HEAP_BYTES_PER_VECTOR,
|
|
549
|
+
perVectorDimension: RESTORE_FLOOR_HEAP_BYTES_PER_VECTOR_DIMENSION
|
|
550
|
+
},
|
|
551
|
+
external: {
|
|
552
|
+
perStoredByte: RESTORE_FLOOR_EXTERNAL_BYTES_PER_STORED_BYTE,
|
|
553
|
+
perVector: RESTORE_FLOOR_EXTERNAL_BYTES_PER_VECTOR,
|
|
554
|
+
perVectorDimension: RESTORE_FLOOR_EXTERNAL_BYTES_PER_VECTOR_DIMENSION
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
var EARLIER_SNAPSHOT_RATES = {
|
|
559
|
+
worst: {
|
|
560
|
+
heap: {
|
|
561
|
+
perStoredByte: RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_BYTE,
|
|
562
|
+
perVector: RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR,
|
|
563
|
+
perVectorDimension: RESTORE_WORST_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION
|
|
564
|
+
},
|
|
565
|
+
external: {
|
|
566
|
+
perStoredByte: RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_BYTE,
|
|
567
|
+
perVector: RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR,
|
|
568
|
+
perVectorDimension: RESTORE_WORST_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
floor: {
|
|
572
|
+
heap: {
|
|
573
|
+
perStoredByte: RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_BYTE,
|
|
574
|
+
perVector: RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR,
|
|
575
|
+
perVectorDimension: RESTORE_FLOOR_HEAP_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION
|
|
576
|
+
},
|
|
577
|
+
external: {
|
|
578
|
+
perStoredByte: RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_BYTE,
|
|
579
|
+
perVector: RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR,
|
|
580
|
+
perVectorDimension: RESTORE_FLOOR_EXTERNAL_BYTES_PER_EARLIER_SNAPSHOT_VECTOR_DIMENSION
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
function bytesAt(rate, storedBytes, vectors) {
|
|
585
|
+
let bytes = storedBytes * rate.perStoredByte;
|
|
586
|
+
for (const { dimension, count } of vectors) bytes += count * (rate.perVector + dimension * rate.perVectorDimension);
|
|
587
|
+
return bytes;
|
|
588
|
+
}
|
|
589
|
+
function footprintAt(rates, replacesIndex, storedBytes, vectors) {
|
|
590
|
+
const chosen = replacesIndex ? rates.worst : rates.floor;
|
|
591
|
+
const scale = replacesIndex ? RESTORE_ESTIMATE_MARGIN : 1 / RESTORE_ESTIMATE_MARGIN;
|
|
592
|
+
return {
|
|
593
|
+
heapBytes: bytesAt(chosen.heap, storedBytes, vectors) * scale,
|
|
594
|
+
externalBytes: bytesAt(chosen.external, storedBytes, vectors) * scale
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function deadCountOf(dead) {
|
|
598
|
+
if (dead === null) return 0;
|
|
599
|
+
let count = 0;
|
|
600
|
+
for (const byte of dead) {
|
|
601
|
+
for (let bits = byte; bits !== 0; bits &= bits - 1) count += 1;
|
|
602
|
+
}
|
|
603
|
+
return count;
|
|
604
|
+
}
|
|
605
|
+
function archiveFootprint(prepared, manifest, replacesIndex) {
|
|
606
|
+
let segmentBytes = 0;
|
|
607
|
+
for (const partition of manifest.partitions) {
|
|
608
|
+
for (const segment of partition.segments) segmentBytes += segment.bytes;
|
|
609
|
+
}
|
|
610
|
+
const dimensions = extractVectorFieldsFromSchema(prepared.config.schema);
|
|
611
|
+
const vectors = [];
|
|
612
|
+
for (const field of manifest.vectors) {
|
|
613
|
+
const dimension = dimensions.get(field.fieldPath) ?? 0;
|
|
614
|
+
for (const file of field.files) vectors.push({ dimension, count: Math.max(0, file.count - deadCountOf(file.dead)) });
|
|
615
|
+
}
|
|
616
|
+
return footprintAt(ARCHIVE_RATES, replacesIndex, segmentBytes, vectors);
|
|
617
|
+
}
|
|
618
|
+
function earlierSnapshotFootprint(prepared, partitionBytes, vectorCounts, replacesIndex) {
|
|
619
|
+
const dimensions = extractVectorFieldsFromSchema(prepared.config.schema);
|
|
620
|
+
const vectors = [...vectorCounts].map(([fieldPath, count]) => ({ dimension: dimensions.get(fieldPath) ?? 0, count }));
|
|
621
|
+
return footprintAt(EARLIER_SNAPSHOT_RATES, replacesIndex, partitionBytes, vectors);
|
|
622
|
+
}
|
|
623
|
+
function inMegabytes(bytes) {
|
|
624
|
+
return Math.ceil(bytes / MEGABYTE_BYTES);
|
|
625
|
+
}
|
|
626
|
+
function shortfallOf(heapBytes, processBytes, countInUse) {
|
|
627
|
+
const heap = readHeapStatistics();
|
|
628
|
+
if (heap !== null) {
|
|
629
|
+
const limitBytes = heap.configuredLimitBytes ?? heap.limitBytes;
|
|
630
|
+
const availableBytes = countInUse ? limitBytes - heap.usedBytes : limitBytes;
|
|
631
|
+
if (heapBytes > availableBytes) return { budget: "heap", neededBytes: heapBytes, availableBytes };
|
|
632
|
+
}
|
|
633
|
+
const resident = readResidentMemory();
|
|
634
|
+
if (resident !== null) {
|
|
635
|
+
const availableBytes = countInUse ? resident.limitBytes - resident.residentBytes : resident.limitBytes;
|
|
636
|
+
if (processBytes > availableBytes) return { budget: "process", neededBytes: processBytes, availableBytes };
|
|
637
|
+
}
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
function refuse(indexName, replacesIndex, shortfall) {
|
|
641
|
+
const { budget, neededBytes, availableBytes } = shortfall;
|
|
642
|
+
const where = budget === "heap" ? "of JavaScript heap" : "of process memory";
|
|
643
|
+
const outcome = replacesIndex ? "so the index keeps its earlier contents. Drop the index first to free the memory that it holds, or give the process more memory, then restore again" : "so the engine creates no index. Give the process more memory, then restore again";
|
|
644
|
+
throw new NarsilError(
|
|
645
|
+
ErrorCodes.RESTORE_MEMORY_EXCEEDED,
|
|
646
|
+
`The restore of index "${indexName}" needs about ${inMegabytes(neededBytes)} MB ${where}, and this process has ${inMegabytes(Math.max(0, availableBytes))} MB free, ${outcome}`,
|
|
647
|
+
{ indexName, budget, neededBytes, availableBytes }
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
function requireRestoreMemory(indexName, footprint, replacesIndex) {
|
|
651
|
+
const processBytes = footprint.heapBytes + footprint.externalBytes;
|
|
652
|
+
if (shortfallOf(footprint.heapBytes, processBytes, true) === null) return;
|
|
653
|
+
const shortfall = shortfallOf(footprint.heapBytes, processBytes, replacesIndex);
|
|
654
|
+
if (shortfall !== null) refuse(indexName, replacesIndex, shortfall);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// src/workers/detached-index.ts
|
|
658
|
+
function attachablePolicy(shared) {
|
|
659
|
+
let attached = false;
|
|
660
|
+
const policy = {
|
|
661
|
+
get enabled() {
|
|
662
|
+
return attached && shared.enabled;
|
|
663
|
+
},
|
|
664
|
+
get count() {
|
|
665
|
+
return shared.count;
|
|
666
|
+
},
|
|
667
|
+
get host() {
|
|
668
|
+
return shared.host;
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
return {
|
|
672
|
+
policy,
|
|
673
|
+
attach() {
|
|
674
|
+
attached = true;
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function createDetachedIndex(indexName, config, language, synonyms, executor) {
|
|
679
|
+
const { policy, attach } = attachablePolicy(executor.vectorWorkerCopies);
|
|
680
|
+
const entry = executor.createDetachedEntry(indexName, config, language, policy);
|
|
681
|
+
entry.manager.synonyms = synonyms;
|
|
682
|
+
return { indexName, manager: entry.manager, entry, attach };
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// src/engine/snapshot/restore-setup.ts
|
|
686
|
+
function prepareRestoredIndex(configuration, deps, reject) {
|
|
687
|
+
const configFields = restoredConfigFields(configuration, reject);
|
|
688
|
+
const embedding = restoredEmbedding(configuration.embedding, reject);
|
|
689
|
+
const languageName = configuration.language ?? "";
|
|
690
|
+
const language = getLanguage(languageName);
|
|
691
|
+
const schema = validateSchema(configuration.schema);
|
|
692
|
+
validatePatternValueLimit(configFields.patternValueLimit);
|
|
693
|
+
requireSurfaceFormsForPartialFields(schema, configFields.surfaceForms);
|
|
694
|
+
validateVectorPromotion(configFields.vectorPromotion);
|
|
695
|
+
validateVectorStorage(configFields.vectorPromotion, deps.filesystemDurability);
|
|
696
|
+
if (configFields.required !== void 0 && configFields.required.length > 0) {
|
|
697
|
+
validateRequiredFieldsInSchema(configFields.required, schema);
|
|
698
|
+
}
|
|
699
|
+
const config = {
|
|
700
|
+
schema,
|
|
701
|
+
language: languageName,
|
|
702
|
+
...configFields,
|
|
703
|
+
...embedding !== void 0 ? {
|
|
704
|
+
embedding: {
|
|
705
|
+
fields: embedding.fields,
|
|
706
|
+
...embedding.adapter !== void 0 ? { adapter: embedding.adapter } : {}
|
|
707
|
+
}
|
|
708
|
+
} : {}
|
|
709
|
+
};
|
|
710
|
+
resolveIndexAnalysis(config);
|
|
711
|
+
const adapterName = embedding?.adapter ?? null;
|
|
712
|
+
let embeddingAdapter = null;
|
|
713
|
+
if (embedding !== void 0) {
|
|
714
|
+
const candidate = adapterName !== null ? deps.embeddingAdapters.get(adapterName) ?? null : deps.defaultEmbeddingAdapter;
|
|
715
|
+
if (candidate) {
|
|
716
|
+
validateEmbeddingConfig({ fields: embedding.fields, adapter: candidate }, schema, void 0);
|
|
717
|
+
embeddingAdapter = candidate;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
const storedRevision = typeof configuration.analysisRevision === "string" ? configuration.analysisRevision : null;
|
|
721
|
+
const synonyms = restoredSynonyms(configuration.synonyms, config, language, reject ?? rejectSnapshot);
|
|
722
|
+
return { config, language, embeddingAdapter, adapterName, storedRevision, synonyms };
|
|
723
|
+
}
|
|
724
|
+
function restoredSynonyms(raw, config, language, reject) {
|
|
725
|
+
if (raw === void 0 || raw === null) return null;
|
|
726
|
+
return prepareStoredSynonyms(raw, config, language, (message) => reject(`synonyms: ${message}`));
|
|
727
|
+
}
|
|
728
|
+
async function prepareDetachedIndex(indexName, prepared, partitionCount, deps) {
|
|
729
|
+
const loadingVectorCode = loadVectorCodeFor(prepared.config.schema);
|
|
730
|
+
if (loadingVectorCode !== null) await loadingVectorCode;
|
|
731
|
+
const detached = createDetachedIndex(
|
|
732
|
+
indexName,
|
|
733
|
+
prepared.config,
|
|
734
|
+
prepared.language,
|
|
735
|
+
prepared.synonyms?.lookup ?? null,
|
|
736
|
+
deps.executor
|
|
737
|
+
);
|
|
738
|
+
while (detached.manager.partitionCount < partitionCount) detached.manager.addPartition();
|
|
739
|
+
return detached;
|
|
740
|
+
}
|
|
741
|
+
function restoredRegistryEntry(prepared, manager, deps) {
|
|
742
|
+
return {
|
|
743
|
+
config: prepared.config,
|
|
744
|
+
language: prepared.language,
|
|
745
|
+
embeddingAdapter: prepared.embeddingAdapter,
|
|
746
|
+
embeddingAdapterName: prepared.adapterName,
|
|
747
|
+
vectorFieldPaths: deps.getVectorFieldPaths(prepared.config.schema),
|
|
748
|
+
indexUuid: null,
|
|
749
|
+
heldPartitions: null,
|
|
750
|
+
documentCount: manager.countDocuments(),
|
|
751
|
+
partitionCount: manager.partitionCount,
|
|
752
|
+
analysisRevision: prepared.storedRevision,
|
|
753
|
+
synonyms: prepared.synonyms?.encoded ?? null
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/engine/snapshot/replace.ts
|
|
758
|
+
function releaseTimedOut(indexName, timeoutMs) {
|
|
759
|
+
return new NarsilError(
|
|
760
|
+
ErrorCodes.WORKER_TIMEOUT,
|
|
761
|
+
`The restore of index "${indexName}" stopped because a worker held the index past ${timeoutMs} ms, and the index keeps its earlier contents`,
|
|
762
|
+
{ indexName, timeoutMs }
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
async function withinLimit(indexName, release, work, deps) {
|
|
766
|
+
release.settled = work.catch(() => {
|
|
767
|
+
release.reloads = true;
|
|
768
|
+
});
|
|
769
|
+
let timer;
|
|
770
|
+
const limit = new Promise((_, reject) => {
|
|
771
|
+
timer = setTimeout(() => {
|
|
772
|
+
release.timedOut = true;
|
|
773
|
+
reject(releaseTimedOut(indexName, deps.releaseTimeoutMs));
|
|
774
|
+
}, deps.releaseTimeoutMs);
|
|
775
|
+
});
|
|
776
|
+
try {
|
|
777
|
+
await Promise.race([work, limit]);
|
|
778
|
+
} finally {
|
|
779
|
+
clearTimeout(timer);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function vectorIndexesOf(indexName, deps) {
|
|
783
|
+
const manager = deps.executor.getManager(indexName);
|
|
784
|
+
return manager === void 0 ? [] : [...manager.getVectorIndexes().values()];
|
|
785
|
+
}
|
|
786
|
+
async function holdVectorCopies(vectorIndexes, release) {
|
|
787
|
+
for (const vectorIndex of vectorIndexes) {
|
|
788
|
+
if (release.held.includes(vectorIndex)) continue;
|
|
789
|
+
release.held.push(vectorIndex);
|
|
790
|
+
await vectorIndex.holdWorkerCopies();
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
async function releaseCopies(indexName, release, deps) {
|
|
794
|
+
release.reloads = await deps.copies.releaseIndexCopies(indexName);
|
|
795
|
+
await holdVectorCopies(vectorIndexesOf(indexName, deps), release);
|
|
796
|
+
}
|
|
797
|
+
async function endRelease(indexName, release, deps) {
|
|
798
|
+
await release.settled;
|
|
799
|
+
for (const vectorIndex of release.held) vectorIndex.resumeWorkerCopies();
|
|
800
|
+
await deps.copies.endCopyRelease(indexName, release.reloads);
|
|
801
|
+
}
|
|
802
|
+
function persistedCheckpoint(indexName, partitionCount, deps) {
|
|
803
|
+
const durable = deps.durability?.manager;
|
|
804
|
+
if (durable === void 0) return [];
|
|
805
|
+
return Array.from({ length: partitionCount }, (_, partitionId) => ({
|
|
806
|
+
partitionId,
|
|
807
|
+
lastSeqNo: durable.highestPersistedSeqNo(indexName, partitionId),
|
|
808
|
+
primaryTerm: SINGLE_NODE_PRIMARY_TERM
|
|
809
|
+
}));
|
|
810
|
+
}
|
|
811
|
+
async function commitToStorage(indexName, restored, previousPartitions, deps) {
|
|
812
|
+
const durable = deps.durability?.manager;
|
|
813
|
+
const staging = restored.staging;
|
|
814
|
+
if (durable === void 0 || staging === null) return;
|
|
815
|
+
const previous = persistedCheckpoint(indexName, previousPartitions, deps);
|
|
816
|
+
if (previousPartitions > 0) await durable.unloadIndex(indexName);
|
|
817
|
+
const vectorIndexes = [...restored.detached.manager.getVectorIndexes().values()];
|
|
818
|
+
try {
|
|
819
|
+
for (const vectorIndex of vectorIndexes) await vectorIndex.releaseVectorFiles();
|
|
820
|
+
await staging.commit();
|
|
821
|
+
} catch (error) {
|
|
822
|
+
if (previousPartitions > 0) durable.adoptRestoredCheckpoint?.(indexName, previous);
|
|
823
|
+
throw error;
|
|
824
|
+
}
|
|
825
|
+
await staging.finish();
|
|
826
|
+
const relocate = await staging.relocation().catch(() => null);
|
|
827
|
+
if (relocate !== null) for (const vectorIndex of vectorIndexes) vectorIndex.relocateVectorFiles(relocate);
|
|
828
|
+
}
|
|
829
|
+
function activate(indexName, restored, entry, deps) {
|
|
830
|
+
deps.executor.installDetachedIndex(restored.detached);
|
|
831
|
+
deps.indexRegistry.set(indexName, entry);
|
|
832
|
+
restored.detached.attach();
|
|
833
|
+
deps.clearAnalysisStale(indexName);
|
|
834
|
+
const { prepared } = restored;
|
|
835
|
+
if (prepared.storedRevision !== prepared.language.revision) {
|
|
836
|
+
deps.markAnalysisStale({
|
|
837
|
+
indexName,
|
|
838
|
+
language: prepared.language.name,
|
|
839
|
+
storedRevision: prepared.storedRevision,
|
|
840
|
+
currentRevision: prepared.language.revision
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
if (restored.staging !== null) deps.durability?.manager.adoptRestoredCheckpoint?.(indexName, restored.checkpoint);
|
|
844
|
+
deps.forgetWatermark(indexName);
|
|
845
|
+
}
|
|
846
|
+
async function replaceExisting(indexName, restored, entry, deps) {
|
|
847
|
+
const release = { reloads: false, held: [], settled: Promise.resolve(), timedOut: false };
|
|
848
|
+
try {
|
|
849
|
+
await withinLimit(indexName, release, releaseCopies(indexName, release, deps), deps);
|
|
850
|
+
await deps.indexState.replace(indexName, async (wasOpen) => {
|
|
851
|
+
await deps.abandonAnalysisRebuild(indexName);
|
|
852
|
+
const previous = wasOpen ? deps.executor.getManager(indexName) : void 0;
|
|
853
|
+
const vectorIndexes = previous === void 0 ? [] : vectorIndexesOf(indexName, deps);
|
|
854
|
+
await withinLimit(indexName, release, holdVectorCopies(vectorIndexes, release), deps);
|
|
855
|
+
for (const vectorIndex of vectorIndexes) await vectorIndex.releaseVectorFiles();
|
|
856
|
+
await commitToStorage(indexName, restored, previous?.partitionCount ?? 0, deps);
|
|
857
|
+
activate(indexName, restored, entry, deps);
|
|
858
|
+
});
|
|
859
|
+
} finally {
|
|
860
|
+
const ending = endRelease(indexName, release, deps).catch(() => void 0);
|
|
861
|
+
if (!release.timedOut) await ending;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
async function createFresh(indexName, restored, entry, deps) {
|
|
865
|
+
deps.copies.desyncIndex(indexName);
|
|
866
|
+
deps.executor.installDetachedIndex(restored.detached);
|
|
867
|
+
deps.indexRegistry.set(indexName, entry);
|
|
868
|
+
try {
|
|
869
|
+
await deps.indexState.registerReplacing(indexName, async () => {
|
|
870
|
+
await commitToStorage(indexName, restored, 0, deps);
|
|
871
|
+
activate(indexName, restored, entry, deps);
|
|
872
|
+
});
|
|
873
|
+
} catch (error) {
|
|
874
|
+
if (deps.indexRegistry.get(indexName) === entry) deps.indexRegistry.delete(indexName);
|
|
875
|
+
throw error;
|
|
876
|
+
} finally {
|
|
877
|
+
await deps.copies.resyncIndex(indexName, false).catch(() => void 0);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
async function stageMetadata(indexName, staging, entry) {
|
|
881
|
+
const metadata = indexMetadataOf(indexName, entry, entry.partitionCount);
|
|
882
|
+
await staging.store.write(`${indexName}/meta`, [await writeMetadataEnvelope(metadata, { checksum: true })]);
|
|
883
|
+
}
|
|
884
|
+
async function installRestoredIndex(indexName, restored, deps) {
|
|
885
|
+
const entry = restoredRegistryEntry(restored.prepared, restored.detached.manager, deps);
|
|
886
|
+
let replaced;
|
|
887
|
+
try {
|
|
888
|
+
if (restored.staging !== null) await stageMetadata(indexName, restored.staging, entry);
|
|
889
|
+
replaced = deps.indexRegistry.get(indexName);
|
|
890
|
+
if (replaced !== void 0) await replaceExisting(indexName, restored, entry, deps);
|
|
891
|
+
else await createFresh(indexName, restored, entry, deps);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (deps.executor.getManager(indexName) === restored.detached.manager) deps.executor.dropIndex(indexName);
|
|
894
|
+
else deps.executor.discardDetachedIndex(restored.detached);
|
|
895
|
+
throw error;
|
|
896
|
+
}
|
|
897
|
+
await restored.staging?.removeRetired().catch(() => void 0);
|
|
898
|
+
const durable = deps.durability?.manager;
|
|
899
|
+
if (restored.staging === null && durable !== void 0) {
|
|
900
|
+
await durable.persistMetadata(indexName);
|
|
901
|
+
await durable.checkpoint(indexName);
|
|
902
|
+
}
|
|
903
|
+
if (replaced !== void 0) await deps.announceIndexDropped(indexName, replaced.config);
|
|
904
|
+
await deps.announceIndexCreated(indexName, restored.prepared.config);
|
|
905
|
+
for (const vectorIndex of restored.detached.manager.getVectorIndexes().values()) {
|
|
906
|
+
vectorIndex.startShuffledRebuildWhenDue();
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// src/engine/snapshot/archive-restore.ts
|
|
911
|
+
function rejectConfiguration(message) {
|
|
912
|
+
throw new NarsilError(ErrorCodes.CONFIG_INVALID, `Invalid index configuration: ${message}`);
|
|
913
|
+
}
|
|
914
|
+
function renamed(manifest, sourceName, indexName) {
|
|
915
|
+
const rename = (key) => `${indexName}/${key.slice(sourceName.length + 1)}`;
|
|
916
|
+
return {
|
|
917
|
+
...manifest,
|
|
918
|
+
partitions: manifest.partitions.map((partition) => ({
|
|
919
|
+
...partition,
|
|
920
|
+
segments: partition.segments.map((segment) => ({ ...segment, key: rename(segment.key) }))
|
|
921
|
+
})),
|
|
922
|
+
vectors: manifest.vectors.map((field) => ({
|
|
923
|
+
...field,
|
|
924
|
+
files: field.files.map((file) => ({ ...file, key: rename(file.key) })),
|
|
925
|
+
graphParts: field.graphParts.map((part) => ({ ...part, key: rename(part.key) }))
|
|
926
|
+
}))
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
function requireSameSchema(prepared, manifest) {
|
|
930
|
+
const configured = flattenSchema(prepared.config.schema);
|
|
931
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(configured), ...Object.keys(manifest.schema)]);
|
|
932
|
+
for (const field of keys) {
|
|
933
|
+
if (configured[field] === manifest.schema[field]) continue;
|
|
934
|
+
throw new NarsilError(
|
|
935
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
936
|
+
`The archive's configuration gives field "${field}" another type than its manifest does`,
|
|
937
|
+
{ field }
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function partitionCountOf(manifest) {
|
|
942
|
+
let count = 1;
|
|
943
|
+
for (const partition of manifest.partitions) count = Math.max(count, partition.partitionId + 1);
|
|
944
|
+
return count;
|
|
945
|
+
}
|
|
946
|
+
function missingPart(what) {
|
|
947
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The archive holds no ${what}`);
|
|
948
|
+
}
|
|
949
|
+
async function stageArchive(indexName, reader, staging, deps) {
|
|
950
|
+
const staged = { prepared: null, manifest: null };
|
|
951
|
+
await readSnapshotArchive(reader, {
|
|
952
|
+
config: async (bytes) => {
|
|
953
|
+
staged.prepared = prepareRestoredIndex(await decodeIndexConfiguration(bytes), deps, rejectConfiguration);
|
|
954
|
+
},
|
|
955
|
+
manifest: async (manifest2, sourceName) => {
|
|
956
|
+
if (staged.prepared === null) missingPart("configuration");
|
|
957
|
+
requireSameSchema(staged.prepared, manifest2);
|
|
958
|
+
const replacesIndex = deps.indexRegistry.has(indexName);
|
|
959
|
+
requireRestoreMemory(indexName, archiveFootprint(staged.prepared, manifest2, replacesIndex), replacesIndex);
|
|
960
|
+
staged.manifest = renamed(manifest2, sourceName, indexName);
|
|
961
|
+
},
|
|
962
|
+
file: async (entryName, _ref, bytes) => {
|
|
963
|
+
if (staged.manifest === null) missingPart("manifest");
|
|
964
|
+
await staging.write(`${indexName}/${entryName}`, [bytes]);
|
|
965
|
+
}
|
|
966
|
+
});
|
|
967
|
+
const { prepared, manifest } = staged;
|
|
968
|
+
if (prepared === null) missingPart("configuration");
|
|
969
|
+
if (manifest === null) missingPart("manifest");
|
|
970
|
+
await validateStagedCheckpoint(staging, manifest);
|
|
971
|
+
return { prepared, manifest };
|
|
972
|
+
}
|
|
973
|
+
async function loadStagedIndex(indexName, staged, staging, store, deps) {
|
|
974
|
+
const { prepared, manifest } = staged;
|
|
975
|
+
await store.write(manifestKey(indexName), (await encodeSegmentManifest(manifest)).chunks);
|
|
976
|
+
const detached = await prepareDetachedIndex(indexName, prepared, partitionCountOf(manifest), deps);
|
|
977
|
+
try {
|
|
978
|
+
await loadSegmentedCheckpoint(
|
|
979
|
+
store,
|
|
980
|
+
indexName,
|
|
981
|
+
manifest,
|
|
982
|
+
{ manager: detached.manager, vectorIndexes: detached.manager.getVectorIndexes() },
|
|
983
|
+
true
|
|
984
|
+
);
|
|
985
|
+
} catch (error) {
|
|
986
|
+
deps.executor.discardDetachedIndex(detached);
|
|
987
|
+
throw error;
|
|
988
|
+
}
|
|
989
|
+
return { prepared, detached, staging, checkpoint: manifest.checkpoint };
|
|
990
|
+
}
|
|
991
|
+
async function restoreArchive(indexName, reader, deps) {
|
|
992
|
+
const staging = deps.durability?.manager.stageRestore?.(indexName) ?? null;
|
|
993
|
+
const store = staging?.store ?? memoryCheckpointStore();
|
|
994
|
+
try {
|
|
995
|
+
const staged = await stageArchive(indexName, reader, store, deps);
|
|
996
|
+
await installRestoredIndex(indexName, await loadStagedIndex(indexName, staged, staging, store, deps), deps);
|
|
997
|
+
} finally {
|
|
998
|
+
await staging?.discard().catch(() => void 0);
|
|
999
|
+
await reader.close();
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
function invalidSnapshot(message, details) {
|
|
1003
|
+
throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, message, details);
|
|
1004
|
+
}
|
|
1005
|
+
async function decodeEarlierSnapshot(data) {
|
|
1006
|
+
const payloadBytes = await unpackIndexSnapshotEnvelope(data);
|
|
1007
|
+
let decoded;
|
|
1008
|
+
try {
|
|
1009
|
+
decoded = decode(payloadBytes);
|
|
1010
|
+
} catch (err) {
|
|
1011
|
+
invalidSnapshot(`Snapshot data is not a Narsil snapshot: ${err instanceof Error ? err.message : String(err)}`, {
|
|
1012
|
+
bytes: data.length
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
1016
|
+
invalidSnapshot("Snapshot data does not hold a snapshot envelope", { bytes: data.length });
|
|
1017
|
+
}
|
|
1018
|
+
const envelope = decoded;
|
|
1019
|
+
if (envelope.version !== 1 && envelope.version !== 2) {
|
|
1020
|
+
invalidSnapshot(`Unsupported snapshot version: ${envelope.version}. Expected version 1 or 2`, {
|
|
1021
|
+
version: envelope.version
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
if (!envelope.schema || typeof envelope.schema !== "object")
|
|
1025
|
+
invalidSnapshot("Invalid snapshot: missing or invalid schema");
|
|
1026
|
+
if (!envelope.language || typeof envelope.language !== "string") {
|
|
1027
|
+
invalidSnapshot("Invalid snapshot: missing or invalid language");
|
|
1028
|
+
}
|
|
1029
|
+
if (!Array.isArray(envelope.partitions)) invalidSnapshot("Invalid snapshot: missing partitions");
|
|
1030
|
+
return { ...envelope, vectorPromotion: raiseEarlierReleaseGraphSetting(envelope.vectorPromotion) };
|
|
1031
|
+
}
|
|
1032
|
+
function vectorsOfSnapshot(envelope) {
|
|
1033
|
+
const byDocument = /* @__PURE__ */ new Map();
|
|
1034
|
+
for (const [fieldPath, rawParts] of Object.entries(envelope.vectorIndexes ?? {})) {
|
|
1035
|
+
for (const part of decodeVectorIndexParts(rawParts)) {
|
|
1036
|
+
const values = bytesToVectors(part.vectors);
|
|
1037
|
+
for (let i = 0; i < part.docIds.length; i++) {
|
|
1038
|
+
let fields = byDocument.get(part.docIds[i]);
|
|
1039
|
+
if (fields === void 0) {
|
|
1040
|
+
fields = /* @__PURE__ */ new Map();
|
|
1041
|
+
byDocument.set(part.docIds[i], fields);
|
|
1042
|
+
}
|
|
1043
|
+
fields.set(fieldPath, values.slice(i * part.dimension, (i + 1) * part.dimension));
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
return byDocument;
|
|
1048
|
+
}
|
|
1049
|
+
function footprintOf(envelope, prepared, replacesIndex) {
|
|
1050
|
+
let partitionBytes = 0;
|
|
1051
|
+
for (const payload of envelope.partitions ?? []) partitionBytes += payload.byteLength;
|
|
1052
|
+
const vectorCounts = /* @__PURE__ */ new Map();
|
|
1053
|
+
for (const [fieldPath, rawParts] of Object.entries(envelope.vectorIndexes ?? {})) {
|
|
1054
|
+
let count = 0;
|
|
1055
|
+
for (const part of decodeVectorIndexParts(rawParts)) count += part.docIds.length;
|
|
1056
|
+
vectorCounts.set(fieldPath, count);
|
|
1057
|
+
}
|
|
1058
|
+
return earlierSnapshotFootprint(prepared, partitionBytes, vectorCounts, replacesIndex);
|
|
1059
|
+
}
|
|
1060
|
+
function documentsOfPartition(envelope, payload) {
|
|
1061
|
+
return envelope.version === 2 ? documentsOfPayloadV2(payload).documents : deserializePayloadV1(payload).documents;
|
|
1062
|
+
}
|
|
1063
|
+
function insertRestoredDocument(manager, docId, fields, vectors) {
|
|
1064
|
+
manager.insert(docId, fields, { skipClone: true });
|
|
1065
|
+
if (vectors === void 0) return;
|
|
1066
|
+
try {
|
|
1067
|
+
insertDocumentVectors(docId, vectors, manager.getVectorIndexes(), manager.partitionIdOf(docId));
|
|
1068
|
+
} catch (err) {
|
|
1069
|
+
manager.remove(docId);
|
|
1070
|
+
throw err;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function insertSnapshotDocuments(envelope, manager) {
|
|
1074
|
+
const vectors = vectorsOfSnapshot(envelope);
|
|
1075
|
+
for (const payload of envelope.partitions ?? []) {
|
|
1076
|
+
for (const [docId, stored] of Object.entries(documentsOfPartition(envelope, payload))) {
|
|
1077
|
+
insertRestoredDocument(manager, docId, stored.fields, vectors.get(docId));
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
for (const vectorIndex of manager.getVectorIndexes().values()) vectorIndex.scheduleBuild();
|
|
1081
|
+
}
|
|
1082
|
+
async function stageBuiltIndex(indexName, prepared, built, staging, deps) {
|
|
1083
|
+
const entry = restoredRegistryEntry(prepared, built.manager, deps);
|
|
1084
|
+
const archive = await buildArchiveFromMemory({
|
|
1085
|
+
indexName,
|
|
1086
|
+
metadata: indexMetadataOf(indexName, entry, built.manager.partitionCount),
|
|
1087
|
+
manager: built.manager,
|
|
1088
|
+
vectorIndexes: built.manager.getVectorIndexes(),
|
|
1089
|
+
appliedSeqNo: () => 0,
|
|
1090
|
+
partitionId: null
|
|
1091
|
+
});
|
|
1092
|
+
try {
|
|
1093
|
+
for (const ref of manifestFileRefs(archive.manifest))
|
|
1094
|
+
await staging.store.write(ref.key, [await archive.readFile(ref)]);
|
|
1095
|
+
} finally {
|
|
1096
|
+
archive.release();
|
|
1097
|
+
}
|
|
1098
|
+
await validateStagedCheckpoint(staging.store, archive.manifest);
|
|
1099
|
+
return archive.manifest;
|
|
1100
|
+
}
|
|
1101
|
+
async function buildRestoredIndex(indexName, envelope, prepared, staging, deps) {
|
|
1102
|
+
const built = await prepareDetachedIndex(indexName, prepared, envelope.partitions?.length ?? 0, deps);
|
|
1103
|
+
let manifest;
|
|
1104
|
+
try {
|
|
1105
|
+
insertSnapshotDocuments(envelope, built.manager);
|
|
1106
|
+
if (staging === null) return { prepared, detached: built, staging: null, checkpoint: [] };
|
|
1107
|
+
manifest = await stageBuiltIndex(indexName, prepared, built, staging, deps);
|
|
1108
|
+
} catch (err) {
|
|
1109
|
+
deps.executor.discardDetachedIndex(built);
|
|
1110
|
+
throw err;
|
|
1111
|
+
}
|
|
1112
|
+
deps.executor.discardDetachedIndex(built);
|
|
1113
|
+
return loadStagedIndex(indexName, { prepared, manifest }, staging, staging.store, deps);
|
|
1114
|
+
}
|
|
1115
|
+
async function restoreEarlierSnapshot(indexName, data, deps) {
|
|
1116
|
+
const envelope = await decodeEarlierSnapshot(data);
|
|
1117
|
+
const prepared = prepareRestoredIndex(envelope, deps);
|
|
1118
|
+
const replacesIndex = deps.indexRegistry.has(indexName);
|
|
1119
|
+
requireRestoreMemory(indexName, footprintOf(envelope, prepared, replacesIndex), replacesIndex);
|
|
1120
|
+
const analysedNow = { ...prepared, storedRevision: prepared.language.revision };
|
|
1121
|
+
const staging = deps.durability?.manager.stageRestore?.(indexName) ?? null;
|
|
1122
|
+
try {
|
|
1123
|
+
await installRestoredIndex(
|
|
1124
|
+
indexName,
|
|
1125
|
+
await buildRestoredIndex(indexName, envelope, analysedNow, staging, deps),
|
|
1126
|
+
deps
|
|
1127
|
+
);
|
|
1128
|
+
} finally {
|
|
1129
|
+
await staging?.discard().catch(() => void 0);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// src/engine/snapshot/index.ts
|
|
1134
|
+
var NRSL_MAGIC_BYTES = 4;
|
|
1135
|
+
async function checkpointForArchive(deps) {
|
|
1136
|
+
const durable = deps.durability?.manager;
|
|
1137
|
+
if (durable?.openArchiveCheckpoint !== void 0) return durable.openArchiveCheckpoint(deps.indexName);
|
|
1138
|
+
return buildArchiveFromMemory({
|
|
1139
|
+
indexName: deps.indexName,
|
|
1140
|
+
metadata: indexMetadataOf(deps.indexName, deps.entry, deps.manager.partitionCount),
|
|
1141
|
+
manager: deps.manager,
|
|
1142
|
+
vectorIndexes: deps.manager.getVectorIndexes(),
|
|
1143
|
+
appliedSeqNo: (partitionId) => durable?.highestPersistedSeqNo(deps.indexName, partitionId) ?? 0,
|
|
1144
|
+
partitionId: null
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
async function createSnapshot(deps) {
|
|
1148
|
+
const config = await encodeIndexConfiguration(deps.entry);
|
|
1149
|
+
const checkpoint = await checkpointForArchive(deps);
|
|
1150
|
+
return archiveStream({ ...checkpoint, config, sourceIndexName: deps.indexName });
|
|
1151
|
+
}
|
|
1152
|
+
function requireSnapshotSource(data) {
|
|
1153
|
+
if (data instanceof Uint8Array) return data;
|
|
1154
|
+
if (data !== null && typeof data === "object") {
|
|
1155
|
+
if (typeof data.getReader === "function") return data;
|
|
1156
|
+
if (typeof data[Symbol.asyncIterator] === "function") {
|
|
1157
|
+
return data;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
throw new NarsilError(
|
|
1161
|
+
ErrorCodes.DOC_VALIDATION_FAILED,
|
|
1162
|
+
"Snapshot data must be a Uint8Array, a ReadableStream of bytes, or an async iterable of bytes"
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
async function readEarlierSnapshotFile(reader) {
|
|
1166
|
+
const length = HEADER_SIZE + readHeader(await reader.peek(HEADER_SIZE)).payloadLength;
|
|
1167
|
+
if (length > MAX_FILE_BYTES) {
|
|
1168
|
+
throw new NarsilError(
|
|
1169
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
1170
|
+
`The snapshot declares ${length} bytes, above the file size limit of ${MAX_FILE_BYTES}`,
|
|
1171
|
+
{ bytes: length }
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
const bytes = await reader.readExactly(length) ?? new Uint8Array(0);
|
|
1175
|
+
if (bytes.byteLength < length) {
|
|
1176
|
+
throw new NarsilError(
|
|
1177
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
1178
|
+
"The snapshot ends before the payload its header declares"
|
|
1179
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
const trailing = await reader.readExactly(1);
|
|
1182
|
+
if (trailing !== null && trailing.byteLength > 0) {
|
|
1183
|
+
throw new NarsilError(
|
|
1184
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
1185
|
+
"The snapshot holds bytes after the payload its header declares"
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
return bytes;
|
|
1189
|
+
}
|
|
1190
|
+
async function restoreFromSnapshot(indexName, data, deps) {
|
|
1191
|
+
const reader = createByteReader(requireSnapshotSource(data));
|
|
1192
|
+
const head = await reader.peek(NRSL_MAGIC_BYTES);
|
|
1193
|
+
if (head.byteLength >= NRSL_MAGIC_BYTES && hasNrslMagic(head)) {
|
|
1194
|
+
let bytes;
|
|
1195
|
+
try {
|
|
1196
|
+
bytes = await readEarlierSnapshotFile(reader);
|
|
1197
|
+
} finally {
|
|
1198
|
+
await reader.close();
|
|
1199
|
+
}
|
|
1200
|
+
await restoreEarlierSnapshot(indexName, bytes, deps);
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
if (head.byteLength === 0) {
|
|
1204
|
+
await reader.close();
|
|
1205
|
+
throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, "Snapshot data is empty");
|
|
1206
|
+
}
|
|
1207
|
+
await restoreArchive(indexName, reader, deps);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
export { checkpointForArchive, createSnapshot, restoreFromSnapshot };
|