@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.
Files changed (165) hide show
  1. package/README.md +9 -8
  2. package/dist/adapters/filesystem.d.ts +1 -1
  3. package/dist/adapters/filesystem.mjs +1 -1
  4. package/dist/adapters/indexeddb.d.ts +1 -1
  5. package/dist/adapters/indexeddb.mjs +1 -1
  6. package/dist/adapters/memory.d.ts +1 -1
  7. package/dist/{adapters-79OIa4xm.d.ts → adapters-BQFQ4PRz.d.ts} +27 -1
  8. package/dist/browser/chunk-BDOSMEEP.mjs +493 -0
  9. package/dist/browser/chunk-EJDUFWSO.mjs +602 -0
  10. package/dist/browser/chunk-HOZW3PKP.mjs +9 -0
  11. package/dist/browser/chunk-JOVZ6HMT.mjs +4358 -0
  12. package/dist/browser/chunk-JPTQZWJQ.mjs +10 -0
  13. package/dist/browser/chunk-KPJMDPHG.mjs +24558 -0
  14. package/dist/browser/chunk-PGIM3HIM.mjs +2743 -0
  15. package/dist/browser/chunk-RHG4O77A.mjs +206 -0
  16. package/dist/browser/chunk-RIJSLY2I.mjs +360 -0
  17. package/dist/browser/durability-wiring-SRUYT3VV.mjs +3875 -0
  18. package/dist/browser/module-CBB2ETYP.mjs +3111 -0
  19. package/dist/browser/release-76MXRPGV.mjs +33 -0
  20. package/dist/browser/replace-RURXTGVG.mjs +57 -0
  21. package/dist/browser/restore-queue-EEZQO6RF.mjs +35 -0
  22. package/dist/browser/runtime-7ZAHCHWR.mjs +557 -0
  23. package/dist/browser/snapshot-OAAA5UJ7.mjs +1210 -0
  24. package/dist/browser/write-7D6VIK6O.mjs +208 -0
  25. package/dist/{capabilities-DSsOGz6F.d.ts → capabilities-DiGlB6Sr.d.ts} +68 -7
  26. package/dist/chunk-2RIRGOUL.mjs +113 -0
  27. package/dist/chunk-37CD3OKS.mjs +87 -0
  28. package/dist/chunk-44W3CBNG.mjs +7 -0
  29. package/dist/chunk-46D6JQIG.mjs +426 -0
  30. package/dist/{chunk-VMRR3DQU.mjs → chunk-5JNA5SKS.mjs} +546 -35
  31. package/dist/chunk-747OHOUA.mjs +11 -0
  32. package/dist/chunk-75XIEF6H.mjs +126 -0
  33. package/dist/chunk-7X5JST5L.mjs +114 -0
  34. package/dist/chunk-BOFBLJFZ.mjs +209 -0
  35. package/dist/{chunk-USKFU7J5.mjs → chunk-BWJVNZPR.mjs} +8 -1
  36. package/dist/chunk-C7SLA6CM.mjs +19 -0
  37. package/dist/{chunk-POWOTUKJ.mjs → chunk-CQUMNIIG.mjs} +3 -6
  38. package/dist/chunk-CVXLLEQ3.mjs +1011 -0
  39. package/dist/chunk-DJHHF2L5.mjs +17 -0
  40. package/dist/chunk-E74YLAIG.mjs +24 -0
  41. package/dist/{chunk-UXNWQZST.mjs → chunk-EMRMGYRE.mjs} +236 -18
  42. package/dist/chunk-EWZLIYHV.mjs +57 -0
  43. package/dist/chunk-GBEEG5AN.mjs +35 -0
  44. package/dist/chunk-GES7U2PM.mjs +68 -0
  45. package/dist/chunk-HJSN7UYG.mjs +10 -0
  46. package/dist/chunk-HLPRHOSO.mjs +17 -0
  47. package/dist/chunk-HMFNFVP7.mjs +14 -0
  48. package/dist/chunk-J5QP52HA.mjs +1751 -0
  49. package/dist/{chunk-YNVIUGF5.mjs → chunk-JZVARCRZ.mjs} +3 -28
  50. package/dist/chunk-KOKM4PQN.mjs +52 -0
  51. package/dist/{chunk-B2TFROFX.mjs → chunk-KWTW6VTG.mjs} +465 -250
  52. package/dist/chunk-KZ3NX2P7.mjs +21 -0
  53. package/dist/chunk-L5ORED7V.mjs +25 -0
  54. package/dist/{chunk-THYRHHO2.mjs → chunk-LGAMKHA2.mjs} +2009 -2351
  55. package/dist/chunk-LKOB5COA.mjs +117 -0
  56. package/dist/chunk-LPQOEU5M.mjs +96 -0
  57. package/dist/{chunk-3LHGNRYE.mjs → chunk-LXWDQLTW.mjs} +7 -2
  58. package/dist/{chunk-L6TNPLAR.mjs → chunk-OEYI3KRB.mjs} +270 -108
  59. package/dist/chunk-OM362BRO.mjs +948 -0
  60. package/dist/chunk-OZDFA4WC.mjs +67 -0
  61. package/dist/chunk-P36MUFEJ.mjs +10 -0
  62. package/dist/chunk-PC2G76VW.mjs +2540 -0
  63. package/dist/{chunk-GCM3JFVA.mjs → chunk-PNEYIHA4.mjs} +11 -2
  64. package/dist/chunk-PNFKUCG3.mjs +1130 -0
  65. package/dist/chunk-Q6XWVUZX.mjs +44 -0
  66. package/dist/chunk-R27EMH5M.mjs +617 -0
  67. package/dist/{chunk-YMZCMH5M.mjs → chunk-R6A773WK.mjs} +19 -24
  68. package/dist/chunk-RF7PLG43.mjs +106 -0
  69. package/dist/chunk-RFBLQLLZ.mjs +16 -0
  70. package/dist/{chunk-Y3L5MDRV.mjs → chunk-RFVUDM5E.mjs} +17 -2
  71. package/dist/chunk-S7FL6UAH.mjs +521 -0
  72. package/dist/chunk-S7GNDRPS.mjs +651 -0
  73. package/dist/chunk-SP3NM3ZG.mjs +3537 -0
  74. package/dist/chunk-U476IXKQ.mjs +10 -0
  75. package/dist/chunk-UA3AUGNV.mjs +462 -0
  76. package/dist/chunk-UTG5YNXV.mjs +507 -0
  77. package/dist/chunk-VI4R6W25.mjs +8484 -0
  78. package/dist/chunk-WQBCBKY3.mjs +8 -0
  79. package/dist/{chunk-24RXHMEL.mjs → chunk-WVCOCKBU.mjs} +3794 -7570
  80. package/dist/chunk-X5CV2E2B.mjs +1 -0
  81. package/dist/chunk-XADZPPZI.mjs +614 -0
  82. package/dist/chunk-YEEQHT4V.mjs +212 -0
  83. package/dist/chunk-YTJCGKM4.mjs +56 -0
  84. package/dist/chunk-YYQIODMF.mjs +275 -0
  85. package/dist/chunk-ZI34TVOA.mjs +144 -0
  86. package/dist/{chunk-OOSIDHA3.mjs → chunk-ZKWYWW4Y.mjs} +1 -1
  87. package/dist/chunk-ZM7KU4YW.mjs +35 -0
  88. package/dist/{client-BQK6Tf6A.d.ts → client-BOStAkc5.d.ts} +160 -37
  89. package/dist/client.d.ts +11 -10
  90. package/dist/client.mjs +209 -45
  91. package/dist/{config-DmXULPa-.d.ts → config-Cjvzbs_j.d.ts} +51 -3
  92. package/dist/config-DffQlmRq.d.ts +421 -0
  93. package/dist/direct-executor-ZD64PPEZ.mjs +24 -0
  94. package/dist/distribution/coordinator/etcd.d.ts +79 -18
  95. package/dist/distribution/coordinator/etcd.mjs +553 -109
  96. package/dist/distribution/coordinator/in-memory.d.ts +4 -3
  97. package/dist/distribution/coordinator/in-memory.mjs +22 -3
  98. package/dist/distribution/transport/grpc.d.ts +2 -2
  99. package/dist/distribution/transport/grpc.mjs +79 -14
  100. package/dist/distribution/transport/in-memory.d.ts +2 -2
  101. package/dist/distribution/transport/in-memory.mjs +12 -7
  102. package/dist/distribution/transport/tcp.d.ts +2 -2
  103. package/dist/distribution/transport/tcp.mjs +50 -28
  104. package/dist/distribution.d.ts +144 -23
  105. package/dist/distribution.mjs +14479 -8173
  106. package/dist/durability-wiring-FEUBR5BT.mjs +3330 -0
  107. package/dist/embeddings/openai.d.ts +2 -2
  108. package/dist/embeddings/openai.mjs +22 -133
  109. package/dist/{engine-CIOyFozK.d.ts → engine-rC0vjjY-.d.ts} +165 -141
  110. package/dist/{memory-yFaVn2xZ.d.ts → events-DqOIg5xa.d.ts} +645 -136
  111. package/dist/{types-DAK7mnUZ.d.ts → index-Bkdt8nDw.d.ts} +182 -45
  112. package/dist/index.browser.mjs +4 -32180
  113. package/dist/index.d.ts +91 -20
  114. package/dist/index.mjs +33 -16
  115. package/dist/invalidation/broadcast-channel.d.ts +1 -1
  116. package/dist/invalidation/filesystem.d.ts +1 -1
  117. package/dist/invalidation/filesystem.mjs +2 -1
  118. package/dist/invalidation/noop.d.ts +1 -1
  119. package/dist/module-3S65MVCM.mjs +2151 -0
  120. package/dist/partial-words-DTIHO8G4.d.ts +19 -0
  121. package/dist/partial-words.d.ts +22 -0
  122. package/dist/partial-words.mjs +17 -0
  123. package/dist/pattern-Cledccbl.d.ts +18 -0
  124. package/dist/pattern.d.ts +22 -0
  125. package/dist/pattern.mjs +12 -0
  126. package/dist/persistence/durability/checkpoint-worker.d.ts +119 -72
  127. package/dist/persistence/durability/checkpoint-worker.mjs +51 -18
  128. package/dist/react.d.ts +279 -183
  129. package/dist/react.mjs +201 -48
  130. package/dist/release-BH3DKW3T.mjs +33 -0
  131. package/dist/replace-CEO5KJJ3.mjs +57 -0
  132. package/dist/rerank-K7C4WZFG.mjs +60 -0
  133. package/dist/rerankers/http.d.ts +50 -0
  134. package/dist/rerankers/http.mjs +104 -0
  135. package/dist/restore-queue-KQHA7ZV2.mjs +35 -0
  136. package/dist/runtime-6Y4ZYXOG.mjs +177 -0
  137. package/dist/{schema-d5Afu03A.d.ts → schema-4W_7tk1f.d.ts} +81 -11
  138. package/dist/server.d.ts +13 -12
  139. package/dist/server.mjs +611 -80
  140. package/dist/snapshot-QGZPODM5.mjs +799 -0
  141. package/dist/synonyms-CpOAHPa-.d.ts +52 -0
  142. package/dist/synonyms.d.ts +22 -0
  143. package/dist/synonyms.mjs +12 -0
  144. package/dist/{tasks-CH2Dod8w.d.ts → tasks-CwPTz-tP.d.ts} +10 -3
  145. package/dist/thread-N3IUGUS3.mjs +697 -0
  146. package/dist/{types-BQDlIvfS.d.ts → types-2qoitTXg.d.ts} +1 -1
  147. package/dist/{types-D5OwhtsQ.d.ts → types-Cz5okLml.d.ts} +2 -2
  148. package/dist/vector/search-worker.d.ts +46 -4
  149. package/dist/vector/search-worker.mjs +21 -11
  150. package/dist/workers/entry.mjs +9 -6
  151. package/dist/write-U5RI7MAX.mjs +241 -0
  152. package/package.json +55 -9
  153. package/dist/chunk-3L4U6EJQ.mjs +0 -49
  154. package/dist/chunk-IFBKLBGB.mjs +0 -7
  155. package/dist/chunk-ORBLD3EL.mjs +0 -6
  156. package/dist/chunk-U7KYW4BA.mjs +0 -135
  157. package/dist/chunk-ZJ4CSAB2.mjs +0 -13
  158. package/dist/chunk-ZNZBXMP5.mjs +0 -2117
  159. package/dist/chunk-ZZT3EAUC.mjs +0 -11168
  160. package/dist/config-BhldZgaK.d.ts +0 -194
  161. package/dist/direct-executor-ALAVE7FC.mjs +0 -12
  162. package/dist/serialization/crc32-worker.d.ts +0 -20
  163. package/dist/serialization/crc32-worker.mjs +0 -62
  164. package/dist/simd-DW5AtJ6B.d.ts +0 -41
  165. package/dist/thread-DYHEQRVY.mjs +0 -402
@@ -0,0 +1,2743 @@
1
+ import { KEYWORD_SEGMENT_ENVELOPE_VERSION, decodeKeywordSegment, restoreVectorFields, KEYWORD_SEGMENT_PAYLOAD_VERSION, littleEndianBytes } from './chunk-EJDUFWSO.mjs';
2
+ import { VERSION, rulesOfStoredSynonyms, flattenSchema, packChecksummedEnvelope, openChecksummedEnvelope, requireValidFieldTypes, isCompositePartition, crc32, reconstructSchemaFromMetadata, extractVectorFieldsFromSchema, readHeader, HEADER_SIZE, engineVersionParts, writeHeader, partialFieldsOf, getLanguage, decodeEveryStoredDocument, createSharedFrozenSegment, shareSegmentArrays, VECTOR_PATTERN, isQuantizationMode, isStorageMode, survivorDocumentsOf, partitionStateOf, freezeSegmentShared, createFrozenSegment, createPartitionManager, createPartitionRouter, buildSegmentPayload, resolvePartitionInsertOptions, fnv1a, selectionKeeps, decodeMapWithoutFields, prepareDocumentVectors, messagePackUpperBoundBytes, segmentArraysOf, mergeSegmentContents, resolveIndexAnalysis } from './chunk-KPJMDPHG.mjs';
3
+ import { decodeVectorGraphPartPayload, assembleGraphParts, decodeVectorFilePayload, countDead, VECTOR_FILE_MAX_VECTORS, deadBytesFor } from './chunk-RIJSLY2I.mjs';
4
+ import { compareCodePoints, MAX_FILE_BYTES, VALID_HNSW_METRICS } from './chunk-BDOSMEEP.mjs';
5
+ import { NarsilError, ErrorCodes } from './chunk-RHG4O77A.mjs';
6
+ import { decode, encode } from '@msgpack/msgpack';
7
+
8
+ // src/engine/durability-metadata.ts
9
+ function metadataFromConfig(indexName, config, partitionCount, documentCount) {
10
+ const metadata = {
11
+ indexName,
12
+ schema: config.schema,
13
+ language: config.language,
14
+ partitionCount: partitionCount ?? config.partitionCount,
15
+ bm25Params: { k1: config.k1, b: config.b },
16
+ createdAt: Date.now(),
17
+ engineVersion: VERSION
18
+ };
19
+ metadata.documentCount = documentCount ?? config.documentCount;
20
+ if (config.embedding) {
21
+ metadata.embedding = config.embedding;
22
+ }
23
+ if (config.surfaceForms !== void 0) {
24
+ metadata.surfaceForms = config.surfaceForms;
25
+ }
26
+ if (config.analysisRevision !== void 0) {
27
+ metadata.analysisRevision = config.analysisRevision;
28
+ }
29
+ if (config.tokenizer !== void 0) {
30
+ metadata.tokenizer = config.tokenizer;
31
+ }
32
+ if (config.stopWords !== void 0) {
33
+ metadata.stopWords = config.stopWords;
34
+ }
35
+ if (config.stopWordList !== void 0) {
36
+ metadata.stopWordList = config.stopWordList;
37
+ }
38
+ if (config.partitionLimits !== void 0) {
39
+ metadata.partitionLimits = config.partitionLimits;
40
+ }
41
+ if (config.defaultScoring !== void 0) {
42
+ metadata.defaultScoring = config.defaultScoring;
43
+ }
44
+ if (config.trackPositions !== void 0) {
45
+ metadata.trackPositions = config.trackPositions;
46
+ }
47
+ if (config.strict !== void 0) {
48
+ metadata.strict = config.strict;
49
+ }
50
+ if (config.required !== void 0) {
51
+ metadata.required = config.required;
52
+ }
53
+ if (config.vectorPromotion !== void 0) {
54
+ metadata.vectorPromotion = config.vectorPromotion;
55
+ }
56
+ if (config.patternValueLimit !== void 0) {
57
+ metadata.patternValueLimit = config.patternValueLimit;
58
+ }
59
+ if (config.indexUuid !== void 0) {
60
+ metadata.indexUuid = config.indexUuid;
61
+ }
62
+ if (config.synonyms !== void 0) {
63
+ metadata.synonyms = config.synonyms;
64
+ }
65
+ if (config.heldPartitions !== void 0) {
66
+ metadata.heldPartitions = config.heldPartitions;
67
+ }
68
+ return metadata;
69
+ }
70
+ function metadataConfigOf(entry) {
71
+ const embedding = entry.config.embedding ? {
72
+ fields: entry.config.embedding.fields,
73
+ ...entry.embeddingAdapterName !== null ? { adapter: entry.embeddingAdapterName } : {}
74
+ } : void 0;
75
+ return {
76
+ ...entry.indexUuid !== null ? { indexUuid: entry.indexUuid } : {},
77
+ ...entry.heldPartitions !== null ? { heldPartitions: entry.heldPartitions } : {},
78
+ documentCount: entry.documentCount,
79
+ partitionCount: entry.partitionCount,
80
+ schema: flattenSchema(entry.config.schema),
81
+ language: entry.language.name,
82
+ k1: entry.config.bm25?.k1 ?? 1.2,
83
+ b: entry.config.bm25?.b ?? 0.75,
84
+ ...embedding !== void 0 ? { embedding } : {},
85
+ surfaceForms: entry.config.surfaceForms !== false,
86
+ ...entry.analysisRevision !== null ? { analysisRevision: entry.analysisRevision } : {},
87
+ ...typeof entry.config.tokenizer === "string" ? { tokenizer: entry.config.tokenizer } : {},
88
+ ...typeof entry.config.stopWords === "string" ? { stopWords: entry.config.stopWords } : {},
89
+ ...entry.config.stopWords instanceof Set ? { stopWordList: [...entry.config.stopWords].sort(compareCodePoints) } : {},
90
+ ...entry.config.partitions !== void 0 ? { partitionLimits: entry.config.partitions } : {},
91
+ ...entry.config.defaultScoring !== void 0 ? { defaultScoring: entry.config.defaultScoring } : {},
92
+ ...entry.config.trackPositions !== void 0 ? { trackPositions: entry.config.trackPositions } : {},
93
+ ...entry.config.strict !== void 0 ? { strict: entry.config.strict } : {},
94
+ ...entry.config.required !== void 0 ? { required: entry.config.required } : {},
95
+ ...entry.config.vectorPromotion !== void 0 ? { vectorPromotion: entry.config.vectorPromotion } : {},
96
+ ...entry.config.patternValueLimit !== void 0 ? { patternValueLimit: entry.config.patternValueLimit } : {},
97
+ ...entry.synonyms !== null ? { synonyms: rulesOfStoredSynonyms(entry.synonyms) } : {}
98
+ };
99
+ }
100
+ function indexMetadataOf(indexName, entry, partitionCount) {
101
+ return metadataFromConfig(indexName, metadataConfigOf(entry), partitionCount);
102
+ }
103
+
104
+ // src/persistence/durability/constants.ts
105
+ var DEFAULT_CHECKPOINT_INTERVAL_MS = 3e5;
106
+ var DEFAULT_CHECKPOINT_MUTATION_THRESHOLD = 1e5;
107
+ var DEFAULT_ASYNC_FLUSH_INTERVAL_MS = 1e3;
108
+ var DIRECTORY_IDENTITY_CHECK_INTERVAL_MS = 1e3;
109
+ var DIRECTORY_LOCK_ATTEMPTS = 3;
110
+ var DIRECTORY_LOCK_SETTLE_MS = 50;
111
+ var DEFAULT_SEGMENT_MAX_BYTES = 67108864;
112
+ var DEFAULT_COMPACTION_THRESHOLD = 12;
113
+ var COMPACTION_LARGEST_MERGED_DOCUMENT_COUNT = 2e5;
114
+ var SEGMENT_FILE_FRAMING_SLACK_BYTES = 65536;
115
+ var SEGMENT_TOKEN_TABLE_SHARE_OF_FILE = 0.25;
116
+ var WHOLE_PARTITION_MIN_CHANGED_SHARE = 0.5;
117
+ var WHOLE_PARTITION_LARGEST_DOCUMENT_COUNT = 1e5;
118
+ var LOG_RECORDS_PER_CHECKPOINT = 1e5;
119
+ var WRITES_STALL_ABOVE_UNCHECKPOINTED_BYTES = 2147483648;
120
+ var CHECKPOINT_WORKER_TIMEOUT_MS = 6e5;
121
+ var CHECKPOINT_WORKER_IDLE_MS = 5e3;
122
+ var CHECKPOINT_TIMEOUT_RECOVERY_BACKOFF_MS = 50;
123
+
124
+ // src/serialization/stored-vector-values.ts
125
+ function dropStoredVectorValues(documents, schema) {
126
+ const vectorFieldPaths = [];
127
+ for (const [fieldPath, fieldType] of Object.entries(schema)) {
128
+ if (typeof fieldType === "string" && VECTOR_PATTERN.test(fieldType)) {
129
+ vectorFieldPaths.push(fieldPath);
130
+ }
131
+ }
132
+ if (vectorFieldPaths.length === 0) {
133
+ return;
134
+ }
135
+ for (const document of Object.values(documents)) {
136
+ for (const fieldPath of vectorFieldPaths) {
137
+ removeFieldAtPath(document.fields, fieldPath);
138
+ }
139
+ }
140
+ }
141
+ function removeFieldAtPath(fields, fieldPath) {
142
+ if (!fieldPath.includes(".")) {
143
+ delete fields[fieldPath];
144
+ return;
145
+ }
146
+ const segments = fieldPath.split(".");
147
+ let current = fields;
148
+ for (let i = 0; i < segments.length - 1; i += 1) {
149
+ const next = current[segments[i]];
150
+ if (next === null || typeof next !== "object") {
151
+ return;
152
+ }
153
+ current = next;
154
+ }
155
+ delete current[segments[segments.length - 1]];
156
+ }
157
+
158
+ // src/serialization/payload-v1/partition.ts
159
+ function sanitizeSurfaceForms(raw) {
160
+ if (raw === void 0 || raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
161
+ const result = /* @__PURE__ */ Object.create(null);
162
+ let count = 0;
163
+ for (const [surface, value] of Object.entries(raw)) {
164
+ if (typeof value === "number") {
165
+ result[surface] = value;
166
+ count++;
167
+ } else if (Array.isArray(value) && typeof value[0] === "number" && typeof value[1] === "string") {
168
+ result[surface] = [value[0], value[1]];
169
+ count++;
170
+ }
171
+ }
172
+ return count > 0 ? result : void 0;
173
+ }
174
+ function isWireRecord(value) {
175
+ return value !== null && typeof value === "object" && !Array.isArray(value);
176
+ }
177
+ function corruptPatternEntry(field) {
178
+ return new NarsilError(
179
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
180
+ `The pattern entry of field "${field}" in this partition must hold a list of document IDs and a map of runs`,
181
+ { field }
182
+ );
183
+ }
184
+ function patternIndexesFromWire(raw) {
185
+ if (raw === void 0 || raw === null) return {};
186
+ if (!isWireRecord(raw)) {
187
+ throw new NarsilError(
188
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
189
+ "The pattern entry of this partition must be a map of fields"
190
+ );
191
+ }
192
+ const pattern = /* @__PURE__ */ Object.create(null);
193
+ for (const [field, index] of Object.entries(raw)) {
194
+ if (!isWireRecord(index) || !isWireRecord(index.runs) || !Array.isArray(index.doc_ids)) {
195
+ throw corruptPatternEntry(field);
196
+ }
197
+ const docIds = [];
198
+ for (const docId of index.doc_ids) {
199
+ if (typeof docId !== "string") throw corruptPatternEntry(field);
200
+ docIds.push(docId);
201
+ }
202
+ pattern[field] = { docIds, runs: index.runs };
203
+ }
204
+ return { pattern };
205
+ }
206
+ function validateHnswMetric(value) {
207
+ if (value === void 0 || value === null) return void 0;
208
+ if (typeof value === "string" && VALID_HNSW_METRICS.has(value)) {
209
+ return value;
210
+ }
211
+ return void 0;
212
+ }
213
+ function wireToPartition(raw) {
214
+ const documents = {};
215
+ for (const [docId, doc] of Object.entries(raw.documents ?? {})) {
216
+ documents[docId] = {
217
+ fields: doc.fields,
218
+ fieldLengths: doc.field_lengths ?? {}
219
+ };
220
+ }
221
+ requireValidFieldTypes(raw.schema ?? {});
222
+ dropStoredVectorValues(documents, raw.schema ?? {});
223
+ const invertedIndex = {};
224
+ for (const [token, list] of Object.entries(raw.inverted_index ?? {})) {
225
+ invertedIndex[token] = {
226
+ docFrequency: list.doc_freq,
227
+ postings: (list.postings ?? []).map((p) => ({
228
+ docId: p.doc_id,
229
+ termFrequency: p.term_freq,
230
+ field: p.field,
231
+ positions: p.positions ?? []
232
+ }))
233
+ };
234
+ }
235
+ const numeric = {};
236
+ for (const [field, entries] of Object.entries(raw.field_indexes?.numeric ?? {})) {
237
+ numeric[field] = entries.map((e) => ({ value: e.value, docId: e.doc_id }));
238
+ }
239
+ const boolean = {};
240
+ for (const [field, idx] of Object.entries(raw.field_indexes?.boolean ?? {})) {
241
+ boolean[field] = { trueDocs: idx.true_docs ?? [], falseDocs: idx.false_docs ?? [] };
242
+ }
243
+ const geopoint = {};
244
+ for (const [field, entries] of Object.entries(raw.field_indexes?.geopoint ?? {})) {
245
+ geopoint[field] = entries.map((e) => ({ lat: e.lat, lon: e.lon, docId: e.doc_id }));
246
+ }
247
+ const vectorData = {};
248
+ for (const [field, data] of Object.entries(raw.vector_data ?? {})) {
249
+ vectorData[field] = {
250
+ dimension: data.dimension,
251
+ vectors: (data.vectors ?? []).map((v) => ({ docId: v.doc_id, vector: v.vector })),
252
+ hnswGraph: data.hnsw_graph ? {
253
+ entryPoint: data.hnsw_graph.entry_point,
254
+ maxLayer: data.hnsw_graph.max_layer,
255
+ m: data.hnsw_graph.m,
256
+ efConstruction: data.hnsw_graph.ef_construction,
257
+ metric: validateHnswMetric(data.hnsw_graph.metric),
258
+ nodes: data.hnsw_graph.nodes
259
+ } : null,
260
+ codes: data.codes ? { bits: data.codes.bits, centroid: data.codes.centroid, records: data.codes.records } : null
261
+ };
262
+ }
263
+ return {
264
+ indexName: raw.index_name,
265
+ partitionId: raw.partition_id,
266
+ totalPartitions: raw.total_partitions,
267
+ language: raw.language ?? "english",
268
+ schema: raw.schema ?? {},
269
+ docCount: raw.doc_count ?? 0,
270
+ avgDocLength: raw.avg_doc_length ?? 0,
271
+ documents,
272
+ invertedIndex,
273
+ fieldIndexes: {
274
+ numeric,
275
+ boolean,
276
+ enum: raw.field_indexes?.enum ?? {},
277
+ geopoint,
278
+ ...patternIndexesFromWire(raw.field_indexes?.pattern)
279
+ },
280
+ surfaceForms: sanitizeSurfaceForms(raw.surface_forms),
281
+ vectorData,
282
+ statistics: {
283
+ totalDocuments: raw.statistics?.total_documents ?? 0,
284
+ totalFieldLengths: raw.statistics?.total_field_lengths ?? {},
285
+ averageFieldLengths: raw.statistics?.average_field_lengths ?? {},
286
+ docFrequencies: raw.statistics?.doc_frequencies ?? {}
287
+ }
288
+ };
289
+ }
290
+ function deserializePayloadV1(data) {
291
+ const raw = decode(data);
292
+ return wireToPartition(raw);
293
+ }
294
+ function metadataToWire(meta) {
295
+ const wire = {
296
+ index_name: meta.indexName,
297
+ schema: meta.schema,
298
+ language: meta.language,
299
+ partition_count: meta.partitionCount,
300
+ bm25_params: meta.bm25Params,
301
+ created_at: meta.createdAt,
302
+ engine_version: meta.engineVersion
303
+ };
304
+ if (meta.vectorFields) {
305
+ wire.vector_fields = meta.vectorFields;
306
+ }
307
+ if (isNonNegativeInteger(meta.documentCount) && Number.isSafeInteger(meta.documentCount)) {
308
+ wire.document_count = meta.documentCount;
309
+ }
310
+ if (meta.embedding) {
311
+ wire.embedding = meta.embedding.adapter !== void 0 ? { adapter: meta.embedding.adapter, fields: meta.embedding.fields } : { fields: meta.embedding.fields };
312
+ }
313
+ if (meta.surfaceForms !== void 0) {
314
+ wire.surface_forms_enabled = meta.surfaceForms;
315
+ }
316
+ if (meta.analysisRevision !== void 0) {
317
+ wire.analysis_revision = meta.analysisRevision;
318
+ }
319
+ if (meta.tokenizer !== void 0) {
320
+ wire.tokenizer = meta.tokenizer;
321
+ }
322
+ if (meta.stopWords !== void 0) {
323
+ wire.stop_words = meta.stopWords;
324
+ }
325
+ if (meta.stopWordList !== void 0) {
326
+ wire.stop_word_list = meta.stopWordList;
327
+ }
328
+ if (meta.partitionLimits !== void 0) {
329
+ wire.partition_limits = {
330
+ ...meta.partitionLimits.maxDocsPerPartition !== void 0 ? { max_docs_per_partition: meta.partitionLimits.maxDocsPerPartition } : {},
331
+ ...meta.partitionLimits.maxPartitions !== void 0 ? { max_partitions: meta.partitionLimits.maxPartitions } : {},
332
+ ...meta.partitionLimits.watermark !== void 0 ? { watermark: meta.partitionLimits.watermark } : {}
333
+ };
334
+ }
335
+ if (meta.defaultScoring !== void 0) {
336
+ wire.default_scoring = meta.defaultScoring;
337
+ }
338
+ if (meta.trackPositions !== void 0) {
339
+ wire.track_positions = meta.trackPositions;
340
+ }
341
+ if (meta.strict !== void 0) {
342
+ wire.strict = meta.strict;
343
+ }
344
+ if (meta.required !== void 0) {
345
+ wire.required = meta.required;
346
+ }
347
+ if (meta.vectorPromotion !== void 0) {
348
+ const promotion = meta.vectorPromotion;
349
+ wire.vector_promotion = {
350
+ ...promotion.threshold !== void 0 ? { threshold: promotion.threshold } : {},
351
+ ...promotion.filterThreshold !== void 0 ? { filter_threshold: promotion.filterThreshold } : {},
352
+ ...promotion.hnswConfig !== void 0 ? {
353
+ hnsw_config: {
354
+ ...promotion.hnswConfig.m !== void 0 ? { m: promotion.hnswConfig.m } : {},
355
+ ...promotion.hnswConfig.efConstruction !== void 0 ? { ef_construction: promotion.hnswConfig.efConstruction } : {},
356
+ ...promotion.hnswConfig.metric !== void 0 ? { metric: promotion.hnswConfig.metric } : {}
357
+ }
358
+ } : {},
359
+ ...promotion.quantization !== void 0 ? { quantization: promotion.quantization } : {},
360
+ ...promotion.storage !== void 0 ? { storage: promotion.storage } : {}
361
+ };
362
+ }
363
+ if (meta.patternValueLimit !== void 0) {
364
+ wire.pattern_value_limit = meta.patternValueLimit;
365
+ }
366
+ if (meta.indexUuid !== void 0) {
367
+ wire.index_uuid = meta.indexUuid;
368
+ }
369
+ if (meta.heldPartitions !== void 0) {
370
+ wire.held_partitions = meta.heldPartitions;
371
+ }
372
+ if (Array.isArray(meta.synonyms) && meta.synonyms.length > 0) {
373
+ wire.synonyms = meta.synonyms;
374
+ }
375
+ return wire;
376
+ }
377
+ function wireToMetadata(raw) {
378
+ const meta = {
379
+ indexName: raw.index_name,
380
+ schema: raw.schema ?? {},
381
+ language: raw.language ?? "english",
382
+ partitionCount: raw.partition_count ?? 1,
383
+ bm25Params: raw.bm25_params ?? { k1: 1.2, b: 0.75 },
384
+ createdAt: raw.created_at ?? 0,
385
+ engineVersion: raw.engine_version ?? "0.0.0"
386
+ };
387
+ if (raw.vector_fields) {
388
+ for (const [fieldPath, field] of Object.entries(raw.vector_fields)) {
389
+ if (!isQuantizationMode(field.quantization)) {
390
+ throw new NarsilError(
391
+ ErrorCodes.CONFIG_INVALID,
392
+ `Index metadata names a vector quantization "${String(field.quantization)}" for "${fieldPath}" this engine does not read`,
393
+ { fieldPath, quantization: field.quantization }
394
+ );
395
+ }
396
+ }
397
+ meta.vectorFields = raw.vector_fields;
398
+ }
399
+ if (isNonNegativeInteger(raw.document_count) && Number.isSafeInteger(raw.document_count)) {
400
+ meta.documentCount = raw.document_count;
401
+ }
402
+ if (raw.embedding && typeof raw.embedding === "object" && typeof raw.embedding.fields === "object") {
403
+ meta.embedding = typeof raw.embedding.adapter === "string" ? { adapter: raw.embedding.adapter, fields: raw.embedding.fields } : { fields: raw.embedding.fields };
404
+ }
405
+ if (typeof raw.surface_forms_enabled === "boolean") {
406
+ meta.surfaceForms = raw.surface_forms_enabled;
407
+ }
408
+ if (typeof raw.analysis_revision === "string") {
409
+ meta.analysisRevision = raw.analysis_revision;
410
+ }
411
+ if (typeof raw.tokenizer === "string") {
412
+ meta.tokenizer = raw.tokenizer;
413
+ }
414
+ if (typeof raw.stop_words === "string") {
415
+ meta.stopWords = raw.stop_words;
416
+ }
417
+ if (Array.isArray(raw.stop_word_list) && raw.stop_word_list.every((word) => typeof word === "string")) {
418
+ meta.stopWordList = raw.stop_word_list;
419
+ }
420
+ if (raw.partition_limits && typeof raw.partition_limits === "object") {
421
+ const limits = {
422
+ ...isPositiveInteger(raw.partition_limits.max_docs_per_partition) ? { maxDocsPerPartition: raw.partition_limits.max_docs_per_partition } : {},
423
+ ...isPositiveInteger(raw.partition_limits.max_partitions) ? { maxPartitions: raw.partition_limits.max_partitions } : {},
424
+ ...isWatermarkFraction(raw.partition_limits.watermark) ? { watermark: raw.partition_limits.watermark } : {}
425
+ };
426
+ if (Object.keys(limits).length > 0) {
427
+ meta.partitionLimits = limits;
428
+ }
429
+ }
430
+ if (raw.default_scoring === "local" || raw.default_scoring === "dfs" || raw.default_scoring === "broadcast") {
431
+ meta.defaultScoring = raw.default_scoring;
432
+ }
433
+ if (typeof raw.track_positions === "boolean") {
434
+ meta.trackPositions = raw.track_positions;
435
+ }
436
+ if (typeof raw.strict === "boolean") {
437
+ meta.strict = raw.strict;
438
+ }
439
+ if (Array.isArray(raw.required) && raw.required.every((field) => typeof field === "string")) {
440
+ meta.required = raw.required;
441
+ }
442
+ if (raw.vector_promotion && typeof raw.vector_promotion === "object") {
443
+ const promotion = raw.vector_promotion;
444
+ const hnsw = promotion.hnsw_config && typeof promotion.hnsw_config === "object" ? promotion.hnsw_config : void 0;
445
+ const metric = hnsw?.metric;
446
+ const restored = {};
447
+ const hnswConfig = {};
448
+ if (isPositiveInteger(hnsw?.m)) {
449
+ hnswConfig.m = hnsw?.m;
450
+ }
451
+ if (isPositiveInteger(hnsw?.ef_construction)) {
452
+ hnswConfig.efConstruction = hnsw?.ef_construction;
453
+ }
454
+ if (metric === "cosine" || metric === "dotProduct" || metric === "euclidean") {
455
+ hnswConfig.metric = metric;
456
+ }
457
+ if (isPositiveInteger(promotion.threshold)) {
458
+ restored.threshold = promotion.threshold;
459
+ }
460
+ if (isSelectivityRatio(promotion.filter_threshold)) {
461
+ restored.filterThreshold = promotion.filter_threshold;
462
+ }
463
+ if (Object.keys(hnswConfig).length > 0) {
464
+ restored.hnswConfig = hnswConfig;
465
+ }
466
+ if (promotion.quantization !== void 0) {
467
+ if (!isQuantizationMode(promotion.quantization)) {
468
+ throw new NarsilError(
469
+ ErrorCodes.CONFIG_INVALID,
470
+ `Index metadata names a vector quantization "${String(promotion.quantization)}" this engine does not read`,
471
+ { quantization: promotion.quantization }
472
+ );
473
+ }
474
+ restored.quantization = promotion.quantization;
475
+ }
476
+ if (promotion.storage !== void 0) {
477
+ if (!isStorageMode(promotion.storage)) {
478
+ throw new NarsilError(
479
+ ErrorCodes.CONFIG_INVALID,
480
+ `Index metadata names a vector storage "${String(promotion.storage)}" this engine does not read`,
481
+ { storage: promotion.storage }
482
+ );
483
+ }
484
+ restored.storage = promotion.storage;
485
+ }
486
+ if (Object.keys(restored).length > 0) {
487
+ meta.vectorPromotion = restored;
488
+ }
489
+ }
490
+ if (raw.pattern_value_limit !== void 0) {
491
+ if (!isPositiveInteger(raw.pattern_value_limit)) {
492
+ throw new NarsilError(
493
+ ErrorCodes.CONFIG_INVALID,
494
+ `The pattern value limit in the index metadata is ${String(raw.pattern_value_limit)}, but the limit must be a whole number of code points`,
495
+ { patternValueLimit: String(raw.pattern_value_limit) }
496
+ );
497
+ }
498
+ meta.patternValueLimit = raw.pattern_value_limit;
499
+ }
500
+ if (typeof raw.index_uuid === "string" && raw.index_uuid.length > 0) {
501
+ meta.indexUuid = raw.index_uuid;
502
+ }
503
+ if (Array.isArray(raw.held_partitions) && raw.held_partitions.every(isNonNegativeInteger)) {
504
+ meta.heldPartitions = raw.held_partitions;
505
+ }
506
+ if (raw.synonyms !== void 0 && raw.synonyms !== null) meta.synonyms = raw.synonyms;
507
+ return meta;
508
+ }
509
+ function isNonNegativeInteger(value) {
510
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
511
+ }
512
+ function isPositiveInteger(value) {
513
+ return typeof value === "number" && Number.isInteger(value) && value >= 1;
514
+ }
515
+ function isSelectivityRatio(value) {
516
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
517
+ }
518
+ function isWatermarkFraction(value) {
519
+ return typeof value === "number" && value > 0 && value <= 1;
520
+ }
521
+ function serializeMetadata(meta) {
522
+ const wire = metadataToWire(meta);
523
+ return encode(wire);
524
+ }
525
+ function deserializeMetadata(data) {
526
+ const raw = decode(data);
527
+ return wireToMetadata(raw);
528
+ }
529
+
530
+ // src/serialization/envelope.ts
531
+ var CURRENT_ENVELOPE_VERSION = 1;
532
+ var SNAPSHOT_ENVELOPE_VERSION = 2;
533
+ var INDEX_SNAPSHOT_ENVELOPE_VERSION = 3;
534
+ async function collectStream(stream) {
535
+ const reader = stream.getReader();
536
+ const chunks = [];
537
+ let totalLength = 0;
538
+ for (; ; ) {
539
+ const { done, value } = await reader.read();
540
+ if (done) break;
541
+ chunks.push(value);
542
+ totalLength += value.length;
543
+ }
544
+ const result = new Uint8Array(totalLength);
545
+ let offset = 0;
546
+ for (const chunk of chunks) {
547
+ result.set(chunk, offset);
548
+ offset += chunk.length;
549
+ }
550
+ return result;
551
+ }
552
+ function toArrayBuffer(data) {
553
+ return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
554
+ }
555
+ async function compressGzip(data) {
556
+ const blob = new Blob([toArrayBuffer(data)]);
557
+ const compressed = blob.stream().pipeThrough(new CompressionStream("gzip"));
558
+ return collectStream(compressed);
559
+ }
560
+ async function decompressGzip(data) {
561
+ const blob = new Blob([toArrayBuffer(data)]);
562
+ const decompressed = blob.stream().pipeThrough(new DecompressionStream("gzip"));
563
+ return collectStream(decompressed);
564
+ }
565
+ function buildFlags(options) {
566
+ const useCompression = options.compression === "gzip";
567
+ return {
568
+ compressionEnabled: useCompression,
569
+ compressionAlgorithm: useCompression ? "gzip" : "none",
570
+ checksumPresent: options.checksum ?? false,
571
+ encryptionEnabled: false
572
+ };
573
+ }
574
+ async function packEnvelope(payloadBytes, options) {
575
+ const flags = buildFlags(options);
576
+ let finalPayload = payloadBytes;
577
+ if (flags.compressionEnabled) {
578
+ finalPayload = await compressGzip(payloadBytes);
579
+ }
580
+ const checksum = flags.checksumPresent ? crc32(finalPayload) : 0;
581
+ const [major, minor, patch] = engineVersionParts();
582
+ const envelopeFormatVersion = options.envelopeFormatVersion ?? CURRENT_ENVELOPE_VERSION;
583
+ const header2 = {
584
+ magic: "NRSL",
585
+ envelopeFormatVersion,
586
+ engineVersionMajor: major,
587
+ engineVersionMinor: minor,
588
+ engineVersionPatch: patch,
589
+ payloadLength: finalPayload.length,
590
+ flags,
591
+ checksum,
592
+ reserved: new Uint8Array(14)
593
+ };
594
+ const headerBytes = writeHeader(header2);
595
+ const envelope = new Uint8Array(HEADER_SIZE + finalPayload.length);
596
+ envelope.set(headerBytes, 0);
597
+ envelope.set(finalPayload, HEADER_SIZE);
598
+ return envelope;
599
+ }
600
+ async function unpackEnvelope(data, maxAcceptedVersion = CURRENT_ENVELOPE_VERSION) {
601
+ const header2 = readHeader(data);
602
+ if (header2.envelopeFormatVersion > maxAcceptedVersion) {
603
+ throw new NarsilError(
604
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
605
+ `This data holds Narsil envelope format v${header2.envelopeFormatVersion}, while this build of @delali/narsil reads up to v${maxAcceptedVersion}, so upgrade the package to read it.`
606
+ );
607
+ }
608
+ if (header2.flags.encryptionEnabled) {
609
+ throw new NarsilError(
610
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
611
+ "Encrypted envelopes are not supported in this version of Narsil"
612
+ );
613
+ }
614
+ const compAlgo = header2.flags.compressionAlgorithm;
615
+ if (header2.flags.compressionEnabled && compAlgo !== "gzip" && compAlgo !== "none") {
616
+ throw new NarsilError(
617
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
618
+ `Compression algorithm "${compAlgo}" is not supported in this version of Narsil`
619
+ );
620
+ }
621
+ const availablePayload = data.length - HEADER_SIZE;
622
+ if (availablePayload < header2.payloadLength) {
623
+ throw new NarsilError(
624
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
625
+ `Envelope data is truncated: header declares ${header2.payloadLength} bytes of payload but only ${availablePayload} bytes are available`
626
+ );
627
+ }
628
+ let payloadBytes = new Uint8Array(data.slice(HEADER_SIZE, HEADER_SIZE + header2.payloadLength));
629
+ if (header2.flags.checksumPresent) {
630
+ const computed = crc32(payloadBytes);
631
+ if (computed !== header2.checksum) {
632
+ throw new NarsilError(ErrorCodes.PERSISTENCE_CRC_MISMATCH, "CRC32 checksum mismatch: data may be corrupted", {
633
+ expected: header2.checksum,
634
+ computed
635
+ });
636
+ }
637
+ }
638
+ if (header2.flags.compressionEnabled) {
639
+ payloadBytes = await decompressGzip(payloadBytes);
640
+ }
641
+ return { header: header2, payloadBytes };
642
+ }
643
+ async function unpackEnvelopeBytes(data) {
644
+ return unpackEnvelope(data, SNAPSHOT_ENVELOPE_VERSION);
645
+ }
646
+ async function unpackIndexSnapshotEnvelope(data) {
647
+ const { header: header2, payloadBytes } = await unpackEnvelope(data, INDEX_SNAPSHOT_ENVELOPE_VERSION);
648
+ if (header2.envelopeFormatVersion !== INDEX_SNAPSHOT_ENVELOPE_VERSION) {
649
+ throw new NarsilError(
650
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
651
+ `Expected an index snapshot envelope of format v${INDEX_SNAPSHOT_ENVELOPE_VERSION}, received format v${header2.envelopeFormatVersion}`
652
+ );
653
+ }
654
+ return payloadBytes;
655
+ }
656
+ async function writeMetadataEnvelope(meta, options = {}) {
657
+ const payloadBytes = serializeMetadata(meta);
658
+ return packEnvelope(payloadBytes, options);
659
+ }
660
+ async function readMetadataEnvelope(data) {
661
+ const { header: header2, payloadBytes } = await unpackEnvelope(data);
662
+ const metadata = deserializeMetadata(payloadBytes);
663
+ return { header: header2, metadata };
664
+ }
665
+
666
+ // src/persistence/durability/segment/layout.ts
667
+ var SEGMENT_ID_WIDTH = 16;
668
+ function manifestKey(indexName) {
669
+ return `${indexName}/manifest`;
670
+ }
671
+ function snapshotBundleKey(indexName) {
672
+ return `${indexName}/snapshot`;
673
+ }
674
+ function segmentPrefix(indexName, partitionId) {
675
+ return `${indexName}/segments/${partitionId}/`;
676
+ }
677
+ function segmentKey(indexName, partitionId, segmentId) {
678
+ return `${segmentPrefix(indexName, partitionId)}s${formatSegmentId(segmentId)}`;
679
+ }
680
+ function segmentsPrefix(indexName) {
681
+ return `${indexName}/segments/`;
682
+ }
683
+ function vectorFileKey(indexName, fieldPath, fileId) {
684
+ return `${segmentsPrefix(indexName)}vec-${encodeFieldPath(fieldPath)}-f${formatSegmentId(fileId)}`;
685
+ }
686
+ function requireGeneration(generation) {
687
+ if (Number.isSafeInteger(generation) && generation > 0) return;
688
+ throw new NarsilError(
689
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
690
+ `Vector graph generation ${generation} must be a positive integer`,
691
+ { generation }
692
+ );
693
+ }
694
+ function graphPartKey(indexName, fieldPath, generation, part) {
695
+ requireGeneration(generation);
696
+ return `${segmentsPrefix(indexName)}vec-${encodeFieldPath(fieldPath)}-graph-g${generation}-p${formatSegmentId(part)}`;
697
+ }
698
+ function formatSegmentId(segmentId) {
699
+ if (!Number.isInteger(segmentId) || segmentId < 0) {
700
+ throw new NarsilError(
701
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
702
+ `Segment id ${segmentId} must be a non-negative integer`,
703
+ { segmentId }
704
+ );
705
+ }
706
+ return segmentId.toString().padStart(SEGMENT_ID_WIDTH, "0");
707
+ }
708
+ var FIELD_PATH_PATTERN = /^[A-Za-z0-9_.]+$/;
709
+ function encodeFieldPath(fieldPath) {
710
+ if (!FIELD_PATH_PATTERN.test(fieldPath)) {
711
+ throw new NarsilError(
712
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
713
+ `Vector field path "${fieldPath}" contains characters that cannot be encoded in a segment key`,
714
+ { fieldPath }
715
+ );
716
+ }
717
+ const fingerprint = fnv1a(fieldPath).toString(36);
718
+ return `${fieldPath.replace(/\./g, "_")}-${fingerprint}`;
719
+ }
720
+ var SEGMENT_MANIFEST_VERSION = 7;
721
+ var EARLIER_SEGMENT_MANIFEST_VERSION = 6;
722
+ var MANIFEST_ENVELOPE_VERSION = 2;
723
+ var MAX_SEGMENTS_PER_PARTITION = 65536;
724
+ var MAX_SEGMENT_ID = 281474976710655;
725
+ function fileRefOnTheWire(ref) {
726
+ return { key: ref.key, bytes: ref.bytes, checksum: ref.checksum };
727
+ }
728
+ function encodeSegmentManifest(manifest) {
729
+ const payload = encode({
730
+ version: SEGMENT_MANIFEST_VERSION,
731
+ schema: manifest.schema,
732
+ language: manifest.language,
733
+ checkpoint: manifest.checkpoint.map((c) => ({
734
+ partitionId: c.partitionId,
735
+ lastSeqNo: c.lastSeqNo,
736
+ primaryTerm: c.primaryTerm
737
+ })),
738
+ partitions: manifest.partitions.map((p) => ({
739
+ partitionId: p.partitionId,
740
+ nextSegmentId: p.nextSegmentId,
741
+ segments: p.segments.map((s) => ({
742
+ id: s.id,
743
+ key: s.key,
744
+ docCount: s.docCount,
745
+ tombstoneCount: s.tombstoneCount,
746
+ bytes: s.bytes,
747
+ checksum: s.checksum
748
+ }))
749
+ })),
750
+ vectors: manifest.vectors.map((v) => ({
751
+ fieldPath: v.fieldPath,
752
+ nextFileId: v.nextFileId,
753
+ files: v.files.map((f) => ({ id: f.id, ...fileRefOnTheWire(f), count: f.count, dead: f.dead })),
754
+ graphGeneration: v.graphGeneration,
755
+ graphParts: v.graphParts.map(fileRefOnTheWire)
756
+ }))
757
+ });
758
+ return packChecksummedEnvelope([payload], MANIFEST_ENVELOPE_VERSION, "segment manifest");
759
+ }
760
+ function manifestReferencedKeys(manifest) {
761
+ const keys = /* @__PURE__ */ new Set();
762
+ for (const partition of manifest.partitions) {
763
+ for (const segment of partition.segments) {
764
+ keys.add(segment.key);
765
+ }
766
+ }
767
+ for (const vector of manifest.vectors) {
768
+ for (const file of vector.files) keys.add(file.key);
769
+ for (const part of vector.graphParts) keys.add(part.key);
770
+ }
771
+ return keys;
772
+ }
773
+ function manifestFileRefs(manifest) {
774
+ const refs = [];
775
+ for (const partition of manifest.partitions) refs.push(...partition.segments);
776
+ for (const vector of manifest.vectors) refs.push(...vector.files, ...vector.graphParts);
777
+ return refs;
778
+ }
779
+
780
+ // src/persistence/durability/segment/manifest-fields.ts
781
+ function invalidManifest(message, details) {
782
+ throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `Segment manifest ${message}`, details);
783
+ }
784
+ function isRecord(value) {
785
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array);
786
+ }
787
+ function isId(value) {
788
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_SEGMENT_ID;
789
+ }
790
+ function isUint32(value) {
791
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
792
+ }
793
+ function isSequenceNumber(value) {
794
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
795
+ }
796
+ function readFileRef(raw, expectedKey, what) {
797
+ if (raw.key !== expectedKey) {
798
+ invalidManifest(`lists the ${what} under the key "${String(raw.key)}" where it belongs at "${expectedKey}"`, {
799
+ key: raw.key,
800
+ expected: expectedKey
801
+ });
802
+ }
803
+ const bytes = raw.bytes;
804
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < HEADER_SIZE || bytes > MAX_FILE_BYTES) {
805
+ invalidManifest(`gives the ${what} "${expectedKey}" an invalid length`, { key: expectedKey, bytes });
806
+ }
807
+ if (!isUint32(raw.checksum)) invalidManifest(`gives the ${what} "${expectedKey}" an invalid checksum`);
808
+ return { key: expectedKey, bytes, checksum: raw.checksum };
809
+ }
810
+
811
+ // src/persistence/durability/segment/manifest-vectors-decode.ts
812
+ function normalizeFile(raw, indexName, fieldPath, nextFileId, seenIds) {
813
+ if (!isRecord(raw) || !isId(raw.id)) invalidManifest("has an invalid vector file reference", { fieldPath });
814
+ if (raw.id >= nextFileId || seenIds.has(raw.id)) {
815
+ invalidManifest(`lists vector file ${raw.id} of "${fieldPath}" twice or at its next file id`, { fieldPath });
816
+ }
817
+ seenIds.add(raw.id);
818
+ const count = raw.count;
819
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 0 || count > VECTOR_FILE_MAX_VECTORS) {
820
+ invalidManifest(`gives vector file ${raw.id} of "${fieldPath}" an invalid count`, { fieldPath, count });
821
+ }
822
+ const dead = raw.dead ?? null;
823
+ if (dead !== null && !(dead instanceof Uint8Array)) invalidManifest("has dead vectors that are not bytes");
824
+ if (dead !== null && dead.byteLength !== deadBytesFor(count)) {
825
+ invalidManifest(`marks the dead vectors of file ${raw.id} of "${fieldPath}" with the wrong number of bytes`);
826
+ }
827
+ const ref = readFileRef(raw, vectorFileKey(indexName, fieldPath, raw.id), "vector file");
828
+ return { ...ref, id: raw.id, count, dead };
829
+ }
830
+ function normalizeGraphParts(raw, indexName, fieldPath, generation) {
831
+ if (!Array.isArray(raw)) invalidManifest(`gives "${fieldPath}" no list of graph parts`, { fieldPath });
832
+ if (raw.length > 0 && generation === 0) invalidManifest(`lists graph parts of "${fieldPath}" at generation 0`);
833
+ return raw.map((part, at) => {
834
+ if (!isRecord(part)) invalidManifest(`has an invalid graph part of "${fieldPath}"`, { fieldPath });
835
+ return readFileRef(part, graphPartKey(indexName, fieldPath, generation, at), "graph part");
836
+ });
837
+ }
838
+ function normalizeField(raw, indexName, seenFields) {
839
+ if (!isRecord(raw) || typeof raw.fieldPath !== "string") invalidManifest("has an invalid vector reference");
840
+ const fieldPath = raw.fieldPath;
841
+ if (seenFields.has(fieldPath)) invalidManifest(`lists the vector field "${fieldPath}" twice`, { fieldPath });
842
+ seenFields.add(fieldPath);
843
+ if (!isId(raw.nextFileId)) invalidManifest(`gives "${fieldPath}" an invalid next file id`, { fieldPath });
844
+ if (!Array.isArray(raw.files)) invalidManifest(`gives "${fieldPath}" no list of vector files`, { fieldPath });
845
+ if (!isId(raw.graphGeneration)) invalidManifest(`gives "${fieldPath}" an invalid graph generation`, { fieldPath });
846
+ const nextFileId = raw.nextFileId;
847
+ const seenIds = /* @__PURE__ */ new Set();
848
+ return {
849
+ fieldPath,
850
+ nextFileId,
851
+ files: raw.files.map((file) => normalizeFile(file, indexName, fieldPath, nextFileId, seenIds)),
852
+ graphGeneration: raw.graphGeneration,
853
+ graphParts: normalizeGraphParts(raw.graphParts, indexName, fieldPath, raw.graphGeneration)
854
+ };
855
+ }
856
+ function normalizeVectorFields(raw, indexName) {
857
+ if (!Array.isArray(raw)) invalidManifest("has malformed vector references");
858
+ const seenFields = /* @__PURE__ */ new Set();
859
+ return raw.map((field) => normalizeField(field, indexName, seenFields));
860
+ }
861
+
862
+ // src/persistence/durability/segment/manifest-decode.ts
863
+ async function openManifestPayload(data) {
864
+ const { payload } = await openChecksummedEnvelope(data, {
865
+ envelopeFormatVersion: MANIFEST_ENVELOPE_VERSION,
866
+ what: "segment manifest",
867
+ allowsCompression: true
868
+ });
869
+ const raw = decode(payload);
870
+ if (!isRecord(raw)) invalidManifest("is not a map");
871
+ return raw;
872
+ }
873
+ function listedKeysOf(raw) {
874
+ const keys = [];
875
+ for (const partition of Array.isArray(raw.partitions) ? raw.partitions : []) {
876
+ if (!isRecord(partition) || !Array.isArray(partition.segments)) continue;
877
+ for (const segment of partition.segments)
878
+ if (isRecord(segment) && typeof segment.key === "string") keys.push(segment.key);
879
+ }
880
+ for (const field of Array.isArray(raw.vectors) ? raw.vectors : []) {
881
+ if (!isRecord(field)) continue;
882
+ for (const list of [field.files, field.graphParts]) {
883
+ if (!Array.isArray(list)) continue;
884
+ for (const file of list) if (isRecord(file) && typeof file.key === "string") keys.push(file.key);
885
+ }
886
+ }
887
+ return keys;
888
+ }
889
+ async function decodeSegmentManifest(data, indexName) {
890
+ return decodeManifestPayload(await openManifestPayload(data), indexName);
891
+ }
892
+ function decodeManifestPayload(raw, indexName) {
893
+ if (raw.version === EARLIER_SEGMENT_MANIFEST_VERSION) return { kind: "earlier", payload: raw };
894
+ if (raw.version !== SEGMENT_MANIFEST_VERSION) {
895
+ throw new NarsilError(
896
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
897
+ `The segment manifest of index "${indexName}" holds layout ${String(raw.version)}, which this release cannot open. Export the index with the release that wrote it and import the export`,
898
+ { indexName, version: raw.version }
899
+ );
900
+ }
901
+ const schema = raw.schema;
902
+ if (!isRecord(schema)) invalidManifest("is missing its schema");
903
+ requireValidFieldTypes(schema);
904
+ if (typeof raw.language !== "string") invalidManifest("is missing its language");
905
+ return {
906
+ kind: "current",
907
+ manifest: {
908
+ version: SEGMENT_MANIFEST_VERSION,
909
+ schema,
910
+ language: raw.language,
911
+ checkpoint: normalizeCheckpoint(raw.checkpoint),
912
+ partitions: normalizePartitions(raw.partitions, indexName),
913
+ vectors: normalizeVectorFields(raw.vectors, indexName)
914
+ }
915
+ };
916
+ }
917
+ function normalizeCheckpoint(raw) {
918
+ if (!Array.isArray(raw)) invalidManifest("is missing its checkpoint list");
919
+ const seen = /* @__PURE__ */ new Set();
920
+ return raw.map((entry) => {
921
+ if (!isRecord(entry) || !isUint32(entry.partitionId) || !isSequenceNumber(entry.lastSeqNo) || !isSequenceNumber(entry.primaryTerm) || seen.has(entry.partitionId)) {
922
+ invalidManifest("has an invalid partition checkpoint", { entry });
923
+ }
924
+ seen.add(entry.partitionId);
925
+ return { partitionId: entry.partitionId, lastSeqNo: entry.lastSeqNo, primaryTerm: entry.primaryTerm };
926
+ });
927
+ }
928
+ function normalizePartitions(raw, indexName) {
929
+ if (!Array.isArray(raw)) invalidManifest("is missing partition entries");
930
+ const seen = /* @__PURE__ */ new Set();
931
+ return raw.map((entry) => {
932
+ if (!isRecord(entry) || !isUint32(entry.partitionId) || seen.has(entry.partitionId)) {
933
+ invalidManifest("has a partition without a valid id", { partitionId: isRecord(entry) ? entry.partitionId : null });
934
+ }
935
+ seen.add(entry.partitionId);
936
+ const segments = normalizeSegments(entry.segments, indexName, entry.partitionId);
937
+ return {
938
+ partitionId: entry.partitionId,
939
+ nextSegmentId: readNextSegmentId(entry.nextSegmentId, segments, entry.partitionId),
940
+ segments
941
+ };
942
+ });
943
+ }
944
+ function normalizeSegments(raw, indexName, partitionId) {
945
+ if (!Array.isArray(raw)) invalidManifest("has malformed segment references", { partitionId });
946
+ if (raw.length > MAX_SEGMENTS_PER_PARTITION) {
947
+ invalidManifest(`lists ${raw.length} segments for partition ${partitionId}, above ${MAX_SEGMENTS_PER_PARTITION}`);
948
+ }
949
+ const seenIds = /* @__PURE__ */ new Set();
950
+ return raw.map((segment) => {
951
+ if (!isRecord(segment) || !isId(segment.id) || !isUint32(segment.docCount) || !isUint32(segment.tombstoneCount)) {
952
+ invalidManifest("has an invalid segment reference", { partitionId });
953
+ }
954
+ if (seenIds.has(segment.id)) invalidManifest(`reuses segment id ${segment.id} in partition ${partitionId}`);
955
+ seenIds.add(segment.id);
956
+ const ref = readFileRef(segment, segmentKey(indexName, partitionId, segment.id), "segment");
957
+ return { ...ref, id: segment.id, docCount: segment.docCount, tombstoneCount: segment.tombstoneCount };
958
+ });
959
+ }
960
+ function readNextSegmentId(value, segments, partitionId) {
961
+ if (!isId(value)) invalidManifest("has an invalid next segment id", { partitionId });
962
+ for (const segment of segments) {
963
+ if (segment.id >= value) {
964
+ invalidManifest(`next segment id ${value} does not exceed segment id ${segment.id}`, { partitionId });
965
+ }
966
+ }
967
+ return value;
968
+ }
969
+
970
+ // src/persistence/durability/segment/captured-partition.ts
971
+ function keepMaskOf(segment) {
972
+ const keep = new Uint8Array(segment.arrays.documentCount);
973
+ for (let ordinal = 0; ordinal < keep.length; ordinal++) keep[ordinal] = segment.isTombstoned(ordinal) ? 0 : 1;
974
+ return keep;
975
+ }
976
+ function selectionOfMask(segment, keep) {
977
+ return { segment, keep: (ordinal) => keep[ordinal] === 1 };
978
+ }
979
+ function frozenLiveTail(live, shared) {
980
+ if (live.count() === 0) return null;
981
+ const payload = live.encodeSegment();
982
+ const documents = survivorDocumentsOf(partitionStateOf(live), payload);
983
+ if (shared) {
984
+ const snapshot = freezeSegmentShared(payload, documents);
985
+ if (snapshot !== null) return createSharedFrozenSegment(snapshot);
986
+ }
987
+ return createFrozenSegment(payload, documents);
988
+ }
989
+ function frozenSegmentsOf(partition, shared) {
990
+ const segments = [];
991
+ const live = isCompositePartition(partition) ? partition.live : partition;
992
+ if (isCompositePartition(partition)) {
993
+ const ids = partition.frozenSegmentSizes().map((size) => size.segmentId);
994
+ segments.push(...partition.frozenSegmentsById(ids));
995
+ }
996
+ const tail = frozenLiveTail(live, shared);
997
+ if (tail !== null) segments.push(tail);
998
+ return segments;
999
+ }
1000
+ function partitionContentsOf(manager, partitionId) {
1001
+ const partition = manager.getPartition(partitionId);
1002
+ const selections = frozenSegmentsOf(partition, false).map((segment) => selectionOfMask(segment, keepMaskOf(segment)));
1003
+ return { partitionId, docCount: partition.count(), selections };
1004
+ }
1005
+ function captureWholePartition(manager, partitionId) {
1006
+ if (typeof SharedArrayBuffer !== "function") return null;
1007
+ const partition = manager.getPartition(partitionId);
1008
+ if (!isCompositePartition(partition) || partition.frozenSegmentCount() === 0) return null;
1009
+ const segments = [];
1010
+ for (const segment of frozenSegmentsOf(partition, true)) {
1011
+ if (segment.sharedSnapshot === null) return null;
1012
+ segments.push({ snapshot: segment.sharedSnapshot, keep: keepMaskOf(segment) });
1013
+ }
1014
+ return { partitionId, docCount: partition.count(), segments };
1015
+ }
1016
+ function contentsOfCaptured(captured) {
1017
+ return {
1018
+ partitionId: captured.partitionId,
1019
+ docCount: captured.docCount,
1020
+ selections: captured.segments.map(
1021
+ ({ snapshot, keep }) => selectionOfMask(createSharedFrozenSegment(snapshot), keep)
1022
+ )
1023
+ };
1024
+ }
1025
+
1026
+ // src/persistence/durability/segment/store.ts
1027
+ function directoryCheckpointStore(directory) {
1028
+ const store = {
1029
+ read: (key) => directory.read(key),
1030
+ write: (key, chunks) => directory.atomicWrite(key, chunks),
1031
+ remove: (key) => directory.remove(key),
1032
+ list: (prefix) => directory.list(prefix),
1033
+ pathOf: (key) => directory.pathOf(key)
1034
+ };
1035
+ const byteLength = directory.byteLength;
1036
+ if (byteLength !== void 0) store.byteLength = (key) => byteLength.call(directory, key);
1037
+ return store;
1038
+ }
1039
+ function joined(chunks) {
1040
+ if (chunks.length === 1) return chunks[0];
1041
+ let total = 0;
1042
+ for (const chunk of chunks) total += chunk.byteLength;
1043
+ const bytes = new Uint8Array(total);
1044
+ let offset = 0;
1045
+ for (const chunk of chunks) {
1046
+ bytes.set(chunk, offset);
1047
+ offset += chunk.byteLength;
1048
+ }
1049
+ return bytes;
1050
+ }
1051
+ function adapterFailure(code, verb, key, error) {
1052
+ if (error instanceof NarsilError) return error;
1053
+ const cause = error instanceof Error ? error.message : String(error);
1054
+ return new NarsilError(code, `The persistence adapter failed to ${verb} "${key}": ${cause}`, { key, cause });
1055
+ }
1056
+ async function guarded(run, code, verb, key) {
1057
+ try {
1058
+ return await run();
1059
+ } catch (error) {
1060
+ throw adapterFailure(code, verb, key, error);
1061
+ }
1062
+ }
1063
+ function adapterCheckpointStore(adapter) {
1064
+ return {
1065
+ read: (key) => guarded(() => adapter.load(key), ErrorCodes.PERSISTENCE_LOAD_FAILED, "load", key),
1066
+ write: (key, chunks) => guarded(() => adapter.save(key, joined(chunks)), ErrorCodes.PERSISTENCE_SAVE_FAILED, "save", key),
1067
+ remove: (key) => guarded(() => adapter.delete(key), ErrorCodes.PERSISTENCE_DELETE_FAILED, "delete", key),
1068
+ list: (prefix) => guarded(() => adapter.list(prefix), ErrorCodes.PERSISTENCE_LOAD_FAILED, "list", prefix)
1069
+ };
1070
+ }
1071
+ async function readListedFile(store, key, expected) {
1072
+ const length = store.byteLength === void 0 ? void 0 : await store.byteLength(key);
1073
+ if (length === null) missingFile(expected.what, key);
1074
+ if (length !== void 0) requireListedLength(expected.what, key, length, expected.bytes);
1075
+ const bytes = await store.read(key);
1076
+ if (bytes === null) missingFile(expected.what, key);
1077
+ requireListedLength(expected.what, key, bytes.byteLength, expected.bytes);
1078
+ return bytes;
1079
+ }
1080
+ function missingFile(what, key) {
1081
+ throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `The ${what} "${key}" that the manifest lists is missing`, {
1082
+ key
1083
+ });
1084
+ }
1085
+ function requireListedLength(what, key, found, listed) {
1086
+ if (found === listed) return;
1087
+ throw new NarsilError(
1088
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1089
+ `The ${what} "${key}" holds ${found} bytes where the manifest lists ${listed}`,
1090
+ { key, bytes: found, listed }
1091
+ );
1092
+ }
1093
+ function requireListedChecksum(what, key, found, listed) {
1094
+ if (found === listed) return;
1095
+ throw new NarsilError(
1096
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1097
+ `The ${what} "${key}" carries checksum ${found} where the manifest lists ${listed}`,
1098
+ { key, checksum: found, listed }
1099
+ );
1100
+ }
1101
+
1102
+ // src/persistence/durability/segment/vector-load.ts
1103
+ var VECTOR_FILE_ENVELOPE_VERSION = 2;
1104
+ var GRAPH_PART_ENVELOPE_VERSION = 2;
1105
+ function liveVectorsOf(ref) {
1106
+ let live = 0;
1107
+ for (const file of ref.files) live += file.count - countDead(file.dead, file.count);
1108
+ return live;
1109
+ }
1110
+ async function openListedFile(store, ref, what, allowsCompression) {
1111
+ const bytes = await readListedFile(store, ref.key, { bytes: ref.bytes, what });
1112
+ const { header: header2, payload } = await openChecksummedEnvelope(bytes, {
1113
+ envelopeFormatVersion: VECTOR_FILE_ENVELOPE_VERSION,
1114
+ what: `${what} "${ref.key}"`,
1115
+ allowsCompression
1116
+ });
1117
+ requireListedChecksum(what, ref.key, header2.checksum, ref.checksum);
1118
+ return { payload, payloadLength: header2.payloadLength };
1119
+ }
1120
+ async function readGraphParts(store, ref) {
1121
+ if (ref.graphParts.length === 0) return null;
1122
+ const parts = [];
1123
+ for (const part of ref.graphParts) {
1124
+ const { payload } = await openListedFile(store, part, "graph part", true);
1125
+ const decoded = decodeVectorGraphPartPayload(decode(payload));
1126
+ if (decoded.fieldName !== ref.fieldPath) {
1127
+ throw new NarsilError(
1128
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1129
+ `The graph part "${part.key}" names field "${decoded.fieldName}" where the manifest lists "${ref.fieldPath}"`,
1130
+ { key: part.key }
1131
+ );
1132
+ }
1133
+ parts.push(decoded);
1134
+ }
1135
+ return assembleGraphParts(parts);
1136
+ }
1137
+ async function readVectorFile(store, file, fieldPath) {
1138
+ const { payload: bytes, payloadLength } = await openListedFile(store, file, "vector file", false);
1139
+ const payload = decodeVectorFilePayload(decode(bytes));
1140
+ if (payload.docIds.length !== file.count) {
1141
+ throw new NarsilError(
1142
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1143
+ `The vector file "${file.key}" holds ${payload.docIds.length} vectors where the manifest counts ${file.count}`,
1144
+ { key: file.key, held: payload.docIds.length, count: file.count }
1145
+ );
1146
+ }
1147
+ if (payload.fieldName !== fieldPath) {
1148
+ throw new NarsilError(
1149
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1150
+ `The vector file "${file.key}" names field "${payload.fieldName}" where the manifest lists "${fieldPath}"`,
1151
+ { key: file.key }
1152
+ );
1153
+ }
1154
+ return { payload, payloadLength };
1155
+ }
1156
+ async function loadVectorField(store, ref, vectorIndex) {
1157
+ const restore = vectorIndex.restoreCheckpoint({
1158
+ liveVectors: liveVectorsOf(ref),
1159
+ holdsGraph: ref.graphParts.length > 0,
1160
+ graph: await readGraphParts(store, ref)
1161
+ });
1162
+ for (const file of ref.files) {
1163
+ const { payload, payloadLength } = await readVectorFile(store, file, ref.fieldPath);
1164
+ restore.addFile({
1165
+ id: file.id,
1166
+ key: file.key,
1167
+ payload,
1168
+ dead: file.dead,
1169
+ location: store.pathOf === void 0 ? null : {
1170
+ path: await store.pathOf(file.key),
1171
+ vectorsOffset: HEADER_SIZE + payloadLength - payload.vectors.byteLength
1172
+ }
1173
+ });
1174
+ }
1175
+ restore.finish();
1176
+ }
1177
+ var EMPTY_BIN = new Uint8Array(0);
1178
+ var EMPTY_BIN_BYTES = 2;
1179
+ var BIN8 = 196;
1180
+ var BIN16 = 197;
1181
+ var BIN32 = 198;
1182
+ var BIN8_MAX_BYTES = 255;
1183
+ var BIN16_MAX_BYTES = 65535;
1184
+ function binHeader(byteLength) {
1185
+ if (byteLength <= BIN8_MAX_BYTES) return Uint8Array.of(BIN8, byteLength);
1186
+ if (byteLength <= BIN16_MAX_BYTES) return Uint8Array.of(BIN16, byteLength >> 8, byteLength & 255);
1187
+ const header2 = new Uint8Array(5);
1188
+ header2[0] = BIN32;
1189
+ new DataView(header2.buffer).setUint32(1, byteLength, false);
1190
+ return header2;
1191
+ }
1192
+ function chunksEndingInBytes(withTheBytes, withEmptyBytesInTheirPlace, bytes) {
1193
+ const head = encode(withEmptyBytesInTheirPlace);
1194
+ const endsWithTheEmptyBin = head[head.length - EMPTY_BIN_BYTES] === BIN8 && head[head.length - 1] === 0;
1195
+ if (!endsWithTheEmptyBin) return [encode(withTheBytes)];
1196
+ return [head.subarray(0, head.length - EMPTY_BIN_BYTES), binHeader(bytes.byteLength), bytes];
1197
+ }
1198
+ function vectorPartChunks(part) {
1199
+ return chunksEndingInBytes(part, { ...part, vectors: EMPTY_BIN }, part.vectors);
1200
+ }
1201
+
1202
+ // src/persistence/durability/segment/vector-write.ts
1203
+ function keptFileRef(input, prior, kept) {
1204
+ const listed = prior?.files.find((file) => file.key === kept.key) ?? input.priorFileRefs?.get(kept.key);
1205
+ if (listed === void 0) {
1206
+ throw new NarsilError(
1207
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
1208
+ `The checkpoint keeps the vector file "${kept.key}", which the previous manifest does not list`,
1209
+ { key: kept.key }
1210
+ );
1211
+ }
1212
+ return { ...kept, bytes: listed.bytes, checksum: listed.checksum };
1213
+ }
1214
+ async function writeGraphParts(input, fieldPath, plan, generation) {
1215
+ const parts = plan.graphParts ?? [];
1216
+ const refs = [];
1217
+ for (let part = 0; part < parts.length; part++) {
1218
+ const key = graphPartKey(input.indexName, fieldPath, generation, part);
1219
+ const packed = await packChecksummedEnvelope(
1220
+ [encode(parts[part])],
1221
+ GRAPH_PART_ENVELOPE_VERSION,
1222
+ `graph part "${key}"`
1223
+ );
1224
+ await input.store.write(key, packed.chunks);
1225
+ refs.push({ key, bytes: packed.byteLength, checksum: packed.checksum });
1226
+ }
1227
+ return refs;
1228
+ }
1229
+ async function writeField(input, fieldPath, plan, outcome) {
1230
+ const prior = input.priorVectors.find((ref) => ref.fieldPath === fieldPath);
1231
+ if (plan.unchanged && prior !== void 0) {
1232
+ outcome.refs.push(prior);
1233
+ return;
1234
+ }
1235
+ let nextFileId = prior?.nextFileId ?? 0;
1236
+ const files = plan.kept.map((kept) => keptFileRef(input, prior, kept));
1237
+ const written = [];
1238
+ for (let index = 0; index < plan.newFiles; index++) {
1239
+ const { payload, ordinals, dead } = plan.readNewFile(index);
1240
+ const id = nextFileId;
1241
+ nextFileId += 1;
1242
+ const key = vectorFileKey(input.indexName, fieldPath, id);
1243
+ const packed = await packChecksummedEnvelope(
1244
+ vectorPartChunks(payload),
1245
+ VECTOR_FILE_ENVELOPE_VERSION,
1246
+ `vector file "${key}"`
1247
+ );
1248
+ await input.store.write(key, packed.chunks);
1249
+ files.push({ id, key, count: payload.docIds.length, dead, bytes: packed.byteLength, checksum: packed.checksum });
1250
+ written.push({ id, key, ordinals });
1251
+ outcome.layouts.push({
1252
+ fieldPath,
1253
+ key,
1254
+ docIds: payload.docIds,
1255
+ dead,
1256
+ vectorsOffset: packed.byteLength - payload.vectors.byteLength
1257
+ });
1258
+ }
1259
+ const priorGeneration = prior?.graphGeneration ?? 0;
1260
+ const holdsGraph = plan.graphParts !== null && plan.graphParts.length > 0;
1261
+ const graphGeneration = holdsGraph ? priorGeneration + 1 : priorGeneration;
1262
+ const graphParts = holdsGraph ? await writeGraphParts(input, fieldPath, plan, graphGeneration) : [];
1263
+ outcome.refs.push({ fieldPath, nextFileId, files, graphGeneration, graphParts });
1264
+ outcome.written.push({ fieldPath, plan, files: written });
1265
+ }
1266
+ async function writeLiveVectors(input) {
1267
+ const outcome = { refs: [], layouts: [], written: [] };
1268
+ for (const [fieldPath, plan] of input.plans) await writeField(input, fieldPath, plan, outcome);
1269
+ return outcome;
1270
+ }
1271
+
1272
+ // src/persistence/durability/seq-owner.ts
1273
+ var SINGLE_NODE_PRIMARY_TERM = 1;
1274
+ function createSeqOwner(startSeqNo, primaryTerm = SINGLE_NODE_PRIMARY_TERM) {
1275
+ let current = startSeqNo;
1276
+ let term = primaryTerm;
1277
+ return {
1278
+ next() {
1279
+ current += 1;
1280
+ return current;
1281
+ },
1282
+ advanceTo(seqNo, nextPrimaryTerm) {
1283
+ current = seqNo;
1284
+ term = nextPrimaryTerm;
1285
+ },
1286
+ get current() {
1287
+ return current;
1288
+ },
1289
+ get primaryTerm() {
1290
+ return term;
1291
+ }
1292
+ };
1293
+ }
1294
+
1295
+ // src/persistence/durability/partition-checkpoint.ts
1296
+ function checkpointLastSeqNo(checkpoint, partitionId) {
1297
+ for (const c of checkpoint) {
1298
+ if (c.partitionId === partitionId) {
1299
+ return c.lastSeqNo;
1300
+ }
1301
+ }
1302
+ return 0;
1303
+ }
1304
+ function checkpointPrimaryTerm(checkpoint, partitionId) {
1305
+ for (const c of checkpoint) {
1306
+ if (c.partitionId === partitionId) {
1307
+ return c.primaryTerm;
1308
+ }
1309
+ }
1310
+ return 0;
1311
+ }
1312
+
1313
+ // src/persistence/durability/commit-marker.ts
1314
+ var COMMIT_MARKER_SLOT_SIZE = 36;
1315
+ var COMMIT_MARKER_SLOT_COUNT = 2;
1316
+ var CRC_OFFSET = 32;
1317
+ function encodeMarkerSlot(state) {
1318
+ const slot = new Uint8Array(COMMIT_MARKER_SLOT_SIZE);
1319
+ const view = new DataView(slot.buffer);
1320
+ view.setBigUint64(0, BigInt(state.writeSeq), false);
1321
+ view.setBigUint64(8, BigInt(state.activeSegmentSeqNo), false);
1322
+ view.setBigUint64(16, BigInt(state.durableByteLength), false);
1323
+ view.setBigUint64(24, BigInt(state.highestDurableSeqNo), false);
1324
+ view.setUint32(CRC_OFFSET, crc32(slot.subarray(0, CRC_OFFSET)), false);
1325
+ return slot;
1326
+ }
1327
+ function decodeSlot(data, slotIndex) {
1328
+ const base = slotIndex * COMMIT_MARKER_SLOT_SIZE;
1329
+ if (base + COMMIT_MARKER_SLOT_SIZE > data.length) {
1330
+ return null;
1331
+ }
1332
+ const slot = data.subarray(base, base + COMMIT_MARKER_SLOT_SIZE);
1333
+ const view = new DataView(slot.buffer, slot.byteOffset, slot.byteLength);
1334
+ const storedCrc = view.getUint32(CRC_OFFSET, false);
1335
+ if (crc32(slot.subarray(0, CRC_OFFSET)) !== storedCrc) {
1336
+ return null;
1337
+ }
1338
+ const writeSeq = view.getBigUint64(0, false);
1339
+ const activeSegmentSeqNo = view.getBigUint64(8, false);
1340
+ const durableByteLength = view.getBigUint64(16, false);
1341
+ const highestDurableSeqNo = view.getBigUint64(24, false);
1342
+ if (writeSeq > BigInt(Number.MAX_SAFE_INTEGER) || activeSegmentSeqNo > BigInt(Number.MAX_SAFE_INTEGER) || durableByteLength > BigInt(Number.MAX_SAFE_INTEGER) || highestDurableSeqNo > BigInt(Number.MAX_SAFE_INTEGER)) {
1343
+ return null;
1344
+ }
1345
+ return {
1346
+ writeSeq: Number(writeSeq),
1347
+ activeSegmentSeqNo: Number(activeSegmentSeqNo),
1348
+ durableByteLength: Number(durableByteLength),
1349
+ highestDurableSeqNo: Number(highestDurableSeqNo)
1350
+ };
1351
+ }
1352
+ function readCommitMarker(data) {
1353
+ let best = null;
1354
+ for (let slotIndex = 0; slotIndex < COMMIT_MARKER_SLOT_COUNT; slotIndex += 1) {
1355
+ const state = decodeSlot(data, slotIndex);
1356
+ if (state === null) {
1357
+ continue;
1358
+ }
1359
+ if (best === null || state.writeSeq > best.state.writeSeq) {
1360
+ best = { state, slotIndex };
1361
+ }
1362
+ }
1363
+ return best;
1364
+ }
1365
+ function nextMarkerSlot(lastWrittenSlot) {
1366
+ if (lastWrittenSlot === null) {
1367
+ return 0;
1368
+ }
1369
+ return (lastWrittenSlot + 1) % COMMIT_MARKER_SLOT_COUNT;
1370
+ }
1371
+ function markerSlotOffset(slotIndex) {
1372
+ return slotIndex * COMMIT_MARKER_SLOT_SIZE;
1373
+ }
1374
+ function isRecord2(value) {
1375
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1376
+ }
1377
+ function optionalIndexUuid(value, payloadName) {
1378
+ if (value === void 0 || value === null) {
1379
+ return void 0;
1380
+ }
1381
+ if (typeof value !== "string" || value.length === 0) {
1382
+ throw new Error(`Invalid ${payloadName}: "indexUuid" must be a non-empty string or absent`);
1383
+ }
1384
+ return value;
1385
+ }
1386
+ function validateEntryPayload(decoded) {
1387
+ if (!isRecord2(decoded) || !isRecord2(decoded.entry)) {
1388
+ throw new Error('Invalid EntryPayload: missing or invalid "entry" field');
1389
+ }
1390
+ const entry = decoded.entry;
1391
+ if (typeof entry.seqNo !== "number") {
1392
+ throw new Error('Invalid EntryPayload: "entry.seqNo" must be a number');
1393
+ }
1394
+ if (typeof entry.primaryTerm !== "number") {
1395
+ throw new Error('Invalid EntryPayload: "entry.primaryTerm" must be a number');
1396
+ }
1397
+ if (entry.operation !== "INDEX" && entry.operation !== "DELETE") {
1398
+ throw new Error('Invalid EntryPayload: "entry.operation" must be "INDEX" or "DELETE"');
1399
+ }
1400
+ if (typeof entry.partitionId !== "number") {
1401
+ throw new Error('Invalid EntryPayload: "entry.partitionId" must be a number');
1402
+ }
1403
+ if (typeof entry.indexName !== "string") {
1404
+ throw new Error('Invalid EntryPayload: "entry.indexName" must be a string');
1405
+ }
1406
+ if (typeof entry.documentId !== "string") {
1407
+ throw new Error('Invalid EntryPayload: "entry.documentId" must be a string');
1408
+ }
1409
+ if (entry.document !== null && !(entry.document instanceof Uint8Array)) {
1410
+ throw new Error('Invalid EntryPayload: "entry.document" must be Uint8Array or null');
1411
+ }
1412
+ if (typeof entry.checksum !== "number") {
1413
+ throw new Error('Invalid EntryPayload: "entry.checksum" must be a number');
1414
+ }
1415
+ optionalIndexUuid(decoded.indexUuid, "EntryPayload");
1416
+ return decoded;
1417
+ }
1418
+ function computeEntryChecksum(entry) {
1419
+ const payload = encode([
1420
+ entry.seqNo,
1421
+ entry.primaryTerm,
1422
+ entry.operation,
1423
+ entry.partitionId,
1424
+ entry.indexName,
1425
+ entry.documentId,
1426
+ entry.document
1427
+ ]);
1428
+ return crc32(payload);
1429
+ }
1430
+ function buildEntry(fields) {
1431
+ return { ...fields, checksum: computeEntryChecksum(fields) };
1432
+ }
1433
+
1434
+ // src/persistence/durability/wal-framing.ts
1435
+ var WAL_MAGIC = new Uint8Array([78, 82, 83, 87]);
1436
+ var WAL_FORMAT_VERSION = 1;
1437
+ var SEGMENT_HEADER_SIZE = 8;
1438
+ var RECORD_LENGTH_SIZE = 4;
1439
+ var FRAME_CRC_SIZE = 4;
1440
+ var MAX_WAL_RECORD_BYTES = 268435456;
1441
+ function writeSegmentHeader() {
1442
+ const header2 = new Uint8Array(SEGMENT_HEADER_SIZE);
1443
+ header2.set(WAL_MAGIC, 0);
1444
+ header2[4] = WAL_FORMAT_VERSION & 255;
1445
+ return header2;
1446
+ }
1447
+ function frameRecord(entry) {
1448
+ const payload = encode(entry);
1449
+ const frame = new Uint8Array(RECORD_LENGTH_SIZE + payload.length + FRAME_CRC_SIZE);
1450
+ const view = new DataView(frame.buffer);
1451
+ view.setUint32(0, payload.length, false);
1452
+ frame.set(payload, RECORD_LENGTH_SIZE);
1453
+ view.setUint32(RECORD_LENGTH_SIZE + payload.length, crc32(payload), false);
1454
+ return frame;
1455
+ }
1456
+ function checkSegmentHeader(data) {
1457
+ if (data.length < SEGMENT_HEADER_SIZE) {
1458
+ return { ok: false, reason: "segment shorter than the 8-byte header" };
1459
+ }
1460
+ for (let i = 0; i < WAL_MAGIC.length; i += 1) {
1461
+ if (data[i] !== WAL_MAGIC[i]) {
1462
+ return { ok: false, reason: "missing NRSW magic" };
1463
+ }
1464
+ }
1465
+ const formatVersion = data[4];
1466
+ if (formatVersion > WAL_FORMAT_VERSION) {
1467
+ return {
1468
+ ok: false,
1469
+ reason: `WAL format version ${formatVersion} is newer than supported version ${WAL_FORMAT_VERSION}`
1470
+ };
1471
+ }
1472
+ return { ok: true };
1473
+ }
1474
+ function decodeEntry(payload) {
1475
+ const decoded = decode(payload);
1476
+ const { entry } = validateEntryPayload({ entry: decoded });
1477
+ if (computeEntryChecksum(entry) !== entry.checksum) {
1478
+ throw new Error("WAL record failed its logical entry checksum");
1479
+ }
1480
+ return entry;
1481
+ }
1482
+ function corrupt(message, details) {
1483
+ throw new NarsilError(ErrorCodes.PERSISTENCE_WAL_CORRUPT, message, details);
1484
+ }
1485
+ function readDurableRegion(data, durableByteLength, maxRecordBytes = MAX_WAL_RECORD_BYTES) {
1486
+ const header2 = checkSegmentHeader(data);
1487
+ if (!header2.ok) {
1488
+ corrupt(`WAL segment header invalid in durable region: ${header2.reason}`, { reason: header2.reason });
1489
+ }
1490
+ if (durableByteLength < SEGMENT_HEADER_SIZE || durableByteLength > data.length) {
1491
+ corrupt("Commit marker durable byte length is outside the segment", {
1492
+ durableByteLength,
1493
+ segmentLength: data.length
1494
+ });
1495
+ }
1496
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1497
+ const entries = [];
1498
+ let offset = SEGMENT_HEADER_SIZE;
1499
+ while (offset < durableByteLength) {
1500
+ if (offset + RECORD_LENGTH_SIZE > durableByteLength) {
1501
+ corrupt("WAL record length field overruns the durable region", { offset, durableByteLength });
1502
+ }
1503
+ const recordLength = view.getUint32(offset, false);
1504
+ if (recordLength === 0 || recordLength > maxRecordBytes) {
1505
+ corrupt("WAL record length is zero or exceeds the maximum record size", { offset, recordLength });
1506
+ }
1507
+ const payloadStart = offset + RECORD_LENGTH_SIZE;
1508
+ const crcStart = payloadStart + recordLength;
1509
+ const frameEnd = crcStart + FRAME_CRC_SIZE;
1510
+ if (frameEnd > durableByteLength) {
1511
+ corrupt("WAL record overruns the durable region", { offset, frameEnd, durableByteLength });
1512
+ }
1513
+ const payload = data.subarray(payloadStart, crcStart);
1514
+ const storedCrc = view.getUint32(crcStart, false);
1515
+ if (crc32(payload) !== storedCrc) {
1516
+ corrupt("WAL record failed its frame checksum inside the durable region", { offset });
1517
+ }
1518
+ let entry;
1519
+ try {
1520
+ entry = decodeEntry(payload);
1521
+ } catch (err) {
1522
+ corrupt("WAL record payload failed to decode inside the durable region", {
1523
+ offset,
1524
+ cause: err instanceof Error ? err.message : String(err)
1525
+ });
1526
+ }
1527
+ if (entries.length > 0 && entry.seqNo <= entries[entries.length - 1].seqNo) {
1528
+ corrupt("WAL sequence numbers are not strictly increasing", {
1529
+ previousSeqNo: entries[entries.length - 1].seqNo,
1530
+ seqNo: entry.seqNo
1531
+ });
1532
+ }
1533
+ entries.push(entry);
1534
+ offset = frameEnd;
1535
+ }
1536
+ return entries;
1537
+ }
1538
+ function readTailBeyondFrontier(data, durableByteLength, lastDurableSeqNo, maxRecordBytes = MAX_WAL_RECORD_BYTES) {
1539
+ const start = Math.max(durableByteLength, SEGMENT_HEADER_SIZE);
1540
+ const entries = [];
1541
+ if (start >= data.length) {
1542
+ return { entries, cleanEnd: start };
1543
+ }
1544
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1545
+ let offset = start;
1546
+ let cleanEnd = start;
1547
+ let previousSeqNo = lastDurableSeqNo;
1548
+ while (offset < data.length) {
1549
+ if (offset + RECORD_LENGTH_SIZE > data.length) {
1550
+ break;
1551
+ }
1552
+ const recordLength = view.getUint32(offset, false);
1553
+ if (recordLength === 0 || recordLength > maxRecordBytes) {
1554
+ break;
1555
+ }
1556
+ const payloadStart = offset + RECORD_LENGTH_SIZE;
1557
+ const crcStart = payloadStart + recordLength;
1558
+ const frameEnd = crcStart + FRAME_CRC_SIZE;
1559
+ if (frameEnd > data.length) {
1560
+ break;
1561
+ }
1562
+ const payload = data.subarray(payloadStart, crcStart);
1563
+ if (crc32(payload) !== view.getUint32(crcStart, false)) {
1564
+ break;
1565
+ }
1566
+ let entry;
1567
+ try {
1568
+ entry = decodeEntry(payload);
1569
+ } catch {
1570
+ break;
1571
+ }
1572
+ if (entry.seqNo <= previousSeqNo) {
1573
+ break;
1574
+ }
1575
+ entries.push(entry);
1576
+ previousSeqNo = entry.seqNo;
1577
+ offset = frameEnd;
1578
+ cleanEnd = frameEnd;
1579
+ }
1580
+ return { entries, cleanEnd };
1581
+ }
1582
+
1583
+ // src/persistence/durability/wal-segments.ts
1584
+ function walPrefix(indexName, partitionId) {
1585
+ return `${indexName}/wal/${partitionId}/`;
1586
+ }
1587
+ function segmentStartSeqNo(key, prefix) {
1588
+ if (!key.startsWith(prefix)) {
1589
+ return null;
1590
+ }
1591
+ const tail = key.slice(prefix.length);
1592
+ if (!/^\d{16}$/.test(tail)) {
1593
+ return null;
1594
+ }
1595
+ const value = Number.parseInt(tail, 10);
1596
+ return Number.isSafeInteger(value) ? value : null;
1597
+ }
1598
+ async function collectSegments(directory, prefix) {
1599
+ const keys = await directory.list(prefix);
1600
+ const refs = [];
1601
+ for (const key of keys) {
1602
+ const startSeqNo = segmentStartSeqNo(key, prefix);
1603
+ if (startSeqNo !== null) {
1604
+ refs.push({ key, startSeqNo });
1605
+ }
1606
+ }
1607
+ refs.sort((a, b) => a.startSeqNo - b.startSeqNo);
1608
+ return refs;
1609
+ }
1610
+ async function openWal(directory, indexName, partitionId) {
1611
+ const prefix = walPrefix(indexName, partitionId);
1612
+ const markerBytes = await directory.read(`${prefix}commit`);
1613
+ const marker = markerBytes === null ? null : readCommitMarker(markerBytes);
1614
+ if (marker === null) {
1615
+ return null;
1616
+ }
1617
+ return { marker, segments: await collectSegments(directory, prefix) };
1618
+ }
1619
+ async function* readSegmentsInOrder(directory, wal) {
1620
+ const { marker, segments } = wal;
1621
+ let highestRead = 0;
1622
+ for (const { key, startSeqNo } of segments) {
1623
+ if (startSeqNo > marker.state.activeSegmentSeqNo) {
1624
+ continue;
1625
+ }
1626
+ const bytes = await directory.read(key);
1627
+ if (bytes === null) {
1628
+ continue;
1629
+ }
1630
+ if (startSeqNo < marker.state.activeSegmentSeqNo) {
1631
+ const header2 = checkSegmentHeader(bytes);
1632
+ if (!header2.ok) {
1633
+ throw new NarsilError(
1634
+ ErrorCodes.PERSISTENCE_WAL_CORRUPT,
1635
+ `Sealed WAL segment header invalid: ${header2.reason}`,
1636
+ {
1637
+ key,
1638
+ reason: header2.reason
1639
+ }
1640
+ );
1641
+ }
1642
+ const durableEntries2 = readDurableRegion(bytes, bytes.length);
1643
+ for (const entry of durableEntries2) highestRead = Math.max(highestRead, entry.seqNo);
1644
+ yield { durableEntries: durableEntries2, activeTail: null };
1645
+ continue;
1646
+ }
1647
+ const durableEntries = readDurableRegion(bytes, marker.state.durableByteLength);
1648
+ for (const entry of durableEntries) highestRead = Math.max(highestRead, entry.seqNo);
1649
+ const tail = readTailBeyondFrontier(
1650
+ bytes,
1651
+ marker.state.durableByteLength,
1652
+ Math.max(highestRead, marker.state.highestDurableSeqNo)
1653
+ );
1654
+ yield {
1655
+ durableEntries,
1656
+ activeTail: { key, entries: tail.entries, cleanEnd: tail.cleanEnd, segmentLength: bytes.length }
1657
+ };
1658
+ }
1659
+ }
1660
+ async function readWalSegments(directory, indexName, partitionId) {
1661
+ const wal = await openWal(directory, indexName, partitionId);
1662
+ if (wal === null) {
1663
+ return null;
1664
+ }
1665
+ const durableEntries = [];
1666
+ let highestReadFromWal = 0;
1667
+ let activeTail = null;
1668
+ for await (const segment of readSegmentsInOrder(directory, wal)) {
1669
+ for (const entry of segment.durableEntries) {
1670
+ durableEntries.push(entry);
1671
+ highestReadFromWal = Math.max(highestReadFromWal, entry.seqNo);
1672
+ }
1673
+ activeTail = segment.activeTail ?? activeTail;
1674
+ }
1675
+ return { marker: wal.marker, segments: wal.segments, durableEntries, activeTail, highestReadFromWal };
1676
+ }
1677
+ function durableRecordMissing(indexName, partitionId, highestRead, marker) {
1678
+ return new NarsilError(
1679
+ ErrorCodes.PERSISTENCE_WAL_CORRUPT,
1680
+ "A durable WAL record is missing: the highest recovered seqNo is below the commit marker",
1681
+ { indexName, partitionId, highestRead, highestDurable: marker.state.highestDurableSeqNo }
1682
+ );
1683
+ }
1684
+ async function* walEntriesInRange(directory, indexName, partitionId, fromSeqNoExclusive, upToSeqNoInclusive) {
1685
+ const wal = await openWal(directory, indexName, partitionId);
1686
+ if (wal === null) {
1687
+ return;
1688
+ }
1689
+ let highestRead = 0;
1690
+ for await (const segment of readSegmentsInOrder(directory, wal)) {
1691
+ for (const entry of segment.durableEntries) {
1692
+ highestRead = Math.max(highestRead, entry.seqNo);
1693
+ if (entry.seqNo > fromSeqNoExclusive && entry.seqNo <= upToSeqNoInclusive) {
1694
+ yield entry;
1695
+ }
1696
+ }
1697
+ }
1698
+ if (Math.max(fromSeqNoExclusive, highestRead) < wal.marker.state.highestDurableSeqNo) {
1699
+ throw durableRecordMissing(indexName, partitionId, highestRead, wal.marker);
1700
+ }
1701
+ }
1702
+ function everyVectorFieldIsTopLevel(vectorFieldPaths) {
1703
+ for (const fieldPath of vectorFieldPaths) {
1704
+ if (fieldPath.includes(".")) return false;
1705
+ }
1706
+ return vectorFieldPaths.size > 0;
1707
+ }
1708
+ function documentWithoutVectors(encoded, vectorFieldPaths, leavesVectorsUndecoded) {
1709
+ const skipped = leavesVectorsUndecoded ? decodeMapWithoutFields(encoded, vectorFieldPaths) : null;
1710
+ if (skipped !== null) return skipped;
1711
+ const document = decode(encoded);
1712
+ restoreVectorFields(document, vectorFieldPaths);
1713
+ return prepareDocumentVectors(document, vectorFieldPaths).partitionDoc;
1714
+ }
1715
+ async function buildSegmentFromEntries(input) {
1716
+ const leavesVectorsUndecoded = everyVectorFieldIsTopLevel(input.vectorFieldPaths);
1717
+ const live = /* @__PURE__ */ new Map();
1718
+ const deleted = /* @__PURE__ */ new Set();
1719
+ for await (const entry of input.entries) {
1720
+ if (entry.operation === "DELETE") {
1721
+ deleted.add(entry.documentId);
1722
+ live.delete(entry.documentId);
1723
+ continue;
1724
+ }
1725
+ if (entry.document === null) continue;
1726
+ live.delete(entry.documentId);
1727
+ live.set(entry.documentId, documentWithoutVectors(entry.document, input.vectorFieldPaths, leavesVectorsUndecoded));
1728
+ }
1729
+ const tombstones = [];
1730
+ for (const docId of deleted) {
1731
+ if (!live.has(docId)) tombstones.push(docId);
1732
+ }
1733
+ if (live.size === 0 && tombstones.length === 0) {
1734
+ return null;
1735
+ }
1736
+ const documents = [];
1737
+ for (const [docId, document] of live) documents.push({ docId, document });
1738
+ const manager = createPartitionManager(input.indexName, input.config, input.language, createPartitionRouter(), 1);
1739
+ const payload = buildSegmentPayload(
1740
+ documents,
1741
+ input.config.schema,
1742
+ input.language,
1743
+ resolvePartitionInsertOptions(input.config, manager.analysis),
1744
+ input.config.trackPositions ?? true
1745
+ );
1746
+ const segment = createFrozenSegment(
1747
+ payload,
1748
+ documents.map((entry) => entry.document)
1749
+ );
1750
+ return { selections: [{ segment }], tombstones, docCount: live.size };
1751
+ }
1752
+ var FIXMAP = 128;
1753
+ var MAP16 = 222;
1754
+ var MAP32 = 223;
1755
+ var FIXARRAY = 144;
1756
+ var ARRAY16 = 220;
1757
+ var ARRAY32 = 221;
1758
+ var BIN82 = 196;
1759
+ var BIN162 = 197;
1760
+ var BIN322 = 198;
1761
+ var FIX_COUNT_LIMIT = 16;
1762
+ var UINT8_LIMIT = 256;
1763
+ var UINT16_LIMIT = 65536;
1764
+ function header(fixed, sixteen, thirtyTwo, count) {
1765
+ if (count < FIX_COUNT_LIMIT) return Uint8Array.of(fixed | count);
1766
+ if (count < UINT16_LIMIT) return Uint8Array.of(sixteen, count >> 8, count & 255);
1767
+ const bytes = new Uint8Array(5);
1768
+ bytes[0] = thirtyTwo;
1769
+ new DataView(bytes.buffer).setUint32(1, count, false);
1770
+ return bytes;
1771
+ }
1772
+ function binHeader2(byteLength) {
1773
+ if (byteLength < UINT8_LIMIT) return Uint8Array.of(BIN82, byteLength);
1774
+ if (byteLength < UINT16_LIMIT) return Uint8Array.of(BIN162, byteLength >> 8, byteLength & 255);
1775
+ const bytes = new Uint8Array(5);
1776
+ bytes[0] = BIN322;
1777
+ new DataView(bytes.buffer).setUint32(1, byteLength, false);
1778
+ return bytes;
1779
+ }
1780
+ var MessagePackChunks = class {
1781
+ chunks = [];
1782
+ byteLength = 0;
1783
+ push(chunk) {
1784
+ if (chunk.byteLength === 0) return;
1785
+ this.chunks.push(chunk);
1786
+ this.byteLength += chunk.byteLength;
1787
+ }
1788
+ map(entries) {
1789
+ this.push(header(FIXMAP, MAP16, MAP32, entries));
1790
+ return this;
1791
+ }
1792
+ array(items) {
1793
+ this.push(header(FIXARRAY, ARRAY16, ARRAY32, items));
1794
+ return this;
1795
+ }
1796
+ value(value) {
1797
+ this.push(encode(value));
1798
+ return this;
1799
+ }
1800
+ key(name) {
1801
+ return this.value(name);
1802
+ }
1803
+ binary(bytes) {
1804
+ this.push(binHeader2(bytes.byteLength));
1805
+ this.push(bytes);
1806
+ return this;
1807
+ }
1808
+ binaryOrNil(bytes) {
1809
+ return bytes === null ? this.value(null) : this.binary(bytes);
1810
+ }
1811
+ };
1812
+
1813
+ // src/serialization/keyword-segment/token-order.ts
1814
+ function slotsAreInTokenOrder(payloadSlots) {
1815
+ for (let at = 0; at < payloadSlots.length; at++) {
1816
+ if (payloadSlots[at] !== at) return false;
1817
+ }
1818
+ return true;
1819
+ }
1820
+ function reorderedPositions(arrays, postingOffsets) {
1821
+ const { positionOffsets, positionValues, tokenTable } = arrays;
1822
+ if (positionOffsets === null || positionValues === null) return { positionOffsets: null, positionValues: null };
1823
+ const postings = postingOffsets[postingOffsets.length - 1];
1824
+ const offsets = new Uint32Array(postings + 1);
1825
+ const values = new Uint32Array(positionValues.length);
1826
+ let cursor = 0;
1827
+ for (let token = 0; token < tokenTable.payloadSlots.length; token++) {
1828
+ const slot = tokenTable.payloadSlots[token];
1829
+ for (let from = arrays.postingOffsets[slot]; from < arrays.postingOffsets[slot + 1]; from++) {
1830
+ const to = postingOffsets[token] + (from - arrays.postingOffsets[slot]);
1831
+ offsets[to] = cursor;
1832
+ const start = positionOffsets[from];
1833
+ const end = positionOffsets[from + 1];
1834
+ values.set(positionValues.subarray(start, end), cursor);
1835
+ cursor += end - start;
1836
+ }
1837
+ }
1838
+ offsets[postings] = cursor;
1839
+ return { positionOffsets: offsets, positionValues: values };
1840
+ }
1841
+ function postingsInTokenOrder(arrays) {
1842
+ const { tokenTable } = arrays;
1843
+ if (slotsAreInTokenOrder(tokenTable.payloadSlots)) return arrays;
1844
+ const tokens = tokenTable.payloadSlots.length;
1845
+ const postingOffsets = new Uint32Array(tokens + 1);
1846
+ for (let token = 0; token < tokens; token++) {
1847
+ const slot = tokenTable.payloadSlots[token];
1848
+ postingOffsets[token + 1] = postingOffsets[token] + arrays.postingOffsets[slot + 1] - arrays.postingOffsets[slot];
1849
+ }
1850
+ const postings = postingOffsets[tokens];
1851
+ const postingDocIds = new Uint32Array(postings);
1852
+ const postingFrequencies = new Uint16Array(postings);
1853
+ const postingFieldIndices = new Uint16Array(postings);
1854
+ for (let token = 0; token < tokens; token++) {
1855
+ const slot = tokenTable.payloadSlots[token];
1856
+ const start = arrays.postingOffsets[slot];
1857
+ const end = arrays.postingOffsets[slot + 1];
1858
+ postingDocIds.set(arrays.postingDocIds.subarray(start, end), postingOffsets[token]);
1859
+ postingFrequencies.set(arrays.postingFrequencies.subarray(start, end), postingOffsets[token]);
1860
+ postingFieldIndices.set(arrays.postingFieldIndices.subarray(start, end), postingOffsets[token]);
1861
+ }
1862
+ return {
1863
+ postingOffsets,
1864
+ postingDocIds,
1865
+ postingFrequencies,
1866
+ postingFieldIndices,
1867
+ ...reorderedPositions(arrays, postingOffsets)
1868
+ };
1869
+ }
1870
+
1871
+ // src/serialization/keyword-segment/encode.ts
1872
+ var TOP_LEVEL_ENTRIES = 28;
1873
+ function writeFieldLengths(out, arrays) {
1874
+ out.array(arrays.fieldLengthNames.length);
1875
+ for (let f = 0; f < arrays.fieldLengthNames.length; f++) {
1876
+ out.map(2).key("field").value(arrays.fieldLengthNames[f]);
1877
+ out.key("lengths").binary(littleEndianBytes(arrays.fieldLengthColumns[f]));
1878
+ }
1879
+ }
1880
+ function writeValueColumns(out, columns) {
1881
+ out.array(columns.length);
1882
+ for (const column of columns) {
1883
+ out.map(3).key("field").value(column.fieldPath);
1884
+ out.key("documents").binary(littleEndianBytes(column.docIds));
1885
+ out.key("values").binary(littleEndianBytes(column.values));
1886
+ }
1887
+ }
1888
+ function writeBooleanColumns(out, columns) {
1889
+ out.array(columns.length);
1890
+ for (const column of columns) {
1891
+ out.map(3).key("field").value(column.fieldPath);
1892
+ out.key("trueDocuments").binary(littleEndianBytes(column.trueDocs));
1893
+ out.key("falseDocuments").binary(littleEndianBytes(column.falseDocs));
1894
+ }
1895
+ }
1896
+ function writeEnumColumns(out, columns) {
1897
+ out.array(columns.length);
1898
+ for (const column of columns) {
1899
+ out.map(4).key("field").value(column.fieldPath);
1900
+ out.key("values").value(column.values);
1901
+ out.key("offsets").binary(littleEndianBytes(column.offsets));
1902
+ out.key("documents").binary(littleEndianBytes(column.docIds));
1903
+ }
1904
+ }
1905
+ function writeGeopointColumns(out, columns) {
1906
+ out.array(columns.length);
1907
+ for (const column of columns) {
1908
+ out.map(4).key("field").value(column.fieldPath);
1909
+ out.key("documents").binary(littleEndianBytes(column.docIds));
1910
+ out.key("latitudes").binary(littleEndianBytes(column.latitudes));
1911
+ out.key("longitudes").binary(littleEndianBytes(column.longitudes));
1912
+ }
1913
+ }
1914
+ function writePatternColumns(out, columns) {
1915
+ out.array(columns.length);
1916
+ for (const column of columns) {
1917
+ out.map(5).key("field").value(column.fieldPath);
1918
+ out.key("documents").binary(littleEndianBytes(column.docIds));
1919
+ out.key("runs").binary(littleEndianBytes(column.runs));
1920
+ out.key("offsets").binary(littleEndianBytes(column.offsets));
1921
+ out.key("postings").binary(littleEndianBytes(column.postings));
1922
+ }
1923
+ }
1924
+ function writeSurfaceForms(out, arrays) {
1925
+ const table = arrays.surfaceTable;
1926
+ if (table === null || table.counts.length === 0) {
1927
+ out.value(null);
1928
+ return;
1929
+ }
1930
+ out.map(3).key("text").binary(table.blob);
1931
+ out.key("offsets").binary(littleEndianBytes(table.offsets));
1932
+ out.key("counts").binary(littleEndianBytes(table.counts));
1933
+ }
1934
+ function writePartialWords(out, arrays) {
1935
+ const table = arrays.partialWords;
1936
+ if (table === null) {
1937
+ out.value(null);
1938
+ return;
1939
+ }
1940
+ out.map(8).key("fields").value(table.fields);
1941
+ out.key("text").binary(table.spellings);
1942
+ out.key("offsets").binary(littleEndianBytes(table.spellingOffsets));
1943
+ out.key("tokens").binary(littleEndianBytes(table.spellingTokens));
1944
+ out.key("counts").binary(littleEndianBytes(table.spellingCounts));
1945
+ out.key("runs").binary(littleEndianBytes(table.runs));
1946
+ out.key("runOffsets").binary(littleEndianBytes(table.runOffsets));
1947
+ out.key("runEntries").binary(littleEndianBytes(table.runEntries));
1948
+ }
1949
+ function encodeKeywordSegment(contents) {
1950
+ const { arrays } = contents;
1951
+ const postings = postingsInTokenOrder(arrays);
1952
+ const out = new MessagePackChunks();
1953
+ out.map(TOP_LEVEL_ENTRIES);
1954
+ out.key("v").value(KEYWORD_SEGMENT_PAYLOAD_VERSION);
1955
+ out.key("schema").value(contents.schema);
1956
+ out.key("tombstones").value(contents.tombstones);
1957
+ out.key("documentCount").value(arrays.documentCount);
1958
+ out.key("ids").binary(arrays.idTable.blob);
1959
+ out.key("idOffsets").binary(littleEndianBytes(arrays.idTable.offsets));
1960
+ out.key("idOrder").binary(littleEndianBytes(arrays.idTable.sortedOrdinals));
1961
+ out.key("documents").binary(arrays.documentTable.blob);
1962
+ out.key("documentOffsets").binary(littleEndianBytes(arrays.documentTable.offsets));
1963
+ out.key("fieldNames").value(arrays.fieldNames);
1964
+ out.key("tokens").binary(arrays.tokenTable.blob);
1965
+ out.key("tokenOffsets").binary(littleEndianBytes(arrays.tokenTable.offsets));
1966
+ out.key("documentFrequencies").binary(littleEndianBytes(arrays.tokenTable.documentFrequencies));
1967
+ out.key("postingOffsets").binary(littleEndianBytes(postings.postingOffsets));
1968
+ out.key("postingDocuments").binary(littleEndianBytes(postings.postingDocIds));
1969
+ out.key("postingFrequencies").binary(littleEndianBytes(postings.postingFrequencies));
1970
+ out.key("postingFields").binary(littleEndianBytes(postings.postingFieldIndices));
1971
+ out.key("positionOffsets").binaryOrNil(postings.positionOffsets === null ? null : littleEndianBytes(postings.positionOffsets));
1972
+ out.key("positions").binaryOrNil(postings.positionValues === null ? null : littleEndianBytes(postings.positionValues));
1973
+ out.key("fieldLengths");
1974
+ writeFieldLengths(out, arrays);
1975
+ out.key("numeric");
1976
+ writeValueColumns(out, arrays.numeric);
1977
+ out.key("sizes");
1978
+ writeValueColumns(out, arrays.sizes);
1979
+ out.key("boolean");
1980
+ writeBooleanColumns(out, arrays.boolean);
1981
+ out.key("enum");
1982
+ writeEnumColumns(out, arrays.enums);
1983
+ out.key("geopoint");
1984
+ writeGeopointColumns(out, arrays.geo);
1985
+ out.key("pattern");
1986
+ writePatternColumns(out, arrays.pattern);
1987
+ out.key("surfaceForms");
1988
+ writeSurfaceForms(out, arrays);
1989
+ out.key("partialWords");
1990
+ writePartialWords(out, arrays);
1991
+ return out;
1992
+ }
1993
+
1994
+ // src/persistence/durability/segment/segment-file.ts
1995
+ function sharesMemoryWithWorkers() {
1996
+ return typeof SharedArrayBuffer === "function";
1997
+ }
1998
+ async function readSegmentFile(store, ref) {
1999
+ const bytes = await readListedFile(store, ref.key, { bytes: ref.bytes, what: "segment" });
2000
+ const { header: header2, payload } = await openChecksummedEnvelope(bytes, {
2001
+ envelopeFormatVersion: KEYWORD_SEGMENT_ENVELOPE_VERSION,
2002
+ what: `segment "${ref.key}"`,
2003
+ allowsCompression: true
2004
+ });
2005
+ requireListedChecksum("segment", ref.key, header2.checksum, ref.checksum);
2006
+ return decodeKeywordSegment(payload, sharesMemoryWithWorkers());
2007
+ }
2008
+ var ORDINAL_BYTES = 4;
2009
+ var POSTING_BYTES = 8;
2010
+ var VALUE_ENTRY_BYTES = 12;
2011
+ var GEOPOINT_ENTRY_BYTES = 20;
2012
+ var TOKEN_ENTRY_BYTES = 12;
2013
+ var STRING_HEADER_BYTES = 5;
2014
+ var encoder = new TextEncoder();
2015
+ function documentBytes(segment, ordinal) {
2016
+ const table = segment.arrays.documentTable;
2017
+ if (table !== null) return table.offsets[ordinal + 1] - table.offsets[ordinal];
2018
+ return messagePackUpperBoundBytes(segment.documentSource.docAt(ordinal));
2019
+ }
2020
+ function addPerEntry(costs, docIds, bytes) {
2021
+ for (let at = 0; at < docIds.length; at++) costs[docIds[at]] += bytes;
2022
+ }
2023
+ function chargePostings(segment, costs, chargesTokens) {
2024
+ const arrays = segment.arrays;
2025
+ const positions = arrays.positionOffsets;
2026
+ for (let p = 0; p < arrays.postingDocIds.length; p++) {
2027
+ let bytes = POSTING_BYTES;
2028
+ if (positions !== null) bytes += ORDINAL_BYTES * (1 + positions[p + 1] - positions[p]);
2029
+ costs[arrays.postingDocIds[p]] += bytes;
2030
+ }
2031
+ if (!chargesTokens) return;
2032
+ const table = arrays.tokenTable;
2033
+ for (let at = 0; at < table.size; at++) {
2034
+ const slot = table.payloadSlot(at);
2035
+ const bytes = table.byteLengthAt(at) + TOKEN_ENTRY_BYTES;
2036
+ for (let p = arrays.postingOffsets[slot]; p < arrays.postingOffsets[slot + 1]; p++) {
2037
+ costs[arrays.postingDocIds[p]] += bytes;
2038
+ }
2039
+ }
2040
+ }
2041
+ function chargeColumns(segment, costs) {
2042
+ const arrays = segment.arrays;
2043
+ for (const column of [...arrays.numeric, ...arrays.sizes]) addPerEntry(costs, column.docIds, VALUE_ENTRY_BYTES);
2044
+ for (const column of arrays.boolean) {
2045
+ addPerEntry(costs, column.trueDocs, ORDINAL_BYTES);
2046
+ addPerEntry(costs, column.falseDocs, ORDINAL_BYTES);
2047
+ }
2048
+ for (const column of arrays.enums) addPerEntry(costs, column.docIds, ORDINAL_BYTES);
2049
+ for (const column of arrays.geo) addPerEntry(costs, column.docIds, GEOPOINT_ENTRY_BYTES);
2050
+ for (const column of arrays.pattern) {
2051
+ addPerEntry(costs, column.docIds, ORDINAL_BYTES);
2052
+ addPerEntry(costs, column.postings, ORDINAL_BYTES);
2053
+ }
2054
+ }
2055
+ function stringListBytes(values) {
2056
+ let bytes = STRING_HEADER_BYTES;
2057
+ for (const value of values) bytes += STRING_HEADER_BYTES + encoder.encode(value).byteLength;
2058
+ return bytes;
2059
+ }
2060
+ function fixedBytesOf(segment, chargesTokens) {
2061
+ const arrays = segment.arrays;
2062
+ let bytes = stringListBytes(arrays.fieldNames);
2063
+ if (!chargesTokens) bytes += arrays.tokenTable.bytes;
2064
+ for (const column of arrays.enums) bytes += stringListBytes(column.values) + column.offsets.byteLength;
2065
+ for (const column of arrays.pattern) bytes += column.runs.byteLength + column.offsets.byteLength;
2066
+ const surfaces = segment.sharedSnapshot?.surfaceTable ?? null;
2067
+ if (surfaces !== null) bytes += surfaces.blob.byteLength + surfaces.offsets.byteLength + surfaces.counts.byteLength;
2068
+ else bytes += messagePackUpperBoundBytes(arrays.readSurfaceForms());
2069
+ return bytes + segment.partialWords.bytes();
2070
+ }
2071
+ function keptDocumentsOf(selection, chargesTokens) {
2072
+ const { segment } = selection;
2073
+ const count = segment.arrays.documentCount;
2074
+ const costs = new Float64Array(count);
2075
+ const perDocument = ORDINAL_BYTES * (3 + segment.arrays.fieldLengthColumns.length);
2076
+ for (let ordinal = 0; ordinal < count; ordinal++) {
2077
+ costs[ordinal] = perDocument + encoder.encode(segment.arrays.idTable.idAt(ordinal)).byteLength;
2078
+ }
2079
+ chargePostings(segment, costs, chargesTokens);
2080
+ chargeColumns(segment, costs);
2081
+ const ordinals = [];
2082
+ for (let ordinal = 0; ordinal < count; ordinal++) {
2083
+ if (!selectionKeeps(selection, ordinal)) continue;
2084
+ costs[ordinal] += documentBytes(segment, ordinal);
2085
+ ordinals.push(ordinal);
2086
+ }
2087
+ return { segment, ordinals, costs };
2088
+ }
2089
+ function selectionOf(segment, ordinals) {
2090
+ const marked = new Uint8Array(segment.arrays.documentCount);
2091
+ for (const ordinal of ordinals) marked[ordinal] = 1;
2092
+ return { segment, keep: (ordinal) => marked[ordinal] === 1 };
2093
+ }
2094
+ function tooLargeForOneFile(cost, budget) {
2095
+ throw new NarsilError(
2096
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2097
+ `A document needs up to ${Math.ceil(cost)} bytes of a segment, more than the ${Math.max(0, Math.floor(budget))} that one file leaves it`,
2098
+ { bytes: Math.ceil(cost), budget: Math.floor(budget), maximum: MAX_FILE_BYTES }
2099
+ );
2100
+ }
2101
+ function splitIntoSegmentFiles(selections, schema, tombstones) {
2102
+ let tokenBytes = 0;
2103
+ for (const { segment } of selections) tokenBytes += segment.arrays.tokenTable.bytes;
2104
+ const chargesTokens = tokenBytes > MAX_FILE_BYTES * SEGMENT_TOKEN_TABLE_SHARE_OF_FILE;
2105
+ let fixed = HEADER_SIZE + SEGMENT_FILE_FRAMING_SLACK_BYTES + encode(schema).byteLength + encode(tombstones).byteLength;
2106
+ for (const { segment } of selections) fixed += fixedBytesOf(segment, chargesTokens);
2107
+ const budget = MAX_FILE_BYTES - fixed;
2108
+ const groups = [];
2109
+ let current = [];
2110
+ let currentBytes = 0;
2111
+ let currentCount = 0;
2112
+ const flush = () => {
2113
+ if (currentCount === 0) return;
2114
+ groups.push({
2115
+ selections: current.map((entry) => selectionOf(entry.segment, entry.ordinals)),
2116
+ documentCount: currentCount
2117
+ });
2118
+ current = [];
2119
+ currentBytes = 0;
2120
+ currentCount = 0;
2121
+ };
2122
+ for (const selection of selections) {
2123
+ const kept = keptDocumentsOf(selection, chargesTokens);
2124
+ let entry = null;
2125
+ for (const ordinal of kept.ordinals) {
2126
+ const cost = kept.costs[ordinal];
2127
+ if (cost > budget) tooLargeForOneFile(cost, budget);
2128
+ if (currentBytes + cost > budget) {
2129
+ flush();
2130
+ entry = null;
2131
+ }
2132
+ if (entry === null) {
2133
+ entry = { segment: kept.segment, ordinals: [] };
2134
+ current.push(entry);
2135
+ }
2136
+ entry.ordinals.push(ordinal);
2137
+ currentBytes += cost;
2138
+ currentCount += 1;
2139
+ }
2140
+ }
2141
+ flush();
2142
+ return groups;
2143
+ }
2144
+ function halvesOf(group) {
2145
+ const flat = [];
2146
+ for (const selection of group.selections) {
2147
+ for (let ordinal = 0; ordinal < selection.segment.arrays.documentCount; ordinal++) {
2148
+ if (!selectionKeeps(selection, ordinal)) continue;
2149
+ flat.push({ segment: selection.segment, ordinal });
2150
+ }
2151
+ }
2152
+ const middle = Math.ceil(flat.length / 2);
2153
+ const groupOf = (entries) => {
2154
+ const bySegment = /* @__PURE__ */ new Map();
2155
+ for (const { segment, ordinal } of entries) {
2156
+ let ordinals = bySegment.get(segment);
2157
+ if (ordinals === void 0) {
2158
+ ordinals = [];
2159
+ bySegment.set(segment, ordinals);
2160
+ }
2161
+ ordinals.push(ordinal);
2162
+ }
2163
+ return {
2164
+ selections: [...bySegment].map(([segment, ordinals]) => selectionOf(segment, ordinals)),
2165
+ documentCount: entries.length
2166
+ };
2167
+ };
2168
+ return [groupOf(flat.slice(0, middle)), groupOf(flat.slice(middle))];
2169
+ }
2170
+
2171
+ // src/persistence/durability/segment/segment-write.ts
2172
+ function emptyPayload() {
2173
+ return {
2174
+ documentCount: 0,
2175
+ docIds: [],
2176
+ fieldNames: [],
2177
+ tokens: [],
2178
+ postingOffsets: new Uint32Array(1),
2179
+ postingDocIds: new Uint32Array(0),
2180
+ postingFrequencies: new Uint16Array(0),
2181
+ postingFieldIndices: new Uint16Array(0),
2182
+ positionOffsets: null,
2183
+ positionValues: null,
2184
+ fieldLengthNames: [],
2185
+ fieldLengthColumns: [],
2186
+ totalFieldLengths: {},
2187
+ docFrequencies: {},
2188
+ surfaceForms: null,
2189
+ partialSpellings: null,
2190
+ numeric: [],
2191
+ boolean: [],
2192
+ enums: [],
2193
+ geo: [],
2194
+ pattern: [],
2195
+ sizes: []
2196
+ };
2197
+ }
2198
+ function noSpellingsOf(analysis) {
2199
+ if (analysis === null || analysis.fields.length === 0) return null;
2200
+ return { fields: [...analysis.fields], tokens: [], spellings: [], counts: [] };
2201
+ }
2202
+ function contentsOfGroup(group, request, tombstones) {
2203
+ const { schema, partialWordAnalysis, textAnalysis } = request;
2204
+ if (group === null) {
2205
+ const payload = { ...emptyPayload(), partialSpellings: noSpellingsOf(partialWordAnalysis) };
2206
+ return {
2207
+ schema,
2208
+ tombstones,
2209
+ arrays: segmentArraysOf(payload, { blob: new Uint8Array(0), offsets: new Uint32Array(1) })
2210
+ };
2211
+ }
2212
+ const merged = mergeSegmentContents(group.selections, partialWordAnalysis, textAnalysis);
2213
+ return {
2214
+ schema,
2215
+ tombstones,
2216
+ arrays: segmentArraysOf(merged.payload, merged.documents, merged.reusedPartialWords)
2217
+ };
2218
+ }
2219
+ function requireRoomForAnotherSegment(state) {
2220
+ if (state.segments.length < MAX_SEGMENTS_PER_PARTITION) return;
2221
+ throw new NarsilError(
2222
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2223
+ `Partition ${state.request.partitionId} would hold more than ${MAX_SEGMENTS_PER_PARTITION} segments`,
2224
+ { partitionId: state.request.partitionId, maximum: MAX_SEGMENTS_PER_PARTITION }
2225
+ );
2226
+ }
2227
+ async function writeGroup(state, group) {
2228
+ const { request } = state;
2229
+ const tombstones = state.tombstonesWritten ? [] : [...request.tombstones];
2230
+ const contents = contentsOfGroup(group, request, tombstones);
2231
+ const encoded = encodeKeywordSegment(contents);
2232
+ if (HEADER_SIZE + encoded.byteLength > MAX_FILE_BYTES && group !== null && group.documentCount > 1) {
2233
+ const [first, second] = halvesOf(group);
2234
+ await writeGroup(state, first);
2235
+ await writeGroup(state, second);
2236
+ return;
2237
+ }
2238
+ requireRoomForAnotherSegment(state);
2239
+ const id = state.nextSegmentId;
2240
+ const key = segmentKey(request.indexName, request.partitionId, id);
2241
+ const packed = await packChecksummedEnvelope(encoded.chunks, KEYWORD_SEGMENT_ENVELOPE_VERSION, `segment "${key}"`);
2242
+ await request.store.write(key, packed.chunks);
2243
+ state.segments.push({
2244
+ id,
2245
+ key,
2246
+ bytes: packed.byteLength,
2247
+ checksum: packed.checksum,
2248
+ docCount: contents.arrays.documentCount,
2249
+ tombstoneCount: tombstones.length
2250
+ });
2251
+ state.nextSegmentId = id + 1;
2252
+ state.tombstonesWritten = true;
2253
+ }
2254
+ function keptDocumentCount(selections) {
2255
+ let count = 0;
2256
+ for (const selection of selections) {
2257
+ for (let ordinal = 0; ordinal < selection.segment.arrays.documentCount; ordinal++) {
2258
+ if (selectionKeeps(selection, ordinal)) count += 1;
2259
+ }
2260
+ }
2261
+ return count;
2262
+ }
2263
+ async function writeSegmentsOf(request) {
2264
+ const state = { request, segments: [], nextSegmentId: request.nextSegmentId, tombstonesWritten: false };
2265
+ const groups = request.mergesIntoOneFile === true ? [{ selections: [...request.selections], documentCount: keptDocumentCount(request.selections) }] : splitIntoSegmentFiles(request.selections, request.schema, request.tombstones);
2266
+ for (const group of groups) {
2267
+ if (group.documentCount > 0) await writeGroup(state, group);
2268
+ }
2269
+ if (!state.tombstonesWritten && request.tombstones.length > 0) await writeGroup(state, null);
2270
+ return { segments: state.segments, nextSegmentId: state.nextSegmentId };
2271
+ }
2272
+
2273
+ // src/persistence/durability/segment/compaction.ts
2274
+ function windowFits(segments, start, windowLength) {
2275
+ let documents = 0;
2276
+ let bytes = SEGMENT_FILE_FRAMING_SLACK_BYTES;
2277
+ for (let at = start; at < start + windowLength; at++) {
2278
+ documents += segments[at].docCount;
2279
+ bytes += segments[at].bytes;
2280
+ }
2281
+ return documents <= COMPACTION_LARGEST_MERGED_DOCUMENT_COUNT && bytes <= MAX_FILE_BYTES;
2282
+ }
2283
+ function smallestFittingWindow(segments, windowLength) {
2284
+ let best = null;
2285
+ let bestBytes = Number.POSITIVE_INFINITY;
2286
+ for (let start = 0; start + windowLength <= segments.length; start++) {
2287
+ if (!windowFits(segments, start, windowLength)) continue;
2288
+ let bytes = 0;
2289
+ for (let at = start; at < start + windowLength; at++) bytes += segments[at].bytes;
2290
+ if (bytes < bestBytes) {
2291
+ bestBytes = bytes;
2292
+ best = { start, windowLength };
2293
+ }
2294
+ }
2295
+ return best;
2296
+ }
2297
+ function chooseWindow(segments, wantedLength) {
2298
+ for (let windowLength = Math.min(wantedLength, segments.length); windowLength >= 2; windowLength--) {
2299
+ const window = smallestFittingWindow(segments, windowLength);
2300
+ if (window !== null) return window;
2301
+ }
2302
+ return null;
2303
+ }
2304
+ function frozenOf(contents) {
2305
+ return createSharedFrozenSegment(shareSegmentArrays(contents.arrays, null));
2306
+ }
2307
+ function applyTimeOrder(frozen, contents) {
2308
+ for (let newer = 1; newer < frozen.length; newer++) {
2309
+ const replaced = new Set(contents[newer].tombstones);
2310
+ const ids = frozen[newer].arrays.idTable;
2311
+ for (let ordinal = 0; ordinal < ids.count; ordinal++) replaced.add(ids.idAt(ordinal));
2312
+ for (let older = 0; older < newer; older++) {
2313
+ for (const docId of replaced) frozen[older].tombstoneDocument(docId);
2314
+ }
2315
+ }
2316
+ }
2317
+ function retainedTombstones(frozen, contents) {
2318
+ const retained = /* @__PURE__ */ new Set();
2319
+ for (const segment of contents) {
2320
+ for (const docId of segment.tombstones) {
2321
+ if (!frozen.some((candidate) => candidate.hasDocument(docId))) retained.add(docId);
2322
+ }
2323
+ }
2324
+ return [...retained];
2325
+ }
2326
+ async function compactPartitionSegments(input) {
2327
+ const { segments, compactionThreshold } = input;
2328
+ if (segments.length <= compactionThreshold) {
2329
+ return { segments, nextSegmentId: input.nextSegmentId };
2330
+ }
2331
+ const window = chooseWindow(segments, segments.length - compactionThreshold + 1);
2332
+ if (window === null) {
2333
+ return { segments, nextSegmentId: input.nextSegmentId };
2334
+ }
2335
+ const windowRefs = segments.slice(window.start, window.start + window.windowLength);
2336
+ const contents = [];
2337
+ for (const ref of windowRefs) contents.push(await readSegmentFile(input.store, ref));
2338
+ const frozen = contents.map(frozenOf);
2339
+ applyTimeOrder(frozen, contents);
2340
+ const written = await writeSegmentsOf({
2341
+ store: input.store,
2342
+ indexName: input.indexName,
2343
+ partitionId: input.partitionId,
2344
+ nextSegmentId: input.nextSegmentId,
2345
+ schema: input.schema,
2346
+ partialWordAnalysis: input.partialWordAnalysis,
2347
+ textAnalysis: input.textAnalysis,
2348
+ selections: frozen.map((segment) => ({ segment })),
2349
+ tombstones: retainedTombstones(frozen, contents),
2350
+ mergesIntoOneFile: true
2351
+ });
2352
+ return {
2353
+ segments: [
2354
+ ...segments.slice(0, window.start),
2355
+ ...written.segments,
2356
+ ...segments.slice(window.start + window.windowLength)
2357
+ ],
2358
+ nextSegmentId: written.nextSegmentId
2359
+ };
2360
+ }
2361
+
2362
+ // src/persistence/durability/segment/write.ts
2363
+ function textAnalysisOf(config) {
2364
+ let resolved = null;
2365
+ const resolve = () => {
2366
+ resolved ??= {
2367
+ language: getLanguage(config.language ?? "english"),
2368
+ options: resolvePartitionInsertOptions(config, resolveIndexAnalysis(config))
2369
+ };
2370
+ return resolved;
2371
+ };
2372
+ return {
2373
+ get language() {
2374
+ return resolve().language;
2375
+ },
2376
+ get options() {
2377
+ return resolve().options;
2378
+ }
2379
+ };
2380
+ }
2381
+ function partialWordAnalysisOf(config, text) {
2382
+ const fields = partialFieldsOf(config.schema);
2383
+ if (fields.length === 0) return null;
2384
+ return {
2385
+ fields,
2386
+ get language() {
2387
+ return text.language;
2388
+ },
2389
+ get options() {
2390
+ return text.options;
2391
+ }
2392
+ };
2393
+ }
2394
+ function resolveCompactionThreshold(configured) {
2395
+ if (!Number.isInteger(configured) || configured <= 0 || configured > MAX_SEGMENTS_PER_PARTITION) {
2396
+ return DEFAULT_COMPACTION_THRESHOLD;
2397
+ }
2398
+ return configured;
2399
+ }
2400
+ function wholeContentsOf(input, partitionId) {
2401
+ const whole = input.wholePartitions?.find((candidate) => candidate.partitionId === partitionId);
2402
+ if (whole !== void 0) return whole;
2403
+ const captured = input.capturedPartitions?.find((candidate) => candidate.partitionId === partitionId);
2404
+ return captured === void 0 ? void 0 : contentsOfCaptured(captured);
2405
+ }
2406
+ async function writeWholePartition(context, partitionId, priorPartition, whole) {
2407
+ const written = await writeSegmentsOf({
2408
+ store: context.input.store,
2409
+ indexName: context.indexName,
2410
+ partitionId,
2411
+ nextSegmentId: priorPartition?.nextSegmentId ?? 0,
2412
+ schema: context.input.metadata.schema,
2413
+ partialWordAnalysis: context.partialWordAnalysis,
2414
+ textAnalysis: context.textAnalysis,
2415
+ selections: whole.selections,
2416
+ tombstones: []
2417
+ });
2418
+ return { partitionId, nextSegmentId: written.nextSegmentId, segments: written.segments };
2419
+ }
2420
+ async function writeLoggedChanges(context, partitionId, priorPartition, entries) {
2421
+ const built = await buildSegmentFromEntries({
2422
+ indexName: context.indexName,
2423
+ config: context.config,
2424
+ language: getLanguage(context.config.language ?? "english"),
2425
+ vectorFieldPaths: context.vectorFieldPaths,
2426
+ entries
2427
+ });
2428
+ let segments = priorPartition ? [...priorPartition.segments] : [];
2429
+ let nextSegmentId = priorPartition?.nextSegmentId ?? 0;
2430
+ if (built !== null) {
2431
+ const written = await writeSegmentsOf({
2432
+ store: context.input.store,
2433
+ indexName: context.indexName,
2434
+ partitionId,
2435
+ nextSegmentId,
2436
+ schema: context.input.metadata.schema,
2437
+ partialWordAnalysis: context.partialWordAnalysis,
2438
+ textAnalysis: context.textAnalysis,
2439
+ selections: built.selections,
2440
+ tombstones: built.tombstones
2441
+ });
2442
+ segments.push(...written.segments);
2443
+ nextSegmentId = written.nextSegmentId;
2444
+ }
2445
+ if (segments.length > MAX_SEGMENTS_PER_PARTITION) {
2446
+ throw new NarsilError(
2447
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2448
+ `Partition ${partitionId} would exceed the maximum of ${MAX_SEGMENTS_PER_PARTITION} segments`,
2449
+ { partitionId, segmentCount: segments.length, maximum: MAX_SEGMENTS_PER_PARTITION }
2450
+ );
2451
+ }
2452
+ const compacted = await compactPartitionSegments({
2453
+ store: context.input.store,
2454
+ indexName: context.indexName,
2455
+ partitionId,
2456
+ schema: context.input.metadata.schema,
2457
+ partialWordAnalysis: context.partialWordAnalysis,
2458
+ textAnalysis: context.textAnalysis,
2459
+ segments,
2460
+ nextSegmentId,
2461
+ compactionThreshold: context.compactionThreshold
2462
+ });
2463
+ segments = compacted.segments;
2464
+ nextSegmentId = compacted.nextSegmentId;
2465
+ return { partitionId, nextSegmentId, segments };
2466
+ }
2467
+ function carryForwardUncheckpointedPartitions(prior, targets, partitions, checkpointByPartition) {
2468
+ if (prior === null) return;
2469
+ const covered = new Set(targets.map((target) => target.partitionId));
2470
+ for (const priorPartition of prior.partitions) {
2471
+ if (covered.has(priorPartition.partitionId)) continue;
2472
+ partitions.push(priorPartition);
2473
+ const priorCheckpoint = prior.checkpoint.find((c) => c.partitionId === priorPartition.partitionId);
2474
+ if (priorCheckpoint !== void 0 && !checkpointByPartition.has(priorPartition.partitionId)) {
2475
+ checkpointByPartition.set(priorPartition.partitionId, priorCheckpoint);
2476
+ }
2477
+ }
2478
+ }
2479
+ async function writeCheckpointSegments(input) {
2480
+ const config = reconstructSchemaFromMetadata(input.metadata);
2481
+ const textAnalysis = textAnalysisOf(config);
2482
+ const context = {
2483
+ input,
2484
+ indexName: input.metadata.indexName,
2485
+ config,
2486
+ partialWordAnalysis: partialWordAnalysisOf(config, textAnalysis),
2487
+ textAnalysis,
2488
+ vectorFieldPaths: new Set(extractVectorFieldsFromSchema(config.schema).keys()),
2489
+ compactionThreshold: resolveCompactionThreshold(input.compactionThreshold)
2490
+ };
2491
+ const checkpointByPartition = /* @__PURE__ */ new Map();
2492
+ for (const target of input.targets) checkpointByPartition.set(target.partitionId, { ...target });
2493
+ const partitions = [];
2494
+ for (const target of input.targets) {
2495
+ const priorPartition = input.prior?.partitions.find((p) => p.partitionId === target.partitionId);
2496
+ const whole = wholeContentsOf(input, target.partitionId);
2497
+ if (whole !== void 0) {
2498
+ partitions.push(await writeWholePartition(context, target.partitionId, priorPartition, whole));
2499
+ continue;
2500
+ }
2501
+ if (input.directory === void 0) {
2502
+ throw new NarsilError(
2503
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2504
+ `The checkpoint of partition ${target.partitionId} holds neither the partition's content nor a log to read it from`,
2505
+ { partitionId: target.partitionId }
2506
+ );
2507
+ }
2508
+ const priorSeqNo = checkpointLastSeqNo(input.prior?.checkpoint ?? [], target.partitionId);
2509
+ const entries = walEntriesInRange(
2510
+ input.directory,
2511
+ context.indexName,
2512
+ target.partitionId,
2513
+ priorSeqNo,
2514
+ target.lastSeqNo
2515
+ );
2516
+ partitions.push(await writeLoggedChanges(context, target.partitionId, priorPartition, entries));
2517
+ }
2518
+ carryForwardUncheckpointedPartitions(input.prior, input.targets, partitions, checkpointByPartition);
2519
+ return { checkpoint: [...checkpointByPartition.values()], partitions };
2520
+ }
2521
+ async function commitCheckpointManifest(store, metadata, written, vectors) {
2522
+ const indexName = metadata.indexName;
2523
+ const manifest = {
2524
+ schema: metadata.schema,
2525
+ language: metadata.language,
2526
+ checkpoint: written.checkpoint,
2527
+ partitions: written.partitions,
2528
+ vectors
2529
+ };
2530
+ const packed = await encodeSegmentManifest(manifest);
2531
+ await store.write(manifestKey(indexName), packed.chunks);
2532
+ return { garbage: await unreferencedKeys(store, indexName, manifest) };
2533
+ }
2534
+ async function unreferencedKeys(store, indexName, manifest) {
2535
+ const referenced = manifestReferencedKeys(manifest);
2536
+ const stored = await store.list(segmentsPrefix(indexName));
2537
+ return [...stored.filter((key) => !referenced.has(key)), snapshotBundleKey(indexName)];
2538
+ }
2539
+ async function removeCheckpointGarbage(store, garbage) {
2540
+ for (const key of garbage) {
2541
+ await store.remove(key);
2542
+ }
2543
+ }
2544
+
2545
+ // src/persistence/durability/segment/load-partition.ts
2546
+ function requireAgreedSchema(agreed, schema, key) {
2547
+ for (const [field, type] of Object.entries(schema)) {
2548
+ const existing = agreed[field];
2549
+ if (existing !== void 0 && existing !== type) {
2550
+ throw new NarsilError(
2551
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
2552
+ `The segment "${key}" gives field "${field}" the type "${type}", while the index gives it "${existing}"`,
2553
+ { key, field, existing, found: type }
2554
+ );
2555
+ }
2556
+ }
2557
+ }
2558
+ function removeWhatTheSegmentReplaces(manager, segment, contents) {
2559
+ manager.beginBatchRemove();
2560
+ try {
2561
+ for (const docId of contents.tombstones) {
2562
+ if (manager.has(docId)) manager.remove(docId);
2563
+ }
2564
+ const ids = segment.arrays.idTable;
2565
+ for (let ordinal = 0; ordinal < ids.count; ordinal++) {
2566
+ const docId = ids.idAt(ordinal);
2567
+ if (manager.has(docId)) manager.remove(docId);
2568
+ }
2569
+ } finally {
2570
+ manager.endBatchRemove();
2571
+ }
2572
+ }
2573
+ function yieldToEventLoop() {
2574
+ return new Promise((resolve) => setTimeout(resolve, 0));
2575
+ }
2576
+ async function loadPartitionSegments(store, partition, manager, options) {
2577
+ for (const ref of partition.segments) {
2578
+ const contents = await readSegmentFile(store, ref);
2579
+ requireAgreedSchema(options.schema, contents.schema, ref.key);
2580
+ if (options.decodesEveryDocument) decodeEveryStoredDocument(contents.arrays.documentTable);
2581
+ const segment = createSharedFrozenSegment(shareSegmentArrays(contents.arrays, manager.partialWordAnalysis));
2582
+ removeWhatTheSegmentReplaces(manager, segment, contents);
2583
+ if (contents.arrays.documentCount > 0) manager.attachFrozenSegment(partition.partitionId, segment);
2584
+ await yieldToEventLoop();
2585
+ }
2586
+ }
2587
+
2588
+ // src/persistence/durability/segment/load.ts
2589
+ async function readSegmentManifest(store, indexName) {
2590
+ const bytes = await store.read(manifestKey(indexName));
2591
+ if (bytes === null) return null;
2592
+ return decodeSegmentManifest(bytes, indexName);
2593
+ }
2594
+ async function readCurrentManifest(store, indexName) {
2595
+ const decoded = await readSegmentManifest(store, indexName);
2596
+ if (decoded === null) return null;
2597
+ if (decoded.kind === "current") return decoded.manifest;
2598
+ throw new NarsilError(
2599
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2600
+ `Index "${indexName}" still holds the layout of an earlier release, which recovery upgrades before any checkpoint`,
2601
+ { indexName }
2602
+ );
2603
+ }
2604
+ function growPartitionsTo(manager, highestPartitionId) {
2605
+ while (manager.partitionCount <= highestPartitionId) {
2606
+ const before = manager.partitionCount;
2607
+ try {
2608
+ manager.addPartition();
2609
+ } catch {
2610
+ break;
2611
+ }
2612
+ if (manager.partitionCount === before) break;
2613
+ }
2614
+ }
2615
+ async function loadSegmentedCheckpoint(store, indexName, manifest, deps, decodesEveryDocument = false) {
2616
+ let highestPartitionId = manifest.partitions.length - 1;
2617
+ for (const partition of manifest.partitions) {
2618
+ if (partition.partitionId > highestPartitionId) highestPartitionId = partition.partitionId;
2619
+ }
2620
+ growPartitionsTo(deps.manager, highestPartitionId);
2621
+ for (const partition of manifest.partitions) {
2622
+ if (partition.partitionId >= deps.manager.partitionCount) {
2623
+ throw new NarsilError(
2624
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
2625
+ `Segment manifest references partition ${partition.partitionId} beyond the partition count ${deps.manager.partitionCount}`,
2626
+ { indexName, partitionId: partition.partitionId, partitionCount: deps.manager.partitionCount }
2627
+ );
2628
+ }
2629
+ await loadPartitionSegments(store, partition, deps.manager, { schema: manifest.schema, decodesEveryDocument });
2630
+ }
2631
+ for (const vector of manifest.vectors) {
2632
+ const vectorIndex = deps.vectorIndexes.get(vector.fieldPath);
2633
+ if (vectorIndex === void 0) continue;
2634
+ await loadVectorField(store, vector, vectorIndex);
2635
+ }
2636
+ return manifest.checkpoint;
2637
+ }
2638
+ async function reclaimUnlistedKeys(store, indexName, referenced) {
2639
+ for (const key of await store.list(segmentsPrefix(indexName))) {
2640
+ if (!referenced.has(key)) await store.remove(key);
2641
+ }
2642
+ }
2643
+ function validateHnswMetric2(value) {
2644
+ if (value === void 0 || value === null) return void 0;
2645
+ if (typeof value === "string" && VALID_HNSW_METRICS.has(value)) {
2646
+ return value;
2647
+ }
2648
+ return void 0;
2649
+ }
2650
+ function storedDocumentsOf(raw) {
2651
+ requireValidFieldTypes(raw.schema ?? {});
2652
+ const documents = {};
2653
+ for (const [docId, doc] of Object.entries(raw.documents ?? {})) {
2654
+ documents[docId] = {
2655
+ fields: doc.fields,
2656
+ fieldLengths: doc.field_lengths ?? {}
2657
+ };
2658
+ }
2659
+ dropStoredVectorValues(documents, raw.schema ?? {});
2660
+ return documents;
2661
+ }
2662
+ function documentsOfPayloadV2(data) {
2663
+ const raw = decode(data);
2664
+ return { documents: storedDocumentsOf(raw), schema: raw.schema ?? {} };
2665
+ }
2666
+ function deserializePayloadV2(data) {
2667
+ const raw = decode(data);
2668
+ const documents = storedDocumentsOf(raw);
2669
+ const fieldNames = raw.inverted_index?.field_names ?? [];
2670
+ const invertedIndex = {};
2671
+ for (const [token, list] of Object.entries(raw.inverted_index?.entries ?? {})) {
2672
+ const count = list.ids.length;
2673
+ const postings = new Array(count);
2674
+ for (let i = 0; i < count; i++) {
2675
+ postings[i] = {
2676
+ docId: list.ids[i],
2677
+ termFrequency: list.tf[i],
2678
+ field: fieldNames[list.fi[i]] ?? "",
2679
+ positions: list.pos ? list.pos[i] : []
2680
+ };
2681
+ }
2682
+ invertedIndex[token] = {
2683
+ docFrequency: list.df,
2684
+ postings
2685
+ };
2686
+ }
2687
+ const numeric = {};
2688
+ for (const [field, entries] of Object.entries(raw.field_indexes?.numeric ?? {})) {
2689
+ numeric[field] = entries.map((e) => ({ value: e.value, docId: e.doc_id }));
2690
+ }
2691
+ const boolean = {};
2692
+ for (const [field, idx] of Object.entries(raw.field_indexes?.boolean ?? {})) {
2693
+ boolean[field] = { trueDocs: idx.true_docs ?? [], falseDocs: idx.false_docs ?? [] };
2694
+ }
2695
+ const geopoint = {};
2696
+ for (const [field, entries] of Object.entries(raw.field_indexes?.geopoint ?? {})) {
2697
+ geopoint[field] = entries.map((e) => ({ lat: e.lat, lon: e.lon, docId: e.doc_id }));
2698
+ }
2699
+ const vectorData = {};
2700
+ for (const [field, data2] of Object.entries(raw.vector_data ?? {})) {
2701
+ vectorData[field] = {
2702
+ dimension: data2.dimension,
2703
+ vectors: (data2.vectors ?? []).map((v) => ({ docId: v.doc_id, vector: v.vector })),
2704
+ hnswGraph: data2.hnsw_graph ? {
2705
+ entryPoint: data2.hnsw_graph.entry_point,
2706
+ maxLayer: data2.hnsw_graph.max_layer,
2707
+ m: data2.hnsw_graph.m,
2708
+ efConstruction: data2.hnsw_graph.ef_construction,
2709
+ metric: validateHnswMetric2(data2.hnsw_graph.metric),
2710
+ nodes: data2.hnsw_graph.nodes
2711
+ } : null,
2712
+ codes: data2.codes ? { bits: data2.codes.bits, centroid: data2.codes.centroid, records: data2.codes.records } : null
2713
+ };
2714
+ }
2715
+ return {
2716
+ indexName: raw.index_name,
2717
+ partitionId: raw.partition_id,
2718
+ totalPartitions: raw.total_partitions,
2719
+ language: raw.language ?? "english",
2720
+ schema: raw.schema ?? {},
2721
+ docCount: raw.doc_count ?? 0,
2722
+ avgDocLength: raw.avg_doc_length ?? 0,
2723
+ documents,
2724
+ invertedIndex,
2725
+ fieldIndexes: {
2726
+ numeric,
2727
+ boolean,
2728
+ enum: raw.field_indexes?.enum ?? {},
2729
+ geopoint,
2730
+ ...patternIndexesFromWire(raw.field_indexes?.pattern)
2731
+ },
2732
+ surfaceForms: sanitizeSurfaceForms(raw.surface_forms),
2733
+ vectorData,
2734
+ statistics: {
2735
+ totalDocuments: raw.statistics?.total_documents ?? 0,
2736
+ totalFieldLengths: raw.statistics?.total_field_lengths ?? {},
2737
+ averageFieldLengths: raw.statistics?.average_field_lengths ?? {},
2738
+ docFrequencies: raw.statistics?.doc_frequencies ?? {}
2739
+ }
2740
+ };
2741
+ }
2742
+
2743
+ export { CHECKPOINT_TIMEOUT_RECOVERY_BACKOFF_MS, CHECKPOINT_WORKER_IDLE_MS, CHECKPOINT_WORKER_TIMEOUT_MS, DEFAULT_ASYNC_FLUSH_INTERVAL_MS, DEFAULT_CHECKPOINT_INTERVAL_MS, DEFAULT_CHECKPOINT_MUTATION_THRESHOLD, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_SEGMENT_MAX_BYTES, DIRECTORY_IDENTITY_CHECK_INTERVAL_MS, DIRECTORY_LOCK_ATTEMPTS, DIRECTORY_LOCK_SETTLE_MS, LOG_RECORDS_PER_CHECKPOINT, MAX_SEGMENTS_PER_PARTITION, SEGMENT_HEADER_SIZE, SINGLE_NODE_PRIMARY_TERM, VECTOR_FILE_ENVELOPE_VERSION, WHOLE_PARTITION_LARGEST_DOCUMENT_COUNT, WHOLE_PARTITION_MIN_CHANGED_SHARE, WRITES_STALL_ABOVE_UNCHECKPOINTED_BYTES, adapterCheckpointStore, buildEntry, captureWholePartition, checkpointLastSeqNo, checkpointPrimaryTerm, commitCheckpointManifest, createSeqOwner, decodeManifestPayload, decodeSegmentManifest, deserializePayloadV1, deserializePayloadV2, directoryCheckpointStore, documentsOfPayloadV2, durableRecordMissing, encodeMarkerSlot, encodeSegmentManifest, frameRecord, growPartitionsTo, indexMetadataOf, invalidManifest, isId, isRecord, isSequenceNumber, isUint32, listedKeysOf, loadSegmentedCheckpoint, manifestFileRefs, manifestKey, manifestReferencedKeys, markerSlotOffset, metadataConfigOf, metadataFromConfig, nextMarkerSlot, openManifestPayload, partitionContentsOf, readCommitMarker, readCurrentManifest, readGraphParts, readListedFile, readMetadataEnvelope, readSegmentFile, readSegmentManifest, readVectorFile, readWalSegments, reclaimUnlistedKeys, removeCheckpointGarbage, snapshotBundleKey, unpackEnvelopeBytes, unpackIndexSnapshotEnvelope, writeCheckpointSegments, writeLiveVectors, writeMetadataEnvelope, writeSegmentHeader };