@harperfast/harper 5.3.0-alpha.1 → 5.3.0-beta.1

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 (291) hide show
  1. package/bin/cliOperations.ts +12 -0
  2. package/bin/restart.ts +66 -6
  3. package/components/Application.ts +1134 -112
  4. package/components/OptionsWatcher.ts +368 -102
  5. package/components/Scope.ts +20 -1
  6. package/components/componentLoader.ts +43 -4
  7. package/components/deploymentOperations.ts +4 -1
  8. package/components/deploymentRecorder.ts +9 -2
  9. package/components/operations.js +284 -52
  10. package/components/operationsValidation.js +49 -2
  11. package/components/packageComponent.ts +25 -1
  12. package/components/requestRestart.ts +11 -0
  13. package/config/RootConfigWatcher.ts +191 -37
  14. package/config/configReadRetry.ts +62 -0
  15. package/config/configUtils.ts +78 -26
  16. package/config/parseConfigFile.ts +34 -0
  17. package/config/readConfigFileSync.ts +44 -0
  18. package/config/watcherArming.ts +59 -0
  19. package/config-root.schema.json +4 -0
  20. package/dataLayer/harperBridge/ResourceBridge.ts +28 -2
  21. package/dist/bin/cliOperations.js +13 -0
  22. package/dist/bin/cliOperations.js.map +1 -1
  23. package/dist/bin/restart.js +42 -6
  24. package/dist/bin/restart.js.map +1 -1
  25. package/dist/components/Application.d.ts +104 -9
  26. package/dist/components/Application.js +954 -102
  27. package/dist/components/Application.js.map +1 -1
  28. package/dist/components/OptionsWatcher.d.ts +4 -1
  29. package/dist/components/OptionsWatcher.js +378 -104
  30. package/dist/components/OptionsWatcher.js.map +1 -1
  31. package/dist/components/Scope.js +15 -1
  32. package/dist/components/Scope.js.map +1 -1
  33. package/dist/components/componentLoader.js +35 -3
  34. package/dist/components/componentLoader.js.map +1 -1
  35. package/dist/components/deploymentOperations.js +4 -1
  36. package/dist/components/deploymentOperations.js.map +1 -1
  37. package/dist/components/deploymentRecorder.d.ts +4 -2
  38. package/dist/components/deploymentRecorder.js +1 -0
  39. package/dist/components/deploymentRecorder.js.map +1 -1
  40. package/dist/components/operations.d.ts +28 -0
  41. package/dist/components/operations.js +263 -54
  42. package/dist/components/operations.js.map +1 -1
  43. package/dist/components/operationsValidation.js +48 -2
  44. package/dist/components/operationsValidation.js.map +1 -1
  45. package/dist/components/packageComponent.js +24 -0
  46. package/dist/components/packageComponent.js.map +1 -1
  47. package/dist/components/requestRestart.d.ts +1 -0
  48. package/dist/components/requestRestart.js +7 -0
  49. package/dist/components/requestRestart.js.map +1 -1
  50. package/dist/config/RootConfigWatcher.d.ts +2 -0
  51. package/dist/config/RootConfigWatcher.js +189 -35
  52. package/dist/config/RootConfigWatcher.js.map +1 -1
  53. package/dist/config/configReadRetry.d.ts +8 -0
  54. package/dist/config/configReadRetry.js +62 -0
  55. package/dist/config/configReadRetry.js.map +1 -0
  56. package/dist/config/configUtils.d.ts +10 -9
  57. package/dist/config/configUtils.js +63 -27
  58. package/dist/config/configUtils.js.map +1 -1
  59. package/dist/config/parseConfigFile.d.ts +4 -0
  60. package/dist/config/parseConfigFile.js +35 -0
  61. package/dist/config/parseConfigFile.js.map +1 -0
  62. package/dist/config/readConfigFileSync.d.ts +1 -0
  63. package/dist/config/readConfigFileSync.js +47 -0
  64. package/dist/config/readConfigFileSync.js.map +1 -0
  65. package/dist/config/watcherArming.d.ts +15 -0
  66. package/dist/config/watcherArming.js +59 -0
  67. package/dist/config/watcherArming.js.map +1 -0
  68. package/dist/dataLayer/harperBridge/ResourceBridge.js +21 -2
  69. package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.js +4 -1
  72. package/dist/index.js.map +1 -1
  73. package/dist/json/systemSchema.json +3 -0
  74. package/dist/resources/DatabaseTransaction.d.ts +25 -0
  75. package/dist/resources/DatabaseTransaction.js +224 -18
  76. package/dist/resources/DatabaseTransaction.js.map +1 -1
  77. package/dist/resources/LMDBTransaction.d.ts +2 -1
  78. package/dist/resources/LMDBTransaction.js +22 -3
  79. package/dist/resources/LMDBTransaction.js.map +1 -1
  80. package/dist/resources/PrimaryRocksDatabase.js +22 -6
  81. package/dist/resources/PrimaryRocksDatabase.js.map +1 -1
  82. package/dist/resources/RecordEncoder.d.ts +1 -1
  83. package/dist/resources/RecordEncoder.js +21 -5
  84. package/dist/resources/RecordEncoder.js.map +1 -1
  85. package/dist/resources/Resource.js +97 -13
  86. package/dist/resources/Resource.js.map +1 -1
  87. package/dist/resources/ResourceInterface.d.ts +8 -0
  88. package/dist/resources/RocksIndexStore.js +2 -1
  89. package/dist/resources/RocksIndexStore.js.map +1 -1
  90. package/dist/resources/RocksTransactionLogStore.d.ts +10 -0
  91. package/dist/resources/RocksTransactionLogStore.js +104 -33
  92. package/dist/resources/RocksTransactionLogStore.js.map +1 -1
  93. package/dist/resources/Table.d.ts +58 -7
  94. package/dist/resources/Table.js +1095 -346
  95. package/dist/resources/Table.js.map +1 -1
  96. package/dist/resources/analytics/write.js +10 -3
  97. package/dist/resources/analytics/write.js.map +1 -1
  98. package/dist/resources/auditStore.d.ts +170 -0
  99. package/dist/resources/auditStore.js +457 -11
  100. package/dist/resources/auditStore.js.map +1 -1
  101. package/dist/resources/dataLoader.js +3 -4
  102. package/dist/resources/dataLoader.js.map +1 -1
  103. package/dist/resources/databases.d.ts +16 -13
  104. package/dist/resources/databases.js +624 -176
  105. package/dist/resources/databases.js.map +1 -1
  106. package/dist/resources/derivedIndexRegistry.d.ts +5 -0
  107. package/dist/resources/derivedIndexRegistry.js +68 -0
  108. package/dist/resources/derivedIndexRegistry.js.map +1 -0
  109. package/dist/resources/derivedIndexRuntime.d.ts +215 -0
  110. package/dist/resources/derivedIndexRuntime.js +2027 -0
  111. package/dist/resources/derivedIndexRuntime.js.map +1 -0
  112. package/dist/resources/graphql.js +3 -2
  113. package/dist/resources/graphql.js.map +1 -1
  114. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.d.ts +102 -9
  115. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js +848 -39
  116. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js.map +1 -1
  117. package/dist/resources/indexes/hnswDerivedIndex.d.ts +67 -0
  118. package/dist/resources/indexes/hnswDerivedIndex.js +464 -0
  119. package/dist/resources/indexes/hnswDerivedIndex.js.map +1 -0
  120. package/dist/resources/indexes/hnswPlaneBinding.d.ts +65 -0
  121. package/dist/resources/indexes/hnswPlaneBinding.js +91 -0
  122. package/dist/resources/indexes/hnswPlaneBinding.js.map +1 -0
  123. package/dist/resources/nodeIdMapping.d.ts +5 -0
  124. package/dist/resources/nodeIdMapping.js +49 -0
  125. package/dist/resources/nodeIdMapping.js.map +1 -1
  126. package/dist/resources/recordLock.d.ts +47 -4
  127. package/dist/resources/recordLock.js +138 -7
  128. package/dist/resources/recordLock.js.map +1 -1
  129. package/dist/resources/recordLockCoordinator.d.ts +557 -0
  130. package/dist/resources/recordLockCoordinator.js +2565 -0
  131. package/dist/resources/recordLockCoordinator.js.map +1 -0
  132. package/dist/resources/replayLogs.js +5 -0
  133. package/dist/resources/replayLogs.js.map +1 -1
  134. package/dist/resources/replicatedApplyFailure.d.ts +16 -0
  135. package/dist/resources/replicatedApplyFailure.js +63 -0
  136. package/dist/resources/replicatedApplyFailure.js.map +1 -0
  137. package/dist/resources/scheduler/scheduler.js +3 -3
  138. package/dist/resources/scheduler/scheduler.js.map +1 -1
  139. package/dist/resources/search.d.ts +10 -4
  140. package/dist/resources/search.js +160 -40
  141. package/dist/resources/search.js.map +1 -1
  142. package/dist/resources/tracked.d.ts +5 -1
  143. package/dist/resources/tracked.js +74 -23
  144. package/dist/resources/tracked.js.map +1 -1
  145. package/dist/security/jsLoader.js +6 -4
  146. package/dist/security/jsLoader.js.map +1 -1
  147. package/dist/server/REST.js +33 -2
  148. package/dist/server/REST.js.map +1 -1
  149. package/dist/server/http.d.ts +5 -1
  150. package/dist/server/http.js +34 -2
  151. package/dist/server/http.js.map +1 -1
  152. package/dist/server/serverHelpers/Headers.d.ts +2 -0
  153. package/dist/server/serverHelpers/Headers.js +6 -0
  154. package/dist/server/serverHelpers/Headers.js.map +1 -1
  155. package/dist/server/serverHelpers/NodeAdapterResponse.d.ts +48 -0
  156. package/dist/server/serverHelpers/NodeAdapterResponse.js +220 -0
  157. package/dist/server/serverHelpers/NodeAdapterResponse.js.map +1 -0
  158. package/dist/server/serverHelpers/Request.d.ts +5 -10
  159. package/dist/server/serverHelpers/Request.js +38 -136
  160. package/dist/server/serverHelpers/Request.js.map +1 -1
  161. package/dist/server/serverHelpers/contentTypes.d.ts +2 -0
  162. package/dist/server/serverHelpers/contentTypes.js +189 -15
  163. package/dist/server/serverHelpers/contentTypes.js.map +1 -1
  164. package/dist/server/serverHelpers/serverUtilities.js +96 -17
  165. package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
  166. package/dist/server/storageReclamation.js +1 -1
  167. package/dist/server/storageReclamation.js.map +1 -1
  168. package/dist/server/threads/isolatedApplications.d.ts +47 -0
  169. package/dist/server/threads/isolatedApplications.js +171 -0
  170. package/dist/server/threads/isolatedApplications.js.map +1 -0
  171. package/dist/server/threads/logRotationTransport.d.ts +1 -0
  172. package/dist/server/threads/logRotationTransport.js +33 -0
  173. package/dist/server/threads/logRotationTransport.js.map +1 -0
  174. package/dist/server/threads/manageThreads.d.ts +64 -6
  175. package/dist/server/threads/manageThreads.js +261 -12
  176. package/dist/server/threads/manageThreads.js.map +1 -1
  177. package/dist/server/threads/socketRouter.d.ts +1 -0
  178. package/dist/server/threads/socketRouter.js +196 -13
  179. package/dist/server/threads/socketRouter.js.map +1 -1
  180. package/dist/server/threads/threadServer.js +30 -7
  181. package/dist/server/threads/threadServer.js.map +1 -1
  182. package/dist/utility/errors/hdbError.d.ts +24 -0
  183. package/dist/utility/errors/hdbError.js +58 -1
  184. package/dist/utility/errors/hdbError.js.map +1 -1
  185. package/dist/utility/hdbTerms.d.ts +2 -0
  186. package/dist/utility/hdbTerms.js +2 -0
  187. package/dist/utility/hdbTerms.js.map +1 -1
  188. package/dist/utility/logging/harper_logger.js +217 -38
  189. package/dist/utility/logging/harper_logger.js.map +1 -1
  190. package/dist/utility/logging/logGenerationCoordinator.d.ts +35 -0
  191. package/dist/utility/logging/logGenerationCoordinator.js +184 -0
  192. package/dist/utility/logging/logGenerationCoordinator.js.map +1 -0
  193. package/dist/utility/logging/logRotation.d.ts +46 -0
  194. package/dist/utility/logging/logRotation.js +365 -0
  195. package/dist/utility/logging/logRotation.js.map +1 -0
  196. package/dist/utility/logging/logRotator.d.ts +1 -1
  197. package/dist/utility/logging/logRotator.js +172 -92
  198. package/dist/utility/logging/logRotator.js.map +1 -1
  199. package/dist/utility/npmUtilities.js +6 -4
  200. package/dist/utility/npmUtilities.js.map +1 -1
  201. package/dist/utility/watcherFallback.d.ts +0 -45
  202. package/dist/utility/watcherFallback.js +1 -125
  203. package/dist/utility/watcherFallback.js.map +1 -1
  204. package/dist/validation/configValidator.js +6 -3
  205. package/dist/validation/configValidator.js.map +1 -1
  206. package/index.ts +6 -0
  207. package/json/systemSchema.json +3 -0
  208. package/npm-shrinkwrap.json +131 -41
  209. package/package.json +10 -3
  210. package/resources/DESIGN.md +124 -19
  211. package/resources/DatabaseTransaction.ts +230 -17
  212. package/resources/LMDBTransaction.ts +21 -3
  213. package/resources/PrimaryRocksDatabase.ts +20 -7
  214. package/resources/RecordEncoder.ts +25 -5
  215. package/resources/Resource.ts +97 -13
  216. package/resources/ResourceInterface.ts +8 -0
  217. package/resources/RocksIndexStore.ts +2 -1
  218. package/resources/RocksTransactionLogStore.ts +111 -31
  219. package/resources/Table.ts +1224 -393
  220. package/resources/analytics/write.ts +10 -3
  221. package/resources/auditStore.ts +460 -11
  222. package/resources/dataLoader.ts +3 -4
  223. package/resources/databases.ts +610 -146
  224. package/resources/derivedIndexRegistry.ts +56 -0
  225. package/resources/derivedIndexRuntime.ts +2292 -0
  226. package/resources/graphql.ts +3 -2
  227. package/resources/indexes/HierarchicalNavigableSmallWorld.ts +905 -46
  228. package/resources/indexes/hnswDerivedIndex.ts +531 -0
  229. package/resources/indexes/hnswPlaneBinding.ts +174 -0
  230. package/resources/nodeIdMapping.ts +50 -0
  231. package/resources/recordLock.ts +173 -7
  232. package/resources/recordLockCoordinator.ts +3043 -0
  233. package/resources/replayLogs.ts +5 -0
  234. package/resources/replicatedApplyFailure.ts +77 -0
  235. package/resources/scheduler/scheduler.ts +4 -4
  236. package/resources/search.ts +169 -49
  237. package/resources/tracked.ts +73 -22
  238. package/security/jsLoader.ts +6 -4
  239. package/server/DESIGN.md +11 -0
  240. package/server/REST.ts +36 -3
  241. package/server/http.ts +34 -2
  242. package/server/serverHelpers/Headers.ts +5 -1
  243. package/server/serverHelpers/NodeAdapterResponse.ts +221 -0
  244. package/server/serverHelpers/Request.ts +33 -131
  245. package/server/serverHelpers/contentTypes.ts +188 -15
  246. package/server/serverHelpers/serverUtilities.ts +143 -24
  247. package/server/storageReclamation.ts +2 -2
  248. package/server/threads/isolatedApplications.ts +157 -0
  249. package/server/threads/logRotationTransport.ts +40 -0
  250. package/server/threads/manageThreads.js +254 -12
  251. package/server/threads/socketRouter.ts +217 -11
  252. package/server/threads/threadServer.js +30 -7
  253. package/studio/web/assets/{Chat-BnCBegQz.js → Chat-D3j-1yY1.js} +1 -1
  254. package/studio/web/assets/{FloatingChat-CoDW1ySS.js → FloatingChat-BxJGYcfB.js} +3 -3
  255. package/studio/web/assets/{apiToken-Bwk5BLXW.js → apiToken-CT55oWOe.js} +1 -1
  256. package/studio/web/assets/{applications-DHxGi7JH.js → applications-D9Ct9_vm.js} +1 -1
  257. package/studio/web/assets/{cssMode-s0cWI-_M.js → cssMode-DV8H7VwA.js} +1 -1
  258. package/studio/web/assets/{editor-DNcRHK54.js → editor-uatc0unt.js} +1 -1
  259. package/studio/web/assets/{html-Bdssedlg.js → html-Bm6D6paN.js} +1 -1
  260. package/studio/web/assets/{htmlMode-CoDlJ3fw.js → htmlMode-CEn7tpLG.js} +1 -1
  261. package/studio/web/assets/{index-D6sxmFLR.js → index-BIXW6Pu4.js} +5 -5
  262. package/studio/web/assets/{index.lazy-tmU5BS8s.js → index.lazy-UI7L-Vrk.js} +1 -1
  263. package/studio/web/assets/{javascript-B8meVSTH.js → javascript-CJ0G3AFZ.js} +1 -1
  264. package/studio/web/assets/{jsonMode-DpIPd35T.js → jsonMode-DQADAYEa.js} +1 -1
  265. package/studio/web/assets/{languageServices-C_5FMJzQ.js → languageServices-CAQJXWcI.js} +1 -1
  266. package/studio/web/assets/{lspLanguageFeatures-BIzNBzPK.js → lspLanguageFeatures-CCQ8P5sY.js} +1 -1
  267. package/studio/web/assets/{notifications-CQf18QKb.js → notifications-BbxTU6Aw.js} +1 -1
  268. package/studio/web/assets/{notifications-CvZivSbh.js → notifications-Cvb3P1lB.js} +1 -1
  269. package/studio/web/assets/{profile-DdOwtntb.js → profile-Yyb7gsvL.js} +1 -1
  270. package/studio/web/assets/{regions-n69fwagr.js → regions-OgjGHlU5.js} +1 -1
  271. package/studio/web/assets/{register-PfWTCXWB.js → register-6qwNEOY3.js} +2 -2
  272. package/studio/web/assets/{setComponentFile-Bg6O7X0S.js → setComponentFile-BilDMtgB.js} +1 -1
  273. package/studio/web/assets/{setup-CUx_aUDl.js → setup-J6qJ7OIU.js} +2 -2
  274. package/studio/web/assets/{status-D7BVKqX9.js → status-0RWGcfyD.js} +1 -1
  275. package/studio/web/assets/{toggleHighContrast-DBSyXzMr.js → toggleHighContrast-BIn-vErT.js} +1 -1
  276. package/studio/web/assets/{tsMode-BByKCjBS.js → tsMode-DgUXku4d.js} +1 -1
  277. package/studio/web/assets/{typescript-DDLnLpw9.js → typescript-C9orXcsM.js} +1 -1
  278. package/studio/web/assets/{useEntityRestURL-31CHGaHk.js → useEntityRestURL-BEoXXbUB.js} +1 -1
  279. package/studio/web/assets/{workers-pR3jRY9D.js → workers-JVzSDmgx.js} +1 -1
  280. package/studio/web/assets/{xml-2iRnMhQO.js → xml-Cq-S8S4X.js} +1 -1
  281. package/studio/web/assets/{yaml-Bf92gJpd.js → yaml-sfoRdh1M.js} +1 -1
  282. package/studio/web/index.html +1 -1
  283. package/utility/errors/hdbError.ts +54 -0
  284. package/utility/hdbTerms.ts +2 -0
  285. package/utility/logging/harper_logger.ts +209 -30
  286. package/utility/logging/logGenerationCoordinator.ts +196 -0
  287. package/utility/logging/logRotation.ts +367 -0
  288. package/utility/logging/logRotator.ts +196 -91
  289. package/utility/npmUtilities.ts +6 -4
  290. package/utility/watcherFallback.ts +0 -122
  291. package/validation/configValidator.ts +6 -3
@@ -1,12 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HierarchicalNavigableSmallWorld = void 0;
4
+ exports.derivedValuesEqual = derivedValuesEqual;
5
+ const node_fs_1 = require("node:fs");
4
6
  const vector_ts_1 = require("./vector.js");
5
7
  const msgpackr_1 = require("msgpackr");
6
8
  const logger_ts_1 = require("../../utility/logging/logger.js");
7
9
  const hdbError_ts_1 = require("../../utility/errors/hdbError.js");
10
+ const hnswDerivedIndex_ts_1 = require("./hnswDerivedIndex.js");
11
+ const derivedIndexRuntime_ts_1 = require("../derivedIndexRuntime.js");
8
12
  const extended_iterable_1 = require("@harperfast/extended-iterable");
13
+ const rocksdb_js_1 = require("@harperfast/rocksdb-js");
14
+ const node_crypto_1 = require("node:crypto");
15
+ const hnswPlaneBinding_ts_1 = require("./hnswPlaneBinding.js");
9
16
  const logger = (0, logger_ts_1.loggerWithTag)('HNSW');
17
+ /** Element-wise equality of the array-like projections a derived index stores; anything else that failed `===` counts as changed. */
18
+ function derivedValuesEqual(a, b) {
19
+ if (a === b)
20
+ return true;
21
+ if (a == null || b == null || typeof a.length !== 'number' || a.length !== b.length)
22
+ return false;
23
+ for (let i = 0; i < a.length; i++)
24
+ if (a[i] !== b[i])
25
+ return false;
26
+ return true;
27
+ }
10
28
  // int8 scalar quantization of stored graph nodes is ON by default. Each node holds the
11
29
  // vector as a compact int8 `bin` plus a per-vector `scale`, roughly a 5x size reduction
12
30
  // over float32 and ~10x cheaper to decode (a single typed-array view instead of decoding
@@ -85,6 +103,10 @@ const ROUTING_EF = 1;
85
103
  // index's own auto-scaled ceiling so the worst case stays the same order. Schema and per-query ef
86
104
  // pins are authoritative cost ceilings; only an automatically scaled index widens from `limit`.
87
105
  const LIMIT_EF_MAX = 2 * AUTO_EF_CEILING;
106
+ // Rerank candidates per row a bounded nearest-neighbor query consumes, with a floor: each
107
+ // candidate costs a record load and an exact distance, so the rerank must not scale with ef.
108
+ const RERANK_FACTOR = 4;
109
+ const RERANK_MIN = 32;
88
110
  // Auto-scaled construction ef, used only when an index does not explicitly configure efConstruction.
89
111
  // At a constant efConstruction, edge quality erodes as the graph grows until true neighbours become
90
112
  // unreachable at ANY search ef; the cap bounds per-insert cost. Measurements and policy in
@@ -103,6 +125,60 @@ function autoScaleEfConstruction(nodeCount) {
103
125
  // ef moves with the square root of the count and is capped, so a slightly stale size is immaterial;
104
126
  // this only has to be short enough that a table growing from empty picks up a larger ef promptly.
105
127
  const NODE_COUNT_TTL = 10_000;
128
+ // Native traversal-plane geometry (DESIGN.md § Native HNSW plane). The layer-0 cap is derived from
129
+ // M/optimizeRouting at creation to cover the JS graph's effective cap (grace overshoot above it
130
+ // truncates by distance); a configuration deriving past this ceiling is refused as ineligible
131
+ // rather than silently truncated. maxNodes is a fixed sparse reservation — pages materialize on
132
+ // write — and ids at or past it are rejected by the crate, which disables the plane.
133
+ const PLANE_LAYER0_CAP_MAX = 1024;
134
+ const PLANE_MAX_NODES = 1 << 24;
135
+ // Default inline primary-key bytes per plane slot (msgpack-encoded); 40 fits UUIDs inside the slot
136
+ // padding. `nativePlaneKeyCap` raises it for tables whose keys are longer.
137
+ const PLANE_KEY_CAP = 40;
138
+ const PLANE_KEY_CAP_MAX = 65535;
139
+ // An existing plane file that cannot be opened is normally another worker mid-create (retry);
140
+ // past this age it is a crashed create and is deleted so the audit-backed runtime can rebuild it.
141
+ const PLANE_STALE_CREATE_MS = 60_000;
142
+ // Retry cadence while another worker holds the create; its header lands shortly after exclusive open.
143
+ const PLANE_ATTACH_RETRY_MS = 250;
144
+ // Marks an error thrown by an app-supplied filter during a plane search: the caller re-raises
145
+ // it as an ordinary query failure instead of disabling the (healthy) plane.
146
+ const NOT_A_PLANE_FAILURE = Symbol('notAPlaneFailure');
147
+ function numericOption(name, value) {
148
+ if (value === undefined || value === null)
149
+ return undefined;
150
+ if ((typeof value !== 'number' && typeof value !== 'string') || (typeof value === 'string' && value.trim() === ''))
151
+ throw new hdbError_ts_1.ClientError(`${name} must be a finite number`);
152
+ const numericValue = Number(value);
153
+ if (!Number.isFinite(numericValue))
154
+ throw new hdbError_ts_1.ClientError(`${name} must be a finite number`);
155
+ return numericValue;
156
+ }
157
+ function normalizeOptimizeRoutingDeclaration(value) {
158
+ if (value === true || value === 'true')
159
+ return 1;
160
+ if (value === false || value === 'false')
161
+ return 0;
162
+ return value;
163
+ }
164
+ function nativePlaneMaxNodes(options) {
165
+ const maxNodes = numericOption('nativePlaneMaxNodes', options?.nativePlaneMaxNodes) ?? PLANE_MAX_NODES;
166
+ if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes >= hnswPlaneBinding_ts_1.PLANE_NO_ID) {
167
+ throw new hdbError_ts_1.ClientError('nativePlaneMaxNodes must be a positive integer below 2^32-1');
168
+ }
169
+ return maxNodes;
170
+ }
171
+ function nativePlaneKeyCap(options) {
172
+ const keyCap = numericOption('nativePlaneKeyCap', options?.nativePlaneKeyCap) ?? PLANE_KEY_CAP;
173
+ if (!Number.isSafeInteger(keyCap) || keyCap < 8 || keyCap > PLANE_KEY_CAP_MAX) {
174
+ throw new hdbError_ts_1.ClientError('nativePlaneKeyCap must be an integer between 8 and 65535');
175
+ }
176
+ return keyCap;
177
+ }
178
+ function nativePlaneDefaultDisabled() {
179
+ const value = process.env.HNSW_NO_NATIVE_DEFAULT;
180
+ return value != null && value !== '' && value !== '0' && value.toLowerCase() !== 'false';
181
+ }
106
182
  class MinHeap {
107
183
  data = [];
108
184
  get size() {
@@ -163,6 +239,10 @@ function bisectInsert(arr, distance) {
163
239
  */
164
240
  const ENTRY_POINT = Symbol.for('entryPoint');
165
241
  const KEY_PREFIX = Symbol.for('key');
242
+ /** A Map key for a primary key: composite keys by their encoding, since arrays compare by reference. */
243
+ function pendingMappingKey(primaryKey) {
244
+ return Array.isArray(primaryKey) ? `\0${(0, msgpackr_1.pack)(primaryKey).toString('latin1')}` : primaryKey;
245
+ }
166
246
  const MAX_LEVEL = 10; // should give good high-level skip list performance up to trillions of nodes
167
247
  // Visit budget for the post-delete connectivity probe (repairSeveredNeighbors, #1712). Severed
168
248
  // islands are small (bounded by the deleted node's neighborhood), so a probe that visits this many
@@ -180,11 +260,131 @@ const PROBE_VISIT_LIMIT = 256;
180
260
  */
181
261
  class HierarchicalNavigableSmallWorld {
182
262
  static useObjectStore = true;
263
+ static numericOptions = new Set([
264
+ 'M',
265
+ 'efConstruction',
266
+ 'efConstructionSearch',
267
+ 'mL',
268
+ 'optimizeRouting',
269
+ 'filterExpansion',
270
+ 'nativePlaneMaxNodes',
271
+ 'nativePlaneKeyCap',
272
+ 'maxLagMilliseconds',
273
+ ]);
274
+ static truthyStructuralOptions = new Set(['nativePlane']);
275
+ static normalizeOptionValue(name, value) {
276
+ if (name !== 'optimizeRouting')
277
+ return value;
278
+ if (value === true)
279
+ return 1;
280
+ if (value === false)
281
+ return 0;
282
+ if (typeof value === 'string' &&
283
+ (value === 'true' || value === 'false' || (value.trim() !== '' && Number(value) === 0)))
284
+ // Legacy strings are truthy at runtime; keep them structurally distinct from false/0 so #1357 rebuilds.
285
+ return `legacy:${value}`;
286
+ return value;
287
+ }
288
+ static normalizeDeclarationOptions(options, persistedOptions) {
289
+ for (const name of HierarchicalNavigableSmallWorld.numericOptions) {
290
+ if (options[name] === undefined)
291
+ continue;
292
+ if (persistedOptions && Object.hasOwn(persistedOptions, name) && Object.is(options[name], persistedOptions[name]))
293
+ continue;
294
+ if (name === 'optimizeRouting' &&
295
+ typeof persistedOptions?.[name] === 'string' &&
296
+ options[name] !== false &&
297
+ options[name] !== 'false') {
298
+ try {
299
+ const declared = numericOption(name, normalizeOptimizeRoutingDeclaration(options[name]));
300
+ const persisted = numericOption(name, normalizeOptimizeRoutingDeclaration(persistedOptions[name]));
301
+ if (Object.is(declared, persisted)) {
302
+ options[name] = persistedOptions[name];
303
+ continue;
304
+ }
305
+ }
306
+ catch { }
307
+ }
308
+ if (options[name] === null) {
309
+ delete options[name];
310
+ continue;
311
+ }
312
+ const value = name === 'optimizeRouting' ? normalizeOptimizeRoutingDeclaration(options[name]) : options[name];
313
+ options[name] = numericOption(name, value);
314
+ }
315
+ if (Object.hasOwn(options, 'nativePlaneMaxNodes'))
316
+ nativePlaneMaxNodes(options);
317
+ if (Object.hasOwn(options, 'nativePlaneKeyCap'))
318
+ nativePlaneKeyCap(options);
319
+ }
320
+ static normalizeNativePlaneDeclaration(value) {
321
+ if (value === undefined || value === null)
322
+ return undefined;
323
+ if (value === true || value === 'true')
324
+ return true;
325
+ if (value === false || value === 'false')
326
+ return false;
327
+ throw new hdbError_ts_1.ClientError('nativePlane must be true or false');
328
+ }
329
+ static validateNativePlaneOptions(rootStore, options) {
330
+ if (!(rootStore instanceof rocksdb_js_1.RocksDatabase)) {
331
+ throw new hdbError_ts_1.ClientError('nativePlane requires the RocksDB storage engine; set nativePlane: false to use the JS index');
332
+ }
333
+ const nativeM = numericOption('M', options?.M);
334
+ const nativeEfConstruction = numericOption('efConstruction', options?.efConstruction);
335
+ const nativeML = numericOption('mL', options?.mL);
336
+ const nativeOptimizeRouting = numericOption('optimizeRouting', normalizeOptimizeRoutingDeclaration(options?.optimizeRouting));
337
+ if (options?.M === null ||
338
+ options?.efConstruction === null ||
339
+ options?.mL === null ||
340
+ options?.optimizeRouting === null ||
341
+ (nativeM !== undefined && nativeM !== 16) ||
342
+ (nativeEfConstruction !== undefined && nativeEfConstruction !== 200) ||
343
+ (nativeML !== undefined && nativeML !== 1 / Math.log(16)) ||
344
+ (nativeOptimizeRouting !== undefined && nativeOptimizeRouting !== 0.5)) {
345
+ throw new hdbError_ts_1.ClientError('nativePlane requires M=16, efConstruction=200, mL=1/ln(16), and optimizeRouting=0.5; set nativePlane: false to use the JS index');
346
+ }
347
+ const maxNodes = nativePlaneMaxNodes(options);
348
+ const keyCap = nativePlaneKeyCap(options);
349
+ if (options?.quantization === 'none' || options?.distance === 'euclidean' || options?.distance === 'dotProduct') {
350
+ throw new hdbError_ts_1.ClientError('nativePlane requires an int8-quantized cosine HNSW index; set nativePlane: false to use the JS index');
351
+ }
352
+ return { nativeM, nativeEfConstruction, nativeML, nativeOptimizeRouting, maxNodes, keyCap };
353
+ }
354
+ static canRunNativePlane(rootStore, options, warnForMissingBinding = true) {
355
+ nativePlaneMaxNodes(options);
356
+ nativePlaneKeyCap(options);
357
+ if (!(rootStore instanceof rocksdb_js_1.RocksDatabase) || (0, hnswPlaneBinding_ts_1.getPlaneBinding)(warnForMissingBinding) == null)
358
+ return false;
359
+ if (options?.M === null ||
360
+ options?.efConstruction === null ||
361
+ options?.mL === null ||
362
+ options?.optimizeRouting === null)
363
+ return false;
364
+ const configuredM = numericOption('M', options?.M);
365
+ const configuredEfConstruction = numericOption('efConstruction', options?.efConstruction);
366
+ const configuredML = numericOption('mL', options?.mL);
367
+ const configuredOptimizeRouting = numericOption('optimizeRouting', normalizeOptimizeRoutingDeclaration(options?.optimizeRouting));
368
+ const baseEligible = options?.quantization !== 'none' &&
369
+ options?.distance !== 'euclidean' &&
370
+ options?.distance !== 'dotProduct' &&
371
+ (configuredM === undefined || configuredM === 16) &&
372
+ (configuredEfConstruction === undefined || configuredEfConstruction === 200) &&
373
+ (configuredML === undefined || configuredML === 1 / Math.log(16)) &&
374
+ (configuredOptimizeRouting === undefined || configuredOptimizeRouting === 0.5);
375
+ if (!baseEligible)
376
+ return false;
377
+ return true;
378
+ }
379
+ static canDefaultToNativePlane(rootStore, options) {
380
+ return (!nativePlaneDefaultDisabled() && HierarchicalNavigableSmallWorld.canRunNativePlane(rootStore, options, false));
381
+ }
183
382
  // Index options that only affect search, not the stored graph — changing them must not trigger a
184
383
  // reindex (databases.ts persists the new value but skips rebuilding). efConstructionSearch is the
185
384
  // search-time candidate-list size; the build uses efConstruction/M/distance, which are structural.
186
- // filterExpansion is the visit-budget multiplier for predicate-aware (filtered) traversal.
187
- static searchOnlyOptions = ['efConstructionSearch', 'filterExpansion'];
385
+ // filterExpansion is the visit-budget multiplier for predicate-aware (filtered) traversal;
386
+ // maxLagMilliseconds controls delivery admission rather than the graph itself.
387
+ static searchOnlyOptions = ['efConstructionSearch', 'filterExpansion', 'maxLagMilliseconds'];
188
388
  // Signals to search.ts that this index accepts a per-record predicate in search() and applies it
189
389
  // during traversal (predicate-aware / ACORN-style filtering), so companion conditions and RBAC can
190
390
  // be pushed down instead of post-filtering an under-filled candidate set (#1241).
@@ -223,6 +423,22 @@ class HierarchicalNavigableSmallWorld {
223
423
  convertedNodes = new WeakMap();
224
424
  nodeCount = 0;
225
425
  nodeCountAt = 0;
426
+ // Native file-primary index. The RocksDB index store holds identity mappings and replay cursors;
427
+ // graph nodes and adjacency exist only in this file.
428
+ // undefined = not yet attached (may retry), null = unavailable or disabled for this process.
429
+ plane;
430
+ planeEligible = false;
431
+ planeRetryAt = 0;
432
+ planeDisabledLogged = false;
433
+ filePrimary = false;
434
+ nativePlaneMaxNodes = PLANE_MAX_NODES;
435
+ nativePlaneKeyCap = PLANE_KEY_CAP;
436
+ // Installed by attachDerivedIndexes on every worker: shared readiness of the index and the way
437
+ // to ask its owner for a rebuild. Only the owning worker's runtime ever destroys native state.
438
+ derivedHost;
439
+ // keyed by pendingMappingKey(pk): a composite key's arrays never compare equal by reference
440
+ pendingDerivedMappings = new Map();
441
+ postCommit;
226
442
  constructor(indexStore, options) {
227
443
  this.indexStore = indexStore;
228
444
  if (indexStore) {
@@ -230,10 +446,16 @@ class HierarchicalNavigableSmallWorld {
230
446
  // (we would actually like to use float16 if it were available)
231
447
  this.indexStore.encoder.useFloat32 = msgpackr_1.FLOAT32_OPTIONS.ALWAYS;
232
448
  }
449
+ const configuredM = options?.M;
450
+ const configuredEfConstruction = options?.efConstruction;
451
+ const configuredEfConstructionSearch = options?.efConstructionSearch;
452
+ const configuredML = options?.mL;
453
+ const configuredOptimizeRouting = options?.optimizeRouting;
454
+ const configuredFilterExpansion = options?.filterExpansion;
233
455
  this.int8 = options?.quantization !== 'none';
234
456
  // Respect an explicitly-configured ef (efConstruction seeds the search ef too); otherwise auto-scale both.
235
- this.efSearchConfigured = options?.efConstructionSearch !== undefined || options?.efConstruction !== undefined;
236
- this.efConstructionConfigured = options?.efConstruction !== undefined;
457
+ this.efSearchConfigured = configuredEfConstructionSearch !== undefined || configuredEfConstruction !== undefined;
458
+ this.efConstructionConfigured = configuredEfConstruction !== undefined;
237
459
  this.distance =
238
460
  options?.distance === 'euclidean'
239
461
  ? vector_ts_1.euclideanDistance
@@ -242,23 +464,499 @@ class HierarchicalNavigableSmallWorld {
242
464
  : vector_ts_1.cosineDistance;
243
465
  if (options) {
244
466
  // allow all the HNSW parameters to be configured/tuned
245
- if (options.M !== undefined) {
246
- this.M = options.M;
467
+ if (configuredM !== undefined) {
468
+ this.M = configuredM;
247
469
  this.mL = 1 / Math.log(this.M); // recalculate
248
470
  }
249
- if (options.efConstruction !== undefined)
250
- this.efConstruction = this.efConstructionSearch = options.efConstruction;
251
- if (options.efConstructionSearch !== undefined)
252
- this.efConstructionSearch = options.efConstructionSearch;
253
- if (options.mL !== undefined)
254
- this.mL = options.mL;
255
- if (options.optimizeRouting !== undefined)
256
- this.optimizeRouting = options.optimizeRouting;
257
- if (options.filterExpansion !== undefined)
258
- this.filterExpansion = options.filterExpansion;
471
+ if (configuredEfConstruction !== undefined)
472
+ this.efConstruction = this.efConstructionSearch = configuredEfConstruction;
473
+ if (configuredEfConstructionSearch !== undefined)
474
+ this.efConstructionSearch = configuredEfConstructionSearch;
475
+ if (configuredML !== undefined)
476
+ this.mL = configuredML;
477
+ if (configuredOptimizeRouting !== undefined)
478
+ this.optimizeRouting = configuredOptimizeRouting;
479
+ if (configuredFilterExpansion !== undefined)
480
+ this.filterExpansion = configuredFilterExpansion;
481
+ }
482
+ if (options?.nativePlane) {
483
+ const { nativeM, nativeEfConstruction, nativeML, nativeOptimizeRouting, maxNodes, keyCap } = HierarchicalNavigableSmallWorld.validateNativePlaneOptions(indexStore?.rootStore, options);
484
+ if (nativeM !== undefined)
485
+ this.M = nativeM;
486
+ if (nativeML !== undefined)
487
+ this.mL = nativeML;
488
+ if (nativeOptimizeRouting !== undefined)
489
+ this.optimizeRouting = nativeOptimizeRouting;
490
+ this.efConstruction = nativeEfConstruction ?? 200;
491
+ this.nativePlaneMaxNodes = maxNodes;
492
+ this.nativePlaneKeyCap = keyCap;
493
+ // The plane stores int8 bins and computes asymmetric cosine only, so the flag is a
494
+ // no-op for float (quantization: "none") and non-cosine indexes; a graph whose derived
495
+ // layer-0 cap exceeds the plane maximum is refused rather than silently truncated.
496
+ this.planeEligible =
497
+ this.int8 && this.distance === vector_ts_1.cosineDistance && this.planeLayer0Cap() <= PLANE_LAYER0_CAP_MAX;
498
+ if (!this.planeEligible) {
499
+ throw new hdbError_ts_1.ClientError('nativePlane requires an int8-quantized cosine HNSW index; set nativePlane: false to use the JS index');
500
+ }
501
+ this.filePrimary = true;
502
+ this.postCommit = true;
503
+ }
504
+ }
505
+ /** Remove derived native state after the option is disabled. */
506
+ cleanupDisabledPlane() {
507
+ if (this.planeEligible)
508
+ return;
509
+ const filePath = this.planeFilePath();
510
+ if (!filePath)
511
+ return;
512
+ try {
513
+ if ((0, node_fs_1.existsSync)(filePath))
514
+ this.invalidatePlaneFile(filePath, this.plane);
515
+ (0, node_fs_1.unlinkSync)(filePath);
516
+ logger.info?.('deleted the HNSW plane file of an index no longer using nativePlane');
517
+ }
518
+ catch (error) {
519
+ if (error?.code !== 'ENOENT') {
520
+ // A later re-enable must not adopt a file that missed mutations while disabled.
521
+ logger.warn?.('could not delete the HNSW plane file; marking it stale', error);
522
+ this.invalidatePlaneFile(filePath);
523
+ }
524
+ }
525
+ }
526
+ /** Absolute path of this index's plane file, or undefined when the store exposes no path. */
527
+ planeFilePath() {
528
+ const storePath = this.indexStore?.path;
529
+ const storeName = this.indexStore?.name;
530
+ if (typeof storePath !== 'string' || typeof storeName !== 'string')
531
+ return undefined;
532
+ return (0, hnswPlaneBinding_ts_1.planeFilePathFor)(storePath, storeName);
533
+ }
534
+ /**
535
+ * Open or lazily create the native file. An exclusive create resolves multi-worker races; the
536
+ * derived-index runtime owns population, replay, and publication.
537
+ */
538
+ getPlane(dims, dimsFromVector = false) {
539
+ if (this.plane !== undefined)
540
+ return this.plane;
541
+ if (!this.planeEligible)
542
+ return (this.plane = null);
543
+ const now = Date.now();
544
+ if (now < this.planeRetryAt)
545
+ return null;
546
+ const Plane = (0, hnswPlaneBinding_ts_1.getPlaneBinding)();
547
+ if (!Plane)
548
+ return (this.plane = null); // the loader warned once already
549
+ if (!('keyCap' in Plane.prototype)) {
550
+ if (!this.planeDisabledLogged) {
551
+ this.planeDisabledLogged = true;
552
+ logger.error?.('the installed @harperfast/hnsw predates 0.3.0; the native HNSW index needs 0.3.0 or later');
553
+ }
554
+ return (this.plane = null);
555
+ }
556
+ const filePath = this.planeFilePath();
557
+ if (!filePath) {
558
+ this.disablePlane(new Error('the index store exposes no path to place the plane file next to'));
559
+ return null;
560
+ }
561
+ try {
562
+ // a tombstone marks a plane a previous unlink could not remove (Windows EBUSY while
563
+ // mapped): the file is stale and must never be opened over a fresh graph
564
+ const stalePath = (0, hnswPlaneBinding_ts_1.planeStalePathFor)(filePath);
565
+ if ((0, node_fs_1.existsSync)(stalePath)) {
566
+ try {
567
+ // force: either artifact may already be gone (the documented rollback deletes the
568
+ // plane file by hand), and an ENOENT here disables the plane on every later attach
569
+ (0, node_fs_1.rmSync)(filePath, { force: true });
570
+ (0, node_fs_1.rmSync)(stalePath, { force: true });
571
+ }
572
+ catch {
573
+ this.planeRetryAt = now + NODE_COUNT_TTL;
574
+ return null;
575
+ }
576
+ }
577
+ if ((0, node_fs_1.existsSync)(filePath)) {
578
+ try {
579
+ // Crash recovery is per-slot inside the crate. The clean flag is advisory;
580
+ // another worker may still be constructing this shared file.
581
+ const opened = Plane.open(filePath);
582
+ if (this.filePrimary && opened.keyCap !== this.nativePlaneKeyCap) {
583
+ // created under another nativePlaneKeyCap: rebuild to the configured layout
584
+ opened.invalidateFile();
585
+ throw new Error(`plane keyCap ${opened.keyCap} differs from the configured ${this.nativePlaneKeyCap}`);
586
+ }
587
+ return (this.plane = opened);
588
+ }
589
+ catch (openError) {
590
+ if (now - (0, node_fs_1.statSync)(filePath).mtimeMs <= PLANE_STALE_CREATE_MS) {
591
+ // another worker is between its exclusive create and the header write
592
+ this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
593
+ return null;
594
+ }
595
+ logger.warn?.('deleting an unopenable HNSW plane file left by an interrupted create', openError);
596
+ (0, node_fs_1.unlinkSync)(filePath);
597
+ if (this.filePrimary) {
598
+ // The surviving mappings still name node ids from the file just removed.
599
+ // Creating a fresh plane here would resolve them against an empty graph;
600
+ // only reconstruction, which clears the mappings first, is safe.
601
+ this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
602
+ return null;
603
+ }
604
+ }
605
+ }
606
+ if (!dims)
607
+ return null; // open-only call and no file: nothing to attach yet
608
+ // A search target must not pin an empty index's dimensionality: creation is deferred to
609
+ // the first committed vector or to the rebuild scan. Return before the exclusive create
610
+ // rather than creating and unlinking — a concurrent insert that saw the empty file would
611
+ // read it as another worker's in-progress create and 503 for PLANE_STALE_CREATE_MS.
612
+ if (!dimsFromVector)
613
+ return null;
614
+ let fd;
615
+ try {
616
+ fd = (0, node_fs_1.openSync)(filePath, 'wx');
617
+ }
618
+ catch {
619
+ // another worker won the create race; its header lands within moments
620
+ this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
621
+ return null;
622
+ }
623
+ (0, node_fs_1.closeSync)(fd);
624
+ try {
625
+ return (this.plane = Plane.create(filePath, dims, this.planeLayer0Cap(), this.nativePlaneMaxNodes, this.nativePlaneKeyCap));
626
+ }
627
+ catch (createError) {
628
+ // Never leave a partial file that a later process could trust as current.
629
+ try {
630
+ (0, node_fs_1.unlinkSync)(filePath);
631
+ }
632
+ catch {
633
+ // the disable below already forces the JS path for this process
634
+ }
635
+ this.disablePlane(createError);
636
+ return null;
637
+ }
638
+ }
639
+ catch (error) {
640
+ this.planeRetryAt = now + NODE_COUNT_TTL;
641
+ logger.warn?.('could not attach the HNSW plane file; will retry', error);
642
+ return null;
643
+ }
644
+ }
645
+ /** True only while the owning runtime publishes the index as ready, on whichever worker owns it. */
646
+ planeSearchReady(plane) {
647
+ if (plane.invalidated()) {
648
+ this.plane = undefined;
649
+ return false;
259
650
  }
651
+ return this.derivedReadiness() === 'ready';
652
+ }
653
+ derivedReadiness() {
654
+ return this.derivedHost?.readiness().state ?? 'unknown';
655
+ }
656
+ /** The JS graph's effective layer-0 cap for this configuration; sizes the plane's slots. */
657
+ planeLayer0Cap() {
658
+ return this.optimizeRouting ? this.M << 3 : this.M << 1;
659
+ }
660
+ /**
661
+ * Detach this process from the plane after a failure and ask the index's owner for a rebuild.
662
+ * Only the owner destroys native state (`resetDerivedStorage` under its epoch), so a failure
663
+ * observed here after a peer has already replaced the file cannot take out the replacement.
664
+ */
665
+ disablePlane(error) {
666
+ this.plane = undefined;
667
+ this.planeRetryAt = Date.now() + PLANE_ATTACH_RETRY_MS;
668
+ if (!this.planeDisabledLogged) {
669
+ this.planeDisabledLogged = true;
670
+ logger.error?.('the HNSW native index failed; requesting a rebuild from its owner', error);
671
+ }
672
+ this.derivedHost?.requestRebuild();
673
+ }
674
+ /**
675
+ * Delete the derived plane state before an audit-backed reconstruction. Path invalidation
676
+ * makes peers stop using an old mapping even when unlink leaves their mmap inode alive.
677
+ */
678
+ resetDerivedStorage() {
679
+ this.pendingDerivedMappings.clear();
680
+ const attached = this.plane;
681
+ this.plane = undefined;
682
+ this.planeRetryAt = 0;
683
+ const filePath = this.planeFilePath();
684
+ if (!filePath)
685
+ return;
686
+ if (this.filePrimary && (0, node_fs_1.existsSync)(filePath))
687
+ this.invalidatePlaneFile(filePath, attached);
688
+ try {
689
+ (0, node_fs_1.unlinkSync)(filePath);
690
+ }
691
+ catch (error) {
692
+ if (error?.code !== 'ENOENT') {
693
+ // a stale file that cannot be deleted (e.g. Windows EBUSY while mapped) must not
694
+ // be reopened as if current — mark it so no process ever adopts it
695
+ this.plane = null;
696
+ logger.warn?.('could not delete the HNSW plane file; marking it stale', error);
697
+ this.invalidatePlaneFile(filePath, attached);
698
+ }
699
+ }
700
+ }
701
+ /** True while any primary-key mapping survives, which is the only proof this index holds nodes. */
702
+ hasNodeMappings() {
703
+ for (const { value } of this.indexStore.getRange({})) {
704
+ if (value && typeof value === 'object' && typeof value.id === 'number')
705
+ return true;
706
+ }
707
+ return false;
708
+ }
709
+ /** Make an undeletable plane unadoptable before this process releases it. */
710
+ invalidatePlaneFile(filePath, attached) {
711
+ try {
712
+ (0, hnswPlaneBinding_ts_1.invalidatePlaneFile)(filePath, attached);
713
+ }
714
+ catch (error) {
715
+ logger.warn?.('could not invalidate the stale HNSW plane file', error);
716
+ }
717
+ }
718
+ /**
719
+ * Native search over the plane: one NAPI crossing, traversal on the libuv pool, every hit
720
+ * carrying its primary key out of the slot. The predicate adapter runs on this thread's event
721
+ * loop (batched over a ThreadsafeFunction), so this promise must never be awaited by code the
722
+ * predicate itself blocks on; the normal request path awaits it safely.
723
+ */
724
+ searchPlane(plane, target, k, ef, filter, filterState) {
725
+ const query = Float32Array.from(target);
726
+ let resultPromise;
727
+ let predicateError;
728
+ let planeError;
729
+ if (filter && filterState) {
730
+ const predicate = (ids, keys, keyEnds) => {
731
+ const verdicts = new Uint8Array(ids.length);
732
+ if (predicateError !== undefined || planeError !== undefined)
733
+ return verdicts;
734
+ for (let i = 0; i < ids.length; i++) {
735
+ const start = i === 0 ? 0 : keyEnds[i - 1];
736
+ const end = keyEnds[i];
737
+ if (end === start)
738
+ continue;
739
+ let primaryKey;
740
+ try {
741
+ primaryKey = (0, msgpackr_1.unpack)(keys.subarray(start, end));
742
+ }
743
+ catch (error) {
744
+ planeError = error;
745
+ break;
746
+ }
747
+ try {
748
+ if (this.admit(filter, filterState, primaryKey))
749
+ verdicts[i] = 1;
750
+ }
751
+ catch (error) {
752
+ predicateError = error;
753
+ break;
754
+ }
755
+ }
756
+ return verdicts;
757
+ };
758
+ resultPromise = plane.searchWithPredicate(query, k, ef, predicate, undefined, filterState.maxVisits);
759
+ }
760
+ else {
761
+ resultPromise = plane.search(query, k, ef);
762
+ }
763
+ return resultPromise.then((hits) => {
764
+ if (planeError !== undefined)
765
+ throw planeError;
766
+ if (predicateError !== undefined) {
767
+ // the plane itself is healthy; mark the failure as the application's so the caller
768
+ // re-raises it rather than disabling the plane and retrying
769
+ try {
770
+ predicateError[NOT_A_PLANE_FAILURE] = true;
771
+ }
772
+ catch {
773
+ // a frozen/primitive throw still propagates, it just also disables the plane
774
+ }
775
+ throw predicateError;
776
+ }
777
+ const entries = [];
778
+ const { distances, keys, keyEnds } = hits;
779
+ // a key appears twice only after a crash (see applyDerivedValue); keep the nearer hit
780
+ const seen = new Set();
781
+ for (let i = 0; i < keyEnds.length; i++) {
782
+ const start = i === 0 ? 0 : keyEnds[i - 1];
783
+ const end = keyEnds[i];
784
+ if (end === start)
785
+ continue;
786
+ const encoded = keys.toString('latin1', start, end);
787
+ if (seen.has(encoded))
788
+ continue;
789
+ seen.add(encoded);
790
+ entries.push({ key: (0, msgpackr_1.unpack)(keys.subarray(start, end)), distance: distances[i] });
791
+ }
792
+ // nodesVisited stays 0 here: layer-0 visits happen inside the native traversal
793
+ // (filterEvaluations is still counted by the predicate adapter)
794
+ return withStats(entries, filterState);
795
+ });
796
+ }
797
+ attachDerivedHost(host) {
798
+ this.derivedHost = host;
799
+ }
800
+ queryCoverage(maxLagMilliseconds) {
801
+ const coverage = this.derivedHost?.coverage(maxLagMilliseconds);
802
+ if (!coverage || coverage.state === 'unknown') {
803
+ const age = coverage?.lagUpperBoundMilliseconds;
804
+ throw new hdbError_ts_1.DerivedIndexLagError(`Cannot certify native HNSW index coverage within ${maxLagMilliseconds} ms` +
805
+ (age === undefined ? '; freshness is unknown' : `; last certified ${Math.ceil(age)} ms ago`) +
806
+ '; retry this query');
807
+ }
808
+ return coverage;
809
+ }
810
+ /**
811
+ * The commit path only validates: a malformed vector is the client's 400 here rather than an
812
+ * unindexable record later. The shared derived-index runtime reads the committed log; nothing
813
+ * is staged on the transaction.
814
+ */
815
+ prepareCommitted(primaryKey, vector, existingVector) {
816
+ // O(dims) on every write to the table, so skip it when the projection did not change — an
817
+ // unchanged vector was validated when it was first written.
818
+ if (derivedValuesEqual(vector, existingVector))
819
+ return;
820
+ this.validateVector(primaryKey, vector);
821
+ }
822
+ /** The runtime's projection guard: what fails here is delivered as unindexable, not applied. */
823
+ assertDerivedValue(vector, label) {
824
+ this.assertPlaneVector(vector, label);
825
+ }
826
+ validateVector(primaryKey, vector) {
827
+ if (!vector)
828
+ return;
829
+ this.assertPlaneVector(vector, `Vector for attribute "${String(primaryKey)}"`);
830
+ }
831
+ /**
832
+ * Everything reaching the plane — a committed record's projection or a query target — has to
833
+ * convert to the f32 it stores, and to a representable magnitude. What fails here would instead
834
+ * throw out of `Float32Array.from` or out of the crate, as an error neither the search path nor
835
+ * reconstruction can attribute to the record: a query would unlink a healthy file, and a record
836
+ * would abort every rebuild attempt at the same entry.
837
+ */
838
+ assertPlaneVector(vector, label) {
839
+ // A positive integer length, not merely a numeric one: a negative or fractional length skips
840
+ // the component loop and the emptiness check, and reaches Plane.create with it.
841
+ const length = vector?.length;
842
+ if (!Number.isInteger(length) || length < 1) {
843
+ throw new hdbError_ts_1.ClientError(`${label} must be an array of at least one number.`);
844
+ }
845
+ let sumOfSquares = 0;
846
+ for (let i = 0; i < vector.length; i++) {
847
+ const component = vector[i];
848
+ // The type check precedes Math.fround, which throws a TypeError on the BigInt a msgpackr
849
+ // or cbor-x decode produces for a large int64.
850
+ if (typeof component !== 'number' || !Number.isFinite(Math.fround(component))) {
851
+ throw new hdbError_ts_1.ClientError(`${label} has a component at index ${i} that is not a finite 32-bit float: ${String(component)}.`);
852
+ }
853
+ const asFloat32 = Math.fround(component);
854
+ sumOfSquares += asFloat32 * asFloat32;
855
+ }
856
+ // Components can each be f32-finite while their squares are not, which stores invMag 0 and
857
+ // makes every distance involving that node NaN.
858
+ if (!Number.isFinite(Math.fround(sumOfSquares))) {
859
+ throw new hdbError_ts_1.ClientError(`${label} has a magnitude too large to represent in 32-bit floats.`);
860
+ }
861
+ // The plane's dimensionality is fixed at create time by the first committed vector.
862
+ const dims = this.plane?.dims;
863
+ if (dims !== undefined && vector.length !== dims) {
864
+ throw new hdbError_ts_1.ClientError(`${label} has ${vector.length} components, but this index stores ${dims}.`);
865
+ }
866
+ }
867
+ applyDerivedValue(primaryKey, vector, version) {
868
+ this.validateVector(primaryKey, vector);
869
+ const safeKey = typeof primaryKey === 'number' ? [KEY_PREFIX, primaryKey] : primaryKey;
870
+ const pendingKey = pendingMappingKey(primaryKey);
871
+ const pendingMapping = this.pendingDerivedMappings.get(pendingKey);
872
+ const storedMapping = pendingMapping ?? this.indexStore.getSync(safeKey);
873
+ const oldNodeId = typeof storedMapping === 'number' ? storedMapping : storedMapping?.id;
874
+ // Neither a plane removal nor an insert is durable before the barrier, so a pending
875
+ // mapping keeps naming the last published node (previousId) for replay to remove.
876
+ const displacedNodeId = storedMapping?.previousId;
877
+ const durableNodeId = storedMapping?.pending ? displacedNodeId : oldNodeId;
878
+ if (storedMapping?.version != null && version != null && storedMapping.version > version)
879
+ return;
880
+ const nativeVector = vector ? Float32Array.from(vector) : undefined;
881
+ const signature = nativeVector
882
+ ? (0, node_crypto_1.createHash)('sha256')
883
+ .update(Buffer.from(nativeVector.buffer, nativeVector.byteOffset, nativeVector.byteLength))
884
+ .digest('base64url')
885
+ : undefined;
886
+ if (oldNodeId != null &&
887
+ signature &&
888
+ storedMapping.signature === signature &&
889
+ !pendingMapping &&
890
+ !storedMapping.pending) {
891
+ this.indexStore.putSync(safeKey, { id: oldNodeId, signature, version });
892
+ return;
893
+ }
894
+ let plane = vector ? this.getPlane(vector.length, true) : this.getPlane();
895
+ if (plane?.invalidated()) {
896
+ this.plane = undefined;
897
+ plane = vector ? this.getPlane(vector.length, true) : this.getPlane();
898
+ }
899
+ // The pre-commit check above ran before this worker had a plane to compare against, so it
900
+ // cannot have caught a mismatch. Reject before the removal below, or the record loses its
901
+ // old node on the way to failing.
902
+ if (vector && plane && vector.length !== plane.dims) {
903
+ throw new hdbError_ts_1.ClientError(`Vector for attribute "${String(primaryKey)}" has ${vector.length} components, but this index stores ${plane.dims}.`);
904
+ }
905
+ // in process a pending mapping's removals already happened and their ids may be reused
906
+ const removeDisplaced = displacedNodeId != null && !pendingMapping && displacedNodeId !== oldNodeId;
907
+ const removeOld = oldNodeId != null && !(pendingMapping && storedMapping.cleared);
908
+ if (removeDisplaced)
909
+ plane?.remove(displacedNodeId);
910
+ if (removeOld)
911
+ plane?.remove(oldNodeId);
912
+ if (!vector) {
913
+ const cleared = { id: oldNodeId, previousId: durableNodeId, version, pending: true, cleared: true };
914
+ if (oldNodeId != null || durableNodeId != null)
915
+ this.indexStore.putSync(safeKey, cleared);
916
+ else
917
+ this.indexStore.removeSync(safeKey);
918
+ this.pendingDerivedMappings.set(pendingKey, { ...cleared, primaryKey });
919
+ return;
920
+ }
921
+ if (!plane)
922
+ throw new hdbError_ts_1.ServerError('The native HNSW module is unavailable for a file-primary index', 503);
923
+ const nodeId = plane.insert(nativeVector, (0, msgpackr_1.pack)(primaryKey));
924
+ const mapping = { id: nodeId, previousId: durableNodeId, signature, version, pending: true };
925
+ this.indexStore.putSync(safeKey, mapping);
926
+ this.pendingDerivedMappings.set(pendingKey, { ...mapping, primaryKey });
927
+ }
928
+ async flushDerived(watermark) {
929
+ const plane = this.getPlane();
930
+ if (!plane) {
931
+ if (!(0, hnswPlaneBinding_ts_1.getPlaneBinding)())
932
+ throw new hdbError_ts_1.ServerError('The native HNSW module is unavailable', 503);
933
+ return this.publishDerivedMappings();
934
+ }
935
+ await plane.flushAsync(watermark);
936
+ this.publishDerivedMappings();
937
+ }
938
+ publishDerivedMappings() {
939
+ for (const { primaryKey, ...mapping } of this.pendingDerivedMappings.values()) {
940
+ const safeKey = typeof primaryKey === 'number' ? [KEY_PREFIX, primaryKey] : primaryKey;
941
+ if (mapping.cleared || mapping.id === undefined) {
942
+ this.indexStore.removeSync(safeKey);
943
+ }
944
+ else {
945
+ const published = { id: mapping.id, signature: mapping.signature, version: mapping.version };
946
+ this.indexStore.putSync(safeKey, published);
947
+ }
948
+ }
949
+ this.pendingDerivedMappings.clear();
260
950
  }
261
951
  index(primaryKey, vector, existingVector, options = {}) {
952
+ if (this.filePrimary) {
953
+ if (options.transaction)
954
+ return this.prepareCommitted(primaryKey, vector, existingVector);
955
+ // runIndexing invokes custom indexes without a transaction. The shared runtime owns the
956
+ // primary-record rebuild and the log replay; populating here would duplicate native
957
+ // construction and race the owner's generation reset.
958
+ return;
959
+ }
262
960
  // Reject non-finite components before touching the graph. NaN in particular poisons
263
961
  // bisectInsert (arr[mid].distance <= NaN is always false → returns 0, pinning the
264
962
  // candidate to rank 1 of every future search). Infinity causes analogous ordering
@@ -504,14 +1202,15 @@ class HierarchicalNavigableSmallWorld {
504
1202
  }
505
1203
  }
506
1204
  // Store the new element
507
- this.indexStore.put(nodeId, {
1205
+ const storedNode = {
508
1206
  vector: storedVector,
509
1207
  scale: storedScale,
510
1208
  invMag,
511
1209
  level,
512
1210
  primaryKey,
513
1211
  ...connections,
514
- }, options);
1212
+ };
1213
+ this.indexStore.put(nodeId, storedNode, options);
515
1214
  }
516
1215
  else {
517
1216
  // removal of this node, but first make sure we have a valid entry point
@@ -822,8 +1521,10 @@ class HierarchicalNavigableSmallWorld {
822
1521
  throw error;
823
1522
  }
824
1523
  }
825
- /** O(1) node count — the shared id counter, else a single reverse seek to the largest node id. */
1524
+ /** O(1) node count: the plane's id high-water, the shared id counter, or one reverse seek. */
826
1525
  resolveNodeCount(options) {
1526
+ if (this.filePrimary)
1527
+ return this.getPlane()?.idHighWater() ?? 0;
827
1528
  if (this.idIncrementer)
828
1529
  return Number(Atomics.load(this.idIncrementer, 0));
829
1530
  try {
@@ -1071,24 +1772,17 @@ class HierarchicalNavigableSmallWorld {
1071
1772
  * This the main entry from Harper's query functionality, where we actually search for an ordered list of nearest
1072
1773
  * neighbors, using the provided sort/order definition object and performing the multi-layer skip-list search.
1073
1774
  * This returns an iterable of the nearest neighbors to the provided target vector, with nearest ordered first.
1074
- * @param target
1075
- * @param value
1076
- * @param descending
1077
- * @param distance
1078
- * @param comparator
1079
- * @param context
1775
+ *
1776
+ * This is also the contract an index implemented outside this repo has to satisfy, so everything
1777
+ * optional is named: a future capability (a paging cursor, a deadline, a recall target) is a new
1778
+ * field on `options` rather than a positional argument that breaks every existing implementation.
1779
+ * @param searchCondition the vector query: `target`, `comparator`, and the optional `value`,
1780
+ * `descending`, `distance`, `ef` and `filterExpansion` tuning knobs
1781
+ * @param context the query context; its `transaction` is the nested RocksDB transaction reads use
1782
+ * @param options optional, named: `filter` (predicate-aware traversal) and `minResults`
1080
1783
  */
1081
- search({ target, value, descending, distance, comparator, ef, filterExpansion, }, context,
1082
- // Predicate-aware traversal (#1241). When provided, only nodes for which `filter(primaryKey)`
1083
- // returns true are admitted to the result list at layer 0; routing is unaffected. Composed by
1084
- // search.ts from companion AND conditions and caller-supplied vector/row filters. Must be
1085
- // synchronous and side-effect free. JS-API only (never from a REST query string).
1086
- filter,
1087
- // offset + limit for a bounded query. A layer-0 search returns at most `ef` candidates, so a
1088
- // query asking for more rows than that used to come back short with no error — capped at 512
1089
- // (AUTO_EF_MAX) however large the limit was. Raising ef to cover the request keeps `limit`
1090
- // meaningful; the caller pays for what it asked for.
1091
- minResults) {
1784
+ search({ target, value, descending, distance, comparator, ef, filterExpansion, maxIndexLagMilliseconds = hnswDerivedIndex_ts_1.DEFAULT_MAX_INDEX_LAG_MILLISECONDS, waitForIndexMilliseconds = 0, }, context, { filter, minResults, } = {}) {
1785
+ const waiting = this.filePrimary && waitForIndexMilliseconds > 0;
1092
1786
  let limit; // only set for threshold comparators; 0 is a valid threshold (e.g. dotProduct)
1093
1787
  let limitInclusive = false; // true for `le`, false for `lt`
1094
1788
  switch (comparator) {
@@ -1124,7 +1818,18 @@ class HierarchicalNavigableSmallWorld {
1124
1818
  throw new hdbError_ts_1.ClientError('A target vector must be provided for an HNSW query');
1125
1819
  if (!Array.isArray(target))
1126
1820
  throw new hdbError_ts_1.ClientError('The target vector must be an array');
1127
- const options = context.transaction; // should have a nested RocksDB transaction
1821
+ if (this.filePrimary &&
1822
+ (typeof maxIndexLagMilliseconds !== 'number' ||
1823
+ !Number.isFinite(maxIndexLagMilliseconds) ||
1824
+ maxIndexLagMilliseconds < 0))
1825
+ throw new hdbError_ts_1.ClientError('maxIndexLagMilliseconds must be a finite nonnegative number');
1826
+ if (this.filePrimary &&
1827
+ (typeof waitForIndexMilliseconds !== 'number' ||
1828
+ !Number.isFinite(waitForIndexMilliseconds) ||
1829
+ waitForIndexMilliseconds < 0 ||
1830
+ waitForIndexMilliseconds > hnswDerivedIndex_ts_1.MAX_WAIT_FOR_INDEX_MILLISECONDS))
1831
+ throw new hdbError_ts_1.ClientError(`waitForIndexMilliseconds must be a finite number between 0 and ${hnswDerivedIndex_ts_1.MAX_WAIT_FOR_INDEX_MILLISECONDS}`);
1832
+ const txnOptions = context.transaction; // should have a nested RocksDB transaction
1128
1833
  // Resolve search ef: per-query ef wins; else use the schema-pinned value (from either ef option);
1129
1834
  // otherwise auto-scale with the graph size so recall holds as the table grows.
1130
1835
  let effectiveEf = this.efConstructionSearch;
@@ -1167,7 +1872,109 @@ class HierarchicalNavigableSmallWorld {
1167
1872
  filterEvaluations: 0,
1168
1873
  }
1169
1874
  : undefined;
1170
- let entryPoint = this.getEntryPoint(options);
1875
+ const rerankK = comparator === 'sort' && minResults !== undefined
1876
+ ? Math.min(effectiveEf, Math.max(RERANK_MIN, minResults * RERANK_FACTOR))
1877
+ : effectiveEf;
1878
+ if (this.filePrimary && distanceFunction !== this.distance) {
1879
+ throw new hdbError_ts_1.ClientError('A nativePlane index only supports its configured cosine distance');
1880
+ }
1881
+ const searchNative = (certified) => {
1882
+ if (this.filePrimary && this.derivedReadiness() !== 'ready') {
1883
+ throw new hdbError_ts_1.ServerError(`The native HNSW index is ${this.derivedReadiness() === 'unavailable' ? 'unavailable' : 'rebuilding'}`, 503);
1884
+ }
1885
+ // The plane traverses the index's own metric (cosine — the eligibility requirement), so a
1886
+ // query overriding `distance` has to take the JS path: rescoreResults only corrects the
1887
+ // reported distances of whatever candidates came back, not which candidates the beam kept.
1888
+ if (this.planeEligible && distanceFunction === this.distance) {
1889
+ const plane = this.getPlane(target.length, false);
1890
+ // A file-primary index has no JS path to fall through to, so a target the plane cannot
1891
+ // accept has to fail as the client error it is. Otherwise it throws out of
1892
+ // Float32Array.from or the traversal, is read as plane corruption, and unlinks a healthy
1893
+ // file — one malformed query costing a full reconstruction.
1894
+ if (this.filePrimary && plane)
1895
+ this.assertPlaneVector(target, 'Search target');
1896
+ // a non-file-primary query whose dimensionality differs from the graph's takes the JS
1897
+ // path, which tolerates the mismatch, rather than disabling the healthy plane
1898
+ if (plane && plane.dims === target.length && this.planeSearchReady(plane)) {
1899
+ const coverage = certified ?? (this.filePrimary ? this.queryCoverage(maxIndexLagMilliseconds) : undefined);
1900
+ try {
1901
+ const searched = this.searchPlane(plane, target, rerankK, effectiveEf, filter, filterState)
1902
+ .catch((error) => {
1903
+ if (error?.[NOT_A_PLANE_FAILURE])
1904
+ throw error;
1905
+ // There is no JS graph behind a file-primary index: it stays unavailable until
1906
+ // its audit-backed rebuild succeeds.
1907
+ this.disablePlane(error);
1908
+ throw new hdbError_ts_1.ServerError('The native HNSW index is rebuilding', 503);
1909
+ })
1910
+ .then((entries) => {
1911
+ if (coverage)
1912
+ Object.defineProperty(entries, 'indexCoverage', { value: coverage });
1913
+ return entries;
1914
+ });
1915
+ if (coverage)
1916
+ Object.defineProperty(searched, 'indexCoverage', { value: coverage });
1917
+ return searched;
1918
+ }
1919
+ catch (error) {
1920
+ // Handle a throw raised before the asynchronous native search returns its promise.
1921
+ this.disablePlane(error);
1922
+ throw new hdbError_ts_1.ServerError('The native HNSW index is rebuilding', 503);
1923
+ }
1924
+ }
1925
+ }
1926
+ if (this.filePrimary) {
1927
+ const state = this.derivedReadiness();
1928
+ if (state === 'unavailable')
1929
+ throw new hdbError_ts_1.ServerError('The native HNSW index is unavailable', 503);
1930
+ const planePath = this.planeFilePath();
1931
+ if (state !== 'ready' || (planePath && (0, node_fs_1.existsSync)(planePath))) {
1932
+ throw new hdbError_ts_1.ServerError('The native HNSW index is rebuilding', 503);
1933
+ }
1934
+ // The absence of a file is not proof of an empty index — it is also the state just after
1935
+ // any process removes an unopenable one. Only the surviving node mappings prove it.
1936
+ if (this.hasNodeMappings()) {
1937
+ // A table taking no further writes never drains, so a query is the only thing left
1938
+ // that can notice the graph is gone and ask for it back.
1939
+ logger.error?.(`${this.indexStore.name} lost its native file while its node mappings survive`);
1940
+ this.derivedHost?.requestRebuild();
1941
+ throw new hdbError_ts_1.ServerError('The native HNSW index is rebuilding', 503);
1942
+ }
1943
+ const entries = withStats([], filterState);
1944
+ Object.defineProperty(entries, 'indexCoverage', {
1945
+ value: certified ?? this.queryCoverage(maxIndexLagMilliseconds),
1946
+ });
1947
+ return entries;
1948
+ }
1949
+ };
1950
+ if (waiting) {
1951
+ context.signal?.throwIfAborted();
1952
+ const host = this.derivedHost;
1953
+ const state = host?.readiness().state;
1954
+ if (state !== 'ready') {
1955
+ throw new hdbError_ts_1.ServerError(`The native HNSW index is ${state === 'unavailable' ? 'unavailable' : 'rebuilding'}`, 503);
1956
+ }
1957
+ const searched = Promise.resolve(context.indexSearchStart).then(async () => {
1958
+ context.signal?.throwIfAborted();
1959
+ if (minResults === 0)
1960
+ return [];
1961
+ const started = (0, derivedIndexRuntime_ts_1.derivedIndexTime)(this.indexStore.rootStore);
1962
+ if (host.coverage(0)?.state !== 'current')
1963
+ await host.waitForCoverage(started, waitForIndexMilliseconds, context.signal);
1964
+ context.signal?.throwIfAborted();
1965
+ return searchNative({
1966
+ state: 'current',
1967
+ maxLagMilliseconds: maxIndexLagMilliseconds,
1968
+ lagUpperBoundMilliseconds: 0,
1969
+ });
1970
+ });
1971
+ searched.catch(() => { });
1972
+ return searched;
1973
+ }
1974
+ const native = searchNative();
1975
+ if (native)
1976
+ return native;
1977
+ let entryPoint = this.getEntryPoint(txnOptions);
1171
1978
  if (!entryPoint)
1172
1979
  return withStats([], filterState);
1173
1980
  let entryPointId = entryPoint.id;
@@ -1180,7 +1987,7 @@ class HierarchicalNavigableSmallWorld {
1180
1987
  // nodes) rather than to ef. See DESIGN.md.
1181
1988
  for (let l = entryPoint.level; l >= 0; l--) {
1182
1989
  // Search for closest neighbors at current level
1183
- results = this.searchLayer(target, entryPointId, entryPoint, l === 0 ? effectiveEf : ROUTING_EF, l, options, distanceFunction, l === 0 ? filter : undefined, l === 0 ? filterState : undefined);
1990
+ results = this.searchLayer(target, entryPointId, entryPoint, l === 0 ? effectiveEf : ROUTING_EF, l, txnOptions, distanceFunction, l === 0 ? filter : undefined, l === 0 ? filterState : undefined);
1184
1991
  if (results.length > 0) {
1185
1992
  const neighbor = results[0]; // closest neighbor becomes new entry point
1186
1993
  entryPoint = neighbor.node;
@@ -1189,6 +1996,8 @@ class HierarchicalNavigableSmallWorld {
1189
1996
  }
1190
1997
  if (limit !== undefined)
1191
1998
  results = results.filter((candidate) => limitInclusive ? candidate.distance <= limit : candidate.distance < limit);
1999
+ if (results.length > rerankK)
2000
+ results = results.slice(0, rerankK);
1192
2001
  return withStats(results.map((candidate) => ({
1193
2002
  // we return the result as an entry so we can provide distance as metadata
1194
2003
  key: candidate.node.primaryKey, // return value