@delali/narsil 0.3.1-next.144 → 0.3.1-next.146

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 (241) hide show
  1. package/dist/adapters/filesystem.d.ts +1 -1
  2. package/dist/adapters/filesystem.mjs +101 -13
  3. package/dist/adapters/gcs.d.ts +49 -0
  4. package/dist/adapters/gcs.mjs +213 -0
  5. package/dist/adapters/indexeddb.d.ts +1 -1
  6. package/dist/adapters/indexeddb.mjs +2 -7
  7. package/dist/adapters/memory.d.ts +1 -1
  8. package/dist/adapters/memory.mjs +5 -0
  9. package/dist/adapters/s3.d.ts +53 -0
  10. package/dist/adapters/s3.mjs +263 -0
  11. package/dist/{adapters-BQFQ4PRz.d.ts → adapters-pljAqmrC.d.ts} +33 -0
  12. package/dist/analysis-change-ZCJNYBJM.mjs +39 -0
  13. package/dist/{browser/analysis-change-entry-7HR4LWL3.mjs → analysis-change-entry-YN3ELL6C.mjs} +1 -1
  14. package/dist/browser/{analysis-change-JPV775LR.mjs → analysis-change-M65AZQQG.mjs} +8 -5
  15. package/dist/{analysis-change-entry-TZTG4AZB.mjs → browser/analysis-change-entry-H3YIOLXZ.mjs} +1 -1
  16. package/dist/browser/{chunk-VFYMPCOV.mjs → chunk-2JABMB4S.mjs} +10 -6
  17. package/dist/{chunk-46NZOPHS.mjs → browser/chunk-4DYLCICG.mjs} +2 -2
  18. package/dist/browser/{chunk-MZI3TEOW.mjs → chunk-4RD3AFSB.mjs} +1 -1
  19. package/dist/browser/{chunk-WCFCHIBB.mjs → chunk-5V74FFZE.mjs} +2 -2
  20. package/dist/{chunk-NN33CZRE.mjs → browser/chunk-6OWX3OP2.mjs} +2 -2
  21. package/dist/browser/chunk-BRWY3JCN.mjs +678 -0
  22. package/dist/browser/{chunk-5DB2VDGI.mjs → chunk-BVX2MEHA.mjs} +306 -607
  23. package/dist/browser/{chunk-KTOK275N.mjs → chunk-D6UFGBF5.mjs} +15 -45
  24. package/dist/browser/{chunk-D33A5VMU.mjs → chunk-IAXZAVYL.mjs} +25 -66
  25. package/dist/browser/chunk-JNOAKDUM.mjs +31 -0
  26. package/dist/browser/{chunk-LVY2LI35.mjs → chunk-KAEVGLYN.mjs} +2 -2
  27. package/dist/browser/{chunk-3ZBJYAS4.mjs → chunk-LURXVCHG.mjs} +1 -1
  28. package/dist/browser/chunk-MPK76GVS.mjs +63 -0
  29. package/dist/browser/{chunk-ZEV26AQ6.mjs → chunk-NVEJJP4R.mjs} +1 -1
  30. package/dist/browser/{chunk-HKX2G6WH.mjs → chunk-ODQP7P3H.mjs} +455 -66
  31. package/dist/browser/{chunk-35B42UFM.mjs → chunk-PIS7ZAP7.mjs} +12 -25
  32. package/dist/browser/{chunk-TCLEOZ4P.mjs → chunk-QMNZFFD3.mjs} +4 -3
  33. package/dist/browser/{chunk-R4WUDZQV.mjs → chunk-SRL47USS.mjs} +2 -2
  34. package/dist/browser/chunk-TY7L6OXO.mjs +69 -0
  35. package/dist/browser/{chunk-MVM33ZUL.mjs → chunk-W643QV3L.mjs} +6 -5
  36. package/dist/browser/chunk-WXLBZJMT.mjs +25 -0
  37. package/dist/browser/{chunk-MWUK3DA5.mjs → chunk-XILIT5MT.mjs} +8 -8
  38. package/dist/browser/{cold-module-MJMKNUYJ.mjs → cold-module-A5S6JFDN.mjs} +20 -20
  39. package/dist/browser/{durability-wiring-SNOWIT6Z.mjs → durability-wiring-W5AVV3RF.mjs} +120 -80
  40. package/dist/browser/gzip-5S7ROJFJ.mjs +1 -0
  41. package/dist/browser/import-PTT63AGK.mjs +12 -0
  42. package/dist/browser/{module-BUFNZMEU.mjs → module-CEKA7MQH.mjs} +13 -10
  43. package/dist/browser/module-X5PGOE47.mjs +4288 -0
  44. package/dist/browser/{phrase-module-HGVBO24W.mjs → phrase-module-CNKMUY4U.mjs} +2 -1
  45. package/dist/browser/pool-DTYSPBMQ.mjs +296 -0
  46. package/dist/{restore-queue-FEYAC4SB.mjs → browser/restore-queue-DD4LWZK7.mjs} +2 -2
  47. package/dist/browser/{runtime-VEUH674B.mjs → runtime-D2ULZGCN.mjs} +3 -2
  48. package/dist/browser/{snapshot-QXBKHJAG.mjs → snapshot-DQ6A4PQP.mjs} +20 -15
  49. package/dist/browser/{write-WHFBDWQS.mjs → write-MAGRAIEH.mjs} +14 -11
  50. package/dist/{capabilities-BCdUwK_L.d.ts → capabilities-BT-HLDC8.d.ts} +3 -3
  51. package/dist/{chunk-O4LJQI4G.mjs → chunk-2HJWQPR6.mjs} +126 -4
  52. package/dist/{chunk-Z4HFMYNX.mjs → chunk-3BVGJ4JR.mjs} +36 -13
  53. package/dist/{chunk-ZPWS2SKJ.mjs → chunk-3HV7M5OJ.mjs} +272 -112
  54. package/dist/{chunk-UIKN2OTQ.mjs → chunk-3MXV3VHR.mjs} +2 -23
  55. package/dist/{browser/chunk-CCOAOO73.mjs → chunk-3SBJVQLL.mjs} +2 -2
  56. package/dist/chunk-3TVDTACC.mjs +104 -0
  57. package/dist/{chunk-YH5OIL7B.mjs → chunk-5QMHMELB.mjs} +6 -1
  58. package/dist/{chunk-SBMAWTRG.mjs → chunk-5WB2A3XU.mjs} +84 -15
  59. package/dist/{chunk-NPNK57CA.mjs → chunk-65WCV5JO.mjs} +1 -1
  60. package/dist/chunk-6BWLDLS3.mjs +58 -0
  61. package/dist/{chunk-UUZCQQG2.mjs → chunk-6C5EX2QR.mjs} +3 -3
  62. package/dist/{chunk-VEFN6X6Q.mjs → chunk-6F6USYII.mjs} +120 -13
  63. package/dist/{chunk-AST3SHFA.mjs → chunk-7HKWO4BJ.mjs} +7 -7
  64. package/dist/{chunk-W2COJ5AH.mjs → chunk-7N223GWV.mjs} +2 -2
  65. package/dist/{chunk-GWOS5DYC.mjs → chunk-ADBS5XRI.mjs} +11 -13
  66. package/dist/{chunk-TNBIK2LQ.mjs → chunk-AWNHDBKV.mjs} +430 -75
  67. package/dist/{chunk-ZMBFWQXN.mjs → chunk-B2FTZNNF.mjs} +2 -2
  68. package/dist/chunk-B7XIOAMK.mjs +100 -0
  69. package/dist/{chunk-W55X2BYN.mjs → chunk-BEZH7VEH.mjs} +1 -1
  70. package/dist/{chunk-QSK35UC2.mjs → chunk-BTPGQC6Z.mjs} +3 -11
  71. package/dist/{chunk-LA4WNDHL.mjs → chunk-CYYSZPVV.mjs} +12 -14
  72. package/dist/{chunk-SRJBFG2T.mjs → chunk-DOY6EG76.mjs} +6 -7
  73. package/dist/{chunk-6SNBQESJ.mjs → chunk-F22IOCR2.mjs} +10 -6
  74. package/dist/{chunk-J6YVB2XM.mjs → chunk-IJPK5PGM.mjs} +1 -1
  75. package/dist/{chunk-L76W3IZJ.mjs → chunk-IRWP524D.mjs} +1 -1
  76. package/dist/{chunk-XS2VM7UE.mjs → chunk-IZT3G24Q.mjs} +2 -2
  77. package/dist/{chunk-NOT5QOHU.mjs → chunk-J7M73VY7.mjs} +1 -1
  78. package/dist/chunk-K5HSUPYS.mjs +11 -0
  79. package/dist/chunk-KAKQ74LS.mjs +53 -0
  80. package/dist/{chunk-ZSWHPKGM.mjs → chunk-KYVRZAYP.mjs} +69 -2
  81. package/dist/{chunk-NRUXBYPH.mjs → chunk-KZ5GQE4Z.mjs} +5 -5
  82. package/dist/{browser/chunk-XNWPP5NS.mjs → chunk-KZQIVGW7.mjs} +2 -2
  83. package/dist/{chunk-KZL72VTC.mjs → chunk-L7TIAYPX.mjs} +11 -10
  84. package/dist/{chunk-DD2673TX.mjs → chunk-LDGGR7YT.mjs} +4 -81
  85. package/dist/{chunk-XZ3SRNDJ.mjs → chunk-LJ4ENXOD.mjs} +77 -16
  86. package/dist/chunk-LQG5G2LY.mjs +39 -0
  87. package/dist/{chunk-HNHCNTVG.mjs → chunk-MDF6PDIA.mjs} +11 -0
  88. package/dist/{chunk-74XB2SXI.mjs → chunk-NVTFQFUL.mjs} +16 -2
  89. package/dist/{chunk-BOJZGUS6.mjs → chunk-NYSONUB7.mjs} +1 -1
  90. package/dist/{chunk-WJGO5PGV.mjs → chunk-O4KUNDVF.mjs} +31 -17
  91. package/dist/{chunk-PWIWSUCX.mjs → chunk-POUYICOU.mjs} +1 -1
  92. package/dist/{chunk-EBIHRL7B.mjs → chunk-Q2UL2TPC.mjs} +1 -1
  93. package/dist/{chunk-NJJCPFXN.mjs → chunk-QEYF2SQ6.mjs} +2 -2
  94. package/dist/{chunk-7AUASRE7.mjs → chunk-QN5WVV5K.mjs} +7 -7
  95. package/dist/{chunk-RIIUZJQ3.mjs → chunk-QYRNLLLI.mjs} +1 -1
  96. package/dist/chunk-SOUZMPME.mjs +1635 -0
  97. package/dist/{chunk-C3YDYX6C.mjs → chunk-T4CJDBBE.mjs} +1 -1
  98. package/dist/{chunk-YLNSJQLX.mjs → chunk-TTCKT2RT.mjs} +5 -5
  99. package/dist/{chunk-KEIYVZUX.mjs → chunk-U2726TL5.mjs} +5 -5
  100. package/dist/{chunk-RKAVHNRW.mjs → chunk-U46IZNCW.mjs} +10 -5
  101. package/dist/{chunk-BRUUBXCB.mjs → chunk-U6NE6RCV.mjs} +10 -38
  102. package/dist/{chunk-VJEGOELZ.mjs → chunk-VP6XRMWR.mjs} +4 -4
  103. package/dist/{chunk-IO5F7ZBE.mjs → chunk-VQDZVWN3.mjs} +874 -413
  104. package/dist/{chunk-IWVEG5CX.mjs → chunk-XIHUI4KB.mjs} +2 -2
  105. package/dist/{chunk-YHUTF6EA.mjs → chunk-XKPNKR3V.mjs} +17 -47
  106. package/dist/{chunk-HJJWY6PT.mjs → chunk-YGQOPB2Z.mjs} +1 -1
  107. package/dist/chunk-YKEHQUSZ.mjs +248 -0
  108. package/dist/{chunk-GLZHNSGB.mjs → chunk-ZAYWOHVG.mjs} +1 -1
  109. package/dist/{chunk-ICW45TTU.mjs → chunk-ZEKDO7YX.mjs} +2 -2
  110. package/dist/chunk-ZXNNR73R.mjs +31 -0
  111. package/dist/{chunk-VJS4JFBQ.mjs → chunk-ZXX5GZEX.mjs} +3 -1
  112. package/dist/{chunk-RHKRTYGO.mjs → chunk-ZYKUD5NX.mjs} +9 -7
  113. package/dist/{client-B12YFALP.d.ts → client-Cn3gNxUU.d.ts} +62 -5
  114. package/dist/client.d.ts +8 -8
  115. package/dist/client.mjs +46 -0
  116. package/dist/{cold-module-4X7WJCFM.mjs → cold-module-2WWGBFJC.mjs} +43 -49
  117. package/dist/{config-CIG5yDyg.d.ts → config-CfhH1IWQ.d.ts} +150 -3
  118. package/dist/{config-BhZxIeb1.d.ts → config-aIsy7mcL.d.ts} +63 -3
  119. package/dist/direct-executor-QLVHMELJ.mjs +24 -0
  120. package/dist/distribution/coordinator/etcd.d.ts +3 -3
  121. package/dist/distribution/coordinator/etcd.mjs +1 -1
  122. package/dist/distribution/coordinator/in-memory.d.ts +3 -3
  123. package/dist/distribution/transport/grpc.mjs +4 -4
  124. package/dist/distribution/transport/in-memory.mjs +2 -2
  125. package/dist/distribution/transport/tcp.mjs +3 -3
  126. package/dist/distribution.d.ts +8 -8
  127. package/dist/distribution.mjs +16116 -14537
  128. package/dist/{durability-wiring-324D2DDD.mjs → durability-wiring-GNWQSZI3.mjs} +142 -109
  129. package/dist/embeddings/openai.d.ts +1 -1
  130. package/dist/embeddings/openai.mjs +2 -2
  131. package/dist/{engine-CtzbHOmG.d.ts → engine-CJRUHXgf.d.ts} +3 -3
  132. package/dist/gzip-F4HMIEEQ.mjs +1 -0
  133. package/dist/import-DX55PN4G.mjs +41 -0
  134. package/dist/{index-DsEurhSl.d.ts → index-MsF7e5hL.d.ts} +2 -2
  135. package/dist/index.browser.mjs +7 -4
  136. package/dist/index.d.ts +542 -8
  137. package/dist/index.mjs +29 -32
  138. package/dist/index.react-native.mjs +19 -0
  139. package/dist/invalidation/broadcast-channel.d.ts +1 -1
  140. package/dist/invalidation/filesystem.d.ts +1 -1
  141. package/dist/invalidation/filesystem.mjs +1 -1
  142. package/dist/invalidation/noop.d.ts +1 -1
  143. package/dist/{long-query-thread-4SW7RWDE.mjs → long-query-thread-SCUE62TO.mjs} +23 -25
  144. package/dist/{module-DXSJ5LT2.mjs → module-HW6IXUM6.mjs} +603 -112
  145. package/dist/module-V5K4ZP23.mjs +45 -0
  146. package/dist/{paged-partition-archive-HFP45PLU.mjs → paged-partition-archive-FDIIWZNR.mjs} +42 -41
  147. package/dist/partial-words.mjs +7 -9
  148. package/dist/pattern.mjs +4 -6
  149. package/dist/persistence/durability/checkpoint-worker.d.ts +2 -2
  150. package/dist/persistence/durability/checkpoint-worker.mjs +36 -39
  151. package/dist/{phrase-module-5QHBD2VJ.mjs → phrase-module-OUQIRUQU.mjs} +1 -1
  152. package/dist/pool-UPV5PVPY.mjs +298 -0
  153. package/dist/react-native/chunks/analysis-change-HGW3L6NY.mjs +893 -0
  154. package/dist/react-native/chunks/analysis-change-entry-BNRU6STO.mjs +1 -0
  155. package/dist/react-native/chunks/chunk-2J2727V4.mjs +495 -0
  156. package/dist/react-native/chunks/chunk-3CTWSQRW.mjs +1251 -0
  157. package/dist/react-native/chunks/chunk-5FV4ZEVA.mjs +2619 -0
  158. package/dist/react-native/chunks/chunk-7VWQLEFV.mjs +642 -0
  159. package/dist/react-native/chunks/chunk-AAAETEJK.mjs +27 -0
  160. package/dist/react-native/chunks/chunk-AM7RSBPF.mjs +32 -0
  161. package/dist/react-native/chunks/chunk-B6OD63Z3.mjs +997 -0
  162. package/dist/react-native/chunks/chunk-BRNAVOKP.mjs +177 -0
  163. package/dist/react-native/chunks/chunk-DKJTZ625.mjs +207 -0
  164. package/dist/react-native/chunks/chunk-FKGG4UOF.mjs +177 -0
  165. package/dist/{browser/chunk-6RHTAVZX.mjs → react-native/chunks/chunk-GV5KFQ6M.mjs} +38 -15
  166. package/dist/react-native/chunks/chunk-HURV3ASY.mjs +4416 -0
  167. package/dist/react-native/chunks/chunk-IO2SMUQD.mjs +10 -0
  168. package/dist/react-native/chunks/chunk-JV6VQY2S.mjs +17 -0
  169. package/dist/react-native/chunks/chunk-KUJOBRKS.mjs +217 -0
  170. package/dist/react-native/chunks/chunk-KWRW5U65.mjs +226 -0
  171. package/dist/react-native/chunks/chunk-L4M7QJNP.mjs +110 -0
  172. package/dist/react-native/chunks/chunk-LQ6Q4L5B.mjs +360 -0
  173. package/dist/react-native/chunks/chunk-LQAKO5QV.mjs +523 -0
  174. package/dist/react-native/chunks/chunk-LRGWK367.mjs +11 -0
  175. package/dist/react-native/chunks/chunk-LVIKKAA6.mjs +93 -0
  176. package/dist/react-native/chunks/chunk-NFGBOI46.mjs +14 -0
  177. package/dist/react-native/chunks/chunk-NNE4VDMM.mjs +8 -0
  178. package/dist/react-native/chunks/chunk-PPEPTUVV.mjs +56 -0
  179. package/dist/react-native/chunks/chunk-PSWKQVVT.mjs +9 -0
  180. package/dist/{chunk-KGOXHLLZ.mjs → react-native/chunks/chunk-PU55IOG4.mjs} +228 -11
  181. package/dist/react-native/chunks/chunk-QC4ZRBSX.mjs +270 -0
  182. package/dist/react-native/chunks/chunk-R4EEMYM6.mjs +21 -0
  183. package/dist/react-native/chunks/chunk-R4OPUZQ5.mjs +86 -0
  184. package/dist/react-native/chunks/chunk-SLGIAD6B.mjs +2634 -0
  185. package/dist/react-native/chunks/chunk-TJMSKBEM.mjs +25 -0
  186. package/dist/react-native/chunks/chunk-TLYD7IJ2.mjs +23 -0
  187. package/dist/react-native/chunks/chunk-UFNCLEQM.mjs +73 -0
  188. package/dist/react-native/chunks/chunk-YH7W556M.mjs +179 -0
  189. package/dist/react-native/chunks/chunk-YJSMEKRE.mjs +22385 -0
  190. package/dist/react-native/chunks/chunk-ZCKNBPQ4.mjs +79 -0
  191. package/dist/react-native/chunks/cold-module-TSFWLYWC.mjs +755 -0
  192. package/dist/react-native/chunks/durability-wiring-PZR6KOQK.mjs +4509 -0
  193. package/dist/react-native/chunks/gzip.react-native-7JWCLVOB.mjs +3 -0
  194. package/dist/react-native/chunks/import-VTODLPLO.mjs +22 -0
  195. package/dist/{browser/module-BVP4TKZU.mjs → react-native/chunks/module-JBBH6PZH.mjs} +671 -146
  196. package/dist/react-native/chunks/module-VEK2KCKU.mjs +25 -0
  197. package/dist/react-native/chunks/phrase-module-76UAPPSG.mjs +329 -0
  198. package/dist/react-native/chunks/pool-CD4ANYUI.mjs +296 -0
  199. package/dist/react-native/chunks/release-D7ZTIANM.mjs +33 -0
  200. package/dist/react-native/chunks/replace-IMZUVUOE.mjs +57 -0
  201. package/dist/{browser/restore-queue-ONYNYUDE.mjs → react-native/chunks/restore-queue-OI5EH7R3.mjs} +2 -2
  202. package/dist/react-native/chunks/runtime-3MCDLJAF.mjs +559 -0
  203. package/dist/react-native/chunks/snapshot-AUZMEV36.mjs +1205 -0
  204. package/dist/react-native/chunks/write-DDC2QBRJ.mjs +197 -0
  205. package/dist/{chunk-DQNKVOJ2.mjs → react-native/partial-words.mjs} +13 -228
  206. package/dist/react-native/pattern.mjs +2442 -0
  207. package/dist/react-native/synonyms.mjs +460 -0
  208. package/dist/react.d.ts +11 -11
  209. package/dist/react.mjs +11 -0
  210. package/dist/{rerank-KTLC3E6N.mjs → rerank-3W54N6P2.mjs} +4 -4
  211. package/dist/rerankers/http.d.ts +1 -1
  212. package/dist/rerankers/http.mjs +2 -2
  213. package/dist/restore-queue-BQWWNNQI.mjs +41 -0
  214. package/dist/{runtime-DYV75DCB.mjs → runtime-L2DZYY6N.mjs} +5 -5
  215. package/dist/{schema-B-Runv0n.d.ts → schema-D33CyXCy.d.ts} +1 -1
  216. package/dist/server.d.ts +24 -12
  217. package/dist/server.mjs +159 -38
  218. package/dist/{snapshot-CGM65VCD.mjs → snapshot-EHXTOTW5.mjs} +47 -50
  219. package/dist/synonyms.mjs +3 -4
  220. package/dist/{tasks-CjRJRGTb.d.ts → tasks-C4ElXr4P.d.ts} +59 -7
  221. package/dist/thread-I7DVHHW7.mjs +31 -0
  222. package/dist/vector/search-worker.d.ts +2 -2
  223. package/dist/vector/search-worker.mjs +8 -7
  224. package/dist/workers/entry.mjs +9 -9
  225. package/dist/{write-2DZPEQL2.mjs → write-SDJXXQ2G.mjs} +36 -39
  226. package/openapi.json +349 -2
  227. package/package.json +108 -8
  228. package/dist/analysis-change-HQUT2Z3I.mjs +0 -43
  229. package/dist/browser/import-TLB2A5LJ.mjs +0 -9
  230. package/dist/chunk-5WYVUPGD.mjs +0 -427
  231. package/dist/chunk-AV4IJKD2.mjs +0 -35
  232. package/dist/chunk-GES7U2PM.mjs +0 -68
  233. package/dist/chunk-N37VMC62.mjs +0 -18
  234. package/dist/chunk-WNBRW4Q2.mjs +0 -128
  235. package/dist/chunk-WQBCBKY3.mjs +0 -8
  236. package/dist/chunk-ZATRDAYU.mjs +0 -160
  237. package/dist/direct-executor-7XOQ7VQP.mjs +0 -28
  238. package/dist/import-OOBUW3RR.mjs +0 -44
  239. package/dist/module-IYPLWHGC.mjs +0 -48
  240. package/dist/thread-KGNAIKPD.mjs +0 -33
  241. /package/dist/{chunk-22YPZVMG.mjs → chunk-ZXNQEW43.mjs} +0 -0
@@ -0,0 +1,2619 @@
1
+ import { decodeVectorGraphPartPayload, assembleGraphParts, decodeVectorFilePayload, countDead, VECTOR_FILE_MAX_VECTORS, deadBytesFor } from './chunk-LQ6Q4L5B.mjs';
2
+ import { gunzip, gzip } from './chunk-LRGWK367.mjs';
3
+ import { MAX_SEGMENT_ID, MANIFEST_ENVELOPE_VERSION, EARLIER_SEGMENT_MANIFEST_VERSION, SEGMENT_MANIFEST_VERSION, MAX_SEGMENTS_PER_PARTITION, segmentKey, encodeSegmentManifest, manifestKey, manifestReferencedKeys, segmentsPrefix, snapshotBundleKey, readListedFile, requireListedChecksum, vectorFileKey, DEFAULT_COMPACTION_THRESHOLD, writeSegmentsOf, readSegmentFile, graphPartKey, requireListedSize, SEGMENT_PAGE_BYTES, STABLE_HEAD_ATTEMPTS, RECORD_PAGE_BYTES, MERGED_SEGMENT_GROWTH_ALLOWANCE, MERGED_SEGMENT_TARGET_BYTES, COMPACTION_LARGEST_MERGED_DOCUMENT_COUNT, SEGMENT_FILE_FRAMING_SLACK_BYTES } from './chunk-B6OD63Z3.mjs';
4
+ import { restoreVectorFields } from './chunk-7VWQLEFV.mjs';
5
+ import { VERSION, DEFAULT_BM25_B, DEFAULT_BM25_K1, rulesOfStoredSynonyms, openChecksummedEnvelope, isCompositePartition, crc32, reconstructSchemaFromMetadata, readHeader, HEADER_SIZE, engineVersionParts, writeHeader, packChecksummedEnvelope, packEnvelopeWithChecksum, checksumOfChunks, decodeEveryStoredDocument, createSharedFrozenSegment, shareSegmentArrays, survivorDocumentsOf, partitionStateOf, freezeSegmentShared, createFrozenSegment, createPartitionManager, createPartitionRouter, buildSegmentPayload, resolvePartitionInsertOptions, decodeMapWithoutFields, prepareDocumentVectors } from './chunk-YJSMEKRE.mjs';
6
+ import { flattenSchema, requireValidFieldTypes, extractVectorFieldsFromSchema, partialFieldsOf, isQuantizationMode, isStorageMode } from './chunk-PU55IOG4.mjs';
7
+ import { MAX_FILE_BYTES, VALID_HNSW_METRICS } from './chunk-TJMSKBEM.mjs';
8
+ import { VECTOR_PATTERN } from './chunk-DKJTZ625.mjs';
9
+ import { getLanguage, resolveIndexAnalysis } from './chunk-3CTWSQRW.mjs';
10
+ import { compareCodePoints } from './chunk-PPEPTUVV.mjs';
11
+ import { NarsilError, ErrorCodes } from './chunk-YH7W556M.mjs';
12
+ import { decode, encode } from '@msgpack/msgpack';
13
+
14
+ // src/engine/durability-metadata.ts
15
+ function metadataFromConfig(indexName, config, partitionCount, documentCount) {
16
+ const metadata = {
17
+ indexName,
18
+ schema: config.schema,
19
+ language: config.language,
20
+ partitionCount: partitionCount ?? config.partitionCount,
21
+ bm25Params: {
22
+ k1: config.k1,
23
+ b: config.b,
24
+ ...config.bm25Fields !== void 0 ? { fields: config.bm25Fields } : {}
25
+ },
26
+ createdAt: Date.now(),
27
+ engineVersion: VERSION
28
+ };
29
+ metadata.documentCount = documentCount ?? config.documentCount;
30
+ if (config.embedding) {
31
+ metadata.embedding = config.embedding;
32
+ }
33
+ if (config.surfaceForms !== void 0) {
34
+ metadata.surfaceForms = config.surfaceForms;
35
+ }
36
+ if (config.analysisRevision !== void 0) {
37
+ metadata.analysisRevision = config.analysisRevision;
38
+ }
39
+ if (config.arrayPositionGap !== void 0) {
40
+ metadata.arrayPositionGap = config.arrayPositionGap;
41
+ }
42
+ if (config.tokenizer !== void 0) {
43
+ metadata.tokenizer = config.tokenizer;
44
+ }
45
+ if (config.stopWords !== void 0) {
46
+ metadata.stopWords = config.stopWords;
47
+ }
48
+ if (config.stopWordList !== void 0) {
49
+ metadata.stopWordList = config.stopWordList;
50
+ }
51
+ if (config.analysisGeneration !== void 0) {
52
+ metadata.analysisGeneration = config.analysisGeneration;
53
+ }
54
+ if (config.pendingAnalysis !== void 0) {
55
+ metadata.pendingAnalysis = config.pendingAnalysis;
56
+ }
57
+ if (config.partitionLimits !== void 0) {
58
+ metadata.partitionLimits = config.partitionLimits;
59
+ }
60
+ if (config.defaultScoring !== void 0) {
61
+ metadata.defaultScoring = config.defaultScoring;
62
+ }
63
+ if (config.trackPositions !== void 0) {
64
+ metadata.trackPositions = config.trackPositions;
65
+ }
66
+ if (config.textStorage !== void 0) {
67
+ metadata.textStorage = config.textStorage;
68
+ }
69
+ if (config.strict !== void 0) {
70
+ metadata.strict = config.strict;
71
+ }
72
+ if (config.required !== void 0) {
73
+ metadata.required = config.required;
74
+ }
75
+ if (config.vectorPromotion !== void 0) {
76
+ metadata.vectorPromotion = config.vectorPromotion;
77
+ }
78
+ if (config.patternValueLimit !== void 0) {
79
+ metadata.patternValueLimit = config.patternValueLimit;
80
+ }
81
+ if (config.indexUuid !== void 0) {
82
+ metadata.indexUuid = config.indexUuid;
83
+ }
84
+ if (config.synonyms !== void 0) {
85
+ metadata.synonyms = config.synonyms;
86
+ }
87
+ if (config.heldPartitions !== void 0) {
88
+ metadata.heldPartitions = config.heldPartitions;
89
+ }
90
+ return metadata;
91
+ }
92
+ function metadataConfigOf(entry) {
93
+ const embedding = entry.config.embedding ? {
94
+ fields: entry.config.embedding.fields,
95
+ ...entry.embeddingAdapterName !== null ? { adapter: entry.embeddingAdapterName } : {}
96
+ } : void 0;
97
+ return {
98
+ ...entry.indexUuid !== null ? { indexUuid: entry.indexUuid } : {},
99
+ ...entry.heldPartitions !== null ? { heldPartitions: entry.heldPartitions } : {},
100
+ documentCount: entry.documentCount,
101
+ partitionCount: entry.partitionCount,
102
+ schema: flattenSchema(entry.config.schema),
103
+ language: entry.language.name,
104
+ k1: entry.config.bm25?.k1 ?? DEFAULT_BM25_K1,
105
+ b: entry.config.bm25?.b ?? DEFAULT_BM25_B,
106
+ ...entry.config.bm25?.fields !== void 0 ? { bm25Fields: entry.config.bm25.fields } : {},
107
+ ...embedding !== void 0 ? { embedding } : {},
108
+ surfaceForms: entry.config.surfaceForms !== false,
109
+ ...entry.analysisRevision !== null ? { analysisRevision: entry.analysisRevision } : {},
110
+ ...entry.arrayPositionGap !== null ? { arrayPositionGap: entry.arrayPositionGap } : {},
111
+ ...typeof entry.config.tokenizer === "string" ? { tokenizer: entry.config.tokenizer } : {},
112
+ ...typeof entry.config.stopWords === "string" ? { stopWords: entry.config.stopWords } : {},
113
+ ...entry.config.stopWords instanceof Set ? { stopWordList: [...entry.config.stopWords].sort(compareCodePoints) } : {},
114
+ ...entry.analysisGeneration > 0 ? { analysisGeneration: entry.analysisGeneration } : {},
115
+ ...entry.pendingAnalysis !== null ? { pendingAnalysis: entry.pendingAnalysis } : {},
116
+ ...entry.config.partitions !== void 0 ? { partitionLimits: entry.config.partitions } : {},
117
+ ...entry.config.defaultScoring !== void 0 ? { defaultScoring: entry.config.defaultScoring } : {},
118
+ ...entry.config.trackPositions !== void 0 ? { trackPositions: entry.config.trackPositions } : {},
119
+ ...entry.config.textStorage !== void 0 ? { textStorage: entry.config.textStorage } : {},
120
+ ...entry.config.strict !== void 0 ? { strict: entry.config.strict } : {},
121
+ ...entry.config.required !== void 0 ? { required: entry.config.required } : {},
122
+ ...entry.config.vectorPromotion !== void 0 ? { vectorPromotion: entry.config.vectorPromotion } : {},
123
+ ...entry.config.patternValueLimit !== void 0 ? { patternValueLimit: entry.config.patternValueLimit } : {},
124
+ ...entry.synonyms !== null ? { synonyms: rulesOfStoredSynonyms(entry.synonyms) } : {}
125
+ };
126
+ }
127
+ function durableMetadataConfigOf(entry) {
128
+ const terms = metadataConfigOf(entry);
129
+ const durable = entry.durableAnalysis;
130
+ if (durable === null) return terms;
131
+ const {
132
+ language,
133
+ tokenizer,
134
+ stopWords,
135
+ stopWordList,
136
+ analysisRevision: _analysisRevision,
137
+ arrayPositionGap: _arrayPositionGap,
138
+ analysisGeneration: _analysisGeneration,
139
+ ...rest
140
+ } = terms;
141
+ return {
142
+ ...rest,
143
+ language: durable.language,
144
+ ...durable.tokenizer !== void 0 ? { tokenizer: durable.tokenizer } : {},
145
+ ...durable.stopWords !== void 0 ? { stopWords: durable.stopWords } : {},
146
+ ...durable.stopWordList !== void 0 ? { stopWordList: durable.stopWordList } : {},
147
+ ...durable.analysisRevision !== null ? { analysisRevision: durable.analysisRevision } : {},
148
+ ...durable.arrayPositionGap !== null ? { arrayPositionGap: durable.arrayPositionGap } : {},
149
+ ...durable.generation > 0 ? { analysisGeneration: durable.generation } : {},
150
+ pendingAnalysis: {
151
+ generation: entry.analysisGeneration,
152
+ language,
153
+ ...tokenizer !== void 0 ? { tokenizer } : {},
154
+ ...stopWords !== void 0 ? { stopWords } : {},
155
+ ...stopWordList !== void 0 ? { stopWordList } : {}
156
+ }
157
+ };
158
+ }
159
+ function indexMetadataOf(indexName, entry, partitionCount) {
160
+ return metadataFromConfig(indexName, metadataConfigOf(entry), partitionCount);
161
+ }
162
+
163
+ // src/serialization/stored-vector-values.ts
164
+ function dropStoredVectorValues(documents, schema) {
165
+ const vectorFieldPaths = [];
166
+ for (const [fieldPath, fieldType] of Object.entries(schema)) {
167
+ if (typeof fieldType === "string" && VECTOR_PATTERN.test(fieldType)) {
168
+ vectorFieldPaths.push(fieldPath);
169
+ }
170
+ }
171
+ if (vectorFieldPaths.length === 0) {
172
+ return;
173
+ }
174
+ for (const document of Object.values(documents)) {
175
+ for (const fieldPath of vectorFieldPaths) {
176
+ removeFieldAtPath(document.fields, fieldPath);
177
+ }
178
+ }
179
+ }
180
+ function removeFieldAtPath(fields, fieldPath) {
181
+ if (!fieldPath.includes(".")) {
182
+ delete fields[fieldPath];
183
+ return;
184
+ }
185
+ const segments = fieldPath.split(".");
186
+ let current = fields;
187
+ for (let i = 0; i < segments.length - 1; i += 1) {
188
+ const next = current[segments[i]];
189
+ if (next === null || typeof next !== "object") {
190
+ return;
191
+ }
192
+ current = next;
193
+ }
194
+ delete current[segments[segments.length - 1]];
195
+ }
196
+
197
+ // src/serialization/payload-v1/partition.ts
198
+ function sanitizeSurfaceForms(raw) {
199
+ if (raw === void 0 || raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
200
+ const result = /* @__PURE__ */ Object.create(null);
201
+ let count = 0;
202
+ for (const [surface, value] of Object.entries(raw)) {
203
+ if (typeof value === "number") {
204
+ result[surface] = value;
205
+ count++;
206
+ } else if (Array.isArray(value) && typeof value[0] === "number" && typeof value[1] === "string") {
207
+ result[surface] = [value[0], value[1]];
208
+ count++;
209
+ }
210
+ }
211
+ return count > 0 ? result : void 0;
212
+ }
213
+ function isWireRecord(value) {
214
+ return value !== null && typeof value === "object" && !Array.isArray(value);
215
+ }
216
+ function corruptPatternEntry(field) {
217
+ return new NarsilError(
218
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
219
+ `The pattern entry of field "${field}" in this partition must hold a list of document IDs and a map of runs`,
220
+ { field }
221
+ );
222
+ }
223
+ function patternIndexesFromWire(raw) {
224
+ if (raw === void 0 || raw === null) return {};
225
+ if (!isWireRecord(raw)) {
226
+ throw new NarsilError(
227
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
228
+ "The pattern entry of this partition must be a map of fields"
229
+ );
230
+ }
231
+ const pattern = /* @__PURE__ */ Object.create(null);
232
+ for (const [field, index] of Object.entries(raw)) {
233
+ if (!isWireRecord(index) || !isWireRecord(index.runs) || !Array.isArray(index.doc_ids)) {
234
+ throw corruptPatternEntry(field);
235
+ }
236
+ const docIds = [];
237
+ for (const docId of index.doc_ids) {
238
+ if (typeof docId !== "string") throw corruptPatternEntry(field);
239
+ docIds.push(docId);
240
+ }
241
+ pattern[field] = { docIds, runs: index.runs };
242
+ }
243
+ return { pattern };
244
+ }
245
+ function validateHnswMetric(value) {
246
+ if (value === void 0 || value === null) return void 0;
247
+ if (typeof value === "string" && VALID_HNSW_METRICS.has(value)) {
248
+ return value;
249
+ }
250
+ return void 0;
251
+ }
252
+ function wireToPartition(raw) {
253
+ const documents = {};
254
+ for (const [docId, doc] of Object.entries(raw.documents ?? {})) {
255
+ documents[docId] = {
256
+ fields: doc.fields,
257
+ fieldLengths: doc.field_lengths ?? {}
258
+ };
259
+ }
260
+ requireValidFieldTypes(raw.schema ?? {});
261
+ dropStoredVectorValues(documents, raw.schema ?? {});
262
+ const invertedIndex = {};
263
+ for (const [token, list] of Object.entries(raw.inverted_index ?? {})) {
264
+ invertedIndex[token] = {
265
+ docFrequency: list.doc_freq,
266
+ postings: (list.postings ?? []).map((p) => ({
267
+ docId: p.doc_id,
268
+ termFrequency: p.term_freq,
269
+ field: p.field,
270
+ positions: p.positions ?? []
271
+ }))
272
+ };
273
+ }
274
+ const numeric = {};
275
+ for (const [field, entries] of Object.entries(raw.field_indexes?.numeric ?? {})) {
276
+ numeric[field] = entries.map((e) => ({ value: e.value, docId: e.doc_id }));
277
+ }
278
+ const boolean = {};
279
+ for (const [field, idx] of Object.entries(raw.field_indexes?.boolean ?? {})) {
280
+ boolean[field] = { trueDocs: idx.true_docs ?? [], falseDocs: idx.false_docs ?? [] };
281
+ }
282
+ const geopoint = {};
283
+ for (const [field, entries] of Object.entries(raw.field_indexes?.geopoint ?? {})) {
284
+ geopoint[field] = entries.map((e) => ({ lat: e.lat, lon: e.lon, docId: e.doc_id }));
285
+ }
286
+ const vectorData = {};
287
+ for (const [field, data] of Object.entries(raw.vector_data ?? {})) {
288
+ vectorData[field] = {
289
+ dimension: data.dimension,
290
+ vectors: (data.vectors ?? []).map((v) => ({ docId: v.doc_id, vector: v.vector })),
291
+ hnswGraph: data.hnsw_graph ? {
292
+ entryPoint: data.hnsw_graph.entry_point,
293
+ maxLayer: data.hnsw_graph.max_layer,
294
+ m: data.hnsw_graph.m,
295
+ efConstruction: data.hnsw_graph.ef_construction,
296
+ metric: validateHnswMetric(data.hnsw_graph.metric),
297
+ nodes: data.hnsw_graph.nodes
298
+ } : null,
299
+ codes: data.codes ? { bits: data.codes.bits, centroid: data.codes.centroid, records: data.codes.records } : null
300
+ };
301
+ }
302
+ return {
303
+ indexName: raw.index_name,
304
+ partitionId: raw.partition_id,
305
+ totalPartitions: raw.total_partitions,
306
+ language: raw.language ?? "english",
307
+ schema: raw.schema ?? {},
308
+ docCount: raw.doc_count ?? 0,
309
+ avgDocLength: raw.avg_doc_length ?? 0,
310
+ documents,
311
+ invertedIndex,
312
+ fieldIndexes: {
313
+ numeric,
314
+ boolean,
315
+ enum: raw.field_indexes?.enum ?? {},
316
+ geopoint,
317
+ ...patternIndexesFromWire(raw.field_indexes?.pattern)
318
+ },
319
+ surfaceForms: sanitizeSurfaceForms(raw.surface_forms),
320
+ vectorData,
321
+ statistics: {
322
+ totalDocuments: raw.statistics?.total_documents ?? 0,
323
+ totalFieldLengths: raw.statistics?.total_field_lengths ?? {},
324
+ averageFieldLengths: raw.statistics?.average_field_lengths ?? {},
325
+ docFrequencies: raw.statistics?.doc_frequencies ?? {}
326
+ }
327
+ };
328
+ }
329
+ function deserializePayloadV1(data) {
330
+ const raw = decode(data);
331
+ return wireToPartition(raw);
332
+ }
333
+ function metadataToWire(meta) {
334
+ const wire = {
335
+ index_name: meta.indexName,
336
+ schema: meta.schema,
337
+ language: meta.language,
338
+ partition_count: meta.partitionCount,
339
+ bm25_params: meta.bm25Params,
340
+ created_at: meta.createdAt,
341
+ engine_version: meta.engineVersion
342
+ };
343
+ if (meta.vectorFields) {
344
+ wire.vector_fields = meta.vectorFields;
345
+ }
346
+ if (isNonNegativeInteger(meta.documentCount) && Number.isSafeInteger(meta.documentCount)) {
347
+ wire.document_count = meta.documentCount;
348
+ }
349
+ if (meta.embedding) {
350
+ wire.embedding = meta.embedding.adapter !== void 0 ? { adapter: meta.embedding.adapter, fields: meta.embedding.fields } : { fields: meta.embedding.fields };
351
+ }
352
+ if (meta.surfaceForms !== void 0) {
353
+ wire.surface_forms_enabled = meta.surfaceForms;
354
+ }
355
+ if (meta.analysisRevision !== void 0) {
356
+ wire.analysis_revision = meta.analysisRevision;
357
+ }
358
+ if (meta.arrayPositionGap !== void 0) {
359
+ wire.array_position_gap = meta.arrayPositionGap;
360
+ }
361
+ if (meta.tokenizer !== void 0) {
362
+ wire.tokenizer = meta.tokenizer;
363
+ }
364
+ if (meta.stopWords !== void 0) {
365
+ wire.stop_words = meta.stopWords;
366
+ }
367
+ if (meta.stopWordList !== void 0) {
368
+ wire.stop_word_list = meta.stopWordList;
369
+ }
370
+ if (meta.analysisGeneration !== void 0) {
371
+ wire.analysis_generation = meta.analysisGeneration;
372
+ }
373
+ if (meta.pendingAnalysis !== void 0) {
374
+ const pending = meta.pendingAnalysis;
375
+ wire.pending_analysis = {
376
+ generation: pending.generation,
377
+ language: pending.language,
378
+ ...pending.tokenizer !== void 0 ? { tokenizer: pending.tokenizer } : {},
379
+ ...pending.stopWords !== void 0 ? { stop_words: pending.stopWords } : {},
380
+ ...pending.stopWordList !== void 0 ? { stop_word_list: pending.stopWordList } : {}
381
+ };
382
+ }
383
+ if (meta.partitionLimits !== void 0) {
384
+ wire.partition_limits = {
385
+ ...meta.partitionLimits.maxDocsPerPartition !== void 0 ? { max_docs_per_partition: meta.partitionLimits.maxDocsPerPartition } : {},
386
+ ...meta.partitionLimits.maxPartitions !== void 0 ? { max_partitions: meta.partitionLimits.maxPartitions } : {},
387
+ ...meta.partitionLimits.watermark !== void 0 ? { watermark: meta.partitionLimits.watermark } : {}
388
+ };
389
+ }
390
+ if (meta.defaultScoring !== void 0) {
391
+ wire.default_scoring = meta.defaultScoring;
392
+ }
393
+ if (meta.trackPositions !== void 0) {
394
+ wire.track_positions = meta.trackPositions;
395
+ }
396
+ if (meta.textStorage !== void 0) {
397
+ wire.text_storage = meta.textStorage;
398
+ }
399
+ if (meta.strict !== void 0) {
400
+ wire.strict = meta.strict;
401
+ }
402
+ if (meta.required !== void 0) {
403
+ wire.required = meta.required;
404
+ }
405
+ if (meta.vectorPromotion !== void 0) {
406
+ const promotion = meta.vectorPromotion;
407
+ wire.vector_promotion = {
408
+ ...promotion.threshold !== void 0 ? { threshold: promotion.threshold } : {},
409
+ ...promotion.filterThreshold !== void 0 ? { filter_threshold: promotion.filterThreshold } : {},
410
+ ...promotion.hnswConfig !== void 0 ? {
411
+ hnsw_config: {
412
+ ...promotion.hnswConfig.m !== void 0 ? { m: promotion.hnswConfig.m } : {},
413
+ ...promotion.hnswConfig.efConstruction !== void 0 ? { ef_construction: promotion.hnswConfig.efConstruction } : {},
414
+ ...promotion.hnswConfig.metric !== void 0 ? { metric: promotion.hnswConfig.metric } : {}
415
+ }
416
+ } : {},
417
+ ...promotion.quantization !== void 0 ? { quantization: promotion.quantization } : {},
418
+ ...promotion.storage !== void 0 ? { storage: promotion.storage } : {}
419
+ };
420
+ }
421
+ if (meta.patternValueLimit !== void 0) {
422
+ wire.pattern_value_limit = meta.patternValueLimit;
423
+ }
424
+ if (meta.indexUuid !== void 0) {
425
+ wire.index_uuid = meta.indexUuid;
426
+ }
427
+ if (meta.heldPartitions !== void 0) {
428
+ wire.held_partitions = meta.heldPartitions;
429
+ }
430
+ if (Array.isArray(meta.synonyms) && meta.synonyms.length > 0) {
431
+ wire.synonyms = meta.synonyms;
432
+ }
433
+ return wire;
434
+ }
435
+ function wireToMetadata(raw) {
436
+ const meta = {
437
+ indexName: raw.index_name,
438
+ schema: raw.schema ?? {},
439
+ language: raw.language ?? "english",
440
+ partitionCount: raw.partition_count ?? 1,
441
+ bm25Params: raw.bm25_params ?? { k1: DEFAULT_BM25_K1, b: DEFAULT_BM25_B },
442
+ createdAt: raw.created_at ?? 0,
443
+ engineVersion: raw.engine_version ?? "0.0.0"
444
+ };
445
+ if (raw.vector_fields) {
446
+ for (const [fieldPath, field] of Object.entries(raw.vector_fields)) {
447
+ if (!isQuantizationMode(field.quantization)) {
448
+ throw new NarsilError(
449
+ ErrorCodes.CONFIG_INVALID,
450
+ `Index metadata names a vector quantization "${String(field.quantization)}" for "${fieldPath}" this engine does not read`,
451
+ { fieldPath, quantization: field.quantization }
452
+ );
453
+ }
454
+ }
455
+ meta.vectorFields = raw.vector_fields;
456
+ }
457
+ if (isNonNegativeInteger(raw.document_count) && Number.isSafeInteger(raw.document_count)) {
458
+ meta.documentCount = raw.document_count;
459
+ }
460
+ if (raw.embedding && typeof raw.embedding === "object" && typeof raw.embedding.fields === "object") {
461
+ meta.embedding = typeof raw.embedding.adapter === "string" ? { adapter: raw.embedding.adapter, fields: raw.embedding.fields } : { fields: raw.embedding.fields };
462
+ }
463
+ if (typeof raw.surface_forms_enabled === "boolean") {
464
+ meta.surfaceForms = raw.surface_forms_enabled;
465
+ }
466
+ if (typeof raw.analysis_revision === "string") {
467
+ meta.analysisRevision = raw.analysis_revision;
468
+ }
469
+ if (typeof raw.array_position_gap === "number") {
470
+ meta.arrayPositionGap = raw.array_position_gap;
471
+ }
472
+ if (typeof raw.tokenizer === "string") {
473
+ meta.tokenizer = raw.tokenizer;
474
+ }
475
+ if (typeof raw.stop_words === "string") {
476
+ meta.stopWords = raw.stop_words;
477
+ }
478
+ if (Array.isArray(raw.stop_word_list) && raw.stop_word_list.every((word) => typeof word === "string")) {
479
+ meta.stopWordList = raw.stop_word_list;
480
+ }
481
+ if (isPositiveInteger(raw.analysis_generation)) {
482
+ meta.analysisGeneration = raw.analysis_generation;
483
+ }
484
+ const pending = raw.pending_analysis;
485
+ if (pending && isPositiveInteger(pending.generation) && typeof pending.language === "string") {
486
+ meta.pendingAnalysis = {
487
+ generation: pending.generation,
488
+ language: pending.language,
489
+ ...typeof pending.tokenizer === "string" ? { tokenizer: pending.tokenizer } : {},
490
+ ...typeof pending.stop_words === "string" ? { stopWords: pending.stop_words } : {},
491
+ ...isStringList(pending.stop_word_list) ? { stopWordList: pending.stop_word_list } : {}
492
+ };
493
+ }
494
+ if (raw.partition_limits && typeof raw.partition_limits === "object") {
495
+ const limits = {
496
+ ...isPositiveInteger(raw.partition_limits.max_docs_per_partition) ? { maxDocsPerPartition: raw.partition_limits.max_docs_per_partition } : {},
497
+ ...isPositiveInteger(raw.partition_limits.max_partitions) ? { maxPartitions: raw.partition_limits.max_partitions } : {},
498
+ ...isWatermarkFraction(raw.partition_limits.watermark) ? { watermark: raw.partition_limits.watermark } : {}
499
+ };
500
+ if (Object.keys(limits).length > 0) {
501
+ meta.partitionLimits = limits;
502
+ }
503
+ }
504
+ if (raw.default_scoring === "local" || raw.default_scoring === "dfs" || raw.default_scoring === "broadcast") {
505
+ meta.defaultScoring = raw.default_scoring;
506
+ }
507
+ if (typeof raw.track_positions === "boolean") {
508
+ meta.trackPositions = raw.track_positions;
509
+ }
510
+ if (raw.text_storage !== void 0) {
511
+ if (raw.text_storage !== "memory" && raw.text_storage !== "disk") {
512
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, "text_storage must be 'memory' or 'disk'", {
513
+ textStorage: raw.text_storage
514
+ });
515
+ }
516
+ meta.textStorage = raw.text_storage;
517
+ }
518
+ if (typeof raw.strict === "boolean") {
519
+ meta.strict = raw.strict;
520
+ }
521
+ if (Array.isArray(raw.required) && raw.required.every((field) => typeof field === "string")) {
522
+ meta.required = raw.required;
523
+ }
524
+ if (raw.vector_promotion && typeof raw.vector_promotion === "object") {
525
+ const promotion = raw.vector_promotion;
526
+ const hnsw = promotion.hnsw_config && typeof promotion.hnsw_config === "object" ? promotion.hnsw_config : void 0;
527
+ const metric = hnsw?.metric;
528
+ const restored = {};
529
+ const hnswConfig = {};
530
+ if (isPositiveInteger(hnsw?.m)) {
531
+ hnswConfig.m = hnsw?.m;
532
+ }
533
+ if (isPositiveInteger(hnsw?.ef_construction)) {
534
+ hnswConfig.efConstruction = hnsw?.ef_construction;
535
+ }
536
+ if (metric === "cosine" || metric === "dotProduct" || metric === "euclidean") {
537
+ hnswConfig.metric = metric;
538
+ }
539
+ if (isPositiveInteger(promotion.threshold)) {
540
+ restored.threshold = promotion.threshold;
541
+ }
542
+ if (isSelectivityRatio(promotion.filter_threshold)) {
543
+ restored.filterThreshold = promotion.filter_threshold;
544
+ }
545
+ if (Object.keys(hnswConfig).length > 0) {
546
+ restored.hnswConfig = hnswConfig;
547
+ }
548
+ if (promotion.quantization !== void 0) {
549
+ if (!isQuantizationMode(promotion.quantization)) {
550
+ throw new NarsilError(
551
+ ErrorCodes.CONFIG_INVALID,
552
+ `Index metadata names a vector quantization "${String(promotion.quantization)}" this engine does not read`,
553
+ { quantization: promotion.quantization }
554
+ );
555
+ }
556
+ restored.quantization = promotion.quantization;
557
+ }
558
+ if (promotion.storage !== void 0) {
559
+ if (!isStorageMode(promotion.storage)) {
560
+ throw new NarsilError(
561
+ ErrorCodes.CONFIG_INVALID,
562
+ `Index metadata names a vector storage "${String(promotion.storage)}" this engine does not read`,
563
+ { storage: promotion.storage }
564
+ );
565
+ }
566
+ restored.storage = promotion.storage;
567
+ }
568
+ if (Object.keys(restored).length > 0) {
569
+ meta.vectorPromotion = restored;
570
+ }
571
+ }
572
+ if (raw.pattern_value_limit !== void 0) {
573
+ if (!isPositiveInteger(raw.pattern_value_limit)) {
574
+ throw new NarsilError(
575
+ ErrorCodes.CONFIG_INVALID,
576
+ `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`,
577
+ { patternValueLimit: String(raw.pattern_value_limit) }
578
+ );
579
+ }
580
+ meta.patternValueLimit = raw.pattern_value_limit;
581
+ }
582
+ if (typeof raw.index_uuid === "string" && raw.index_uuid.length > 0) {
583
+ meta.indexUuid = raw.index_uuid;
584
+ }
585
+ if (Array.isArray(raw.held_partitions) && raw.held_partitions.every(isNonNegativeInteger)) {
586
+ meta.heldPartitions = raw.held_partitions;
587
+ }
588
+ if (raw.synonyms !== void 0 && raw.synonyms !== null) meta.synonyms = raw.synonyms;
589
+ return meta;
590
+ }
591
+ function isNonNegativeInteger(value) {
592
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
593
+ }
594
+ function isStringList(value) {
595
+ return Array.isArray(value) && value.every((word) => typeof word === "string");
596
+ }
597
+ function isPositiveInteger(value) {
598
+ return typeof value === "number" && Number.isInteger(value) && value >= 1;
599
+ }
600
+ function isSelectivityRatio(value) {
601
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
602
+ }
603
+ function isWatermarkFraction(value) {
604
+ return typeof value === "number" && value > 0 && value <= 1;
605
+ }
606
+ function serializeMetadata(meta) {
607
+ const wire = metadataToWire(meta);
608
+ return encode(wire);
609
+ }
610
+ function deserializeMetadata(data) {
611
+ const raw = decode(data);
612
+ return wireToMetadata(raw);
613
+ }
614
+
615
+ // src/serialization/envelope.ts
616
+ var CURRENT_ENVELOPE_VERSION = 1;
617
+ var SNAPSHOT_ENVELOPE_VERSION = 2;
618
+ var INDEX_SNAPSHOT_ENVELOPE_VERSION = 3;
619
+ function buildFlags(options) {
620
+ const useCompression = options.compression === "gzip";
621
+ return {
622
+ compressionEnabled: useCompression,
623
+ compressionAlgorithm: useCompression ? "gzip" : "none",
624
+ checksumPresent: options.checksum ?? false,
625
+ encryptionEnabled: false
626
+ };
627
+ }
628
+ async function packEnvelope(payloadBytes, options) {
629
+ const flags = buildFlags(options);
630
+ let finalPayload = payloadBytes;
631
+ if (flags.compressionEnabled) {
632
+ finalPayload = await gzip(payloadBytes);
633
+ }
634
+ const checksum = flags.checksumPresent ? crc32(finalPayload) : 0;
635
+ const [major, minor, patch] = engineVersionParts();
636
+ const envelopeFormatVersion = options.envelopeFormatVersion ?? CURRENT_ENVELOPE_VERSION;
637
+ const header = {
638
+ magic: "NRSL",
639
+ envelopeFormatVersion,
640
+ engineVersionMajor: major,
641
+ engineVersionMinor: minor,
642
+ engineVersionPatch: patch,
643
+ payloadLength: finalPayload.length,
644
+ flags,
645
+ checksum,
646
+ reserved: new Uint8Array(14)
647
+ };
648
+ const headerBytes = writeHeader(header);
649
+ const envelope = new Uint8Array(HEADER_SIZE + finalPayload.length);
650
+ envelope.set(headerBytes, 0);
651
+ envelope.set(finalPayload, HEADER_SIZE);
652
+ return envelope;
653
+ }
654
+ async function unpackEnvelope(data, maxAcceptedVersion = CURRENT_ENVELOPE_VERSION) {
655
+ const header = readHeader(data);
656
+ if (header.envelopeFormatVersion > maxAcceptedVersion) {
657
+ throw new NarsilError(
658
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
659
+ `This data holds Narsil envelope format v${header.envelopeFormatVersion}, while this build of @delali/narsil reads up to v${maxAcceptedVersion}, so upgrade the package to read it.`
660
+ );
661
+ }
662
+ if (header.flags.encryptionEnabled) {
663
+ throw new NarsilError(
664
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
665
+ "Encrypted envelopes are not supported in this version of Narsil"
666
+ );
667
+ }
668
+ const compAlgo = header.flags.compressionAlgorithm;
669
+ if (header.flags.compressionEnabled && compAlgo !== "gzip" && compAlgo !== "none") {
670
+ throw new NarsilError(
671
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
672
+ `Compression algorithm "${compAlgo}" is not supported in this version of Narsil`
673
+ );
674
+ }
675
+ const availablePayload = data.length - HEADER_SIZE;
676
+ if (availablePayload < header.payloadLength) {
677
+ throw new NarsilError(
678
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
679
+ `Envelope data is truncated: header declares ${header.payloadLength} bytes of payload but only ${availablePayload} bytes are available`
680
+ );
681
+ }
682
+ let payloadBytes = new Uint8Array(data.slice(HEADER_SIZE, HEADER_SIZE + header.payloadLength));
683
+ if (header.flags.checksumPresent) {
684
+ const computed = crc32(payloadBytes);
685
+ if (computed !== header.checksum) {
686
+ throw new NarsilError(ErrorCodes.PERSISTENCE_CRC_MISMATCH, "CRC32 checksum mismatch: data may be corrupted", {
687
+ expected: header.checksum,
688
+ computed
689
+ });
690
+ }
691
+ }
692
+ if (header.flags.compressionEnabled) {
693
+ payloadBytes = await gunzip(payloadBytes);
694
+ }
695
+ return { header, payloadBytes };
696
+ }
697
+ async function unpackEnvelopeBytes(data) {
698
+ return unpackEnvelope(data, SNAPSHOT_ENVELOPE_VERSION);
699
+ }
700
+ async function unpackIndexSnapshotEnvelope(data) {
701
+ const { header, payloadBytes } = await unpackEnvelope(data, INDEX_SNAPSHOT_ENVELOPE_VERSION);
702
+ if (header.envelopeFormatVersion !== INDEX_SNAPSHOT_ENVELOPE_VERSION) {
703
+ throw new NarsilError(
704
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
705
+ `Expected an index snapshot envelope of format v${INDEX_SNAPSHOT_ENVELOPE_VERSION}, received format v${header.envelopeFormatVersion}`
706
+ );
707
+ }
708
+ return payloadBytes;
709
+ }
710
+ async function writeMetadataEnvelope(meta, options = {}) {
711
+ const payloadBytes = serializeMetadata(meta);
712
+ return packEnvelope(payloadBytes, options);
713
+ }
714
+ async function readMetadataEnvelope(data) {
715
+ const { header, payloadBytes } = await unpackEnvelope(data);
716
+ const metadata = deserializeMetadata(payloadBytes);
717
+ return { header, metadata };
718
+ }
719
+
720
+ // src/persistence/durability/segment/manifest-fields.ts
721
+ function invalidManifest(message, details) {
722
+ throw new NarsilError(ErrorCodes.PERSISTENCE_LOAD_FAILED, `Segment manifest ${message}`, details);
723
+ }
724
+ function isRecord(value) {
725
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array);
726
+ }
727
+ function isId(value) {
728
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_SEGMENT_ID;
729
+ }
730
+ function isUint32(value) {
731
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4294967295;
732
+ }
733
+ function isSequenceNumber(value) {
734
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
735
+ }
736
+ function readFileRef(raw, expectedKey, what) {
737
+ if (raw.key !== expectedKey) {
738
+ invalidManifest(`lists the ${what} under the key "${String(raw.key)}" where it belongs at "${expectedKey}"`, {
739
+ key: raw.key,
740
+ expected: expectedKey
741
+ });
742
+ }
743
+ const bytes = raw.bytes;
744
+ if (typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < HEADER_SIZE || bytes > MAX_FILE_BYTES) {
745
+ invalidManifest(`gives the ${what} "${expectedKey}" an invalid length`, { key: expectedKey, bytes });
746
+ }
747
+ if (!isUint32(raw.checksum)) invalidManifest(`gives the ${what} "${expectedKey}" an invalid checksum`);
748
+ if (raw.headOffset === void 0) return { key: expectedKey, bytes, checksum: raw.checksum };
749
+ const { headOffset, headLength, headChecksum } = raw;
750
+ if (!isSequenceNumber(headOffset) || !isUint32(headLength) || !isUint32(headChecksum)) {
751
+ invalidManifest(`gives the ${what} "${expectedKey}" an invalid head`, { key: expectedKey });
752
+ }
753
+ if (headOffset + headLength > bytes - HEADER_SIZE) {
754
+ invalidManifest(`ends the head of the ${what} "${expectedKey}" outside its payload`, {
755
+ key: expectedKey,
756
+ headOffset,
757
+ headLength,
758
+ bytes
759
+ });
760
+ }
761
+ return { key: expectedKey, bytes, checksum: raw.checksum, headOffset, headLength, headChecksum };
762
+ }
763
+
764
+ // src/persistence/durability/segment/manifest-vectors-decode.ts
765
+ function normalizeFile(raw, indexName, fieldPath, nextFileId, seenIds) {
766
+ if (!isRecord(raw) || !isId(raw.id)) invalidManifest("has an invalid vector file reference", { fieldPath });
767
+ if (raw.id >= nextFileId || seenIds.has(raw.id)) {
768
+ invalidManifest(`lists vector file ${raw.id} of "${fieldPath}" twice or at its next file id`, { fieldPath });
769
+ }
770
+ seenIds.add(raw.id);
771
+ const count = raw.count;
772
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 0 || count > VECTOR_FILE_MAX_VECTORS) {
773
+ invalidManifest(`gives vector file ${raw.id} of "${fieldPath}" an invalid count`, { fieldPath, count });
774
+ }
775
+ const dead = raw.dead ?? null;
776
+ if (dead !== null && !(dead instanceof Uint8Array)) invalidManifest("has dead vectors that are not bytes");
777
+ if (dead !== null && dead.byteLength !== deadBytesFor(count)) {
778
+ invalidManifest(`marks the dead vectors of file ${raw.id} of "${fieldPath}" with the wrong number of bytes`);
779
+ }
780
+ const ref = readFileRef(raw, vectorFileKey(indexName, fieldPath, raw.id), "vector file");
781
+ return { ...ref, id: raw.id, count, dead };
782
+ }
783
+ function normalizeGraphParts(raw, indexName, fieldPath, generation) {
784
+ if (!Array.isArray(raw)) invalidManifest(`gives "${fieldPath}" no list of graph parts`, { fieldPath });
785
+ if (raw.length > 0 && generation === 0) invalidManifest(`lists graph parts of "${fieldPath}" at generation 0`);
786
+ return raw.map((part, at) => {
787
+ if (!isRecord(part)) invalidManifest(`has an invalid graph part of "${fieldPath}"`, { fieldPath });
788
+ return readFileRef(part, graphPartKey(indexName, fieldPath, generation, at), "graph part");
789
+ });
790
+ }
791
+ function normalizeField(raw, indexName, seenFields) {
792
+ if (!isRecord(raw) || typeof raw.fieldPath !== "string") invalidManifest("has an invalid vector reference");
793
+ const fieldPath = raw.fieldPath;
794
+ if (seenFields.has(fieldPath)) invalidManifest(`lists the vector field "${fieldPath}" twice`, { fieldPath });
795
+ seenFields.add(fieldPath);
796
+ if (!isId(raw.nextFileId)) invalidManifest(`gives "${fieldPath}" an invalid next file id`, { fieldPath });
797
+ if (!Array.isArray(raw.files)) invalidManifest(`gives "${fieldPath}" no list of vector files`, { fieldPath });
798
+ if (!isId(raw.graphGeneration)) invalidManifest(`gives "${fieldPath}" an invalid graph generation`, { fieldPath });
799
+ const nextFileId = raw.nextFileId;
800
+ const seenIds = /* @__PURE__ */ new Set();
801
+ return {
802
+ fieldPath,
803
+ nextFileId,
804
+ files: raw.files.map((file) => normalizeFile(file, indexName, fieldPath, nextFileId, seenIds)),
805
+ graphGeneration: raw.graphGeneration,
806
+ graphParts: normalizeGraphParts(raw.graphParts, indexName, fieldPath, raw.graphGeneration)
807
+ };
808
+ }
809
+ function normalizeVectorFields(raw, indexName) {
810
+ if (!Array.isArray(raw)) invalidManifest("has malformed vector references");
811
+ const seenFields = /* @__PURE__ */ new Set();
812
+ return raw.map((field) => normalizeField(field, indexName, seenFields));
813
+ }
814
+
815
+ // src/persistence/durability/segment/manifest-decode.ts
816
+ async function openManifestPayload(data) {
817
+ const { payload } = await openChecksummedEnvelope(data, {
818
+ envelopeFormatVersion: MANIFEST_ENVELOPE_VERSION,
819
+ what: "segment manifest",
820
+ allowsCompression: true
821
+ });
822
+ const raw = decode(payload);
823
+ if (!isRecord(raw)) invalidManifest("is not a map");
824
+ return raw;
825
+ }
826
+ function listedKeysOf(raw) {
827
+ const keys = [];
828
+ for (const partition of Array.isArray(raw.partitions) ? raw.partitions : []) {
829
+ if (!isRecord(partition) || !Array.isArray(partition.segments)) continue;
830
+ for (const segment of partition.segments)
831
+ if (isRecord(segment) && typeof segment.key === "string") keys.push(segment.key);
832
+ }
833
+ for (const field of Array.isArray(raw.vectors) ? raw.vectors : []) {
834
+ if (!isRecord(field)) continue;
835
+ for (const list of [field.files, field.graphParts]) {
836
+ if (!Array.isArray(list)) continue;
837
+ for (const file of list) if (isRecord(file) && typeof file.key === "string") keys.push(file.key);
838
+ }
839
+ }
840
+ return keys;
841
+ }
842
+ async function decodeSegmentManifest(data, indexName) {
843
+ return decodeManifestPayload(await openManifestPayload(data), indexName);
844
+ }
845
+ function decodeManifestPayload(raw, indexName) {
846
+ if (raw.version === EARLIER_SEGMENT_MANIFEST_VERSION) return { kind: "earlier", payload: raw };
847
+ if (raw.version !== SEGMENT_MANIFEST_VERSION) {
848
+ throw new NarsilError(
849
+ ErrorCodes.ENVELOPE_VERSION_MISMATCH,
850
+ `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`,
851
+ { indexName, version: raw.version }
852
+ );
853
+ }
854
+ const schema = raw.schema;
855
+ if (!isRecord(schema)) invalidManifest("is missing its schema");
856
+ requireValidFieldTypes(schema);
857
+ if (typeof raw.language !== "string") invalidManifest("is missing its language");
858
+ if (raw.analysisGeneration !== void 0 && !isSequenceNumber(raw.analysisGeneration)) {
859
+ invalidManifest("has an invalid analysis generation");
860
+ }
861
+ return {
862
+ kind: "current",
863
+ manifest: {
864
+ version: SEGMENT_MANIFEST_VERSION,
865
+ schema,
866
+ language: raw.language,
867
+ ...raw.analysisGeneration ? { analysisGeneration: raw.analysisGeneration } : {},
868
+ checkpoint: normalizeCheckpoint(raw.checkpoint),
869
+ partitions: normalizePartitions(raw.partitions, indexName),
870
+ vectors: normalizeVectorFields(raw.vectors, indexName)
871
+ }
872
+ };
873
+ }
874
+ function normalizeCheckpoint(raw) {
875
+ if (!Array.isArray(raw)) invalidManifest("is missing its checkpoint list");
876
+ const seen = /* @__PURE__ */ new Set();
877
+ return raw.map((entry) => {
878
+ if (!isRecord(entry) || !isUint32(entry.partitionId) || !isSequenceNumber(entry.lastSeqNo) || !isSequenceNumber(entry.primaryTerm) || seen.has(entry.partitionId)) {
879
+ invalidManifest("has an invalid partition checkpoint", { entry });
880
+ }
881
+ seen.add(entry.partitionId);
882
+ const checkpoint = {
883
+ partitionId: entry.partitionId,
884
+ lastSeqNo: entry.lastSeqNo,
885
+ primaryTerm: entry.primaryTerm
886
+ };
887
+ if (entry.termHistory !== void 0) {
888
+ checkpoint.termHistory = normalizeTermHistory(entry.termHistory, entry.partitionId, entry.lastSeqNo);
889
+ }
890
+ return checkpoint;
891
+ });
892
+ }
893
+ function normalizeTermHistory(raw, partitionId, lastSeqNo) {
894
+ if (!Array.isArray(raw)) invalidManifest("has a term history that is not a list", { partitionId });
895
+ let previous = null;
896
+ return raw.map((start) => {
897
+ if (!isRecord(start) || !isSequenceNumber(start.primaryTerm) || !isSequenceNumber(start.firstSeqNo)) {
898
+ invalidManifest("has an invalid term history entry", { partitionId });
899
+ }
900
+ const read = { primaryTerm: start.primaryTerm, firstSeqNo: start.firstSeqNo };
901
+ if (read.firstSeqNo > lastSeqNo) {
902
+ invalidManifest(`has a term starting at seqNo ${read.firstSeqNo}, above lastSeqNo ${lastSeqNo}`, { partitionId });
903
+ }
904
+ if (previous !== null && (read.primaryTerm <= previous.primaryTerm || read.firstSeqNo <= previous.firstSeqNo)) {
905
+ invalidManifest("has a term history that fails to ascend strictly", { partitionId });
906
+ }
907
+ previous = read;
908
+ return read;
909
+ });
910
+ }
911
+ function normalizePartitions(raw, indexName) {
912
+ if (!Array.isArray(raw)) invalidManifest("is missing partition entries");
913
+ const seen = /* @__PURE__ */ new Set();
914
+ return raw.map((entry) => {
915
+ if (!isRecord(entry) || !isUint32(entry.partitionId) || seen.has(entry.partitionId)) {
916
+ invalidManifest("has a partition without a valid id", { partitionId: isRecord(entry) ? entry.partitionId : null });
917
+ }
918
+ seen.add(entry.partitionId);
919
+ const segments = normalizeSegments(entry.segments, indexName, entry.partitionId);
920
+ return {
921
+ partitionId: entry.partitionId,
922
+ nextSegmentId: readNextSegmentId(entry.nextSegmentId, segments, entry.partitionId),
923
+ segments
924
+ };
925
+ });
926
+ }
927
+ function normalizeSegments(raw, indexName, partitionId) {
928
+ if (!Array.isArray(raw)) invalidManifest("has malformed segment references", { partitionId });
929
+ if (raw.length > MAX_SEGMENTS_PER_PARTITION) {
930
+ invalidManifest(`lists ${raw.length} segments for partition ${partitionId}, above ${MAX_SEGMENTS_PER_PARTITION}`);
931
+ }
932
+ const seenIds = /* @__PURE__ */ new Set();
933
+ return raw.map((segment) => {
934
+ if (!isRecord(segment) || !isId(segment.id) || !isUint32(segment.docCount) || !isUint32(segment.tombstoneCount)) {
935
+ invalidManifest("has an invalid segment reference", { partitionId });
936
+ }
937
+ if (seenIds.has(segment.id)) invalidManifest(`reuses segment id ${segment.id} in partition ${partitionId}`);
938
+ seenIds.add(segment.id);
939
+ const ref = readFileRef(segment, segmentKey(indexName, partitionId, segment.id), "segment");
940
+ return { ...ref, id: segment.id, docCount: segment.docCount, tombstoneCount: segment.tombstoneCount };
941
+ });
942
+ }
943
+ function readNextSegmentId(value, segments, partitionId) {
944
+ if (!isId(value)) invalidManifest("has an invalid next segment id", { partitionId });
945
+ for (const segment of segments) {
946
+ if (segment.id >= value) {
947
+ invalidManifest(`next segment id ${value} does not exceed segment id ${segment.id}`, { partitionId });
948
+ }
949
+ }
950
+ return value;
951
+ }
952
+
953
+ // src/persistence/durability/segment/captured-partition.ts
954
+ function keepMaskOf(segment) {
955
+ const keep = new Uint8Array(segment.arrays.documentCount);
956
+ for (let ordinal = 0; ordinal < keep.length; ordinal++) keep[ordinal] = segment.isTombstoned(ordinal) ? 0 : 1;
957
+ return keep;
958
+ }
959
+ function selectionOfMask(segment, keep) {
960
+ return { segment, keep: (ordinal) => keep[ordinal] === 1 };
961
+ }
962
+ function frozenLiveTail(live, shared) {
963
+ if (live.count() === 0) return null;
964
+ const payload = live.encodeSegment();
965
+ const documents = survivorDocumentsOf(partitionStateOf(live), payload);
966
+ if (shared) {
967
+ const snapshot = freezeSegmentShared(payload, documents);
968
+ if (snapshot !== null) return createSharedFrozenSegment(snapshot);
969
+ }
970
+ return createFrozenSegment(payload, documents);
971
+ }
972
+ function frozenSegmentsOf(partition, shared) {
973
+ const segments = [];
974
+ const live = isCompositePartition(partition) ? partition.live : partition;
975
+ if (isCompositePartition(partition)) {
976
+ const ids = partition.frozenSegmentSizes().map((size) => size.segmentId);
977
+ segments.push(...partition.frozenSegmentsById(ids));
978
+ }
979
+ const tail = frozenLiveTail(live, shared);
980
+ if (tail !== null) segments.push(tail);
981
+ return segments;
982
+ }
983
+ function partitionContentsOf(manager, partitionId, captureRecords) {
984
+ const partition = manager.getPartition(partitionId);
985
+ const segments = frozenSegmentsOf(partition, false);
986
+ const selections = segments.map((segment) => selectionOfMask(segment, keepMaskOf(segment)));
987
+ const contents = { partitionId, docCount: partition.count(), selections };
988
+ if (captureRecords !== void 0) contents.writeRecords = captureRecords(segments);
989
+ return contents;
990
+ }
991
+ function captureWholePartition(manager, partitionId, captureRecords) {
992
+ if (typeof SharedArrayBuffer !== "function") return null;
993
+ const partition = manager.getPartition(partitionId);
994
+ if (!isCompositePartition(partition) || partition.frozenSegmentCount() === 0) return null;
995
+ const frozen = frozenSegmentsOf(partition, true);
996
+ const records = captureRecords?.(frozen);
997
+ const segments = [];
998
+ for (const segment of frozen) {
999
+ if (segment.sharedSnapshot === null) return null;
1000
+ const captured = { snapshot: segment.sharedSnapshot, keep: keepMaskOf(segment) };
1001
+ const held = records?.get(segment);
1002
+ if (held !== void 0) captured.writeRecords = held;
1003
+ segments.push(captured);
1004
+ }
1005
+ return { partitionId, docCount: partition.count(), segments };
1006
+ }
1007
+ function contentsOfCaptured(captured) {
1008
+ const writeRecords = /* @__PURE__ */ new Map();
1009
+ const selections = captured.segments.map(({ snapshot, keep, writeRecords: held }) => {
1010
+ const segment = createSharedFrozenSegment(snapshot);
1011
+ if (held !== void 0) writeRecords.set(segment, held);
1012
+ return selectionOfMask(segment, keep);
1013
+ });
1014
+ const contents = { partitionId: captured.partitionId, docCount: captured.docCount, selections };
1015
+ if (writeRecords.size > 0) contents.writeRecords = writeRecords;
1016
+ return contents;
1017
+ }
1018
+
1019
+ // src/serialization/crc32-combine.ts
1020
+ var IEEE_POLYNOMIAL = 3988292384;
1021
+ var CRC_BITS = 32;
1022
+ var zeroByteOperators = [];
1023
+ function timesVector(operator, vector) {
1024
+ let sum = 0;
1025
+ let rest = vector >>> 0;
1026
+ for (let row = 0; rest !== 0; row++, rest >>>= 1) {
1027
+ if (rest & 1) sum ^= operator[row];
1028
+ }
1029
+ return sum >>> 0;
1030
+ }
1031
+ function squared(operator) {
1032
+ const result = new Uint32Array(CRC_BITS);
1033
+ for (let row = 0; row < CRC_BITS; row++) result[row] = timesVector(operator, operator[row]);
1034
+ return result;
1035
+ }
1036
+ function firstOperator() {
1037
+ let oneZeroBit = new Uint32Array(CRC_BITS);
1038
+ oneZeroBit[0] = IEEE_POLYNOMIAL;
1039
+ for (let row = 1; row < CRC_BITS; row++) oneZeroBit[row] = 1 << row - 1;
1040
+ for (let doubling = 0; doubling < 3; doubling++) oneZeroBit = squared(oneZeroBit);
1041
+ return oneZeroBit;
1042
+ }
1043
+ function operatorForZeroBytesPower(power) {
1044
+ if (zeroByteOperators.length === 0) zeroByteOperators.push(firstOperator());
1045
+ while (zeroByteOperators.length <= power) {
1046
+ zeroByteOperators.push(squared(zeroByteOperators[zeroByteOperators.length - 1]));
1047
+ }
1048
+ return zeroByteOperators[power];
1049
+ }
1050
+ function crc32Combine(first, second, secondByteLength) {
1051
+ let crc = first >>> 0;
1052
+ let rest = secondByteLength;
1053
+ for (let power = 0; rest > 0; power++) {
1054
+ if (rest % 2 === 1) crc = timesVector(operatorForZeroBytesPower(power), crc);
1055
+ rest = Math.floor(rest / 2);
1056
+ }
1057
+ return (crc ^ second) >>> 0;
1058
+ }
1059
+ var BIN8 = 196;
1060
+ var BIN16 = 197;
1061
+ var BIN32 = 198;
1062
+ var ARRAY16 = 220;
1063
+ var ARRAY32 = 221;
1064
+ var FIXMAP = 128;
1065
+ var FIXARRAY = 144;
1066
+ var FIXED_LIST_MAX = 15;
1067
+ var FIXSTR = 160;
1068
+ var FIXSTR_MAX_LENGTH = 31;
1069
+ var ASCII_MAX = 127;
1070
+ var UTF8_MAX_BYTES_PER_UNIT = 3;
1071
+ var STRING_HEADER_MAX_BYTES = 5;
1072
+ var BIN8_MAX_BYTES = 255;
1073
+ var UINT16_MAX = 65535;
1074
+ function binHeader(byteLength) {
1075
+ if (byteLength <= BIN8_MAX_BYTES) return Uint8Array.of(BIN8, byteLength);
1076
+ if (byteLength <= UINT16_MAX) return Uint8Array.of(BIN16, byteLength >> 8, byteLength & 255);
1077
+ const header = new Uint8Array(5);
1078
+ header[0] = BIN32;
1079
+ new DataView(header.buffer).setUint32(1, byteLength, false);
1080
+ return header;
1081
+ }
1082
+ function arrayHeader(count) {
1083
+ if (count <= FIXED_LIST_MAX) return Uint8Array.of(FIXARRAY | count);
1084
+ if (count <= UINT16_MAX) return Uint8Array.of(ARRAY16, count >> 8, count & 255);
1085
+ const header = new Uint8Array(5);
1086
+ header[0] = ARRAY32;
1087
+ new DataView(header.buffer).setUint32(1, count, false);
1088
+ return header;
1089
+ }
1090
+ function createPayloadBuilder() {
1091
+ const chunks = [];
1092
+ let offset = 0;
1093
+ function push(chunk) {
1094
+ chunks.push(chunk);
1095
+ offset += chunk.byteLength;
1096
+ }
1097
+ return {
1098
+ chunks,
1099
+ get offset() {
1100
+ return offset;
1101
+ },
1102
+ push,
1103
+ entry(key, value) {
1104
+ push(encode(key));
1105
+ push(encode(value));
1106
+ },
1107
+ rawEntry(key, encoded) {
1108
+ push(encode(key));
1109
+ const at = offset;
1110
+ push(encoded);
1111
+ return at;
1112
+ },
1113
+ bytesEntry(key, bytes) {
1114
+ push(encode(key));
1115
+ push(binHeader(bytes.byteLength));
1116
+ const at = offset;
1117
+ push(bytes);
1118
+ return at;
1119
+ }
1120
+ };
1121
+ }
1122
+ function pageChecksums(bytes, pageBytes) {
1123
+ const pages = Math.ceil(bytes.byteLength / pageBytes);
1124
+ const checksums = new Uint8Array(pages * 4);
1125
+ const view = new DataView(checksums.buffer);
1126
+ for (let page = 0; page < pages; page++) {
1127
+ const from = page * pageBytes;
1128
+ view.setUint32(page * 4, crc32(bytes.subarray(from, Math.min(from + pageBytes, bytes.byteLength))), true);
1129
+ }
1130
+ return checksums;
1131
+ }
1132
+ function sectionOf(name, offset, bytes, pageBytes) {
1133
+ return { name, offset, length: bytes.byteLength, pageBytes, checksums: pageChecksums(bytes, pageBytes) };
1134
+ }
1135
+ function uint32Bytes(values) {
1136
+ const bytes = new Uint8Array(values.length * 4);
1137
+ const view = new DataView(bytes.buffer);
1138
+ for (let i = 0; i < values.length; i++) view.setUint32(i * 4, values[i], true);
1139
+ return bytes;
1140
+ }
1141
+ function writtenAsShortAscii(docId, list, at) {
1142
+ if (docId.length > FIXSTR_MAX_LENGTH) return false;
1143
+ for (let unit = 0; unit < docId.length; unit++) {
1144
+ const code = docId.charCodeAt(unit);
1145
+ if (code > ASCII_MAX) return false;
1146
+ list[at + 1 + unit] = code;
1147
+ }
1148
+ list[at] = FIXSTR | docId.length;
1149
+ return true;
1150
+ }
1151
+ function encodedIdList(docIds) {
1152
+ const header = arrayHeader(docIds.length);
1153
+ let capacity = header.byteLength;
1154
+ for (const docId of docIds) capacity += docId.length * UTF8_MAX_BYTES_PER_UNIT + STRING_HEADER_MAX_BYTES;
1155
+ const list = new Uint8Array(capacity);
1156
+ list.set(header);
1157
+ const offsets = new Uint32Array(docIds.length + 1);
1158
+ let cursor = header.byteLength;
1159
+ for (let i = 0; i < docIds.length; i++) {
1160
+ offsets[i] = cursor;
1161
+ if (writtenAsShortAscii(docIds[i], list, cursor)) {
1162
+ cursor += docIds[i].length + 1;
1163
+ continue;
1164
+ }
1165
+ const encoded = encode(docIds[i]);
1166
+ list.set(encoded, cursor);
1167
+ cursor += encoded.byteLength;
1168
+ }
1169
+ offsets[docIds.length] = cursor;
1170
+ return { list: list.subarray(0, cursor), offsets };
1171
+ }
1172
+ function positionsInIdOrder(docIds) {
1173
+ const positions = Array.from(docIds.keys());
1174
+ positions.sort((left, right) => compareCodePoints(docIds[left], docIds[right]));
1175
+ return Uint32Array.from(positions);
1176
+ }
1177
+ function magnitudeBytes(magnitudes) {
1178
+ const bytes = new Uint8Array(magnitudes.length * 8);
1179
+ const view = new DataView(bytes.buffer);
1180
+ for (let i = 0; i < magnitudes.length; i++) view.setFloat64(i * 8, magnitudes[i], true);
1181
+ return bytes;
1182
+ }
1183
+ function checksumAcrossPages(checksums, byteLength, pageBytes) {
1184
+ const view = new DataView(checksums.buffer, checksums.byteOffset, checksums.byteLength);
1185
+ let whole = 0;
1186
+ for (let page = 0; page * 4 < checksums.byteLength; page++) {
1187
+ const pageLength = Math.min(pageBytes, byteLength - page * pageBytes);
1188
+ whole = crc32Combine(whole, view.getUint32(page * 4, true), pageLength);
1189
+ }
1190
+ return whole;
1191
+ }
1192
+ function encodedHeadAndVectorsPlace(sections, headOffsetAfterHeader, vectors, checksums, vectorsKeyAndHeaderBytes) {
1193
+ let headLength = 0;
1194
+ let head = new Uint8Array(0);
1195
+ let vectorsSection = {
1196
+ name: "vectors",
1197
+ offset: 0,
1198
+ length: vectors.byteLength,
1199
+ pageBytes: SEGMENT_PAGE_BYTES,
1200
+ checksums
1201
+ };
1202
+ for (let attempt = 0; attempt < STABLE_HEAD_ATTEMPTS; attempt++) {
1203
+ vectorsSection = {
1204
+ ...vectorsSection,
1205
+ offset: headOffsetAfterHeader(headLength) + headLength + vectorsKeyAndHeaderBytes
1206
+ };
1207
+ head = encode({ sections: [...sections, vectorsSection] });
1208
+ if (head.byteLength === headLength) break;
1209
+ headLength = head.byteLength;
1210
+ }
1211
+ return { head, vectorsSection };
1212
+ }
1213
+ function pagedVectorFileChunks(payload, heldMagnitudes) {
1214
+ const builder = createPayloadBuilder();
1215
+ const { codes } = payload;
1216
+ builder.push(Uint8Array.of(FIXMAP | 10));
1217
+ builder.entry("v", payload.v);
1218
+ builder.entry("fieldName", payload.fieldName);
1219
+ builder.entry("dimension", payload.dimension);
1220
+ const { list, offsets } = encodedIdList(payload.docIds);
1221
+ const docIdsAt = builder.rawEntry("docIds", list);
1222
+ const sections = [sectionOf("docIds", docIdsAt, list, SEGMENT_PAGE_BYTES)];
1223
+ builder.push(encode("codes"));
1224
+ if (codes === null) {
1225
+ builder.push(encode(null));
1226
+ } else {
1227
+ builder.push(Uint8Array.of(FIXMAP | 3));
1228
+ builder.entry("bits", codes.bits);
1229
+ builder.entry("centroid", codes.centroid);
1230
+ const recordsAt = builder.bytesEntry("records", codes.records);
1231
+ sections.push(sectionOf("records", recordsAt, codes.records, RECORD_PAGE_BYTES));
1232
+ }
1233
+ const magnitudes = magnitudeBytes(heldMagnitudes);
1234
+ sections.push(sectionOf("magnitudes", builder.bytesEntry("magnitudes", magnitudes), magnitudes, SEGMENT_PAGE_BYTES));
1235
+ const idOffsets = uint32Bytes(offsets);
1236
+ sections.push(sectionOf("idOffsets", builder.bytesEntry("idOffsets", idOffsets), idOffsets, SEGMENT_PAGE_BYTES));
1237
+ const idOrder = uint32Bytes(positionsInIdOrder(payload.docIds));
1238
+ sections.push(sectionOf("idOrder", builder.bytesEntry("idOrder", idOrder), idOrder, SEGMENT_PAGE_BYTES));
1239
+ const headKey = encode("head");
1240
+ const vectorsKey = encode("vectors");
1241
+ const vectorsHeader = binHeader(payload.vectors.byteLength);
1242
+ const beforeHead = builder.offset + headKey.byteLength;
1243
+ const vectorChecksums = pageChecksums(payload.vectors, SEGMENT_PAGE_BYTES);
1244
+ const { head } = encodedHeadAndVectorsPlace(
1245
+ sections,
1246
+ (headLength) => beforeHead + binHeader(headLength).byteLength,
1247
+ payload.vectors,
1248
+ vectorChecksums,
1249
+ vectorsKey.byteLength + vectorsHeader.byteLength
1250
+ );
1251
+ const headOffset = builder.bytesEntry("head", head);
1252
+ builder.push(vectorsKey);
1253
+ builder.push(vectorsHeader);
1254
+ const beforeVectors = [...builder.chunks];
1255
+ builder.push(payload.vectors);
1256
+ return {
1257
+ chunks: builder.chunks,
1258
+ headOffset,
1259
+ headLength: head.byteLength,
1260
+ headChecksum: crc32(head),
1261
+ beforeVectors,
1262
+ vectors: {
1263
+ byteLength: payload.vectors.byteLength,
1264
+ checksum: checksumAcrossPages(vectorChecksums, payload.vectors.byteLength, SEGMENT_PAGE_BYTES)
1265
+ }
1266
+ };
1267
+ }
1268
+ function nodeOffsetsOf(graph) {
1269
+ const offsets = new Uint32Array(graph.levels.length + 1);
1270
+ const view = new DataView(graph.neighbours.buffer, graph.neighbours.byteOffset, graph.neighbours.byteLength);
1271
+ let cursor = 0;
1272
+ for (let at = 0; at < graph.levels.length; at++) {
1273
+ offsets[at] = cursor;
1274
+ for (let layer = 0; layer < graph.levels[at]; layer++) cursor += (view.getUint32(cursor, true) + 1) * 4;
1275
+ }
1276
+ offsets[graph.levels.length] = cursor;
1277
+ return uint32Bytes(offsets);
1278
+ }
1279
+ function pagedGraphPartChunks(part) {
1280
+ const builder = createPayloadBuilder();
1281
+ builder.push(Uint8Array.of(FIXMAP | 4));
1282
+ builder.entry("v", part.v);
1283
+ builder.entry("fieldName", part.fieldName);
1284
+ builder.push(encode("graphs"));
1285
+ builder.push(arrayHeader(part.graphs.length));
1286
+ const layouts = [];
1287
+ for (const graph of part.graphs) {
1288
+ const { levels, neighbours, ...header } = graph;
1289
+ const headerEntries = Object.entries(header).filter(([, value]) => value !== void 0);
1290
+ builder.push(Uint8Array.of(FIXMAP | headerEntries.length + 2));
1291
+ for (const [key, value] of headerEntries) builder.entry(key, value);
1292
+ const levelsAt = builder.bytesEntry("levels", levels);
1293
+ const neighboursAt = builder.bytesEntry("neighbours", neighbours);
1294
+ layouts.push({
1295
+ ...header,
1296
+ levels: sectionOf("levels", levelsAt, levels, SEGMENT_PAGE_BYTES),
1297
+ nodeOffsets: nodeOffsetsOf(graph),
1298
+ neighbours: sectionOf("neighbours", neighboursAt, neighbours, RECORD_PAGE_BYTES)
1299
+ });
1300
+ }
1301
+ const head = encode({ graphs: layouts });
1302
+ const headOffset = builder.bytesEntry("head", head);
1303
+ return { chunks: builder.chunks, headOffset, headLength: head.byteLength, headChecksum: crc32(head) };
1304
+ }
1305
+ var VECTOR_FILE_ENVELOPE_VERSION = 2;
1306
+ var GRAPH_PART_ENVELOPE_VERSION = 2;
1307
+ function liveVectorsOf(ref) {
1308
+ let live = 0;
1309
+ for (const file of ref.files) live += file.count - countDead(file.dead, file.count);
1310
+ return live;
1311
+ }
1312
+ async function openListedFile(store, ref, what, allowsCompression) {
1313
+ const bytes = await readListedFile(store, ref.key, { bytes: ref.bytes, what });
1314
+ const { header, payload } = await openChecksummedEnvelope(bytes, {
1315
+ envelopeFormatVersion: VECTOR_FILE_ENVELOPE_VERSION,
1316
+ what: `${what} "${ref.key}"`,
1317
+ allowsCompression
1318
+ });
1319
+ requireListedChecksum(what, ref.key, header.checksum, ref.checksum);
1320
+ return { payload, payloadLength: header.payloadLength };
1321
+ }
1322
+ async function readGraphParts(store, ref) {
1323
+ if (ref.graphParts.length === 0) return null;
1324
+ const parts = [];
1325
+ for (const part of ref.graphParts) {
1326
+ const { payload } = await openListedFile(store, part, "graph part", true);
1327
+ const decoded = decodeVectorGraphPartPayload(decode(payload));
1328
+ if (decoded.fieldName !== ref.fieldPath) {
1329
+ throw new NarsilError(
1330
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1331
+ `The graph part "${part.key}" names field "${decoded.fieldName}" where the manifest lists "${ref.fieldPath}"`,
1332
+ { key: part.key }
1333
+ );
1334
+ }
1335
+ parts.push(decoded);
1336
+ }
1337
+ return assembleGraphParts(parts);
1338
+ }
1339
+ async function readVectorFile(store, file, fieldPath) {
1340
+ const { payload: bytes, payloadLength } = await openListedFile(store, file, "vector file", false);
1341
+ const payload = decodeVectorFilePayload(decode(bytes));
1342
+ if (payload.docIds.length !== file.count) {
1343
+ throw new NarsilError(
1344
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1345
+ `The vector file "${file.key}" holds ${payload.docIds.length} vectors where the manifest counts ${file.count}`,
1346
+ { key: file.key, held: payload.docIds.length, count: file.count }
1347
+ );
1348
+ }
1349
+ if (payload.fieldName !== fieldPath) {
1350
+ throw new NarsilError(
1351
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
1352
+ `The vector file "${file.key}" names field "${payload.fieldName}" where the manifest lists "${fieldPath}"`,
1353
+ { key: file.key }
1354
+ );
1355
+ }
1356
+ return { payload, payloadLength };
1357
+ }
1358
+ function holdsEveryHead(ref) {
1359
+ if (ref.graphParts.length === 0 || ref.files.length === 0) return false;
1360
+ return [...ref.files, ...ref.graphParts].every((file) => file.headOffset !== void 0);
1361
+ }
1362
+ async function loadFieldOnDemand(store, ref, vectorIndex, resolvePartition) {
1363
+ const { pathOf } = store;
1364
+ if (pathOf === void 0 || vectorIndex.storage !== "disk" || !holdsEveryHead(ref)) return false;
1365
+ const { loadFilesByParts, openColdVectorField, osqBitsOf, waitBeforeColdLoad } = await import('./cold-module-TSFWLYWC.mjs');
1366
+ await Promise.all([
1367
+ ...ref.files.map((file) => requireListedSize(store, file.key, { bytes: file.bytes, what: "vector file" })),
1368
+ ...ref.graphParts.map((part) => requireListedSize(store, part.key, { bytes: part.bytes, what: "graph part" }))
1369
+ ]);
1370
+ const files = await Promise.all(
1371
+ ref.files.map(async (file) => ({ ref: file, path: await pathOf.call(store, file.key) }))
1372
+ );
1373
+ const graphParts = await Promise.all(
1374
+ ref.graphParts.map(async (part) => ({ ref: part, path: await pathOf.call(store, part.key) }))
1375
+ );
1376
+ const field = openColdVectorField({
1377
+ fieldPath: ref.fieldPath,
1378
+ dimension: vectorIndex.dimension,
1379
+ metric: vectorIndex.metric,
1380
+ codeBits: osqBitsOf(vectorIndex.quantization),
1381
+ files,
1382
+ graphParts,
1383
+ resolvePartition
1384
+ });
1385
+ if (field === null) return false;
1386
+ vectorIndex.openColdField(field, async (beginRestore, stillWanted, firstSearchAnswered) => {
1387
+ await waitBeforeColdLoad(firstSearchAnswered);
1388
+ if (!stillWanted()) return;
1389
+ const graph = await readGraphParts(store, ref);
1390
+ if (!stillWanted()) return;
1391
+ const restore = beginRestore({ liveVectors: liveVectorsOf(ref), holdsGraph: true, graph });
1392
+ await loadFilesByParts(files, restore, ref.fieldPath, vectorIndex.dimension, stillWanted);
1393
+ });
1394
+ return true;
1395
+ }
1396
+ async function loadVectorField(store, ref, vectorIndex, resolvePartition = null) {
1397
+ if (resolvePartition !== null && await loadFieldOnDemand(store, ref, vectorIndex, resolvePartition)) return;
1398
+ const restore = vectorIndex.restoreCheckpoint({
1399
+ liveVectors: liveVectorsOf(ref),
1400
+ holdsGraph: ref.graphParts.length > 0,
1401
+ graph: await readGraphParts(store, ref)
1402
+ });
1403
+ for (const file of ref.files) {
1404
+ const { payload, payloadLength } = await readVectorFile(store, file, ref.fieldPath);
1405
+ restore.addFile({
1406
+ id: file.id,
1407
+ key: file.key,
1408
+ payload,
1409
+ dead: file.dead,
1410
+ location: store.pathOf === void 0 ? null : {
1411
+ path: await store.pathOf(file.key),
1412
+ vectorsOffset: HEADER_SIZE + payloadLength - payload.vectors.byteLength
1413
+ }
1414
+ });
1415
+ }
1416
+ restore.finish();
1417
+ }
1418
+ var EMPTY_BIN = new Uint8Array(0);
1419
+ var EMPTY_BIN_BYTES = 2;
1420
+ var BIN82 = 196;
1421
+ var BIN162 = 197;
1422
+ var BIN322 = 198;
1423
+ var BIN8_MAX_BYTES2 = 255;
1424
+ var BIN16_MAX_BYTES = 65535;
1425
+ function binHeader2(byteLength) {
1426
+ if (byteLength <= BIN8_MAX_BYTES2) return Uint8Array.of(BIN82, byteLength);
1427
+ if (byteLength <= BIN16_MAX_BYTES) return Uint8Array.of(BIN162, byteLength >> 8, byteLength & 255);
1428
+ const header = new Uint8Array(5);
1429
+ header[0] = BIN322;
1430
+ new DataView(header.buffer).setUint32(1, byteLength, false);
1431
+ return header;
1432
+ }
1433
+ function chunksEndingInBytes(withTheBytes, withEmptyBytesInTheirPlace, bytes) {
1434
+ const head = encode(withEmptyBytesInTheirPlace);
1435
+ const endsWithTheEmptyBin = head[head.length - EMPTY_BIN_BYTES] === BIN82 && head[head.length - 1] === 0;
1436
+ if (!endsWithTheEmptyBin) return [encode(withTheBytes)];
1437
+ return [head.subarray(0, head.length - EMPTY_BIN_BYTES), binHeader2(bytes.byteLength), bytes];
1438
+ }
1439
+ function vectorPartChunks(part) {
1440
+ return chunksEndingInBytes(part, { ...part, vectors: EMPTY_BIN }, part.vectors);
1441
+ }
1442
+
1443
+ // src/persistence/durability/segment/vector-write.ts
1444
+ function keptFileRef(input, prior, kept) {
1445
+ const listed = prior?.files.find((file) => file.key === kept.key) ?? input.priorFileRefs?.get(kept.key);
1446
+ if (listed === void 0) {
1447
+ throw new NarsilError(
1448
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
1449
+ `The checkpoint keeps the vector file "${kept.key}", which the previous manifest does not list`,
1450
+ { key: kept.key }
1451
+ );
1452
+ }
1453
+ return { ...kept, bytes: listed.bytes, checksum: listed.checksum, ...headFieldsOf(listed) };
1454
+ }
1455
+ function headFieldsOf(ref) {
1456
+ return ref.headOffset === void 0 ? {} : { headOffset: ref.headOffset, headLength: ref.headLength, headChecksum: ref.headChecksum };
1457
+ }
1458
+ function headRefOf(paged) {
1459
+ return paged === null ? {} : { headOffset: paged.headOffset, headLength: paged.headLength, headChecksum: paged.headChecksum };
1460
+ }
1461
+ async function writeGraphParts(input, fieldPath, plan, generation) {
1462
+ const parts = plan.graphParts ?? [];
1463
+ const refs = [];
1464
+ for (let part = 0; part < parts.length; part++) {
1465
+ const key = graphPartKey(input.indexName, fieldPath, generation, part);
1466
+ const paged = plan.storesHeads ? pagedGraphPartChunks(parts[part]) : null;
1467
+ const packed = await packChecksummedEnvelope(
1468
+ paged === null ? [encode(parts[part])] : paged.chunks,
1469
+ GRAPH_PART_ENVELOPE_VERSION,
1470
+ `graph part "${key}"`
1471
+ );
1472
+ await input.store.write(key, packed.chunks);
1473
+ refs.push({ key, bytes: packed.byteLength, checksum: packed.checksum, ...headRefOf(paged) });
1474
+ }
1475
+ return refs;
1476
+ }
1477
+ async function writeField(input, fieldPath, plan, outcome) {
1478
+ const prior = input.priorVectors.find((ref) => ref.fieldPath === fieldPath);
1479
+ if (plan.unchanged && prior !== void 0) {
1480
+ outcome.refs.push(prior);
1481
+ return;
1482
+ }
1483
+ let nextFileId = prior?.nextFileId ?? 0;
1484
+ const files = plan.kept.map((kept) => keptFileRef(input, prior, kept));
1485
+ const written = [];
1486
+ for (let index = 0; index < plan.newFiles; index++) {
1487
+ const { payload, ordinals, dead, magnitudes } = plan.readNewFile(index);
1488
+ const id = nextFileId;
1489
+ nextFileId += 1;
1490
+ const key = vectorFileKey(input.indexName, fieldPath, id);
1491
+ const paged = plan.storesHeads && magnitudes !== null ? pagedVectorFileChunks(payload, magnitudes) : null;
1492
+ const what = `vector file "${key}"`;
1493
+ const packed = paged === null ? await packChecksummedEnvelope(vectorPartChunks(payload), VECTOR_FILE_ENVELOPE_VERSION, what) : packEnvelopeWithChecksum(
1494
+ paged.chunks,
1495
+ VECTOR_FILE_ENVELOPE_VERSION,
1496
+ what,
1497
+ crc32Combine(await checksumOfChunks(paged.beforeVectors), paged.vectors.checksum, paged.vectors.byteLength)
1498
+ );
1499
+ await input.store.write(key, packed.chunks);
1500
+ files.push({
1501
+ id,
1502
+ key,
1503
+ count: payload.docIds.length,
1504
+ dead,
1505
+ bytes: packed.byteLength,
1506
+ checksum: packed.checksum,
1507
+ ...headRefOf(paged)
1508
+ });
1509
+ written.push({ id, key, ordinals });
1510
+ outcome.layouts.push({
1511
+ fieldPath,
1512
+ key,
1513
+ docIds: payload.docIds,
1514
+ dead,
1515
+ vectorsOffset: packed.byteLength - payload.vectors.byteLength
1516
+ });
1517
+ }
1518
+ const priorGeneration = prior?.graphGeneration ?? 0;
1519
+ const holdsGraph = plan.graphParts !== null && plan.graphParts.length > 0;
1520
+ const graphGeneration = holdsGraph ? priorGeneration + 1 : priorGeneration;
1521
+ const graphParts = holdsGraph ? await writeGraphParts(input, fieldPath, plan, graphGeneration) : [];
1522
+ outcome.refs.push({ fieldPath, nextFileId, files, graphGeneration, graphParts });
1523
+ outcome.written.push({ fieldPath, plan, files: written });
1524
+ }
1525
+ async function writeLiveVectors(input) {
1526
+ const outcome = { refs: [], layouts: [], written: [] };
1527
+ for (const [fieldPath, plan] of input.plans) await writeField(input, fieldPath, plan, outcome);
1528
+ return outcome;
1529
+ }
1530
+
1531
+ // src/persistence/durability/seq-owner.ts
1532
+ var SINGLE_NODE_PRIMARY_TERM = 1;
1533
+ function createSeqOwner(startSeqNo, primaryTerm = SINGLE_NODE_PRIMARY_TERM) {
1534
+ let current = startSeqNo;
1535
+ let term = primaryTerm;
1536
+ return {
1537
+ next() {
1538
+ current += 1;
1539
+ return current;
1540
+ },
1541
+ advanceTo(seqNo, nextPrimaryTerm) {
1542
+ current = seqNo;
1543
+ term = nextPrimaryTerm;
1544
+ },
1545
+ get current() {
1546
+ return current;
1547
+ },
1548
+ get primaryTerm() {
1549
+ return term;
1550
+ }
1551
+ };
1552
+ }
1553
+
1554
+ // src/persistence/durability/partition-checkpoint.ts
1555
+ function checkpointLastSeqNo(checkpoint, partitionId) {
1556
+ for (const c of checkpoint) {
1557
+ if (c.partitionId === partitionId) {
1558
+ return c.lastSeqNo;
1559
+ }
1560
+ }
1561
+ return 0;
1562
+ }
1563
+ function checkpointPrimaryTerm(checkpoint, partitionId) {
1564
+ for (const c of checkpoint) {
1565
+ if (c.partitionId === partitionId) {
1566
+ return c.primaryTerm;
1567
+ }
1568
+ }
1569
+ return 0;
1570
+ }
1571
+
1572
+ // src/persistence/durability/commit-marker.ts
1573
+ var COMMIT_MARKER_SLOT_SIZE = 36;
1574
+ var COMMIT_MARKER_SLOT_COUNT = 2;
1575
+ var CRC_OFFSET = 32;
1576
+ function encodeMarkerSlot(state) {
1577
+ const slot = new Uint8Array(COMMIT_MARKER_SLOT_SIZE);
1578
+ const view = new DataView(slot.buffer);
1579
+ view.setBigUint64(0, BigInt(state.writeSeq), false);
1580
+ view.setBigUint64(8, BigInt(state.activeSegmentSeqNo), false);
1581
+ view.setBigUint64(16, BigInt(state.durableByteLength), false);
1582
+ view.setBigUint64(24, BigInt(state.highestDurableSeqNo), false);
1583
+ view.setUint32(CRC_OFFSET, crc32(slot.subarray(0, CRC_OFFSET)), false);
1584
+ return slot;
1585
+ }
1586
+ function decodeSlot(data, slotIndex) {
1587
+ const base = slotIndex * COMMIT_MARKER_SLOT_SIZE;
1588
+ if (base + COMMIT_MARKER_SLOT_SIZE > data.length) {
1589
+ return null;
1590
+ }
1591
+ const slot = data.subarray(base, base + COMMIT_MARKER_SLOT_SIZE);
1592
+ const view = new DataView(slot.buffer, slot.byteOffset, slot.byteLength);
1593
+ const storedCrc = view.getUint32(CRC_OFFSET, false);
1594
+ if (crc32(slot.subarray(0, CRC_OFFSET)) !== storedCrc) {
1595
+ return null;
1596
+ }
1597
+ const writeSeq = view.getBigUint64(0, false);
1598
+ const activeSegmentSeqNo = view.getBigUint64(8, false);
1599
+ const durableByteLength = view.getBigUint64(16, false);
1600
+ const highestDurableSeqNo = view.getBigUint64(24, false);
1601
+ 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)) {
1602
+ return null;
1603
+ }
1604
+ return {
1605
+ writeSeq: Number(writeSeq),
1606
+ activeSegmentSeqNo: Number(activeSegmentSeqNo),
1607
+ durableByteLength: Number(durableByteLength),
1608
+ highestDurableSeqNo: Number(highestDurableSeqNo)
1609
+ };
1610
+ }
1611
+ function readCommitMarker(data) {
1612
+ let best = null;
1613
+ for (let slotIndex = 0; slotIndex < COMMIT_MARKER_SLOT_COUNT; slotIndex += 1) {
1614
+ const state = decodeSlot(data, slotIndex);
1615
+ if (state === null) {
1616
+ continue;
1617
+ }
1618
+ if (best === null || state.writeSeq > best.state.writeSeq) {
1619
+ best = { state, slotIndex };
1620
+ }
1621
+ }
1622
+ return best;
1623
+ }
1624
+ function nextMarkerSlot(lastWrittenSlot) {
1625
+ if (lastWrittenSlot === null) {
1626
+ return 0;
1627
+ }
1628
+ return (lastWrittenSlot + 1) % COMMIT_MARKER_SLOT_COUNT;
1629
+ }
1630
+ function markerSlotOffset(slotIndex) {
1631
+ return slotIndex * COMMIT_MARKER_SLOT_SIZE;
1632
+ }
1633
+ function isRecord2(value) {
1634
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1635
+ }
1636
+ function optionalIndexUuid(value, payloadName) {
1637
+ if (value === void 0 || value === null) {
1638
+ return void 0;
1639
+ }
1640
+ if (typeof value !== "string" || value.length === 0) {
1641
+ throw new Error(`Invalid ${payloadName}: "indexUuid" must be a non-empty string or absent`);
1642
+ }
1643
+ return value;
1644
+ }
1645
+ function optionalPreviousPrimaryTerm(value, payloadName) {
1646
+ if (value === void 0 || value === null) {
1647
+ return void 0;
1648
+ }
1649
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1650
+ throw new Error(`Invalid ${payloadName}: "previousPrimaryTerm" must be a non-negative integer or absent`);
1651
+ }
1652
+ return value;
1653
+ }
1654
+ function validateEntryPayload(decoded) {
1655
+ if (!isRecord2(decoded) || !isRecord2(decoded.entry)) {
1656
+ throw new Error('Invalid EntryPayload: missing or invalid "entry" field');
1657
+ }
1658
+ const entry = decoded.entry;
1659
+ if (typeof entry.seqNo !== "number") {
1660
+ throw new Error('Invalid EntryPayload: "entry.seqNo" must be a number');
1661
+ }
1662
+ if (typeof entry.primaryTerm !== "number") {
1663
+ throw new Error('Invalid EntryPayload: "entry.primaryTerm" must be a number');
1664
+ }
1665
+ if (entry.operation !== "INDEX" && entry.operation !== "DELETE") {
1666
+ throw new Error('Invalid EntryPayload: "entry.operation" must be "INDEX" or "DELETE"');
1667
+ }
1668
+ if (typeof entry.partitionId !== "number") {
1669
+ throw new Error('Invalid EntryPayload: "entry.partitionId" must be a number');
1670
+ }
1671
+ if (typeof entry.indexName !== "string") {
1672
+ throw new Error('Invalid EntryPayload: "entry.indexName" must be a string');
1673
+ }
1674
+ if (typeof entry.documentId !== "string") {
1675
+ throw new Error('Invalid EntryPayload: "entry.documentId" must be a string');
1676
+ }
1677
+ if (entry.document !== null && !(entry.document instanceof Uint8Array)) {
1678
+ throw new Error('Invalid EntryPayload: "entry.document" must be Uint8Array or null');
1679
+ }
1680
+ if (typeof entry.checksum !== "number") {
1681
+ throw new Error('Invalid EntryPayload: "entry.checksum" must be a number');
1682
+ }
1683
+ optionalIndexUuid(decoded.indexUuid, "EntryPayload");
1684
+ optionalPreviousPrimaryTerm(decoded.previousPrimaryTerm, "EntryPayload");
1685
+ return decoded;
1686
+ }
1687
+ function computeEntryChecksum(entry) {
1688
+ const payload = encode([
1689
+ entry.seqNo,
1690
+ entry.primaryTerm,
1691
+ entry.operation,
1692
+ entry.partitionId,
1693
+ entry.indexName,
1694
+ entry.documentId,
1695
+ entry.document
1696
+ ]);
1697
+ return crc32(payload);
1698
+ }
1699
+ function buildEntry(fields) {
1700
+ return { ...fields, checksum: computeEntryChecksum(fields) };
1701
+ }
1702
+
1703
+ // src/persistence/durability/wal-framing.ts
1704
+ var WAL_MAGIC = new Uint8Array([78, 82, 83, 87]);
1705
+ var WAL_FORMAT_VERSION = 1;
1706
+ var SEGMENT_HEADER_SIZE = 8;
1707
+ var RECORD_LENGTH_SIZE = 4;
1708
+ var FRAME_CRC_SIZE = 4;
1709
+ var MAX_WAL_RECORD_BYTES = 268435456;
1710
+ function writeSegmentHeader() {
1711
+ const header = new Uint8Array(SEGMENT_HEADER_SIZE);
1712
+ header.set(WAL_MAGIC, 0);
1713
+ header[4] = WAL_FORMAT_VERSION & 255;
1714
+ return header;
1715
+ }
1716
+ function frameRecord(entry) {
1717
+ const payload = encode(entry);
1718
+ const frame = new Uint8Array(RECORD_LENGTH_SIZE + payload.length + FRAME_CRC_SIZE);
1719
+ const view = new DataView(frame.buffer);
1720
+ view.setUint32(0, payload.length, false);
1721
+ frame.set(payload, RECORD_LENGTH_SIZE);
1722
+ view.setUint32(RECORD_LENGTH_SIZE + payload.length, crc32(payload), false);
1723
+ return frame;
1724
+ }
1725
+ function checkSegmentHeader(data) {
1726
+ if (data.length < SEGMENT_HEADER_SIZE) {
1727
+ return { ok: false, reason: "segment shorter than the 8-byte header" };
1728
+ }
1729
+ for (let i = 0; i < WAL_MAGIC.length; i += 1) {
1730
+ if (data[i] !== WAL_MAGIC[i]) {
1731
+ return { ok: false, reason: "missing NRSW magic" };
1732
+ }
1733
+ }
1734
+ const formatVersion = data[4];
1735
+ if (formatVersion > WAL_FORMAT_VERSION) {
1736
+ return {
1737
+ ok: false,
1738
+ reason: `WAL format version ${formatVersion} is newer than supported version ${WAL_FORMAT_VERSION}`
1739
+ };
1740
+ }
1741
+ return { ok: true };
1742
+ }
1743
+ function decodeEntry(payload) {
1744
+ const decoded = decode(payload);
1745
+ const { entry } = validateEntryPayload({ entry: decoded });
1746
+ if (computeEntryChecksum(entry) !== entry.checksum) {
1747
+ throw new Error("WAL record failed its logical entry checksum");
1748
+ }
1749
+ return entry;
1750
+ }
1751
+ function corrupt(message, details) {
1752
+ throw new NarsilError(ErrorCodes.PERSISTENCE_WAL_CORRUPT, message, details);
1753
+ }
1754
+ function readDurableRegion(data, durableByteLength, maxRecordBytes = MAX_WAL_RECORD_BYTES) {
1755
+ const header = checkSegmentHeader(data);
1756
+ if (!header.ok) {
1757
+ corrupt(`WAL segment header invalid in durable region: ${header.reason}`, { reason: header.reason });
1758
+ }
1759
+ if (durableByteLength < SEGMENT_HEADER_SIZE || durableByteLength > data.length) {
1760
+ corrupt("Commit marker durable byte length is outside the segment", {
1761
+ durableByteLength,
1762
+ segmentLength: data.length
1763
+ });
1764
+ }
1765
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1766
+ const entries = [];
1767
+ let offset = SEGMENT_HEADER_SIZE;
1768
+ while (offset < durableByteLength) {
1769
+ if (offset + RECORD_LENGTH_SIZE > durableByteLength) {
1770
+ corrupt("WAL record length field overruns the durable region", { offset, durableByteLength });
1771
+ }
1772
+ const recordLength = view.getUint32(offset, false);
1773
+ if (recordLength === 0 || recordLength > maxRecordBytes) {
1774
+ corrupt("WAL record length is zero or exceeds the maximum record size", { offset, recordLength });
1775
+ }
1776
+ const payloadStart = offset + RECORD_LENGTH_SIZE;
1777
+ const crcStart = payloadStart + recordLength;
1778
+ const frameEnd = crcStart + FRAME_CRC_SIZE;
1779
+ if (frameEnd > durableByteLength) {
1780
+ corrupt("WAL record overruns the durable region", { offset, frameEnd, durableByteLength });
1781
+ }
1782
+ const payload = data.subarray(payloadStart, crcStart);
1783
+ const storedCrc = view.getUint32(crcStart, false);
1784
+ if (crc32(payload) !== storedCrc) {
1785
+ corrupt("WAL record failed its frame checksum inside the durable region", { offset });
1786
+ }
1787
+ let entry;
1788
+ try {
1789
+ entry = decodeEntry(payload);
1790
+ } catch (err) {
1791
+ corrupt("WAL record payload failed to decode inside the durable region", {
1792
+ offset,
1793
+ cause: err instanceof Error ? err.message : String(err)
1794
+ });
1795
+ }
1796
+ if (entries.length > 0 && entry.seqNo <= entries[entries.length - 1].seqNo) {
1797
+ corrupt("WAL sequence numbers are not strictly increasing", {
1798
+ previousSeqNo: entries[entries.length - 1].seqNo,
1799
+ seqNo: entry.seqNo
1800
+ });
1801
+ }
1802
+ entries.push(entry);
1803
+ offset = frameEnd;
1804
+ }
1805
+ return entries;
1806
+ }
1807
+ function readTailBeyondFrontier(data, durableByteLength, lastDurableSeqNo, maxRecordBytes = MAX_WAL_RECORD_BYTES) {
1808
+ const start = Math.max(durableByteLength, SEGMENT_HEADER_SIZE);
1809
+ const entries = [];
1810
+ if (start >= data.length) {
1811
+ return { entries, cleanEnd: start };
1812
+ }
1813
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1814
+ let offset = start;
1815
+ let cleanEnd = start;
1816
+ let previousSeqNo = lastDurableSeqNo;
1817
+ while (offset < data.length) {
1818
+ if (offset + RECORD_LENGTH_SIZE > data.length) {
1819
+ break;
1820
+ }
1821
+ const recordLength = view.getUint32(offset, false);
1822
+ if (recordLength === 0 || recordLength > maxRecordBytes) {
1823
+ break;
1824
+ }
1825
+ const payloadStart = offset + RECORD_LENGTH_SIZE;
1826
+ const crcStart = payloadStart + recordLength;
1827
+ const frameEnd = crcStart + FRAME_CRC_SIZE;
1828
+ if (frameEnd > data.length) {
1829
+ break;
1830
+ }
1831
+ const payload = data.subarray(payloadStart, crcStart);
1832
+ if (crc32(payload) !== view.getUint32(crcStart, false)) {
1833
+ break;
1834
+ }
1835
+ let entry;
1836
+ try {
1837
+ entry = decodeEntry(payload);
1838
+ } catch {
1839
+ break;
1840
+ }
1841
+ if (entry.seqNo <= previousSeqNo) {
1842
+ break;
1843
+ }
1844
+ entries.push(entry);
1845
+ previousSeqNo = entry.seqNo;
1846
+ offset = frameEnd;
1847
+ cleanEnd = frameEnd;
1848
+ }
1849
+ return { entries, cleanEnd };
1850
+ }
1851
+
1852
+ // src/persistence/durability/wal-segments.ts
1853
+ function walPrefix(indexName, partitionId) {
1854
+ return `${indexName}/wal/${partitionId}/`;
1855
+ }
1856
+ function nextSegmentKey(indexName, partitionId) {
1857
+ return `${walPrefix(indexName, partitionId)}next`;
1858
+ }
1859
+ function segmentStartSeqNo(key, prefix) {
1860
+ if (!key.startsWith(prefix)) {
1861
+ return null;
1862
+ }
1863
+ const tail = key.slice(prefix.length);
1864
+ if (!/^\d{16}$/.test(tail)) {
1865
+ return null;
1866
+ }
1867
+ const value = Number.parseInt(tail, 10);
1868
+ return Number.isSafeInteger(value) ? value : null;
1869
+ }
1870
+ async function collectSegments(directory, prefix) {
1871
+ const keys = await directory.list(prefix);
1872
+ const refs = [];
1873
+ for (const key of keys) {
1874
+ const startSeqNo = segmentStartSeqNo(key, prefix);
1875
+ if (startSeqNo !== null) {
1876
+ refs.push({ key, startSeqNo });
1877
+ }
1878
+ }
1879
+ refs.sort((a, b) => a.startSeqNo - b.startSeqNo);
1880
+ return refs;
1881
+ }
1882
+ async function openWal(directory, indexName, partitionId) {
1883
+ const prefix = walPrefix(indexName, partitionId);
1884
+ const markerBytes = await directory.read(`${prefix}commit`);
1885
+ const marker = markerBytes === null ? null : readCommitMarker(markerBytes);
1886
+ if (marker === null) {
1887
+ return null;
1888
+ }
1889
+ return { marker, segments: await collectSegments(directory, prefix) };
1890
+ }
1891
+ async function* readSegmentsInOrder(directory, wal) {
1892
+ const { marker, segments } = wal;
1893
+ let highestRead = 0;
1894
+ for (const { key, startSeqNo } of segments) {
1895
+ if (startSeqNo > marker.state.activeSegmentSeqNo) {
1896
+ continue;
1897
+ }
1898
+ const bytes = await directory.read(key);
1899
+ if (bytes === null) {
1900
+ continue;
1901
+ }
1902
+ if (startSeqNo < marker.state.activeSegmentSeqNo) {
1903
+ const header = checkSegmentHeader(bytes);
1904
+ if (!header.ok) {
1905
+ throw new NarsilError(
1906
+ ErrorCodes.PERSISTENCE_WAL_CORRUPT,
1907
+ `Sealed WAL segment header invalid: ${header.reason}`,
1908
+ {
1909
+ key,
1910
+ reason: header.reason
1911
+ }
1912
+ );
1913
+ }
1914
+ const durableEntries2 = readDurableRegion(bytes, bytes.length);
1915
+ for (const entry of durableEntries2) highestRead = Math.max(highestRead, entry.seqNo);
1916
+ yield { durableEntries: durableEntries2, activeTail: null };
1917
+ continue;
1918
+ }
1919
+ const durableEntries = readDurableRegion(bytes, marker.state.durableByteLength);
1920
+ for (const entry of durableEntries) highestRead = Math.max(highestRead, entry.seqNo);
1921
+ const tail = readTailBeyondFrontier(
1922
+ bytes,
1923
+ marker.state.durableByteLength,
1924
+ Math.max(highestRead, marker.state.highestDurableSeqNo)
1925
+ );
1926
+ yield {
1927
+ durableEntries,
1928
+ activeTail: { key, entries: tail.entries, cleanEnd: tail.cleanEnd, segmentLength: bytes.length }
1929
+ };
1930
+ }
1931
+ }
1932
+ async function readWalSegments(directory, indexName, partitionId) {
1933
+ const wal = await openWal(directory, indexName, partitionId);
1934
+ if (wal === null) {
1935
+ return null;
1936
+ }
1937
+ const durableEntries = [];
1938
+ let highestReadFromWal = 0;
1939
+ let activeTail = null;
1940
+ for await (const segment of readSegmentsInOrder(directory, wal)) {
1941
+ for (const entry of segment.durableEntries) {
1942
+ durableEntries.push(entry);
1943
+ highestReadFromWal = Math.max(highestReadFromWal, entry.seqNo);
1944
+ }
1945
+ activeTail = segment.activeTail ?? activeTail;
1946
+ }
1947
+ return { marker: wal.marker, segments: wal.segments, durableEntries, activeTail, highestReadFromWal };
1948
+ }
1949
+ function durableRecordMissing(indexName, partitionId, highestRead, marker) {
1950
+ return new NarsilError(
1951
+ ErrorCodes.PERSISTENCE_WAL_CORRUPT,
1952
+ "A durable WAL record is missing: the highest recovered seqNo is below the commit marker",
1953
+ { indexName, partitionId, highestRead, highestDurable: marker.state.highestDurableSeqNo }
1954
+ );
1955
+ }
1956
+ async function* walEntriesInRange(directory, indexName, partitionId, fromSeqNoExclusive, upToSeqNoInclusive) {
1957
+ const wal = await openWal(directory, indexName, partitionId);
1958
+ if (wal === null) {
1959
+ return;
1960
+ }
1961
+ let highestRead = 0;
1962
+ for await (const segment of readSegmentsInOrder(directory, wal)) {
1963
+ for (const entry of segment.durableEntries) {
1964
+ highestRead = Math.max(highestRead, entry.seqNo);
1965
+ if (entry.seqNo > fromSeqNoExclusive && entry.seqNo <= upToSeqNoInclusive) {
1966
+ yield entry;
1967
+ }
1968
+ }
1969
+ }
1970
+ if (Math.max(fromSeqNoExclusive, highestRead) < wal.marker.state.highestDurableSeqNo) {
1971
+ throw durableRecordMissing(indexName, partitionId, highestRead, wal.marker);
1972
+ }
1973
+ }
1974
+ function writeRecordsOf(documents, written) {
1975
+ const seqNos = new Float64Array(documents.length);
1976
+ const primaryTerms = new Float64Array(documents.length);
1977
+ for (let at = 0; at < documents.length; at++) {
1978
+ const entry = written.get(documents[at].docId);
1979
+ if (entry === void 0) continue;
1980
+ seqNos[at] = entry.seqNo;
1981
+ primaryTerms[at] = entry.primaryTerm;
1982
+ }
1983
+ return { seqNos, primaryTerms };
1984
+ }
1985
+ function everyVectorFieldIsTopLevel(vectorFieldPaths) {
1986
+ for (const fieldPath of vectorFieldPaths) {
1987
+ if (fieldPath.includes(".")) return false;
1988
+ }
1989
+ return vectorFieldPaths.size > 0;
1990
+ }
1991
+ function documentWithoutVectors(encoded, vectorFieldPaths, leavesVectorsUndecoded) {
1992
+ const skipped = leavesVectorsUndecoded ? decodeMapWithoutFields(encoded, vectorFieldPaths) : null;
1993
+ if (skipped !== null) return skipped;
1994
+ const document = decode(encoded);
1995
+ restoreVectorFields(document, vectorFieldPaths);
1996
+ return prepareDocumentVectors(document, vectorFieldPaths).partitionDoc;
1997
+ }
1998
+ async function buildSegmentFromEntries(input) {
1999
+ const leavesVectorsUndecoded = everyVectorFieldIsTopLevel(input.vectorFieldPaths);
2000
+ const live = /* @__PURE__ */ new Map();
2001
+ const deleted = /* @__PURE__ */ new Set();
2002
+ const written = /* @__PURE__ */ new Map();
2003
+ for await (const entry of input.entries) {
2004
+ if (entry.operation === "DELETE") {
2005
+ deleted.add(entry.documentId);
2006
+ live.delete(entry.documentId);
2007
+ written.delete(entry.documentId);
2008
+ continue;
2009
+ }
2010
+ if (entry.document === null) continue;
2011
+ live.delete(entry.documentId);
2012
+ live.set(entry.documentId, documentWithoutVectors(entry.document, input.vectorFieldPaths, leavesVectorsUndecoded));
2013
+ if (input.keepsWriteRecords) written.set(entry.documentId, entry);
2014
+ }
2015
+ const tombstones = [];
2016
+ for (const docId of deleted) {
2017
+ if (!live.has(docId)) tombstones.push(docId);
2018
+ }
2019
+ if (live.size === 0 && tombstones.length === 0) {
2020
+ return null;
2021
+ }
2022
+ const documents = [];
2023
+ for (const [docId, document] of live) documents.push({ docId, document });
2024
+ const manager = createPartitionManager(input.indexName, input.config, input.language, createPartitionRouter(), 1);
2025
+ const payload = buildSegmentPayload(
2026
+ documents,
2027
+ input.config.schema,
2028
+ input.language,
2029
+ resolvePartitionInsertOptions(input.config, manager.analysis),
2030
+ input.config.trackPositions ?? true
2031
+ );
2032
+ const segment = createFrozenSegment(
2033
+ payload,
2034
+ documents.map((entry) => entry.document)
2035
+ );
2036
+ const built = { selections: [{ segment }], tombstones, docCount: live.size };
2037
+ if (input.keepsWriteRecords) built.writeRecords = /* @__PURE__ */ new Map([[segment, writeRecordsOf(documents, written)]]);
2038
+ return built;
2039
+ }
2040
+
2041
+ // src/persistence/durability/segment/compaction.ts
2042
+ function windowFits(segments, start, windowLength, paged) {
2043
+ let documents = 0;
2044
+ let bytes = SEGMENT_FILE_FRAMING_SLACK_BYTES;
2045
+ for (let at = start; at < start + windowLength; at++) {
2046
+ documents += segments[at].docCount;
2047
+ bytes += segments[at].bytes;
2048
+ }
2049
+ if (paged) return bytes * MERGED_SEGMENT_GROWTH_ALLOWANCE <= MERGED_SEGMENT_TARGET_BYTES;
2050
+ return documents <= COMPACTION_LARGEST_MERGED_DOCUMENT_COUNT && bytes <= MAX_FILE_BYTES;
2051
+ }
2052
+ function smallestFittingWindow(segments, windowLength, paged) {
2053
+ let best = null;
2054
+ let bestBytes = Number.POSITIVE_INFINITY;
2055
+ for (let start = 0; start + windowLength <= segments.length; start++) {
2056
+ if (!windowFits(segments, start, windowLength, paged)) continue;
2057
+ let bytes = 0;
2058
+ for (let at = start; at < start + windowLength; at++) bytes += segments[at].bytes;
2059
+ if (bytes < bestBytes) {
2060
+ bestBytes = bytes;
2061
+ best = { start, windowLength };
2062
+ }
2063
+ }
2064
+ return best;
2065
+ }
2066
+ function chooseWindow(segments, wantedLength, paged) {
2067
+ for (let windowLength = Math.min(wantedLength, segments.length); windowLength >= 2; windowLength--) {
2068
+ const window = smallestFittingWindow(segments, windowLength, paged);
2069
+ if (window !== null) return window;
2070
+ }
2071
+ return null;
2072
+ }
2073
+ function frozenOf(contents) {
2074
+ return createSharedFrozenSegment(shareSegmentArrays(contents.arrays, null));
2075
+ }
2076
+ function applyTimeOrder(frozen, contents) {
2077
+ for (let newer = 1; newer < frozen.length; newer++) {
2078
+ const replaced = new Set(contents[newer].tombstones);
2079
+ const ids = frozen[newer].arrays.idTable;
2080
+ for (let ordinal = 0; ordinal < ids.count; ordinal++) replaced.add(ids.idAt(ordinal));
2081
+ for (let older = 0; older < newer; older++) {
2082
+ for (const docId of replaced) frozen[older].tombstoneDocument(docId);
2083
+ }
2084
+ }
2085
+ }
2086
+ function writeRecordsOf2(frozen, contents) {
2087
+ if (contents.every((segment) => segment.writeRecords === void 0)) return void 0;
2088
+ const records = /* @__PURE__ */ new Map();
2089
+ for (let at = 0; at < frozen.length; at++) {
2090
+ const held = contents[at].writeRecords;
2091
+ if (held !== void 0) records.set(frozen[at], held);
2092
+ }
2093
+ return records;
2094
+ }
2095
+ function retainedTombstones(frozen, contents) {
2096
+ const retained = /* @__PURE__ */ new Set();
2097
+ for (const segment of contents) {
2098
+ for (const docId of segment.tombstones) {
2099
+ if (!frozen.some((candidate) => candidate.hasDocument(docId))) retained.add(docId);
2100
+ }
2101
+ }
2102
+ return [...retained];
2103
+ }
2104
+ async function compactPartitionSegments(input) {
2105
+ const { segments, compactionThreshold } = input;
2106
+ if (segments.length <= compactionThreshold) {
2107
+ return { segments, nextSegmentId: input.nextSegmentId };
2108
+ }
2109
+ const paged = input.paged === true;
2110
+ const window = chooseWindow(segments, segments.length - compactionThreshold + 1, paged);
2111
+ if (window === null) {
2112
+ return { segments, nextSegmentId: input.nextSegmentId };
2113
+ }
2114
+ const windowRefs = segments.slice(window.start, window.start + window.windowLength);
2115
+ const replacing = (written2) => ({
2116
+ segments: [
2117
+ ...segments.slice(0, window.start),
2118
+ ...written2.segments,
2119
+ ...segments.slice(window.start + window.windowLength)
2120
+ ],
2121
+ nextSegmentId: written2.nextSegmentId
2122
+ });
2123
+ if (paged) {
2124
+ const { directory } = input.store;
2125
+ if (directory === void 0) return { segments, nextSegmentId: input.nextSegmentId };
2126
+ const { mergePagedWindow } = await import('./module-VEK2KCKU.mjs');
2127
+ return replacing(
2128
+ await mergePagedWindow({
2129
+ store: input.store,
2130
+ directory,
2131
+ indexName: input.indexName,
2132
+ partitionId: input.partitionId,
2133
+ schema: input.schema,
2134
+ partialWordAnalysis: input.partialWordAnalysis,
2135
+ textAnalysis: input.textAnalysis,
2136
+ nextSegmentId: input.nextSegmentId,
2137
+ refs: windowRefs,
2138
+ dropsEveryTombstone: window.start === 0
2139
+ })
2140
+ );
2141
+ }
2142
+ const contents = [];
2143
+ for (const ref of windowRefs) contents.push(await readSegmentFile(input.store, ref));
2144
+ const frozen = contents.map(frozenOf);
2145
+ applyTimeOrder(frozen, contents);
2146
+ const writeRecords = writeRecordsOf2(frozen, contents);
2147
+ const written = await writeSegmentsOf({
2148
+ store: input.store,
2149
+ indexName: input.indexName,
2150
+ partitionId: input.partitionId,
2151
+ nextSegmentId: input.nextSegmentId,
2152
+ schema: input.schema,
2153
+ partialWordAnalysis: input.partialWordAnalysis,
2154
+ textAnalysis: input.textAnalysis,
2155
+ selections: frozen.map((segment) => ({ segment })),
2156
+ tombstones: retainedTombstones(frozen, contents),
2157
+ mergesIntoOneFile: true,
2158
+ ...writeRecords === void 0 ? {} : { writeRecords }
2159
+ });
2160
+ return replacing(written);
2161
+ }
2162
+
2163
+ // src/persistence/durability/segment/write.ts
2164
+ function textAnalysisOf(config) {
2165
+ let resolved = null;
2166
+ const resolve = () => {
2167
+ resolved ??= {
2168
+ language: getLanguage(config.language ?? "english"),
2169
+ options: resolvePartitionInsertOptions(config, resolveIndexAnalysis(config))
2170
+ };
2171
+ return resolved;
2172
+ };
2173
+ return {
2174
+ get language() {
2175
+ return resolve().language;
2176
+ },
2177
+ get options() {
2178
+ return resolve().options;
2179
+ }
2180
+ };
2181
+ }
2182
+ function partialWordAnalysisOf(config, text) {
2183
+ const fields = partialFieldsOf(config.schema);
2184
+ if (fields.length === 0) return null;
2185
+ return {
2186
+ fields,
2187
+ get language() {
2188
+ return text.language;
2189
+ },
2190
+ get options() {
2191
+ return text.options;
2192
+ }
2193
+ };
2194
+ }
2195
+ function resolveCompactionThreshold(configured) {
2196
+ if (!Number.isInteger(configured) || configured <= 0 || configured > MAX_SEGMENTS_PER_PARTITION) {
2197
+ return DEFAULT_COMPACTION_THRESHOLD;
2198
+ }
2199
+ return configured;
2200
+ }
2201
+ function wholeContentsOf(input, partitionId) {
2202
+ const whole = input.wholePartitions?.find((candidate) => candidate.partitionId === partitionId);
2203
+ if (whole !== void 0) return whole;
2204
+ const captured = input.capturedPartitions?.find((candidate) => candidate.partitionId === partitionId);
2205
+ return captured === void 0 ? void 0 : contentsOfCaptured(captured);
2206
+ }
2207
+ function pagedSettingsOf(context) {
2208
+ if (context.input.metadata.textStorage !== "disk") return {};
2209
+ return { paged: true, keepsWriteRecords: context.input.keepsWriteRecords === true };
2210
+ }
2211
+ async function tombstonesOfDelta(context, older, selections, deleted) {
2212
+ const { directory } = context.input.store;
2213
+ if (context.input.metadata.textStorage !== "disk" || directory === void 0) return deleted;
2214
+ const { pagedTombstonesFor } = await import('./module-VEK2KCKU.mjs');
2215
+ return pagedTombstonesFor(
2216
+ directory,
2217
+ older,
2218
+ selections.map((selection) => selection.segment),
2219
+ deleted
2220
+ );
2221
+ }
2222
+ async function writeWholePartition(context, partitionId, priorPartition, whole) {
2223
+ const written = await writeSegmentsOf({
2224
+ store: context.input.store,
2225
+ indexName: context.indexName,
2226
+ partitionId,
2227
+ nextSegmentId: priorPartition?.nextSegmentId ?? 0,
2228
+ schema: context.input.metadata.schema,
2229
+ partialWordAnalysis: context.partialWordAnalysis,
2230
+ textAnalysis: context.textAnalysis,
2231
+ selections: whole.selections,
2232
+ tombstones: [],
2233
+ ...whole.writeRecords === void 0 ? {} : { writeRecords: whole.writeRecords },
2234
+ ...pagedSettingsOf(context)
2235
+ });
2236
+ return { partitionId, nextSegmentId: written.nextSegmentId, segments: written.segments };
2237
+ }
2238
+ async function writeLoggedChanges(context, partitionId, priorPartition, entries) {
2239
+ const built = await buildSegmentFromEntries({
2240
+ indexName: context.indexName,
2241
+ config: context.config,
2242
+ language: getLanguage(context.config.language ?? "english"),
2243
+ vectorFieldPaths: context.vectorFieldPaths,
2244
+ entries,
2245
+ keepsWriteRecords: context.input.keepsWriteRecords === true
2246
+ });
2247
+ let segments = priorPartition ? [...priorPartition.segments] : [];
2248
+ let nextSegmentId = priorPartition?.nextSegmentId ?? 0;
2249
+ if (built !== null) {
2250
+ const tombstones = await tombstonesOfDelta(context, segments, built.selections, built.tombstones);
2251
+ const written = await writeSegmentsOf({
2252
+ store: context.input.store,
2253
+ indexName: context.indexName,
2254
+ partitionId,
2255
+ nextSegmentId,
2256
+ schema: context.input.metadata.schema,
2257
+ partialWordAnalysis: context.partialWordAnalysis,
2258
+ textAnalysis: context.textAnalysis,
2259
+ selections: built.selections,
2260
+ tombstones,
2261
+ ...built.writeRecords === void 0 ? {} : { writeRecords: built.writeRecords },
2262
+ ...pagedSettingsOf(context)
2263
+ });
2264
+ segments.push(...written.segments);
2265
+ nextSegmentId = written.nextSegmentId;
2266
+ }
2267
+ if (segments.length > MAX_SEGMENTS_PER_PARTITION) {
2268
+ throw new NarsilError(
2269
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2270
+ `Partition ${partitionId} would exceed the maximum of ${MAX_SEGMENTS_PER_PARTITION} segments`,
2271
+ { partitionId, segmentCount: segments.length, maximum: MAX_SEGMENTS_PER_PARTITION }
2272
+ );
2273
+ }
2274
+ const compacted = await compactPartitionSegments({
2275
+ store: context.input.store,
2276
+ indexName: context.indexName,
2277
+ partitionId,
2278
+ schema: context.input.metadata.schema,
2279
+ partialWordAnalysis: context.partialWordAnalysis,
2280
+ textAnalysis: context.textAnalysis,
2281
+ segments,
2282
+ nextSegmentId,
2283
+ compactionThreshold: context.compactionThreshold,
2284
+ paged: context.input.metadata.textStorage === "disk"
2285
+ });
2286
+ segments = compacted.segments;
2287
+ nextSegmentId = compacted.nextSegmentId;
2288
+ return { partitionId, nextSegmentId, segments };
2289
+ }
2290
+ function carryForwardUncheckpointedPartitions(prior, targets, partitions, checkpointByPartition) {
2291
+ if (prior === null) return;
2292
+ const covered = new Set(targets.map((target) => target.partitionId));
2293
+ for (const priorPartition of prior.partitions) {
2294
+ if (covered.has(priorPartition.partitionId)) continue;
2295
+ partitions.push(priorPartition);
2296
+ const priorCheckpoint = prior.checkpoint.find((c) => c.partitionId === priorPartition.partitionId);
2297
+ if (priorCheckpoint !== void 0 && !checkpointByPartition.has(priorPartition.partitionId)) {
2298
+ checkpointByPartition.set(priorPartition.partitionId, priorCheckpoint);
2299
+ }
2300
+ }
2301
+ }
2302
+ async function writeCheckpointSegments(input) {
2303
+ const config = reconstructSchemaFromMetadata(input.metadata);
2304
+ const textAnalysis = textAnalysisOf(config);
2305
+ const context = {
2306
+ input,
2307
+ indexName: input.metadata.indexName,
2308
+ config,
2309
+ partialWordAnalysis: partialWordAnalysisOf(config, textAnalysis),
2310
+ textAnalysis,
2311
+ vectorFieldPaths: new Set(extractVectorFieldsFromSchema(config.schema).keys()),
2312
+ compactionThreshold: resolveCompactionThreshold(input.compactionThreshold)
2313
+ };
2314
+ const checkpointByPartition = /* @__PURE__ */ new Map();
2315
+ for (const target of input.targets) checkpointByPartition.set(target.partitionId, { ...target });
2316
+ const partitions = [];
2317
+ for (const target of input.targets) {
2318
+ const priorPartition = input.prior?.partitions.find((p) => p.partitionId === target.partitionId);
2319
+ const whole = wholeContentsOf(input, target.partitionId);
2320
+ if (whole !== void 0) {
2321
+ partitions.push(await writeWholePartition(context, target.partitionId, priorPartition, whole));
2322
+ continue;
2323
+ }
2324
+ if (input.directory === void 0) {
2325
+ throw new NarsilError(
2326
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2327
+ `The checkpoint of partition ${target.partitionId} holds neither the partition's content nor a log to read it from`,
2328
+ { partitionId: target.partitionId }
2329
+ );
2330
+ }
2331
+ const priorSeqNo = checkpointLastSeqNo(input.prior?.checkpoint ?? [], target.partitionId);
2332
+ const entries = walEntriesInRange(
2333
+ input.directory,
2334
+ context.indexName,
2335
+ target.partitionId,
2336
+ priorSeqNo,
2337
+ target.lastSeqNo
2338
+ );
2339
+ partitions.push(await writeLoggedChanges(context, target.partitionId, priorPartition, entries));
2340
+ }
2341
+ carryForwardUncheckpointedPartitions(input.prior, input.targets, partitions, checkpointByPartition);
2342
+ return { checkpoint: [...checkpointByPartition.values()], partitions };
2343
+ }
2344
+ async function commitCheckpointManifest(store, metadata, written, vectors) {
2345
+ const indexName = metadata.indexName;
2346
+ const manifest = {
2347
+ version: SEGMENT_MANIFEST_VERSION,
2348
+ schema: metadata.schema,
2349
+ language: metadata.language,
2350
+ ...metadata.analysisGeneration ? { analysisGeneration: metadata.analysisGeneration } : {},
2351
+ checkpoint: written.checkpoint,
2352
+ partitions: written.partitions,
2353
+ vectors
2354
+ };
2355
+ const packed = await encodeSegmentManifest(manifest);
2356
+ await store.write(manifestKey(indexName), packed.chunks);
2357
+ return { garbage: await unreferencedKeys(store, indexName, manifest) };
2358
+ }
2359
+ async function unreferencedKeys(store, indexName, manifest) {
2360
+ const referenced = manifestReferencedKeys(manifest);
2361
+ const stored = await store.list(segmentsPrefix(indexName));
2362
+ return [...stored.filter((key) => !referenced.has(key)), snapshotBundleKey(indexName)];
2363
+ }
2364
+ async function removeCheckpointGarbage(store, garbage) {
2365
+ for (const key of garbage) {
2366
+ await store.remove(key);
2367
+ }
2368
+ }
2369
+
2370
+ // src/persistence/durability/segment/load-partition.ts
2371
+ function requireAgreedSchema(agreed, schema, key) {
2372
+ for (const [field, type] of Object.entries(schema)) {
2373
+ const existing = agreed[field];
2374
+ if (existing !== void 0 && existing !== type) {
2375
+ throw new NarsilError(
2376
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
2377
+ `The segment "${key}" gives field "${field}" the type "${type}", while the index gives it "${existing}"`,
2378
+ { key, field, existing, found: type }
2379
+ );
2380
+ }
2381
+ }
2382
+ }
2383
+ function removeWhatTheSegmentReplaces(manager, segment, contents) {
2384
+ manager.beginBatchRemove();
2385
+ try {
2386
+ for (const docId of contents.tombstones) {
2387
+ if (manager.has(docId)) manager.remove(docId);
2388
+ }
2389
+ const ids = segment.arrays.idTable;
2390
+ for (let ordinal = 0; ordinal < ids.count; ordinal++) {
2391
+ const docId = ids.idAt(ordinal);
2392
+ if (manager.has(docId)) manager.remove(docId);
2393
+ }
2394
+ } finally {
2395
+ manager.endBatchRemove();
2396
+ }
2397
+ }
2398
+ function yieldToEventLoop() {
2399
+ return new Promise((resolve) => setTimeout(resolve, 0));
2400
+ }
2401
+ function removeFromPartition(manager, partitionId, docIds) {
2402
+ const { composite, docPartitionMap, insertOptions } = manager.diskSegmentAccess(partitionId);
2403
+ composite.beginBatch();
2404
+ try {
2405
+ for (const docId of docIds) {
2406
+ if (!composite.has(docId)) continue;
2407
+ composite.remove(docId, manager.config.schema, manager.language, insertOptions);
2408
+ docPartitionMap.delete(docId);
2409
+ }
2410
+ } finally {
2411
+ composite.endBatch();
2412
+ }
2413
+ }
2414
+ async function attachPagedSegment(directory, ref, partitionId, manager, options) {
2415
+ const { checkPagedSegmentFully, createPagedFrozenSegment, openPagedSnapshot, pagedListingOf } = await import('./module-VEK2KCKU.mjs');
2416
+ if (options.decodesEveryDocument) await checkPagedSegmentFully(directory, ref);
2417
+ const snapshot = openPagedSnapshot(await pagedListingOf(directory, ref));
2418
+ requireAgreedSchema(options.schema, snapshot.schema, ref.key);
2419
+ const segment = createPagedFrozenSegment(snapshot);
2420
+ removeFromPartition(manager, partitionId, snapshot.tombstones);
2421
+ options.writeRecords?.loadPagedSegment(manager.indexName, partitionId, segment);
2422
+ if (snapshot.documentCount > 0) manager.attachFrozenSegment(partitionId, segment);
2423
+ else segment.paged?.close();
2424
+ }
2425
+ async function loadPartitionSegments(store, partition, manager, options) {
2426
+ const { directory } = store;
2427
+ for (const ref of partition.segments) {
2428
+ if (manager.config.textStorage === "disk" && directory !== void 0) {
2429
+ const { isPagedSegmentFile } = await import('./module-VEK2KCKU.mjs');
2430
+ if (await isPagedSegmentFile(directory, ref.key)) {
2431
+ await attachPagedSegment(directory, ref, partition.partitionId, manager, options);
2432
+ await yieldToEventLoop();
2433
+ continue;
2434
+ }
2435
+ }
2436
+ const contents = await readSegmentFile(store, ref);
2437
+ requireAgreedSchema(options.schema, contents.schema, ref.key);
2438
+ if (options.decodesEveryDocument) decodeEveryStoredDocument(contents.arrays.documentTable);
2439
+ const segment = createSharedFrozenSegment(shareSegmentArrays(contents.arrays, manager.partialWordAnalysis));
2440
+ removeWhatTheSegmentReplaces(manager, segment, contents);
2441
+ options.writeRecords?.loadSegment(manager.indexName, partition.partitionId, segment, contents);
2442
+ if (contents.arrays.documentCount > 0) manager.attachFrozenSegment(partition.partitionId, segment);
2443
+ await yieldToEventLoop();
2444
+ }
2445
+ }
2446
+
2447
+ // src/persistence/durability/segment/load.ts
2448
+ async function readSegmentManifest(store, indexName) {
2449
+ const bytes = await store.read(manifestKey(indexName));
2450
+ if (bytes === null) return null;
2451
+ return decodeSegmentManifest(bytes, indexName);
2452
+ }
2453
+ async function readCurrentManifest(store, indexName) {
2454
+ const decoded = await readSegmentManifest(store, indexName);
2455
+ if (decoded === null) return null;
2456
+ if (decoded.kind === "current") return decoded.manifest;
2457
+ throw new NarsilError(
2458
+ ErrorCodes.PERSISTENCE_SAVE_FAILED,
2459
+ `Index "${indexName}" still holds the layout of an earlier release, which recovery upgrades before any checkpoint`,
2460
+ { indexName }
2461
+ );
2462
+ }
2463
+ function growPartitionsTo(manager, highestPartitionId) {
2464
+ while (manager.partitionCount <= highestPartitionId) {
2465
+ const before = manager.partitionCount;
2466
+ try {
2467
+ manager.addPartition();
2468
+ } catch {
2469
+ break;
2470
+ }
2471
+ if (manager.partitionCount === before) break;
2472
+ }
2473
+ }
2474
+ async function loadSegmentedCheckpoint(store, indexName, manifest, deps, decodesEveryDocument = false) {
2475
+ let highestPartitionId = manifest.partitions.length - 1;
2476
+ for (const partition of manifest.partitions) {
2477
+ if (partition.partitionId > highestPartitionId) highestPartitionId = partition.partitionId;
2478
+ }
2479
+ growPartitionsTo(deps.manager, highestPartitionId);
2480
+ const { directory } = store;
2481
+ const opensVectorsOnDemand = manifest.vectors.some(
2482
+ (field) => deps.vectorIndexes.get(field.fieldPath)?.storage === "disk" && field.files.some((file) => file.headOffset !== void 0)
2483
+ );
2484
+ if (!decodesEveryDocument && directory !== void 0 && opensVectorsOnDemand) {
2485
+ const { startReadingOpeningSectionsAhead } = await import('./module-VEK2KCKU.mjs');
2486
+ await startReadingOpeningSectionsAhead(directory, manifest);
2487
+ }
2488
+ for (const partition of manifest.partitions) {
2489
+ if (partition.partitionId >= deps.manager.partitionCount) {
2490
+ throw new NarsilError(
2491
+ ErrorCodes.PERSISTENCE_LOAD_FAILED,
2492
+ `Segment manifest references partition ${partition.partitionId} beyond the partition count ${deps.manager.partitionCount}`,
2493
+ { indexName, partitionId: partition.partitionId, partitionCount: deps.manager.partitionCount }
2494
+ );
2495
+ }
2496
+ await loadPartitionSegments(store, partition, deps.manager, {
2497
+ schema: manifest.schema,
2498
+ decodesEveryDocument,
2499
+ writeRecords: deps.writeRecords ?? null
2500
+ });
2501
+ }
2502
+ for (const vector of manifest.vectors) {
2503
+ const vectorIndex = deps.vectorIndexes.get(vector.fieldPath);
2504
+ if (vectorIndex === void 0) continue;
2505
+ await loadVectorField(
2506
+ store,
2507
+ vector,
2508
+ vectorIndex,
2509
+ decodesEveryDocument ? null : (docId) => deps.manager.partitionIdOf(docId)
2510
+ );
2511
+ }
2512
+ return manifest.checkpoint;
2513
+ }
2514
+ async function reclaimUnlistedKeys(store, indexName, referenced) {
2515
+ for (const key of await store.list(segmentsPrefix(indexName))) {
2516
+ if (!referenced.has(key)) await store.remove(key);
2517
+ }
2518
+ }
2519
+ function validateHnswMetric2(value) {
2520
+ if (value === void 0 || value === null) return void 0;
2521
+ if (typeof value === "string" && VALID_HNSW_METRICS.has(value)) {
2522
+ return value;
2523
+ }
2524
+ return void 0;
2525
+ }
2526
+ function storedDocumentsOf(raw) {
2527
+ requireValidFieldTypes(raw.schema ?? {});
2528
+ const documents = {};
2529
+ for (const [docId, doc] of Object.entries(raw.documents ?? {})) {
2530
+ documents[docId] = {
2531
+ fields: doc.fields,
2532
+ fieldLengths: doc.field_lengths ?? {}
2533
+ };
2534
+ }
2535
+ dropStoredVectorValues(documents, raw.schema ?? {});
2536
+ return documents;
2537
+ }
2538
+ function documentsOfPayloadV2(data) {
2539
+ const raw = decode(data);
2540
+ return { documents: storedDocumentsOf(raw), schema: raw.schema ?? {} };
2541
+ }
2542
+ function deserializePayloadV2(data) {
2543
+ const raw = decode(data);
2544
+ const documents = storedDocumentsOf(raw);
2545
+ const fieldNames = raw.inverted_index?.field_names ?? [];
2546
+ const invertedIndex = {};
2547
+ for (const [token, list] of Object.entries(raw.inverted_index?.entries ?? {})) {
2548
+ const count = list.ids.length;
2549
+ const postings = new Array(count);
2550
+ for (let i = 0; i < count; i++) {
2551
+ postings[i] = {
2552
+ docId: list.ids[i],
2553
+ termFrequency: list.tf[i],
2554
+ field: fieldNames[list.fi[i]] ?? "",
2555
+ positions: list.pos ? list.pos[i] : []
2556
+ };
2557
+ }
2558
+ invertedIndex[token] = {
2559
+ docFrequency: list.df,
2560
+ postings
2561
+ };
2562
+ }
2563
+ const numeric = {};
2564
+ for (const [field, entries] of Object.entries(raw.field_indexes?.numeric ?? {})) {
2565
+ numeric[field] = entries.map((e) => ({ value: e.value, docId: e.doc_id }));
2566
+ }
2567
+ const boolean = {};
2568
+ for (const [field, idx] of Object.entries(raw.field_indexes?.boolean ?? {})) {
2569
+ boolean[field] = { trueDocs: idx.true_docs ?? [], falseDocs: idx.false_docs ?? [] };
2570
+ }
2571
+ const geopoint = {};
2572
+ for (const [field, entries] of Object.entries(raw.field_indexes?.geopoint ?? {})) {
2573
+ geopoint[field] = entries.map((e) => ({ lat: e.lat, lon: e.lon, docId: e.doc_id }));
2574
+ }
2575
+ const vectorData = {};
2576
+ for (const [field, data2] of Object.entries(raw.vector_data ?? {})) {
2577
+ vectorData[field] = {
2578
+ dimension: data2.dimension,
2579
+ vectors: (data2.vectors ?? []).map((v) => ({ docId: v.doc_id, vector: v.vector })),
2580
+ hnswGraph: data2.hnsw_graph ? {
2581
+ entryPoint: data2.hnsw_graph.entry_point,
2582
+ maxLayer: data2.hnsw_graph.max_layer,
2583
+ m: data2.hnsw_graph.m,
2584
+ efConstruction: data2.hnsw_graph.ef_construction,
2585
+ metric: validateHnswMetric2(data2.hnsw_graph.metric),
2586
+ nodes: data2.hnsw_graph.nodes
2587
+ } : null,
2588
+ codes: data2.codes ? { bits: data2.codes.bits, centroid: data2.codes.centroid, records: data2.codes.records } : null
2589
+ };
2590
+ }
2591
+ return {
2592
+ indexName: raw.index_name,
2593
+ partitionId: raw.partition_id,
2594
+ totalPartitions: raw.total_partitions,
2595
+ language: raw.language ?? "english",
2596
+ schema: raw.schema ?? {},
2597
+ docCount: raw.doc_count ?? 0,
2598
+ avgDocLength: raw.avg_doc_length ?? 0,
2599
+ documents,
2600
+ invertedIndex,
2601
+ fieldIndexes: {
2602
+ numeric,
2603
+ boolean,
2604
+ enum: raw.field_indexes?.enum ?? {},
2605
+ geopoint,
2606
+ ...patternIndexesFromWire(raw.field_indexes?.pattern)
2607
+ },
2608
+ surfaceForms: sanitizeSurfaceForms(raw.surface_forms),
2609
+ vectorData,
2610
+ statistics: {
2611
+ totalDocuments: raw.statistics?.total_documents ?? 0,
2612
+ totalFieldLengths: raw.statistics?.total_field_lengths ?? {},
2613
+ averageFieldLengths: raw.statistics?.average_field_lengths ?? {},
2614
+ docFrequencies: raw.statistics?.doc_frequencies ?? {}
2615
+ }
2616
+ };
2617
+ }
2618
+
2619
+ export { SEGMENT_HEADER_SIZE, SINGLE_NODE_PRIMARY_TERM, VECTOR_FILE_ENVELOPE_VERSION, buildEntry, captureWholePartition, checkpointLastSeqNo, checkpointPrimaryTerm, commitCheckpointManifest, createSeqOwner, decodeManifestPayload, decodeSegmentManifest, deserializePayloadV1, deserializePayloadV2, documentsOfPayloadV2, durableMetadataConfigOf, durableRecordMissing, encodeMarkerSlot, frameRecord, growPartitionsTo, indexMetadataOf, invalidManifest, isId, isRecord, isSequenceNumber, isUint32, listedKeysOf, loadSegmentedCheckpoint, markerSlotOffset, metadataConfigOf, metadataFromConfig, nextMarkerSlot, nextSegmentKey, openManifestPayload, partitionContentsOf, readCommitMarker, readCurrentManifest, readGraphParts, readMetadataEnvelope, readSegmentManifest, readVectorFile, readWalSegments, reclaimUnlistedKeys, removeCheckpointGarbage, unpackEnvelopeBytes, unpackIndexSnapshotEnvelope, writeCheckpointSegments, writeLiveVectors, writeMetadataEnvelope, writeSegmentHeader };