@delali/narsil 0.3.1-next.86 → 0.3.1-next.88
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/dist/browser/chunk-3GZQKGVQ.mjs +2719 -0
- package/dist/browser/chunk-3ZRMZIH4.mjs +3959 -0
- package/dist/browser/chunk-FHFFWLEK.mjs +669 -0
- package/dist/browser/chunk-HOZW3PKP.mjs +9 -0
- package/dist/browser/chunk-JACCR3BJ.mjs +602 -0
- package/dist/browser/chunk-NQW2YXEX.mjs +346 -0
- package/dist/browser/chunk-RAHUQOJL.mjs +24103 -0
- package/dist/browser/durability-wiring-VSUBLUDK.mjs +3250 -0
- package/dist/browser/module-E25UDADM.mjs +2766 -0
- package/dist/browser/snapshot-5MXBEDXF.mjs +888 -0
- package/dist/browser/write-6SBYTS62.mjs +206 -0
- package/dist/{capabilities-CAdkp2P-.d.ts → capabilities-SJPttcgQ.d.ts} +2 -2
- package/dist/chunk-37CD3OKS.mjs +87 -0
- package/dist/{chunk-4VBG6PEH.mjs → chunk-A3UB2MXL.mjs} +175 -124
- package/dist/{chunk-OLXM65YH.mjs → chunk-AV4IJKD2.mjs} +1 -18
- package/dist/{chunk-LS5IRM23.mjs → chunk-BVOJIYRV.mjs} +2 -25
- package/dist/chunk-C7SLA6CM.mjs +19 -0
- package/dist/chunk-CL4OM7GB.mjs +522 -0
- package/dist/{chunk-KJ7LB3TR.mjs → chunk-CVQWQVFX.mjs} +3 -22
- package/dist/{chunk-4D6OH4EF.mjs → chunk-DCK4P5BI.mjs} +32 -32
- package/dist/chunk-DJHHF2L5.mjs +17 -0
- package/dist/{chunk-XPK3GB2P.mjs → chunk-EMXAYPTQ.mjs} +1776 -3336
- package/dist/chunk-FGMGUDHX.mjs +21 -0
- package/dist/{chunk-2453RJYK.mjs → chunk-J2BPXTD7.mjs} +167 -176
- package/dist/chunk-L5ORED7V.mjs +25 -0
- package/dist/chunk-MWJIAREY.mjs +614 -0
- package/dist/chunk-MXS5HWIH.mjs +515 -0
- package/dist/chunk-P36MUFEJ.mjs +10 -0
- package/dist/chunk-PR4O7CAP.mjs +18 -0
- package/dist/{chunk-ZCKPRCYI.mjs → chunk-Q5DC6WAB.mjs} +1 -1
- package/dist/chunk-QAMUC2BJ.mjs +1730 -0
- package/dist/{chunk-NFF5TDRG.mjs → chunk-QZN3MIJ3.mjs} +1 -16
- package/dist/chunk-R6BMMQXH.mjs +7316 -0
- package/dist/chunk-R7OSDAFK.mjs +44 -0
- package/dist/chunk-RVM7AODE.mjs +73 -0
- package/dist/chunk-S4LQDSUL.mjs +462 -0
- package/dist/{chunk-SREPGC6O.mjs → chunk-T6CNO72J.mjs} +1 -1
- package/dist/chunk-UKSUENHK.mjs +997 -0
- package/dist/{chunk-B3F7LZXM.mjs → chunk-ULRPNYAG.mjs} +1220 -2318
- package/dist/{chunk-GNYXCLJS.mjs → chunk-URGLSNKR.mjs} +4 -3
- package/dist/chunk-V7YUSKKZ.mjs +703 -0
- package/dist/chunk-VY4DXZ5P.mjs +631 -0
- package/dist/{chunk-XYDP7CCJ.mjs → chunk-X4SEXL4U.mjs} +54 -14
- package/dist/{chunk-RM6FRYEC.mjs → chunk-XSZVS4S3.mjs} +3 -2
- package/dist/chunk-Y2F66IQJ.mjs +74 -0
- package/dist/chunk-YCJLVNWR.mjs +262 -0
- package/dist/{client-CKUtkLz3.d.ts → client-BMK53IR2.d.ts} +3 -3
- package/dist/client.d.ts +8 -8
- package/dist/{config-CSDEPraV.d.ts → config-BUR-7eVQ.d.ts} +2 -2
- package/dist/{config-BuIkeM5C.d.ts → config-UJx1dyX1.d.ts} +2 -2
- package/dist/direct-executor-EGESD26S.mjs +18 -0
- package/dist/distribution/coordinator/etcd.d.ts +2 -2
- package/dist/distribution/coordinator/in-memory.d.ts +2 -2
- package/dist/distribution.d.ts +8 -8
- package/dist/distribution.mjs +35 -33
- package/dist/durability-wiring-ZLRQU6FG.mjs +2797 -0
- package/dist/{engine-DMNZJAUq.d.ts → engine-9X6W5naj.d.ts} +2 -2
- package/dist/{index-DzONZUKE.d.ts → index-vCMu8OeQ.d.ts} +1 -1
- package/dist/index.browser.mjs +2 -38128
- package/dist/index.d.ts +23 -9
- package/dist/index.mjs +18 -14
- package/dist/{memory-BPKNx9Tl.d.ts → memory-CV9NAxLY.d.ts} +1 -1
- package/dist/module-WIDYIJLY.mjs +1819 -0
- package/dist/partial-words.mjs +5 -3
- package/dist/pattern.mjs +3 -2
- package/dist/persistence/durability/checkpoint-worker.d.ts +1 -1
- package/dist/persistence/durability/checkpoint-worker.mjs +23 -13
- package/dist/react.d.ts +7 -7
- package/dist/{schema-DgyDijhf.d.ts → schema-DtsgmNfU.d.ts} +1 -1
- package/dist/server.d.ts +10 -10
- package/dist/server.mjs +14 -9
- package/dist/snapshot-22CUEYYW.mjs +469 -0
- package/dist/{tasks-DGyz586z.d.ts → tasks-BGaZJyoY.d.ts} +1 -1
- package/dist/{thread-EUUNJNKU.mjs → thread-ZP3UMIZT.mjs} +12 -9
- package/dist/vector/search-worker.d.ts +30 -3
- package/dist/vector/search-worker.mjs +6 -2
- package/dist/workers/entry.mjs +5 -3
- package/dist/write-PXDKPG2R.mjs +233 -0
- package/package.json +17 -8
- package/dist/chunk-IDLP54FH.mjs +0 -15198
- package/dist/direct-executor-SI2QV4YI.mjs +0 -19
- package/dist/simd-DW5AtJ6B.d.ts +0 -41
|
@@ -0,0 +1,888 @@
|
|
|
1
|
+
import { vectorsPerFile } from './chunk-3ZRMZIH4.mjs';
|
|
2
|
+
import { indexMetadataOf, writeCheckpointSegments, DEFAULT_COMPACTION_THRESHOLD, writeLiveVectors, commitCheckpointManifest, manifestKey, decodeSegmentManifest, SINGLE_NODE_PRIMARY_TERM, partitionContentsOf, manifestFileRefs, unpackIndexSnapshotEnvelope, encodeSegmentManifest, loadSegmentedCheckpoint, documentsOfPayloadV2, deserializePayloadV1, openManifestPayload, listedKeysOf, decodeManifestPayload, readSegmentFile, readVectorFile, readGraphParts } from './chunk-3GZQKGVQ.mjs';
|
|
3
|
+
import './chunk-JACCR3BJ.mjs';
|
|
4
|
+
import { encodeIndexConfiguration, createByteReader, hasNrslMagic, HEADER_SIZE, readHeader, raiseEarlierReleaseGraphSetting, restoredConfigFields, restoredEmbedding, getLanguage, validateSchema, validatePatternValueLimit, requireSurfaceFormsForPartialFields, validateVectorPromotion, validateVectorStorage, validateRequiredFieldsInSchema, resolveIndexAnalysis, validateEmbeddingConfig, loadVectorCodeFor, decodeEveryStoredDocument, parseVectorDimension, insertDocumentVectors, setNestedValue, decodeIndexConfiguration, flattenSchema } from './chunk-RAHUQOJL.mjs';
|
|
5
|
+
import { vectorsToBytes, VECTOR_FILE_PAYLOAD_VERSION, decodeVectorIndexParts, bytesToVectors } from './chunk-NQW2YXEX.mjs';
|
|
6
|
+
import { NarsilError, ErrorCodes, MAX_FILE_BYTES, BATCH_CHUNK_SIZE } from './chunk-FHFFWLEK.mjs';
|
|
7
|
+
import { decode } from '@msgpack/msgpack';
|
|
8
|
+
|
|
9
|
+
// src/persistence/archive/memory-store.ts
|
|
10
|
+
function joined(chunks) {
|
|
11
|
+
let total = 0;
|
|
12
|
+
for (const chunk of chunks) total += chunk.byteLength;
|
|
13
|
+
const bytes = new Uint8Array(total);
|
|
14
|
+
let offset = 0;
|
|
15
|
+
for (const chunk of chunks) {
|
|
16
|
+
bytes.set(chunk, offset);
|
|
17
|
+
offset += chunk.byteLength;
|
|
18
|
+
}
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
function memoryCheckpointStore() {
|
|
22
|
+
const files = /* @__PURE__ */ new Map();
|
|
23
|
+
return {
|
|
24
|
+
files,
|
|
25
|
+
read: async (key) => files.get(key) ?? null,
|
|
26
|
+
write: async (key, chunks) => {
|
|
27
|
+
files.set(key, joined(chunks));
|
|
28
|
+
},
|
|
29
|
+
remove: async (key) => {
|
|
30
|
+
files.delete(key);
|
|
31
|
+
},
|
|
32
|
+
list: async (prefix) => [...files.keys()].filter((key) => key.startsWith(prefix)).sort(),
|
|
33
|
+
byteLength: async (key) => files.get(key)?.byteLength ?? null
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/persistence/archive/from-memory.ts
|
|
38
|
+
function frozenPlan(plan) {
|
|
39
|
+
const files = [];
|
|
40
|
+
for (let index = 0; index < plan.newFiles; index++) files.push(plan.readNewFile(index));
|
|
41
|
+
return { ...plan, readNewFile: (index) => files[index] };
|
|
42
|
+
}
|
|
43
|
+
function partitionVectorPlan(vectorIndex, docIds) {
|
|
44
|
+
const held = [];
|
|
45
|
+
const vectors = [];
|
|
46
|
+
for (const docId of docIds) {
|
|
47
|
+
const vector = vectorIndex.getVector(docId);
|
|
48
|
+
if (vector === null) continue;
|
|
49
|
+
held.push(docId);
|
|
50
|
+
vectors.push(Float32Array.from(vector));
|
|
51
|
+
}
|
|
52
|
+
const capacity = vectorsPerFile(vectorIndex.dimension, null);
|
|
53
|
+
const files = [];
|
|
54
|
+
for (let start = 0; start < held.length; start += capacity) {
|
|
55
|
+
const slice = held.slice(start, start + capacity);
|
|
56
|
+
const packed = new Float32Array(slice.length * vectorIndex.dimension);
|
|
57
|
+
for (let i = 0; i < slice.length; i++) packed.set(vectors[start + i], i * vectorIndex.dimension);
|
|
58
|
+
const payload = {
|
|
59
|
+
v: VECTOR_FILE_PAYLOAD_VERSION,
|
|
60
|
+
fieldName: vectorIndex.fieldName,
|
|
61
|
+
dimension: vectorIndex.dimension,
|
|
62
|
+
docIds: slice,
|
|
63
|
+
codes: null,
|
|
64
|
+
vectors: vectorsToBytes(packed)
|
|
65
|
+
};
|
|
66
|
+
files.push({ payload, ordinals: new Int32Array(slice.length), dead: null });
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
unchanged: false,
|
|
70
|
+
kept: [],
|
|
71
|
+
keptFiles: [],
|
|
72
|
+
newFiles: files.length,
|
|
73
|
+
graphParts: null,
|
|
74
|
+
signature: { revision: 0, graphSize: -1, calibration: null },
|
|
75
|
+
readNewFile: (index) => files[index]
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function capture(input) {
|
|
79
|
+
const partitionIds = input.partitionId === null ? Array.from({ length: input.manager.partitionCount }, (_, partitionId) => partitionId) : [input.partitionId];
|
|
80
|
+
const targets = partitionIds.map((partitionId) => ({
|
|
81
|
+
partitionId,
|
|
82
|
+
lastSeqNo: input.appliedSeqNo(partitionId),
|
|
83
|
+
primaryTerm: SINGLE_NODE_PRIMARY_TERM
|
|
84
|
+
}));
|
|
85
|
+
const contents = partitionIds.map((partitionId) => partitionContentsOf(input.manager, partitionId));
|
|
86
|
+
const plans = /* @__PURE__ */ new Map();
|
|
87
|
+
const partitionDocIds = input.partitionId === null ? null : [...input.manager.getPartition(input.partitionId).docIds()];
|
|
88
|
+
for (const [fieldPath, vectorIndex] of input.vectorIndexes) {
|
|
89
|
+
plans.set(
|
|
90
|
+
fieldPath,
|
|
91
|
+
partitionDocIds === null ? frozenPlan(vectorIndex.planCheckpoint(null)) : partitionVectorPlan(vectorIndex, partitionDocIds)
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
return { targets, contents, plans };
|
|
95
|
+
}
|
|
96
|
+
async function buildArchiveFromMemory(input) {
|
|
97
|
+
if (input.partitionId === null) {
|
|
98
|
+
for (const vectorIndex of input.vectorIndexes.values()) await vectorIndex.completeGraph();
|
|
99
|
+
}
|
|
100
|
+
const captured = capture(input);
|
|
101
|
+
const store = memoryCheckpointStore();
|
|
102
|
+
const written = await writeCheckpointSegments({
|
|
103
|
+
store,
|
|
104
|
+
metadata: input.metadata,
|
|
105
|
+
targets: captured.targets,
|
|
106
|
+
compactionThreshold: DEFAULT_COMPACTION_THRESHOLD,
|
|
107
|
+
prior: null,
|
|
108
|
+
wholePartitions: captured.contents
|
|
109
|
+
});
|
|
110
|
+
const vectors = await writeLiveVectors({ store, indexName: input.indexName, plans: captured.plans, priorVectors: [] });
|
|
111
|
+
const refs = vectors.refs;
|
|
112
|
+
await commitCheckpointManifest(store, input.metadata, written, refs);
|
|
113
|
+
const manifestBytes = store.files.get(manifestKey(input.indexName));
|
|
114
|
+
const decoded = manifestBytes === void 0 ? null : await decodeSegmentManifest(manifestBytes, input.indexName);
|
|
115
|
+
if (manifestBytes === void 0 || decoded === null || decoded.kind !== "current") {
|
|
116
|
+
throw new NarsilError(
|
|
117
|
+
ErrorCodes.PERSISTENCE_SAVE_FAILED,
|
|
118
|
+
`The archive of index "${input.indexName}" holds no manifest`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
manifestBytes,
|
|
123
|
+
manifest: decoded.manifest,
|
|
124
|
+
readFile: async (ref) => {
|
|
125
|
+
const bytes = store.files.get(ref.key);
|
|
126
|
+
if (bytes === void 0) {
|
|
127
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_SAVE_FAILED, `The archive file "${ref.key}" is missing`, {
|
|
128
|
+
key: ref.key
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return bytes;
|
|
132
|
+
},
|
|
133
|
+
readRange: async (ref, offset, length) => {
|
|
134
|
+
const bytes = store.files.get(ref.key);
|
|
135
|
+
if (bytes === void 0 || offset + length > bytes.byteLength) {
|
|
136
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The archive file "${ref.key}" is missing`, {
|
|
137
|
+
key: ref.key
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return bytes.subarray(offset, offset + length);
|
|
141
|
+
},
|
|
142
|
+
release: () => store.files.clear()
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/persistence/archive/constants.ts
|
|
147
|
+
var MAX_PAX_HEADER_BYTES = 65536;
|
|
148
|
+
|
|
149
|
+
// src/persistence/archive/tar.ts
|
|
150
|
+
var TAR_BLOCK_BYTES = 512;
|
|
151
|
+
var NAME_OFFSET = 0;
|
|
152
|
+
var NAME_BYTES = 100;
|
|
153
|
+
var MODE_OFFSET = 100;
|
|
154
|
+
var OWNER_OFFSET = 108;
|
|
155
|
+
var GROUP_OFFSET = 116;
|
|
156
|
+
var ID_FIELD_BYTES = 8;
|
|
157
|
+
var SIZE_OFFSET = 124;
|
|
158
|
+
var SIZE_FIELD_BYTES = 12;
|
|
159
|
+
var SIZE_FIELD_DIGITS = 11;
|
|
160
|
+
var MTIME_OFFSET = 136;
|
|
161
|
+
var MTIME_FIELD_BYTES = 12;
|
|
162
|
+
var CHECKSUM_FIELD_OFFSET = 148;
|
|
163
|
+
var CHECKSUM_FIELD_BYTES = 8;
|
|
164
|
+
var CHECKSUM_DIGITS = 6;
|
|
165
|
+
var TYPEFLAG_OFFSET = 156;
|
|
166
|
+
var MAGIC_OFFSET = 257;
|
|
167
|
+
var MAGIC_BYTES = 6;
|
|
168
|
+
var VERSION_OFFSET = 263;
|
|
169
|
+
var VERSION_BYTES = 2;
|
|
170
|
+
var PREFIX_OFFSET = 345;
|
|
171
|
+
var PREFIX_BYTES = 155;
|
|
172
|
+
var MODE_OCTAL = "0000644";
|
|
173
|
+
var ZERO_OCTAL_7 = "0000000";
|
|
174
|
+
var ZERO_OCTAL_11 = "00000000000";
|
|
175
|
+
var REGULAR_FILE = 48;
|
|
176
|
+
var OLD_REGULAR_FILE = 0;
|
|
177
|
+
var PAX_EXTENDED_HEADER = 120;
|
|
178
|
+
var PAX_HEADER_NAME = "PaxHeader";
|
|
179
|
+
var encoder = new TextEncoder();
|
|
180
|
+
var decoder = new TextDecoder("utf-8", { fatal: true });
|
|
181
|
+
function writeString(block, offset, length, value) {
|
|
182
|
+
const bytes = encoder.encode(value);
|
|
183
|
+
block.set(bytes.subarray(0, length), offset);
|
|
184
|
+
}
|
|
185
|
+
function writeOctal(block, offset, digits, value) {
|
|
186
|
+
writeString(block, offset, digits, value.toString(8).padStart(digits, "0"));
|
|
187
|
+
}
|
|
188
|
+
function headerChecksum(block) {
|
|
189
|
+
let sum = 0;
|
|
190
|
+
const checksumEnd = CHECKSUM_FIELD_OFFSET + CHECKSUM_FIELD_BYTES;
|
|
191
|
+
for (let at = 0; at < TAR_BLOCK_BYTES; at++) {
|
|
192
|
+
sum += at >= CHECKSUM_FIELD_OFFSET && at < checksumEnd ? 32 : block[at];
|
|
193
|
+
}
|
|
194
|
+
return sum;
|
|
195
|
+
}
|
|
196
|
+
function ustarBlock(name, prefix, size, typeflag) {
|
|
197
|
+
const block = new Uint8Array(TAR_BLOCK_BYTES);
|
|
198
|
+
writeString(block, NAME_OFFSET, NAME_BYTES, name);
|
|
199
|
+
writeString(block, MODE_OFFSET, ID_FIELD_BYTES, MODE_OCTAL);
|
|
200
|
+
writeString(block, OWNER_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
|
|
201
|
+
writeString(block, GROUP_OFFSET, ID_FIELD_BYTES, ZERO_OCTAL_7);
|
|
202
|
+
writeOctal(block, SIZE_OFFSET, SIZE_FIELD_DIGITS, size);
|
|
203
|
+
writeString(block, MTIME_OFFSET, MTIME_FIELD_BYTES, ZERO_OCTAL_11);
|
|
204
|
+
block[TYPEFLAG_OFFSET] = typeflag;
|
|
205
|
+
writeString(block, MAGIC_OFFSET, MAGIC_BYTES, "ustar");
|
|
206
|
+
writeString(block, VERSION_OFFSET, VERSION_BYTES, "00");
|
|
207
|
+
writeString(block, PREFIX_OFFSET, PREFIX_BYTES, prefix);
|
|
208
|
+
const checksum = headerChecksum(block);
|
|
209
|
+
writeString(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_DIGITS, checksum.toString(8).padStart(CHECKSUM_DIGITS, "0"));
|
|
210
|
+
block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS] = 0;
|
|
211
|
+
block[CHECKSUM_FIELD_OFFSET + CHECKSUM_DIGITS + 1] = 32;
|
|
212
|
+
return block;
|
|
213
|
+
}
|
|
214
|
+
function splitForUstar(name) {
|
|
215
|
+
if (encoder.encode(name).byteLength <= NAME_BYTES) return { name, prefix: "" };
|
|
216
|
+
for (let slash = name.indexOf("/"); slash >= 0; slash = name.indexOf("/", slash + 1)) {
|
|
217
|
+
const prefix = name.slice(0, slash);
|
|
218
|
+
const rest = name.slice(slash + 1);
|
|
219
|
+
if (encoder.encode(prefix).byteLength <= PREFIX_BYTES && encoder.encode(rest).byteLength <= NAME_BYTES) {
|
|
220
|
+
return { name: rest, prefix };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
function paxRecord(key, value) {
|
|
226
|
+
const body = ` ${key}=${value}
|
|
227
|
+
`;
|
|
228
|
+
const bodyBytes = encoder.encode(body).byteLength;
|
|
229
|
+
let digits = 1;
|
|
230
|
+
while (String(bodyBytes + digits).length !== digits) digits += 1;
|
|
231
|
+
return `${bodyBytes + digits}${body}`;
|
|
232
|
+
}
|
|
233
|
+
function tarPadding(size) {
|
|
234
|
+
const remainder = size % TAR_BLOCK_BYTES;
|
|
235
|
+
return new Uint8Array(remainder === 0 ? 0 : TAR_BLOCK_BYTES - remainder);
|
|
236
|
+
}
|
|
237
|
+
function tarEntryHeaders(name, size) {
|
|
238
|
+
const split = splitForUstar(name);
|
|
239
|
+
if (split !== null) return [ustarBlock(split.name, split.prefix, size, REGULAR_FILE)];
|
|
240
|
+
const record = encoder.encode(paxRecord("path", name));
|
|
241
|
+
return [
|
|
242
|
+
ustarBlock(PAX_HEADER_NAME, "", record.byteLength, PAX_EXTENDED_HEADER),
|
|
243
|
+
record,
|
|
244
|
+
tarPadding(record.byteLength),
|
|
245
|
+
ustarBlock(name.slice(-NAME_BYTES).replace(/^[^/]*\//, ""), "", size, REGULAR_FILE)
|
|
246
|
+
];
|
|
247
|
+
}
|
|
248
|
+
function tarEnd() {
|
|
249
|
+
return new Uint8Array(TAR_BLOCK_BYTES * 2);
|
|
250
|
+
}
|
|
251
|
+
function invalidArchive(message, details) {
|
|
252
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `Invalid snapshot archive: ${message}`, details);
|
|
253
|
+
}
|
|
254
|
+
function readString(block, offset, length) {
|
|
255
|
+
let end = offset;
|
|
256
|
+
while (end < offset + length && block[end] !== 0) end++;
|
|
257
|
+
try {
|
|
258
|
+
return decoder.decode(block.subarray(offset, end));
|
|
259
|
+
} catch {
|
|
260
|
+
invalidArchive("an entry header holds a name that is not UTF-8");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function readOctal(block, offset, length, what) {
|
|
264
|
+
const text = readString(block, offset, length).trim();
|
|
265
|
+
if (!/^[0-7]+$/.test(text)) invalidArchive(`an entry header holds an invalid ${what}`);
|
|
266
|
+
const value = Number.parseInt(text, 8);
|
|
267
|
+
if (!Number.isSafeInteger(value)) invalidArchive(`an entry header holds an invalid ${what}`);
|
|
268
|
+
return value;
|
|
269
|
+
}
|
|
270
|
+
function isZeroBlock(block) {
|
|
271
|
+
for (let at = 0; at < block.length; at++) if (block[at] !== 0) return false;
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
function parseTarHeader(block) {
|
|
275
|
+
if (readOctal(block, CHECKSUM_FIELD_OFFSET, CHECKSUM_FIELD_BYTES, "checksum") !== headerChecksum(block)) {
|
|
276
|
+
invalidArchive("an entry header fails its checksum");
|
|
277
|
+
}
|
|
278
|
+
const typeflag = block[TYPEFLAG_OFFSET];
|
|
279
|
+
if (typeflag !== REGULAR_FILE && typeflag !== OLD_REGULAR_FILE && typeflag !== PAX_EXTENDED_HEADER) {
|
|
280
|
+
invalidArchive(`an entry has type ${String.fromCharCode(typeflag)}, while an archive holds regular files alone`);
|
|
281
|
+
}
|
|
282
|
+
const name = readString(block, NAME_OFFSET, NAME_BYTES);
|
|
283
|
+
const prefix = readString(block, PREFIX_OFFSET, PREFIX_BYTES);
|
|
284
|
+
return {
|
|
285
|
+
name: prefix.length > 0 ? `${prefix}/${name}` : name,
|
|
286
|
+
size: readOctal(block, SIZE_OFFSET, SIZE_FIELD_BYTES, "size"),
|
|
287
|
+
isPaxHeader: typeflag === PAX_EXTENDED_HEADER
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
var SPACE = 32;
|
|
291
|
+
var EQUALS = 61;
|
|
292
|
+
var NEWLINE = 10;
|
|
293
|
+
function decodeRecordText(bytes) {
|
|
294
|
+
try {
|
|
295
|
+
return decoder.decode(bytes);
|
|
296
|
+
} catch {
|
|
297
|
+
invalidArchive("a pax extended header is not UTF-8");
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function parsePaxRecords(body) {
|
|
301
|
+
const records = /* @__PURE__ */ new Map();
|
|
302
|
+
let at = 0;
|
|
303
|
+
while (at < body.length) {
|
|
304
|
+
const space = body.indexOf(SPACE, at);
|
|
305
|
+
if (space < 0) invalidArchive("a pax extended header holds a malformed record");
|
|
306
|
+
const length = Number.parseInt(decodeRecordText(body.subarray(at, space)), 10);
|
|
307
|
+
if (!Number.isSafeInteger(length) || length <= space - at || at + length > body.length) {
|
|
308
|
+
invalidArchive("a pax extended header holds a malformed record");
|
|
309
|
+
}
|
|
310
|
+
const record = body.subarray(space + 1, at + length);
|
|
311
|
+
const equals = record.indexOf(EQUALS);
|
|
312
|
+
if (equals < 0 || record[record.length - 1] !== NEWLINE) {
|
|
313
|
+
invalidArchive("a pax extended header holds a record without a value");
|
|
314
|
+
}
|
|
315
|
+
records.set(decodeRecordText(record.subarray(0, equals)), decodeRecordText(record.subarray(equals + 1, -1)));
|
|
316
|
+
at += length;
|
|
317
|
+
}
|
|
318
|
+
return records;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// src/persistence/archive/read.ts
|
|
322
|
+
var ARCHIVE_CONFIG_ENTRY = "config";
|
|
323
|
+
var ARCHIVE_MANIFEST_ENTRY = "manifest";
|
|
324
|
+
var SEGMENTS_MARKER = "/segments/";
|
|
325
|
+
var CHECKSUM_OFFSET = 14;
|
|
326
|
+
async function readBlock(reader) {
|
|
327
|
+
const block = await reader.readExactly(TAR_BLOCK_BYTES);
|
|
328
|
+
if (block === null) return null;
|
|
329
|
+
if (block.byteLength < TAR_BLOCK_BYTES) invalidArchive("the archive ends inside an entry header");
|
|
330
|
+
return block;
|
|
331
|
+
}
|
|
332
|
+
async function readPadded(reader, size) {
|
|
333
|
+
const body = await reader.readExactly(size) ?? new Uint8Array(0);
|
|
334
|
+
if (body.byteLength < size) invalidArchive("the archive ends inside an entry");
|
|
335
|
+
const remainder = size % TAR_BLOCK_BYTES;
|
|
336
|
+
if (remainder !== 0) {
|
|
337
|
+
const padding = await reader.readExactly(TAR_BLOCK_BYTES - remainder);
|
|
338
|
+
if (padding === null || padding.byteLength < TAR_BLOCK_BYTES - remainder) {
|
|
339
|
+
invalidArchive("the archive ends inside the padding of an entry");
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return body;
|
|
343
|
+
}
|
|
344
|
+
async function nextEntryHeader(reader) {
|
|
345
|
+
const block = await readBlock(reader);
|
|
346
|
+
if (block === null || isZeroBlock(block)) return null;
|
|
347
|
+
const header = parseTarHeader(block);
|
|
348
|
+
if (!header.isPaxHeader) return { name: header.name, size: header.size };
|
|
349
|
+
if (header.size > MAX_PAX_HEADER_BYTES) invalidArchive("a pax extended header is too long");
|
|
350
|
+
const records = parsePaxRecords(await readPadded(reader, header.size));
|
|
351
|
+
const next = await readBlock(reader);
|
|
352
|
+
if (next === null || isZeroBlock(next)) invalidArchive("a pax extended header precedes no entry");
|
|
353
|
+
const entry = parseTarHeader(next);
|
|
354
|
+
if (entry.isPaxHeader) invalidArchive("a pax extended header follows another");
|
|
355
|
+
const path = records.get("path");
|
|
356
|
+
const size = records.get("size");
|
|
357
|
+
const parsedSize = size === void 0 ? entry.size : Number.parseInt(size, 10);
|
|
358
|
+
if (!Number.isSafeInteger(parsedSize) || parsedSize < 0) invalidArchive("a pax extended header holds an invalid size");
|
|
359
|
+
return { name: path ?? entry.name, size: parsedSize };
|
|
360
|
+
}
|
|
361
|
+
async function readNamedEntry(reader, expected) {
|
|
362
|
+
const header = await nextEntryHeader(reader);
|
|
363
|
+
if (header === null) invalidArchive(`the archive ends before its ${expected} entry`);
|
|
364
|
+
if (header.name !== expected) invalidArchive(`the archive holds "${header.name}" where its ${expected} entry belongs`);
|
|
365
|
+
if (header.size > MAX_FILE_BYTES) invalidArchive(`the ${expected} entry passes the file size limit`);
|
|
366
|
+
return readPadded(reader, header.size);
|
|
367
|
+
}
|
|
368
|
+
function sourceIndexNameOf(keys) {
|
|
369
|
+
const first = keys[0];
|
|
370
|
+
if (first === void 0) return "archive";
|
|
371
|
+
const at = first.indexOf(SEGMENTS_MARKER);
|
|
372
|
+
if (at <= 0) invalidArchive(`the manifest lists the key "${first}" outside any index`);
|
|
373
|
+
return first.slice(0, at);
|
|
374
|
+
}
|
|
375
|
+
function headerChecksumOf(bytes) {
|
|
376
|
+
if (bytes.byteLength < HEADER_SIZE) return -1;
|
|
377
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(CHECKSUM_OFFSET, false);
|
|
378
|
+
}
|
|
379
|
+
async function readSnapshotArchive(reader, handlers) {
|
|
380
|
+
await handlers.config(await readNamedEntry(reader, ARCHIVE_CONFIG_ENTRY));
|
|
381
|
+
const raw = await openManifestPayload(await readNamedEntry(reader, ARCHIVE_MANIFEST_ENTRY));
|
|
382
|
+
const sourceIndexName = sourceIndexNameOf(listedKeysOf(raw));
|
|
383
|
+
const decoded = decodeManifestPayload(raw, sourceIndexName);
|
|
384
|
+
if (decoded.kind !== "current") invalidArchive("the manifest holds the layout of an earlier release");
|
|
385
|
+
const manifest = decoded.manifest;
|
|
386
|
+
await handlers.manifest(manifest, sourceIndexName);
|
|
387
|
+
const files = manifestFileRefs(manifest);
|
|
388
|
+
const prefix = `${sourceIndexName}/`;
|
|
389
|
+
const listedNames = new Set(files.map((file) => file.key.slice(prefix.length)));
|
|
390
|
+
const seen = /* @__PURE__ */ new Set();
|
|
391
|
+
for (const ref of files) {
|
|
392
|
+
const expected = ref.key.slice(prefix.length);
|
|
393
|
+
const header = await nextEntryHeader(reader);
|
|
394
|
+
if (header === null) invalidArchive(`the archive ends before it holds "${expected}"`);
|
|
395
|
+
if (header.name !== expected) {
|
|
396
|
+
const why = !listedNames.has(header.name) ? "that the manifest does not list" : seen.has(header.name) ? "twice" : "out of order";
|
|
397
|
+
invalidArchive(`the archive holds the entry "${header.name}" ${why}`, { entry: header.name });
|
|
398
|
+
}
|
|
399
|
+
if (header.size !== ref.bytes) {
|
|
400
|
+
invalidArchive(`the entry "${expected}" holds ${header.size} bytes where the manifest lists ${ref.bytes}`);
|
|
401
|
+
}
|
|
402
|
+
const bytes = await readPadded(reader, header.size);
|
|
403
|
+
if (headerChecksumOf(bytes) !== ref.checksum) {
|
|
404
|
+
invalidArchive(`the entry "${expected}" carries a checksum other than the manifest lists`, { entry: expected });
|
|
405
|
+
}
|
|
406
|
+
seen.add(expected);
|
|
407
|
+
await handlers.file(expected, ref, bytes);
|
|
408
|
+
}
|
|
409
|
+
const trailing = await nextEntryHeader(reader);
|
|
410
|
+
if (trailing !== null) {
|
|
411
|
+
invalidArchive(`the archive holds the entry "${trailing.name}" that the manifest does not list`, {
|
|
412
|
+
entry: trailing.name
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/persistence/archive/write.ts
|
|
418
|
+
function entryChunks(name, bytes) {
|
|
419
|
+
return [...tarEntryHeaders(name, bytes.byteLength), bytes, tarPadding(bytes.byteLength)].filter(
|
|
420
|
+
(chunk) => chunk.byteLength > 0
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
async function* archiveChunks(source) {
|
|
424
|
+
yield* entryChunks(ARCHIVE_CONFIG_ENTRY, source.config);
|
|
425
|
+
yield* entryChunks(ARCHIVE_MANIFEST_ENTRY, source.manifestBytes);
|
|
426
|
+
const prefix = `${source.sourceIndexName}/`;
|
|
427
|
+
for (const ref of manifestFileRefs(source.manifest)) {
|
|
428
|
+
yield* entryChunks(ref.key.slice(prefix.length), await source.readFile(ref));
|
|
429
|
+
}
|
|
430
|
+
yield tarEnd();
|
|
431
|
+
}
|
|
432
|
+
function archiveStream(source) {
|
|
433
|
+
const chunks = archiveChunks(source);
|
|
434
|
+
let released = false;
|
|
435
|
+
const release = () => {
|
|
436
|
+
if (released) return;
|
|
437
|
+
released = true;
|
|
438
|
+
source.release();
|
|
439
|
+
};
|
|
440
|
+
return new ReadableStream({
|
|
441
|
+
async pull(controller) {
|
|
442
|
+
try {
|
|
443
|
+
const step = await chunks.next();
|
|
444
|
+
if (step.done) {
|
|
445
|
+
release();
|
|
446
|
+
controller.close();
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
controller.enqueue(step.value);
|
|
450
|
+
} catch (error) {
|
|
451
|
+
release();
|
|
452
|
+
controller.error(error);
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
async cancel() {
|
|
456
|
+
release();
|
|
457
|
+
await chunks.return(void 0);
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// src/persistence/archive/validate.ts
|
|
463
|
+
function requireDimension(key, found, expected) {
|
|
464
|
+
if (expected === found) return;
|
|
465
|
+
throw new NarsilError(
|
|
466
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
467
|
+
`The vector file "${key}" holds vectors of ${found} dimensions where the schema gives ${String(expected)}`,
|
|
468
|
+
{ key, found, expected }
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
function requireSchemaOfManifest(key, schema, manifest) {
|
|
472
|
+
for (const [field, type] of Object.entries(schema)) {
|
|
473
|
+
const listed = manifest.schema[field];
|
|
474
|
+
if (listed === void 0 || listed === type) continue;
|
|
475
|
+
throw new NarsilError(
|
|
476
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
477
|
+
`The segment "${key}" gives field "${field}" the type "${type}", while the manifest gives it "${listed}"`,
|
|
478
|
+
{ key, field }
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
async function validateStagedCheckpoint(store, manifest) {
|
|
483
|
+
for (const partition of manifest.partitions) {
|
|
484
|
+
for (const ref of partition.segments) {
|
|
485
|
+
const contents = await readSegmentFile(store, ref);
|
|
486
|
+
requireSchemaOfManifest(ref.key, contents.schema, manifest);
|
|
487
|
+
decodeEveryStoredDocument(contents.arrays.documentTable);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
for (const field of manifest.vectors) {
|
|
491
|
+
const fieldType = manifest.schema[field.fieldPath];
|
|
492
|
+
const dimension = fieldType === void 0 ? null : parseVectorDimension(fieldType);
|
|
493
|
+
for (const file of field.files) {
|
|
494
|
+
const { payload } = await readVectorFile(store, file, field.fieldPath);
|
|
495
|
+
requireDimension(file.key, payload.dimension, dimension);
|
|
496
|
+
}
|
|
497
|
+
await readGraphParts(store, field);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/engine/snapshot/restore-setup.ts
|
|
502
|
+
function prepareRestoredIndex(configuration, deps, reject) {
|
|
503
|
+
const configFields = restoredConfigFields(configuration, reject);
|
|
504
|
+
const embedding = restoredEmbedding(configuration.embedding, reject);
|
|
505
|
+
const languageName = configuration.language ?? "";
|
|
506
|
+
const language = getLanguage(languageName);
|
|
507
|
+
const schema = validateSchema(configuration.schema);
|
|
508
|
+
validatePatternValueLimit(configFields.patternValueLimit);
|
|
509
|
+
requireSurfaceFormsForPartialFields(schema, configFields.surfaceForms);
|
|
510
|
+
validateVectorPromotion(configFields.vectorPromotion);
|
|
511
|
+
validateVectorStorage(configFields.vectorPromotion, deps.filesystemDurability);
|
|
512
|
+
if (configFields.required !== void 0 && configFields.required.length > 0) {
|
|
513
|
+
validateRequiredFieldsInSchema(configFields.required, schema);
|
|
514
|
+
}
|
|
515
|
+
const config = {
|
|
516
|
+
schema,
|
|
517
|
+
language: languageName,
|
|
518
|
+
...configFields,
|
|
519
|
+
...embedding !== void 0 ? {
|
|
520
|
+
embedding: {
|
|
521
|
+
fields: embedding.fields,
|
|
522
|
+
...embedding.adapter !== void 0 ? { adapter: embedding.adapter } : {}
|
|
523
|
+
}
|
|
524
|
+
} : {}
|
|
525
|
+
};
|
|
526
|
+
resolveIndexAnalysis(config);
|
|
527
|
+
const adapterName = embedding?.adapter ?? null;
|
|
528
|
+
let embeddingAdapter = null;
|
|
529
|
+
if (embedding !== void 0) {
|
|
530
|
+
const candidate = adapterName !== null ? deps.embeddingAdapters.get(adapterName) ?? null : deps.defaultEmbeddingAdapter;
|
|
531
|
+
if (candidate) {
|
|
532
|
+
validateEmbeddingConfig({ fields: embedding.fields, adapter: candidate }, schema, void 0);
|
|
533
|
+
embeddingAdapter = candidate;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
const storedRevision = typeof configuration.analysisRevision === "string" ? configuration.analysisRevision : null;
|
|
537
|
+
return { config, language, embeddingAdapter, adapterName, storedRevision };
|
|
538
|
+
}
|
|
539
|
+
async function createRestoredIndex(indexName, prepared, partitionCount, deps) {
|
|
540
|
+
const loadingVectorCode = loadVectorCodeFor(prepared.config.schema);
|
|
541
|
+
if (loadingVectorCode !== null) await loadingVectorCode;
|
|
542
|
+
if (deps.indexRegistry.has(indexName)) {
|
|
543
|
+
await deps.dropIndex(indexName);
|
|
544
|
+
}
|
|
545
|
+
deps.clearAnalysisStale(indexName);
|
|
546
|
+
if (prepared.storedRevision !== prepared.language.revision) {
|
|
547
|
+
deps.markAnalysisStale({
|
|
548
|
+
indexName,
|
|
549
|
+
language: prepared.language.name,
|
|
550
|
+
storedRevision: prepared.storedRevision,
|
|
551
|
+
currentRevision: prepared.language.revision
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
deps.executor.createIndex(indexName, prepared.config, prepared.language);
|
|
555
|
+
deps.indexRegistry.set(indexName, {
|
|
556
|
+
config: prepared.config,
|
|
557
|
+
language: prepared.language,
|
|
558
|
+
embeddingAdapter: prepared.embeddingAdapter,
|
|
559
|
+
embeddingAdapterName: prepared.adapterName,
|
|
560
|
+
vectorFieldPaths: deps.getVectorFieldPaths(prepared.config.schema),
|
|
561
|
+
indexUuid: null,
|
|
562
|
+
heldPartitions: null,
|
|
563
|
+
documentCount: 0,
|
|
564
|
+
partitionCount,
|
|
565
|
+
analysisRevision: prepared.storedRevision
|
|
566
|
+
});
|
|
567
|
+
await deps.indexState.registerOpen(indexName);
|
|
568
|
+
const release = await deps.indexState.acquire(indexName, false);
|
|
569
|
+
const manager = deps.requireManager(indexName);
|
|
570
|
+
while (manager.partitionCount < partitionCount) manager.addPartition();
|
|
571
|
+
return { manager, release };
|
|
572
|
+
}
|
|
573
|
+
async function abandonRestoredIndex(indexName, deps) {
|
|
574
|
+
try {
|
|
575
|
+
deps.executor.dropIndex(indexName);
|
|
576
|
+
} catch (_) {
|
|
577
|
+
}
|
|
578
|
+
deps.indexRegistry.delete(indexName);
|
|
579
|
+
deps.indexState.forget(indexName);
|
|
580
|
+
if (deps.durability) {
|
|
581
|
+
await deps.durability.manager.removeIndex(indexName).catch(() => void 0);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function recordRestoredCounts(indexName, manager, deps) {
|
|
585
|
+
const entry = deps.indexRegistry.get(indexName);
|
|
586
|
+
if (entry !== void 0) {
|
|
587
|
+
entry.documentCount = manager.countDocuments();
|
|
588
|
+
entry.partitionCount = manager.partitionCount;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/engine/snapshot/archive-restore.ts
|
|
593
|
+
function rejectConfiguration(message) {
|
|
594
|
+
throw new NarsilError(ErrorCodes.CONFIG_INVALID, `Invalid index configuration: ${message}`);
|
|
595
|
+
}
|
|
596
|
+
function renamed(manifest, sourceName, indexName) {
|
|
597
|
+
const rename = (key) => `${indexName}/${key.slice(sourceName.length + 1)}`;
|
|
598
|
+
return {
|
|
599
|
+
...manifest,
|
|
600
|
+
partitions: manifest.partitions.map((partition) => ({
|
|
601
|
+
...partition,
|
|
602
|
+
segments: partition.segments.map((segment) => ({ ...segment, key: rename(segment.key) }))
|
|
603
|
+
})),
|
|
604
|
+
vectors: manifest.vectors.map((field) => ({
|
|
605
|
+
...field,
|
|
606
|
+
files: field.files.map((file) => ({ ...file, key: rename(file.key) })),
|
|
607
|
+
graphParts: field.graphParts.map((part) => ({ ...part, key: rename(part.key) }))
|
|
608
|
+
}))
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
function requireSameSchema(prepared, manifest) {
|
|
612
|
+
const configured = flattenSchema(prepared.config.schema);
|
|
613
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(configured), ...Object.keys(manifest.schema)]);
|
|
614
|
+
for (const field of keys) {
|
|
615
|
+
if (configured[field] === manifest.schema[field]) continue;
|
|
616
|
+
throw new NarsilError(
|
|
617
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
618
|
+
`The archive's configuration gives field "${field}" another type than its manifest does`,
|
|
619
|
+
{ field }
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function partitionCountOf(manifest) {
|
|
624
|
+
let count = 1;
|
|
625
|
+
for (const partition of manifest.partitions) count = Math.max(count, partition.partitionId + 1);
|
|
626
|
+
return count;
|
|
627
|
+
}
|
|
628
|
+
function missingPart(what) {
|
|
629
|
+
throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The archive holds no ${what}`);
|
|
630
|
+
}
|
|
631
|
+
async function stageArchive(indexName, reader, staging, deps) {
|
|
632
|
+
const staged = { prepared: null, manifest: null };
|
|
633
|
+
await readSnapshotArchive(reader, {
|
|
634
|
+
config: async (bytes) => {
|
|
635
|
+
staged.prepared = prepareRestoredIndex(await decodeIndexConfiguration(bytes), deps, rejectConfiguration);
|
|
636
|
+
},
|
|
637
|
+
manifest: async (manifest2, sourceName) => {
|
|
638
|
+
if (staged.prepared === null) missingPart("configuration");
|
|
639
|
+
requireSameSchema(staged.prepared, manifest2);
|
|
640
|
+
staged.manifest = renamed(manifest2, sourceName, indexName);
|
|
641
|
+
},
|
|
642
|
+
file: async (entryName, _ref, bytes) => {
|
|
643
|
+
if (staged.manifest === null) missingPart("manifest");
|
|
644
|
+
await staging.write(`${indexName}/${entryName}`, [bytes]);
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
const { prepared, manifest } = staged;
|
|
648
|
+
if (prepared === null) missingPart("configuration");
|
|
649
|
+
if (manifest === null) missingPart("manifest");
|
|
650
|
+
await validateStagedCheckpoint(staging, manifest);
|
|
651
|
+
return { prepared, manifest };
|
|
652
|
+
}
|
|
653
|
+
async function replaceWithStaged(indexName, staged, staging, memory, deps) {
|
|
654
|
+
const { prepared, manifest } = staged;
|
|
655
|
+
const durable = deps.durability?.manager;
|
|
656
|
+
const created = await createRestoredIndex(indexName, prepared, partitionCountOf(manifest), deps);
|
|
657
|
+
try {
|
|
658
|
+
if (staging !== null && durable !== void 0) await durable.persistMetadata(indexName);
|
|
659
|
+
const store = staging === null ? memory : await staging.commit();
|
|
660
|
+
await store.write(manifestKey(indexName), (await encodeSegmentManifest(manifest)).chunks);
|
|
661
|
+
await loadSegmentedCheckpoint(
|
|
662
|
+
store,
|
|
663
|
+
indexName,
|
|
664
|
+
manifest,
|
|
665
|
+
{ manager: created.manager, vectorIndexes: created.manager.getVectorIndexes() },
|
|
666
|
+
true
|
|
667
|
+
);
|
|
668
|
+
recordRestoredCounts(indexName, created.manager, deps);
|
|
669
|
+
if (durable?.adoptRestoredCheckpoint !== void 0 && staging !== null) {
|
|
670
|
+
durable.adoptRestoredCheckpoint(indexName, manifest.checkpoint);
|
|
671
|
+
await durable.persistMetadata(indexName);
|
|
672
|
+
} else if (durable !== void 0) {
|
|
673
|
+
await durable.persistMetadata(indexName);
|
|
674
|
+
await durable.checkpoint(indexName);
|
|
675
|
+
}
|
|
676
|
+
await deps.announceIndexCreated(indexName, prepared.config);
|
|
677
|
+
return created;
|
|
678
|
+
} catch (error) {
|
|
679
|
+
created.release();
|
|
680
|
+
await abandonRestoredIndex(indexName, deps);
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
async function restoreArchive(indexName, reader, deps) {
|
|
685
|
+
const staging = deps.durability?.manager.stageRestore?.(indexName) ?? null;
|
|
686
|
+
const memory = memoryCheckpointStore();
|
|
687
|
+
try {
|
|
688
|
+
const staged = await stageArchive(indexName, reader, staging?.store ?? memory, deps);
|
|
689
|
+
const created = await replaceWithStaged(indexName, staged, staging, memory, deps);
|
|
690
|
+
created.release();
|
|
691
|
+
} finally {
|
|
692
|
+
await staging?.discard().catch(() => void 0);
|
|
693
|
+
await reader.close();
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function invalidSnapshot(message, details) {
|
|
697
|
+
throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, message, details);
|
|
698
|
+
}
|
|
699
|
+
async function decodeEarlierSnapshot(data) {
|
|
700
|
+
const payloadBytes = await unpackIndexSnapshotEnvelope(data);
|
|
701
|
+
let decoded;
|
|
702
|
+
try {
|
|
703
|
+
decoded = decode(payloadBytes);
|
|
704
|
+
} catch (err) {
|
|
705
|
+
invalidSnapshot(`Snapshot data is not a Narsil snapshot: ${err instanceof Error ? err.message : String(err)}`, {
|
|
706
|
+
bytes: data.length
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
710
|
+
invalidSnapshot("Snapshot data does not hold a snapshot envelope", { bytes: data.length });
|
|
711
|
+
}
|
|
712
|
+
const envelope = decoded;
|
|
713
|
+
if (envelope.version !== 1 && envelope.version !== 2) {
|
|
714
|
+
invalidSnapshot(`Unsupported snapshot version: ${envelope.version}. Expected version 1 or 2`, {
|
|
715
|
+
version: envelope.version
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
if (!envelope.schema || typeof envelope.schema !== "object")
|
|
719
|
+
invalidSnapshot("Invalid snapshot: missing or invalid schema");
|
|
720
|
+
if (!envelope.language || typeof envelope.language !== "string") {
|
|
721
|
+
invalidSnapshot("Invalid snapshot: missing or invalid language");
|
|
722
|
+
}
|
|
723
|
+
if (!Array.isArray(envelope.partitions)) invalidSnapshot("Invalid snapshot: missing partitions");
|
|
724
|
+
return { ...envelope, vectorPromotion: raiseEarlierReleaseGraphSetting(envelope.vectorPromotion) };
|
|
725
|
+
}
|
|
726
|
+
function vectorsOfSnapshot(envelope) {
|
|
727
|
+
const byDocument = /* @__PURE__ */ new Map();
|
|
728
|
+
for (const [fieldPath, rawParts] of Object.entries(envelope.vectorIndexes ?? {})) {
|
|
729
|
+
for (const part of decodeVectorIndexParts(rawParts)) {
|
|
730
|
+
const values = bytesToVectors(part.vectors);
|
|
731
|
+
for (let i = 0; i < part.docIds.length; i++) {
|
|
732
|
+
let fields = byDocument.get(part.docIds[i]);
|
|
733
|
+
if (fields === void 0) {
|
|
734
|
+
fields = /* @__PURE__ */ new Map();
|
|
735
|
+
byDocument.set(part.docIds[i], fields);
|
|
736
|
+
}
|
|
737
|
+
fields.set(fieldPath, values.slice(i * part.dimension, (i + 1) * part.dimension));
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return byDocument;
|
|
742
|
+
}
|
|
743
|
+
function documentsOfPartition(envelope, payload) {
|
|
744
|
+
return envelope.version === 2 ? documentsOfPayloadV2(payload).documents : deserializePayloadV1(payload).documents;
|
|
745
|
+
}
|
|
746
|
+
function withVectors(fields, vectors) {
|
|
747
|
+
if (vectors === void 0 || vectors.size === 0) return fields;
|
|
748
|
+
const nested = [...vectors.keys()].some((fieldPath) => fieldPath.includes("."));
|
|
749
|
+
const document = nested ? structuredClone(fields) : { ...fields };
|
|
750
|
+
for (const [fieldPath, vector] of vectors) setNestedValue(document, fieldPath, vector);
|
|
751
|
+
return document;
|
|
752
|
+
}
|
|
753
|
+
function insertRestoredDocument(manager, docId, fields, vectors) {
|
|
754
|
+
manager.insert(docId, fields, { skipClone: true });
|
|
755
|
+
if (vectors === void 0) return;
|
|
756
|
+
try {
|
|
757
|
+
insertDocumentVectors(docId, vectors, manager.getVectorIndexes(), manager.partitionIdOf(docId));
|
|
758
|
+
} catch (err) {
|
|
759
|
+
manager.remove(docId);
|
|
760
|
+
throw err;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
async function insertRestoredChunk(indexName, manager, chunk, vectors, deps) {
|
|
764
|
+
if (deps.durability === null) {
|
|
765
|
+
for (const [docId, fields] of chunk) insertRestoredDocument(manager, docId, fields, vectors.get(docId));
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
const mutations = chunk.map(([docId, fields]) => ({
|
|
769
|
+
docId,
|
|
770
|
+
document: withVectors(fields, vectors.get(docId)),
|
|
771
|
+
apply: () => insertRestoredDocument(manager, docId, fields, vectors.get(docId))
|
|
772
|
+
}));
|
|
773
|
+
for (const outcome of await deps.durability.recordMutationBatch(indexName, mutations)) {
|
|
774
|
+
if (!outcome.ok) throw outcome.error;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
async function insertSnapshotDocuments(indexName, envelope, manager, deps) {
|
|
778
|
+
const vectors = vectorsOfSnapshot(envelope);
|
|
779
|
+
for (const payload of envelope.partitions ?? []) {
|
|
780
|
+
const documents = Object.entries(documentsOfPartition(envelope, payload)).map(
|
|
781
|
+
([docId, stored]) => [docId, stored.fields]
|
|
782
|
+
);
|
|
783
|
+
for (let start = 0; start < documents.length; start += BATCH_CHUNK_SIZE) {
|
|
784
|
+
await insertRestoredChunk(indexName, manager, documents.slice(start, start + BATCH_CHUNK_SIZE), vectors, deps);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
for (const vectorIndex of manager.getVectorIndexes().values()) vectorIndex.scheduleBuild();
|
|
788
|
+
}
|
|
789
|
+
async function restoreEarlierSnapshot(indexName, data, deps) {
|
|
790
|
+
const envelope = await decodeEarlierSnapshot(data);
|
|
791
|
+
const prepared = prepareRestoredIndex(envelope, deps);
|
|
792
|
+
const analysedNow = { ...prepared, storedRevision: prepared.language.revision };
|
|
793
|
+
const partitionCount = envelope.partitions?.length ?? 0;
|
|
794
|
+
const { manager, release } = await createRestoredIndex(indexName, analysedNow, partitionCount, deps);
|
|
795
|
+
try {
|
|
796
|
+
await insertSnapshotDocuments(indexName, envelope, manager, deps);
|
|
797
|
+
recordRestoredCounts(indexName, manager, deps);
|
|
798
|
+
if (deps.durability) {
|
|
799
|
+
await deps.durability.manager.persistMetadata(indexName);
|
|
800
|
+
await deps.durability.manager.checkpoint(indexName);
|
|
801
|
+
}
|
|
802
|
+
await deps.announceIndexCreated(indexName, prepared.config);
|
|
803
|
+
} catch (err) {
|
|
804
|
+
await abandonRestoredIndex(indexName, deps);
|
|
805
|
+
throw err;
|
|
806
|
+
} finally {
|
|
807
|
+
release();
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/engine/snapshot/index.ts
|
|
812
|
+
var NRSL_MAGIC_BYTES = 4;
|
|
813
|
+
async function checkpointForArchive(deps) {
|
|
814
|
+
const durable = deps.durability?.manager;
|
|
815
|
+
if (durable?.openArchiveCheckpoint !== void 0) return durable.openArchiveCheckpoint(deps.indexName);
|
|
816
|
+
return buildArchiveFromMemory({
|
|
817
|
+
indexName: deps.indexName,
|
|
818
|
+
metadata: indexMetadataOf(deps.indexName, deps.entry, deps.manager.partitionCount),
|
|
819
|
+
manager: deps.manager,
|
|
820
|
+
vectorIndexes: deps.manager.getVectorIndexes(),
|
|
821
|
+
appliedSeqNo: (partitionId) => durable?.highestPersistedSeqNo(deps.indexName, partitionId) ?? 0,
|
|
822
|
+
partitionId: null
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
async function createSnapshot(deps) {
|
|
826
|
+
const config = await encodeIndexConfiguration(deps.entry);
|
|
827
|
+
const checkpoint = await checkpointForArchive(deps);
|
|
828
|
+
return archiveStream({ ...checkpoint, config, sourceIndexName: deps.indexName });
|
|
829
|
+
}
|
|
830
|
+
function requireSnapshotSource(data) {
|
|
831
|
+
if (data instanceof Uint8Array) return data;
|
|
832
|
+
if (data !== null && typeof data === "object") {
|
|
833
|
+
if (typeof data.getReader === "function") return data;
|
|
834
|
+
if (typeof data[Symbol.asyncIterator] === "function") {
|
|
835
|
+
return data;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
throw new NarsilError(
|
|
839
|
+
ErrorCodes.DOC_VALIDATION_FAILED,
|
|
840
|
+
"Snapshot data must be a Uint8Array, a ReadableStream of bytes, or an async iterable of bytes"
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
async function readEarlierSnapshotFile(reader) {
|
|
844
|
+
const length = HEADER_SIZE + readHeader(await reader.peek(HEADER_SIZE)).payloadLength;
|
|
845
|
+
if (length > MAX_FILE_BYTES) {
|
|
846
|
+
throw new NarsilError(
|
|
847
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
848
|
+
`The snapshot declares ${length} bytes, above the file size limit of ${MAX_FILE_BYTES}`,
|
|
849
|
+
{ bytes: length }
|
|
850
|
+
);
|
|
851
|
+
}
|
|
852
|
+
const bytes = await reader.readExactly(length) ?? new Uint8Array(0);
|
|
853
|
+
if (bytes.byteLength < length) {
|
|
854
|
+
throw new NarsilError(
|
|
855
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
856
|
+
"The snapshot ends before the payload its header declares"
|
|
857
|
+
);
|
|
858
|
+
}
|
|
859
|
+
const trailing = await reader.readExactly(1);
|
|
860
|
+
if (trailing !== null && trailing.byteLength > 0) {
|
|
861
|
+
throw new NarsilError(
|
|
862
|
+
ErrorCodes.PERSISTENCE_LOAD_FAILED,
|
|
863
|
+
"The snapshot holds bytes after the payload its header declares"
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
return bytes;
|
|
867
|
+
}
|
|
868
|
+
async function restoreFromSnapshot(indexName, data, deps) {
|
|
869
|
+
const reader = createByteReader(requireSnapshotSource(data));
|
|
870
|
+
const head = await reader.peek(NRSL_MAGIC_BYTES);
|
|
871
|
+
if (head.byteLength >= NRSL_MAGIC_BYTES && hasNrslMagic(head)) {
|
|
872
|
+
let bytes;
|
|
873
|
+
try {
|
|
874
|
+
bytes = await readEarlierSnapshotFile(reader);
|
|
875
|
+
} finally {
|
|
876
|
+
await reader.close();
|
|
877
|
+
}
|
|
878
|
+
await restoreEarlierSnapshot(indexName, bytes, deps);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (head.byteLength === 0) {
|
|
882
|
+
await reader.close();
|
|
883
|
+
throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, "Snapshot data is empty");
|
|
884
|
+
}
|
|
885
|
+
await restoreArchive(indexName, reader, deps);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export { checkpointForArchive, createSnapshot, restoreFromSnapshot };
|