@harperfast/harper 5.2.13 → 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 (655) hide show
  1. package/agent/mcpTools.ts +1 -1
  2. package/agent/session.ts +25 -14
  3. package/bin/cliOperations.ts +58 -9
  4. package/bin/copyDb.ts +282 -59
  5. package/bin/deploySetup.ts +16 -5
  6. package/bin/harper.ts +1 -1
  7. package/bin/help.ts +4 -1
  8. package/bin/lite.ts +4 -1
  9. package/bin/restart.ts +120 -4
  10. package/bin/run.ts +6 -11
  11. package/bin/upgrade.js +7 -3
  12. package/bin/workloadIdentity.ts +119 -0
  13. package/components/Application.ts +3436 -242
  14. package/components/ApplicationScope.ts +8 -0
  15. package/components/EntryHandler.ts +59 -39
  16. package/components/OptionsWatcher.ts +440 -98
  17. package/components/RuntimeModuleTracker.ts +38 -7
  18. package/components/Scope.ts +56 -15
  19. package/components/awaitRestart.ts +84 -0
  20. package/components/componentLoader.ts +381 -32
  21. package/components/componentPreparationLock.ts +16 -5
  22. package/components/deploymentOperations.ts +4 -1
  23. package/components/deploymentRecorder.ts +9 -2
  24. package/components/mcp/adapters/harperHttp.ts +4 -0
  25. package/components/mcp/listChanged.ts +4 -0
  26. package/components/mcp/toolRegistry.ts +2 -0
  27. package/components/mcp/tools/operations.ts +9 -0
  28. package/components/mcp/tools/schemas/operationDescriptions.ts +2 -2
  29. package/components/operations.js +537 -113
  30. package/components/operationsValidation.js +98 -3
  31. package/components/packageComponent.ts +25 -1
  32. package/components/requestRestart.ts +11 -0
  33. package/components/status/ComponentStatusRegistry.ts +59 -0
  34. package/config/RootConfigWatcher.ts +240 -40
  35. package/config/configReadRetry.ts +62 -0
  36. package/config/configUtils.ts +357 -48
  37. package/config/harperConfigEnvVars.ts +170 -27
  38. package/config/parseConfigFile.ts +34 -0
  39. package/config/readConfigFileSync.ts +44 -0
  40. package/config/watcherArming.ts +59 -0
  41. package/config-root.schema.json +33 -0
  42. package/dataLayer/blobBackup.ts +160 -50
  43. package/dataLayer/delete.ts +6 -1
  44. package/dataLayer/harperBridge/ResourceBridge.ts +80 -10
  45. package/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js +3 -1
  46. package/dataLayer/hdbInfoController.ts +34 -1
  47. package/dataLayer/insert.ts +44 -1
  48. package/dataLayer/rocksdbBackup.ts +53 -10
  49. package/dataLayer/schema.ts +11 -1
  50. package/dataLayer/schemaDescribe.ts +8 -1
  51. package/dist/agent/mcpTools.js +1 -1
  52. package/dist/agent/mcpTools.js.map +1 -1
  53. package/dist/agent/session.d.ts +22 -0
  54. package/dist/agent/session.js +26 -15
  55. package/dist/agent/session.js.map +1 -1
  56. package/dist/bin/cliOperations.js +61 -9
  57. package/dist/bin/cliOperations.js.map +1 -1
  58. package/dist/bin/copyDb.d.ts +12 -1
  59. package/dist/bin/copyDb.js +248 -60
  60. package/dist/bin/copyDb.js.map +1 -1
  61. package/dist/bin/deploySetup.d.ts +2 -0
  62. package/dist/bin/deploySetup.js +11 -3
  63. package/dist/bin/deploySetup.js.map +1 -1
  64. package/dist/bin/harper.js +1 -1
  65. package/dist/bin/harper.js.map +1 -1
  66. package/dist/bin/help.js +4 -1
  67. package/dist/bin/help.js.map +1 -1
  68. package/dist/bin/lite.js +4 -1
  69. package/dist/bin/lite.js.map +1 -1
  70. package/dist/bin/restart.js +91 -6
  71. package/dist/bin/restart.js.map +1 -1
  72. package/dist/bin/run.js +4 -10
  73. package/dist/bin/run.js.map +1 -1
  74. package/dist/bin/upgrade.js +4 -3
  75. package/dist/bin/upgrade.js.map +1 -1
  76. package/dist/bin/workloadIdentity.d.ts +18 -0
  77. package/dist/bin/workloadIdentity.js +100 -0
  78. package/dist/bin/workloadIdentity.js.map +1 -0
  79. package/dist/components/Application.d.ts +235 -17
  80. package/dist/components/Application.js +3038 -238
  81. package/dist/components/Application.js.map +1 -1
  82. package/dist/components/ApplicationScope.d.ts +8 -0
  83. package/dist/components/ApplicationScope.js +7 -0
  84. package/dist/components/ApplicationScope.js.map +1 -1
  85. package/dist/components/EntryHandler.js +26 -10
  86. package/dist/components/EntryHandler.js.map +1 -1
  87. package/dist/components/OptionsWatcher.d.ts +4 -0
  88. package/dist/components/OptionsWatcher.js +440 -99
  89. package/dist/components/OptionsWatcher.js.map +1 -1
  90. package/dist/components/RuntimeModuleTracker.js +40 -6
  91. package/dist/components/RuntimeModuleTracker.js.map +1 -1
  92. package/dist/components/Scope.js +52 -13
  93. package/dist/components/Scope.js.map +1 -1
  94. package/dist/components/awaitRestart.d.ts +33 -0
  95. package/dist/components/awaitRestart.js +61 -0
  96. package/dist/components/awaitRestart.js.map +1 -0
  97. package/dist/components/componentLoader.d.ts +38 -1
  98. package/dist/components/componentLoader.js +313 -24
  99. package/dist/components/componentLoader.js.map +1 -1
  100. package/dist/components/componentPreparationLock.d.ts +5 -0
  101. package/dist/components/componentPreparationLock.js +14 -6
  102. package/dist/components/componentPreparationLock.js.map +1 -1
  103. package/dist/components/deploymentOperations.js +4 -1
  104. package/dist/components/deploymentOperations.js.map +1 -1
  105. package/dist/components/deploymentRecorder.d.ts +4 -2
  106. package/dist/components/deploymentRecorder.js +1 -0
  107. package/dist/components/deploymentRecorder.js.map +1 -1
  108. package/dist/components/mcp/adapters/harperHttp.js +4 -0
  109. package/dist/components/mcp/adapters/harperHttp.js.map +1 -1
  110. package/dist/components/mcp/listChanged.js +5 -0
  111. package/dist/components/mcp/listChanged.js.map +1 -1
  112. package/dist/components/mcp/toolRegistry.d.ts +1 -0
  113. package/dist/components/mcp/toolRegistry.js.map +1 -1
  114. package/dist/components/mcp/tools/operations.d.ts +5 -0
  115. package/dist/components/mcp/tools/operations.js +9 -0
  116. package/dist/components/mcp/tools/operations.js.map +1 -1
  117. package/dist/components/mcp/tools/schemas/operationDescriptions.js +2 -2
  118. package/dist/components/mcp/tools/schemas/operationDescriptions.js.map +1 -1
  119. package/dist/components/operations.d.ts +28 -0
  120. package/dist/components/operations.js +476 -113
  121. package/dist/components/operations.js.map +1 -1
  122. package/dist/components/operationsValidation.js +97 -3
  123. package/dist/components/operationsValidation.js.map +1 -1
  124. package/dist/components/packageComponent.js +24 -0
  125. package/dist/components/packageComponent.js.map +1 -1
  126. package/dist/components/requestRestart.d.ts +1 -0
  127. package/dist/components/requestRestart.js +7 -0
  128. package/dist/components/requestRestart.js.map +1 -1
  129. package/dist/components/status/ComponentStatusRegistry.d.ts +0 -4
  130. package/dist/components/status/ComponentStatusRegistry.js +63 -0
  131. package/dist/components/status/ComponentStatusRegistry.js.map +1 -1
  132. package/dist/config/RootConfigWatcher.d.ts +9 -1
  133. package/dist/config/RootConfigWatcher.js +228 -37
  134. package/dist/config/RootConfigWatcher.js.map +1 -1
  135. package/dist/config/configReadRetry.d.ts +8 -0
  136. package/dist/config/configReadRetry.js +62 -0
  137. package/dist/config/configReadRetry.js.map +1 -0
  138. package/dist/config/configUtils.d.ts +11 -2
  139. package/dist/config/configUtils.js +304 -47
  140. package/dist/config/configUtils.js.map +1 -1
  141. package/dist/config/harperConfigEnvVars.d.ts +16 -0
  142. package/dist/config/harperConfigEnvVars.js +162 -25
  143. package/dist/config/harperConfigEnvVars.js.map +1 -1
  144. package/dist/config/parseConfigFile.d.ts +4 -0
  145. package/dist/config/parseConfigFile.js +35 -0
  146. package/dist/config/parseConfigFile.js.map +1 -0
  147. package/dist/config/readConfigFileSync.d.ts +1 -0
  148. package/dist/config/readConfigFileSync.js +47 -0
  149. package/dist/config/readConfigFileSync.js.map +1 -0
  150. package/dist/config/watcherArming.d.ts +15 -0
  151. package/dist/config/watcherArming.js +59 -0
  152. package/dist/config/watcherArming.js.map +1 -0
  153. package/dist/dataLayer/blobBackup.d.ts +49 -20
  154. package/dist/dataLayer/blobBackup.js +139 -50
  155. package/dist/dataLayer/blobBackup.js.map +1 -1
  156. package/dist/dataLayer/delete.js +1 -1
  157. package/dist/dataLayer/delete.js.map +1 -1
  158. package/dist/dataLayer/harperBridge/ResourceBridge.d.ts +14 -1
  159. package/dist/dataLayer/harperBridge/ResourceBridge.js +72 -12
  160. package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
  161. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.d.ts +3 -1
  162. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js +3 -1
  163. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js.map +1 -1
  164. package/dist/dataLayer/hdbInfoController.d.ts +10 -0
  165. package/dist/dataLayer/hdbInfoController.js +30 -1
  166. package/dist/dataLayer/hdbInfoController.js.map +1 -1
  167. package/dist/dataLayer/insert.d.ts +9 -1
  168. package/dist/dataLayer/insert.js +30 -0
  169. package/dist/dataLayer/insert.js.map +1 -1
  170. package/dist/dataLayer/rocksdbBackup.d.ts +2 -2
  171. package/dist/dataLayer/rocksdbBackup.js +45 -8
  172. package/dist/dataLayer/rocksdbBackup.js.map +1 -1
  173. package/dist/dataLayer/schema.js +8 -0
  174. package/dist/dataLayer/schema.js.map +1 -1
  175. package/dist/dataLayer/schemaDescribe.js +8 -1
  176. package/dist/dataLayer/schemaDescribe.js.map +1 -1
  177. package/dist/index.d.ts +2 -1
  178. package/dist/index.js +4 -1
  179. package/dist/index.js.map +1 -1
  180. package/dist/json/systemSchema.json +55 -0
  181. package/dist/resources/DatabaseTransaction.d.ts +77 -0
  182. package/dist/resources/DatabaseTransaction.js +586 -54
  183. package/dist/resources/DatabaseTransaction.js.map +1 -1
  184. package/dist/resources/LMDBTransaction.d.ts +2 -1
  185. package/dist/resources/LMDBTransaction.js +43 -6
  186. package/dist/resources/LMDBTransaction.js.map +1 -1
  187. package/dist/resources/PrimaryRocksDatabase.d.ts +1 -0
  188. package/dist/resources/PrimaryRocksDatabase.js +49 -5
  189. package/dist/resources/PrimaryRocksDatabase.js.map +1 -1
  190. package/dist/resources/RecordEncoder.d.ts +20 -0
  191. package/dist/resources/RecordEncoder.js +110 -9
  192. package/dist/resources/RecordEncoder.js.map +1 -1
  193. package/dist/resources/RequestTarget.d.ts +2 -0
  194. package/dist/resources/RequestTarget.js.map +1 -1
  195. package/dist/resources/Resource.js +117 -24
  196. package/dist/resources/Resource.js.map +1 -1
  197. package/dist/resources/ResourceInterface.d.ts +28 -1
  198. package/dist/resources/ResourceInterface.js.map +1 -1
  199. package/dist/resources/RocksIndexStore.d.ts +6 -1
  200. package/dist/resources/RocksIndexStore.js +24 -9
  201. package/dist/resources/RocksIndexStore.js.map +1 -1
  202. package/dist/resources/RocksTransactionLogStore.d.ts +24 -1
  203. package/dist/resources/RocksTransactionLogStore.js +160 -49
  204. package/dist/resources/RocksTransactionLogStore.js.map +1 -1
  205. package/dist/resources/Table.d.ts +165 -10
  206. package/dist/resources/Table.js +1805 -303
  207. package/dist/resources/Table.js.map +1 -1
  208. package/dist/resources/analytics/write.js +10 -3
  209. package/dist/resources/analytics/write.js.map +1 -1
  210. package/dist/resources/auditStore.d.ts +181 -2
  211. package/dist/resources/auditStore.js +640 -29
  212. package/dist/resources/auditStore.js.map +1 -1
  213. package/dist/resources/blob.d.ts +129 -9
  214. package/dist/resources/blob.js +992 -114
  215. package/dist/resources/blob.js.map +1 -1
  216. package/dist/resources/branchDatabase.d.ts +48 -0
  217. package/dist/resources/branchDatabase.js +892 -0
  218. package/dist/resources/branchDatabase.js.map +1 -0
  219. package/dist/resources/crdt.js +50 -12
  220. package/dist/resources/crdt.js.map +1 -1
  221. package/dist/resources/dataLoader.js +3 -4
  222. package/dist/resources/dataLoader.js.map +1 -1
  223. package/dist/resources/databases.d.ts +157 -14
  224. package/dist/resources/databases.js +1462 -325
  225. package/dist/resources/databases.js.map +1 -1
  226. package/dist/resources/defineTable.d.ts +10 -2
  227. package/dist/resources/defineTable.js +9 -1
  228. package/dist/resources/defineTable.js.map +1 -1
  229. package/dist/resources/derivedIndexRegistry.d.ts +5 -0
  230. package/dist/resources/derivedIndexRegistry.js +68 -0
  231. package/dist/resources/derivedIndexRegistry.js.map +1 -0
  232. package/dist/resources/derivedIndexRuntime.d.ts +215 -0
  233. package/dist/resources/derivedIndexRuntime.js +2027 -0
  234. package/dist/resources/derivedIndexRuntime.js.map +1 -0
  235. package/dist/resources/graphql.d.ts +1 -1
  236. package/dist/resources/graphql.js +52 -16
  237. package/dist/resources/graphql.js.map +1 -1
  238. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.d.ts +103 -9
  239. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js +854 -41
  240. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js.map +1 -1
  241. package/dist/resources/indexes/hnswDerivedIndex.d.ts +67 -0
  242. package/dist/resources/indexes/hnswDerivedIndex.js +464 -0
  243. package/dist/resources/indexes/hnswDerivedIndex.js.map +1 -0
  244. package/dist/resources/indexes/hnswPlaneBinding.d.ts +65 -0
  245. package/dist/resources/indexes/hnswPlaneBinding.js +91 -0
  246. package/dist/resources/indexes/hnswPlaneBinding.js.map +1 -0
  247. package/dist/resources/longLivedTransactions.d.ts +71 -0
  248. package/dist/resources/longLivedTransactions.js +358 -0
  249. package/dist/resources/longLivedTransactions.js.map +1 -0
  250. package/dist/resources/models/backendRegistry.d.ts +26 -0
  251. package/dist/resources/models/backendRegistry.js +60 -2
  252. package/dist/resources/models/backendRegistry.js.map +1 -1
  253. package/dist/resources/models/bootstrap.d.ts +33 -1
  254. package/dist/resources/models/bootstrap.js +416 -31
  255. package/dist/resources/models/bootstrap.js.map +1 -1
  256. package/dist/resources/nodeIdMapping.d.ts +5 -0
  257. package/dist/resources/nodeIdMapping.js +49 -0
  258. package/dist/resources/nodeIdMapping.js.map +1 -1
  259. package/dist/resources/recordLock.d.ts +123 -0
  260. package/dist/resources/recordLock.js +315 -0
  261. package/dist/resources/recordLock.js.map +1 -0
  262. package/dist/resources/recordLockCoordinator.d.ts +557 -0
  263. package/dist/resources/recordLockCoordinator.js +2565 -0
  264. package/dist/resources/recordLockCoordinator.js.map +1 -0
  265. package/dist/resources/replayLogs.d.ts +14 -1
  266. package/dist/resources/replayLogs.js +157 -24
  267. package/dist/resources/replayLogs.js.map +1 -1
  268. package/dist/resources/replayLogsGuards.d.ts +94 -7
  269. package/dist/resources/replayLogsGuards.js +111 -7
  270. package/dist/resources/replayLogsGuards.js.map +1 -1
  271. package/dist/resources/replicatedApplyFailure.d.ts +16 -0
  272. package/dist/resources/replicatedApplyFailure.js +63 -0
  273. package/dist/resources/replicatedApplyFailure.js.map +1 -0
  274. package/dist/resources/scheduler/scheduler.js +3 -3
  275. package/dist/resources/scheduler/scheduler.js.map +1 -1
  276. package/dist/resources/search.d.ts +10 -4
  277. package/dist/resources/search.js +283 -37
  278. package/dist/resources/search.js.map +1 -1
  279. package/dist/resources/tracked.d.ts +5 -1
  280. package/dist/resources/tracked.js +74 -23
  281. package/dist/resources/tracked.js.map +1 -1
  282. package/dist/resources/transactionBroadcast.d.ts +1 -1
  283. package/dist/resources/transactionBroadcast.js +2 -2
  284. package/dist/resources/transactionBroadcast.js.map +1 -1
  285. package/dist/security/auth.js +61 -30
  286. package/dist/security/auth.js.map +1 -1
  287. package/dist/security/authn/oidc/claims.d.ts +22 -0
  288. package/dist/security/authn/oidc/claims.js +71 -0
  289. package/dist/security/authn/oidc/claims.js.map +1 -0
  290. package/dist/security/authn/oidc/identityToken.d.ts +27 -0
  291. package/dist/security/authn/oidc/identityToken.js +111 -0
  292. package/dist/security/authn/oidc/identityToken.js.map +1 -0
  293. package/dist/security/authn/oidc/jwks.d.ts +25 -0
  294. package/dist/security/authn/oidc/jwks.js +261 -0
  295. package/dist/security/authn/oidc/jwks.js.map +1 -0
  296. package/dist/security/authn/oidc/providers/generic.d.ts +13 -0
  297. package/dist/security/authn/oidc/providers/generic.js +34 -0
  298. package/dist/security/authn/oidc/providers/generic.js.map +1 -0
  299. package/dist/security/authn/oidc/providers/githubActions.d.ts +11 -0
  300. package/dist/security/authn/oidc/providers/githubActions.js +129 -0
  301. package/dist/security/authn/oidc/providers/githubActions.js.map +1 -0
  302. package/dist/security/authn/oidc/providers/index.d.ts +37 -0
  303. package/dist/security/authn/oidc/providers/index.js +24 -0
  304. package/dist/security/authn/oidc/providers/index.js.map +1 -0
  305. package/dist/security/authn/oidc/tokenExchange.d.ts +12 -0
  306. package/dist/security/authn/oidc/tokenExchange.js +306 -0
  307. package/dist/security/authn/oidc/tokenExchange.js.map +1 -0
  308. package/dist/security/authn/oidc/trustPolicyOperations.d.ts +49 -0
  309. package/dist/security/authn/oidc/trustPolicyOperations.js +358 -0
  310. package/dist/security/authn/oidc/trustPolicyOperations.js.map +1 -0
  311. package/dist/security/authn/oidc/types.d.ts +38 -0
  312. package/dist/security/authn/oidc/types.js +6 -0
  313. package/dist/security/authn/oidc/types.js.map +1 -0
  314. package/dist/security/certificateVerification/index.js +40 -11
  315. package/dist/security/certificateVerification/index.js.map +1 -1
  316. package/dist/security/certificateVerification/trustedIssuers.d.ts +24 -0
  317. package/dist/security/certificateVerification/trustedIssuers.js +79 -0
  318. package/dist/security/certificateVerification/trustedIssuers.js.map +1 -0
  319. package/dist/security/certificateVerification/types.d.ts +1 -0
  320. package/dist/security/credentialProvenance.d.ts +35 -0
  321. package/dist/security/credentialProvenance.js +51 -0
  322. package/dist/security/credentialProvenance.js.map +1 -0
  323. package/dist/security/credentialRejection.d.ts +4 -0
  324. package/dist/security/credentialRejection.js +24 -0
  325. package/dist/security/credentialRejection.js.map +1 -0
  326. package/dist/security/deferredAuthentication.d.ts +36 -0
  327. package/dist/security/deferredAuthentication.js +70 -0
  328. package/dist/security/deferredAuthentication.js.map +1 -0
  329. package/dist/security/impersonation.d.ts +21 -0
  330. package/dist/security/impersonation.js +108 -9
  331. package/dist/security/impersonation.js.map +1 -1
  332. package/dist/security/jsLoader.d.ts +6 -0
  333. package/dist/security/jsLoader.js +77 -15
  334. package/dist/security/jsLoader.js.map +1 -1
  335. package/dist/security/keys.js +301 -71
  336. package/dist/security/keys.js.map +1 -1
  337. package/dist/security/operationScope.d.ts +21 -0
  338. package/dist/security/operationScope.js +36 -0
  339. package/dist/security/operationScope.js.map +1 -0
  340. package/dist/security/permissionsTranslator.js +21 -0
  341. package/dist/security/permissionsTranslator.js.map +1 -1
  342. package/dist/security/tokenAuthentication.d.ts +19 -1
  343. package/dist/security/tokenAuthentication.js +191 -10
  344. package/dist/security/tokenAuthentication.js.map +1 -1
  345. package/dist/security/user.js +4 -3
  346. package/dist/security/user.js.map +1 -1
  347. package/dist/server/DurableSubscriptionsSession.d.ts +2 -2
  348. package/dist/server/DurableSubscriptionsSession.js +67 -10
  349. package/dist/server/DurableSubscriptionsSession.js.map +1 -1
  350. package/dist/server/REST.js +106 -2
  351. package/dist/server/REST.js.map +1 -1
  352. package/dist/server/graphqlQuerying.js +4 -0
  353. package/dist/server/graphqlQuerying.js.map +1 -1
  354. package/dist/server/http.d.ts +16 -1
  355. package/dist/server/http.js +122 -17
  356. package/dist/server/http.js.map +1 -1
  357. package/dist/server/itc/serverHandlers.js +8 -1
  358. package/dist/server/itc/serverHandlers.js.map +1 -1
  359. package/dist/server/jobs/jobProcess.js +6 -2
  360. package/dist/server/jobs/jobProcess.js.map +1 -1
  361. package/dist/server/jobs/jobs.js +4 -1
  362. package/dist/server/jobs/jobs.js.map +1 -1
  363. package/dist/server/liveSubscriptionAuth.d.ts +26 -4
  364. package/dist/server/liveSubscriptionAuth.js +105 -39
  365. package/dist/server/liveSubscriptionAuth.js.map +1 -1
  366. package/dist/server/loadRootComponents.js +49 -10
  367. package/dist/server/loadRootComponents.js.map +1 -1
  368. package/dist/server/mqtt.d.ts +2 -0
  369. package/dist/server/mqtt.js +165 -30
  370. package/dist/server/mqtt.js.map +1 -1
  371. package/dist/server/nodeName.d.ts +2 -0
  372. package/dist/server/nodeName.js +107 -23
  373. package/dist/server/nodeName.js.map +1 -1
  374. package/dist/server/serverHelpers/Headers.d.ts +27 -0
  375. package/dist/server/serverHelpers/Headers.js +145 -1
  376. package/dist/server/serverHelpers/Headers.js.map +1 -1
  377. package/dist/server/serverHelpers/NodeAdapterResponse.d.ts +48 -0
  378. package/dist/server/serverHelpers/NodeAdapterResponse.js +220 -0
  379. package/dist/server/serverHelpers/NodeAdapterResponse.js.map +1 -0
  380. package/dist/server/serverHelpers/Request.d.ts +5 -10
  381. package/dist/server/serverHelpers/Request.js +38 -136
  382. package/dist/server/serverHelpers/Request.js.map +1 -1
  383. package/dist/server/serverHelpers/contentTypes.d.ts +11 -0
  384. package/dist/server/serverHelpers/contentTypes.js +221 -40
  385. package/dist/server/serverHelpers/contentTypes.js.map +1 -1
  386. package/dist/server/serverHelpers/deployValidationState.d.ts +3 -0
  387. package/dist/server/serverHelpers/deployValidationState.js +9 -19
  388. package/dist/server/serverHelpers/deployValidationState.js.map +1 -1
  389. package/dist/server/serverHelpers/operationAuthorizationState.d.ts +12 -0
  390. package/dist/server/serverHelpers/operationAuthorizationState.js +24 -2
  391. package/dist/server/serverHelpers/operationAuthorizationState.js.map +1 -1
  392. package/dist/server/serverHelpers/registeredOperations.d.ts +5 -4
  393. package/dist/server/serverHelpers/registeredOperations.js +74 -21
  394. package/dist/server/serverHelpers/registeredOperations.js.map +1 -1
  395. package/dist/server/serverHelpers/requestSanitization.d.ts +11 -0
  396. package/dist/server/serverHelpers/requestSanitization.js +20 -0
  397. package/dist/server/serverHelpers/requestSanitization.js.map +1 -0
  398. package/dist/server/serverHelpers/serverHandlers.js +6 -3
  399. package/dist/server/serverHelpers/serverHandlers.js.map +1 -1
  400. package/dist/server/serverHelpers/serverUtilities.d.ts +18 -0
  401. package/dist/server/serverHelpers/serverUtilities.js +178 -29
  402. package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
  403. package/dist/server/serverHelpers/sharedMessageEncoding.d.ts +67 -0
  404. package/dist/server/serverHelpers/sharedMessageEncoding.js +280 -0
  405. package/dist/server/serverHelpers/sharedMessageEncoding.js.map +1 -0
  406. package/dist/server/serverHelpers/uwsServer.js +19 -1
  407. package/dist/server/serverHelpers/uwsServer.js.map +1 -1
  408. package/dist/server/static.js +24 -28
  409. package/dist/server/static.js.map +1 -1
  410. package/dist/server/storageReclamation.d.ts +5 -0
  411. package/dist/server/storageReclamation.js +17 -1
  412. package/dist/server/storageReclamation.js.map +1 -1
  413. package/dist/server/threads/isolatedApplications.d.ts +47 -0
  414. package/dist/server/threads/isolatedApplications.js +171 -0
  415. package/dist/server/threads/isolatedApplications.js.map +1 -0
  416. package/dist/server/threads/itc.d.ts +7 -2
  417. package/dist/server/threads/itc.js +5 -1
  418. package/dist/server/threads/itc.js.map +1 -1
  419. package/dist/server/threads/logRotationTransport.d.ts +1 -0
  420. package/dist/server/threads/logRotationTransport.js +33 -0
  421. package/dist/server/threads/logRotationTransport.js.map +1 -0
  422. package/dist/server/threads/manageThreads.d.ts +83 -3
  423. package/dist/server/threads/manageThreads.js +769 -75
  424. package/dist/server/threads/manageThreads.js.map +1 -1
  425. package/dist/server/threads/socketRouter.d.ts +1 -0
  426. package/dist/server/threads/socketRouter.js +277 -31
  427. package/dist/server/threads/socketRouter.js.map +1 -1
  428. package/dist/server/threads/threadHeapMemory.d.ts +2 -0
  429. package/dist/server/threads/threadHeapMemory.js +31 -0
  430. package/dist/server/threads/threadHeapMemory.js.map +1 -0
  431. package/dist/server/threads/threadServer.js +76 -22
  432. package/dist/server/threads/threadServer.js.map +1 -1
  433. package/dist/sqlEngine/config.d.ts +1 -3
  434. package/dist/sqlEngine/config.js +19 -16
  435. package/dist/sqlEngine/config.js.map +1 -1
  436. package/dist/sqlTranslator/index.d.ts +1 -1
  437. package/dist/sqlTranslator/index.js +30 -7
  438. package/dist/sqlTranslator/index.js.map +1 -1
  439. package/dist/upgrade/directives/5-3-0.d.ts +7 -0
  440. package/dist/upgrade/directives/5-3-0.js +148 -0
  441. package/dist/upgrade/directives/5-3-0.js.map +1 -0
  442. package/dist/upgrade/directives/directivesController.js +2 -1
  443. package/dist/upgrade/directives/directivesController.js.map +1 -1
  444. package/dist/utility/OperationFunctionCaller.js +2 -1
  445. package/dist/utility/OperationFunctionCaller.js.map +1 -1
  446. package/dist/utility/common_utils.d.ts +16 -0
  447. package/dist/utility/common_utils.js +32 -6
  448. package/dist/utility/common_utils.js.map +1 -1
  449. package/dist/utility/componentNames.d.ts +8 -0
  450. package/dist/utility/componentNames.js +12 -1
  451. package/dist/utility/componentNames.js.map +1 -1
  452. package/dist/utility/environment/environmentManager.js +3 -6
  453. package/dist/utility/environment/environmentManager.js.map +1 -1
  454. package/dist/utility/environment/systemInformation.d.ts +1 -0
  455. package/dist/utility/environment/systemInformation.js +1 -0
  456. package/dist/utility/environment/systemInformation.js.map +1 -1
  457. package/dist/utility/errors/commonErrors.d.ts +2 -0
  458. package/dist/utility/errors/commonErrors.js +2 -0
  459. package/dist/utility/errors/commonErrors.js.map +1 -1
  460. package/dist/utility/errors/hdbError.d.ts +33 -0
  461. package/dist/utility/errors/hdbError.js +58 -1
  462. package/dist/utility/errors/hdbError.js.map +1 -1
  463. package/dist/utility/globalSchema.d.ts +18 -0
  464. package/dist/utility/hdbTerms.d.ts +18 -0
  465. package/dist/utility/hdbTerms.js +20 -2
  466. package/dist/utility/hdbTerms.js.map +1 -1
  467. package/dist/utility/logging/harper_logger.d.ts +2 -0
  468. package/dist/utility/logging/harper_logger.js +286 -30
  469. package/dist/utility/logging/harper_logger.js.map +1 -1
  470. package/dist/utility/logging/logGenerationCoordinator.d.ts +35 -0
  471. package/dist/utility/logging/logGenerationCoordinator.js +184 -0
  472. package/dist/utility/logging/logGenerationCoordinator.js.map +1 -0
  473. package/dist/utility/logging/logRotation.d.ts +46 -0
  474. package/dist/utility/logging/logRotation.js +365 -0
  475. package/dist/utility/logging/logRotation.js.map +1 -0
  476. package/dist/utility/logging/logRotator.d.ts +1 -1
  477. package/dist/utility/logging/logRotator.js +192 -85
  478. package/dist/utility/logging/logRotator.js.map +1 -1
  479. package/dist/utility/nodeIdentity.d.ts +9 -0
  480. package/dist/utility/nodeIdentity.js +58 -0
  481. package/dist/utility/nodeIdentity.js.map +1 -0
  482. package/dist/utility/npmUtilities.js +11 -7
  483. package/dist/utility/npmUtilities.js.map +1 -1
  484. package/dist/utility/operationPermissions.d.ts +3 -1
  485. package/dist/utility/operationPermissions.js +16 -1
  486. package/dist/utility/operationPermissions.js.map +1 -1
  487. package/dist/utility/operation_authorization.d.ts +10 -7
  488. package/dist/utility/operation_authorization.js +212 -41
  489. package/dist/utility/operation_authorization.js.map +1 -1
  490. package/dist/utility/watchPath.d.ts +29 -0
  491. package/dist/utility/watchPath.js +68 -0
  492. package/dist/utility/watchPath.js.map +1 -0
  493. package/dist/utility/watcherFallback.d.ts +41 -0
  494. package/dist/utility/watcherFallback.js +153 -0
  495. package/dist/utility/watcherFallback.js.map +1 -1
  496. package/dist/validation/configValidator.d.ts +12 -0
  497. package/dist/validation/configValidator.js +205 -75
  498. package/dist/validation/configValidator.js.map +1 -1
  499. package/dist/validation/installValidator.js +12 -0
  500. package/dist/validation/installValidator.js.map +1 -1
  501. package/dist/validation/validationWrapper.d.ts +11 -0
  502. package/dist/validation/validationWrapper.js +16 -3
  503. package/dist/validation/validationWrapper.js.map +1 -1
  504. package/index.ts +8 -0
  505. package/json/systemSchema.json +55 -0
  506. package/npm-shrinkwrap.json +286 -194
  507. package/package.json +15 -7
  508. package/resources/DESIGN.md +219 -52
  509. package/resources/DatabaseTransaction.ts +657 -52
  510. package/resources/LMDBTransaction.ts +46 -6
  511. package/resources/PrimaryRocksDatabase.ts +46 -7
  512. package/resources/RecordEncoder.ts +124 -9
  513. package/resources/RequestTarget.ts +2 -0
  514. package/resources/Resource.ts +114 -22
  515. package/resources/ResourceInterface.ts +31 -0
  516. package/resources/RocksIndexStore.ts +30 -9
  517. package/resources/RocksTransactionLogStore.ts +188 -51
  518. package/resources/Table.ts +1960 -301
  519. package/resources/analytics/write.ts +10 -3
  520. package/resources/auditStore.ts +647 -32
  521. package/resources/blob.ts +1029 -110
  522. package/resources/branchDatabase.ts +941 -0
  523. package/resources/crdt.ts +76 -12
  524. package/resources/dataLoader.ts +3 -4
  525. package/resources/databases.ts +1584 -320
  526. package/resources/defineTable.ts +18 -2
  527. package/resources/derivedIndexRegistry.ts +56 -0
  528. package/resources/derivedIndexRuntime.ts +2292 -0
  529. package/resources/graphql.ts +72 -17
  530. package/resources/indexes/HierarchicalNavigableSmallWorld.ts +911 -48
  531. package/resources/indexes/hnswDerivedIndex.ts +531 -0
  532. package/resources/indexes/hnswPlaneBinding.ts +174 -0
  533. package/resources/longLivedTransactions.ts +360 -0
  534. package/resources/models/backendRegistry.ts +84 -2
  535. package/resources/models/bootstrap.ts +473 -28
  536. package/resources/nodeIdMapping.ts +50 -0
  537. package/resources/recordLock.ts +419 -0
  538. package/resources/recordLockCoordinator.ts +3043 -0
  539. package/resources/replayLogs.ts +152 -26
  540. package/resources/replayLogsGuards.ts +171 -8
  541. package/resources/replicatedApplyFailure.ts +77 -0
  542. package/resources/scheduler/scheduler.ts +4 -4
  543. package/resources/search.ts +288 -46
  544. package/resources/tracked.ts +73 -22
  545. package/resources/transactionBroadcast.ts +3 -3
  546. package/security/auth.ts +68 -29
  547. package/security/authn/oidc/claims.ts +72 -0
  548. package/security/authn/oidc/identityToken.ts +129 -0
  549. package/security/authn/oidc/jwks.ts +260 -0
  550. package/security/authn/oidc/providers/generic.ts +40 -0
  551. package/security/authn/oidc/providers/githubActions.ts +137 -0
  552. package/security/authn/oidc/providers/index.ts +52 -0
  553. package/security/authn/oidc/tokenExchange.ts +300 -0
  554. package/security/authn/oidc/trustPolicyOperations.ts +343 -0
  555. package/security/authn/oidc/types.ts +41 -0
  556. package/security/certificateVerification/index.ts +54 -13
  557. package/security/certificateVerification/trustedIssuers.ts +76 -0
  558. package/security/certificateVerification/types.ts +1 -0
  559. package/security/credentialProvenance.ts +47 -0
  560. package/security/credentialRejection.ts +22 -0
  561. package/security/deferredAuthentication.ts +71 -0
  562. package/security/impersonation.ts +117 -12
  563. package/security/jsLoader.ts +83 -18
  564. package/security/keys.ts +298 -72
  565. package/security/operationScope.ts +33 -0
  566. package/security/permissionsTranslator.js +23 -0
  567. package/security/tokenAuthentication.ts +233 -12
  568. package/security/user.ts +4 -3
  569. package/server/DESIGN.md +194 -16
  570. package/server/DurableSubscriptionsSession.ts +71 -11
  571. package/server/REST.ts +115 -4
  572. package/server/graphqlQuerying.ts +4 -0
  573. package/server/http.ts +133 -20
  574. package/server/itc/serverHandlers.js +8 -1
  575. package/server/jobs/jobProcess.ts +8 -2
  576. package/server/jobs/jobs.ts +4 -1
  577. package/server/liveSubscriptionAuth.ts +129 -46
  578. package/server/loadRootComponents.js +50 -8
  579. package/server/mqtt.ts +179 -38
  580. package/server/nodeName.ts +103 -21
  581. package/server/serverHelpers/Headers.ts +135 -0
  582. package/server/serverHelpers/NodeAdapterResponse.ts +221 -0
  583. package/server/serverHelpers/Request.ts +33 -131
  584. package/server/serverHelpers/contentTypes.ts +217 -36
  585. package/server/serverHelpers/deployValidationState.ts +24 -13
  586. package/server/serverHelpers/operationAuthorizationState.ts +34 -3
  587. package/server/serverHelpers/registeredOperations.ts +79 -22
  588. package/server/serverHelpers/requestSanitization.ts +15 -0
  589. package/server/serverHelpers/serverHandlers.js +6 -3
  590. package/server/serverHelpers/serverUtilities.ts +232 -40
  591. package/server/serverHelpers/sharedMessageEncoding.ts +307 -0
  592. package/server/serverHelpers/uwsServer.ts +17 -2
  593. package/server/static.ts +23 -29
  594. package/server/storageReclamation.ts +15 -2
  595. package/server/threads/isolatedApplications.ts +157 -0
  596. package/server/threads/itc.js +11 -1
  597. package/server/threads/logRotationTransport.ts +40 -0
  598. package/server/threads/manageThreads.js +771 -66
  599. package/server/threads/socketRouter.ts +291 -30
  600. package/server/threads/threadHeapMemory.ts +26 -0
  601. package/server/threads/threadServer.js +73 -22
  602. package/sqlTranslator/index.ts +31 -8
  603. package/studio/web/assets/{Chat-4RrB5134.js → Chat-D3j-1yY1.js} +1 -1
  604. package/studio/web/assets/{FloatingChat-omlNMDcJ.js → FloatingChat-BxJGYcfB.js} +3 -3
  605. package/studio/web/assets/{apiToken-Bke3wvfZ.js → apiToken-CT55oWOe.js} +1 -1
  606. package/studio/web/assets/{applications-DvFDYJgK.js → applications-D9Ct9_vm.js} +1 -1
  607. package/studio/web/assets/{cssMode-C1vRa7zh.js → cssMode-DV8H7VwA.js} +1 -1
  608. package/studio/web/assets/{editor-3XRWEDWX.js → editor-uatc0unt.js} +1 -1
  609. package/studio/web/assets/{html-CTY5tdMr.js → html-Bm6D6paN.js} +1 -1
  610. package/studio/web/assets/{htmlMode-CG1vSD9t.js → htmlMode-CEn7tpLG.js} +1 -1
  611. package/studio/web/assets/{index-Dfpeofdu.js → index-BIXW6Pu4.js} +5 -5
  612. package/studio/web/assets/{index.lazy-B1VOIv-t.js → index.lazy-UI7L-Vrk.js} +1 -1
  613. package/studio/web/assets/{javascript-CJeJzGnI.js → javascript-CJ0G3AFZ.js} +1 -1
  614. package/studio/web/assets/{jsonMode-CYPBwM82.js → jsonMode-DQADAYEa.js} +1 -1
  615. package/studio/web/assets/{languageServices-IKH4GUHl.js → languageServices-CAQJXWcI.js} +1 -1
  616. package/studio/web/assets/{lspLanguageFeatures-BC8_gxKG.js → lspLanguageFeatures-CCQ8P5sY.js} +1 -1
  617. package/studio/web/assets/{notifications-BfKBpYcq.js → notifications-BbxTU6Aw.js} +1 -1
  618. package/studio/web/assets/{notifications-DFbArTfC.js → notifications-Cvb3P1lB.js} +1 -1
  619. package/studio/web/assets/{profile-Q4-T6c-S.js → profile-Yyb7gsvL.js} +1 -1
  620. package/studio/web/assets/{regions-CtkV0xje.js → regions-OgjGHlU5.js} +1 -1
  621. package/studio/web/assets/{register-1ZZuMsiA.js → register-6qwNEOY3.js} +2 -2
  622. package/studio/web/assets/{setComponentFile-ZWLcWv5X.js → setComponentFile-BilDMtgB.js} +1 -1
  623. package/studio/web/assets/{setup-DWprJyJy.js → setup-J6qJ7OIU.js} +2 -2
  624. package/studio/web/assets/{status--aNm8isn.js → status-0RWGcfyD.js} +1 -1
  625. package/studio/web/assets/{toggleHighContrast-Cq_lt3XD.js → toggleHighContrast-BIn-vErT.js} +1 -1
  626. package/studio/web/assets/{tsMode-pjgytARx.js → tsMode-DgUXku4d.js} +1 -1
  627. package/studio/web/assets/{typescript-Cdg0mqUh.js → typescript-C9orXcsM.js} +1 -1
  628. package/studio/web/assets/{useEntityRestURL-RZhaY8Rn.js → useEntityRestURL-BEoXXbUB.js} +1 -1
  629. package/studio/web/assets/{workers-BgoXIqQe.js → workers-JVzSDmgx.js} +1 -1
  630. package/studio/web/assets/{xml-BwSeDMiP.js → xml-Cq-S8S4X.js} +1 -1
  631. package/studio/web/assets/{yaml-DotCUG5l.js → yaml-sfoRdh1M.js} +1 -1
  632. package/studio/web/index.html +1 -1
  633. package/upgrade/directives/5-3-0.ts +132 -0
  634. package/upgrade/directives/directivesController.ts +2 -1
  635. package/utility/OperationFunctionCaller.ts +2 -1
  636. package/utility/common_utils.ts +30 -5
  637. package/utility/componentNames.ts +12 -0
  638. package/utility/environment/environmentManager.ts +3 -7
  639. package/utility/environment/systemInformation.ts +7 -0
  640. package/utility/errors/commonErrors.ts +4 -0
  641. package/utility/errors/hdbError.ts +57 -0
  642. package/utility/hdbTerms.ts +19 -0
  643. package/utility/logging/harper_logger.ts +278 -26
  644. package/utility/logging/logGenerationCoordinator.ts +196 -0
  645. package/utility/logging/logRotation.ts +367 -0
  646. package/utility/logging/logRotator.ts +213 -81
  647. package/utility/nodeIdentity.ts +45 -0
  648. package/utility/npmUtilities.ts +12 -8
  649. package/utility/operationPermissions.ts +18 -1
  650. package/utility/operation_authorization.ts +231 -42
  651. package/utility/watchPath.ts +63 -0
  652. package/utility/watcherFallback.ts +148 -0
  653. package/validation/configValidator.ts +215 -75
  654. package/validation/installValidator.ts +15 -0
  655. package/validation/validationWrapper.ts +18 -4
@@ -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).
@@ -198,6 +398,10 @@ class HierarchicalNavigableSmallWorld {
198
398
  // a value of 1 is extremely aggressive.
199
399
  optimizeRouting = 0.5;
200
400
  nodesVisitedCount = 0;
401
+ // Test seam: source of randomness for level assignment. Tests that assert exact result-set
402
+ // equality across search strategies replace this with a seeded PRNG so the graph shape is
403
+ // reproducible; greedy routing legitimately diverges on rare unlucky graphs otherwise.
404
+ random = Math.random;
201
405
  // Visit-budget multiplier for predicate-aware traversal (#1241). Under-filled filtered searches
202
406
  // stop after the resolved budget ef * filterExpansion visits; automatic search ef contributes at
203
407
  // most AUTO_EF_MAX, while explicit schema/query ef remains authoritative. A filter that fills its
@@ -219,6 +423,22 @@ class HierarchicalNavigableSmallWorld {
219
423
  convertedNodes = new WeakMap();
220
424
  nodeCount = 0;
221
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;
222
442
  constructor(indexStore, options) {
223
443
  this.indexStore = indexStore;
224
444
  if (indexStore) {
@@ -226,10 +446,16 @@ class HierarchicalNavigableSmallWorld {
226
446
  // (we would actually like to use float16 if it were available)
227
447
  this.indexStore.encoder.useFloat32 = msgpackr_1.FLOAT32_OPTIONS.ALWAYS;
228
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;
229
455
  this.int8 = options?.quantization !== 'none';
230
456
  // Respect an explicitly-configured ef (efConstruction seeds the search ef too); otherwise auto-scale both.
231
- this.efSearchConfigured = options?.efConstructionSearch !== undefined || options?.efConstruction !== undefined;
232
- this.efConstructionConfigured = options?.efConstruction !== undefined;
457
+ this.efSearchConfigured = configuredEfConstructionSearch !== undefined || configuredEfConstruction !== undefined;
458
+ this.efConstructionConfigured = configuredEfConstruction !== undefined;
233
459
  this.distance =
234
460
  options?.distance === 'euclidean'
235
461
  ? vector_ts_1.euclideanDistance
@@ -238,23 +464,499 @@ class HierarchicalNavigableSmallWorld {
238
464
  : vector_ts_1.cosineDistance;
239
465
  if (options) {
240
466
  // allow all the HNSW parameters to be configured/tuned
241
- if (options.M !== undefined) {
242
- this.M = options.M;
467
+ if (configuredM !== undefined) {
468
+ this.M = configuredM;
243
469
  this.mL = 1 / Math.log(this.M); // recalculate
244
470
  }
245
- if (options.efConstruction !== undefined)
246
- this.efConstruction = this.efConstructionSearch = options.efConstruction;
247
- if (options.efConstructionSearch !== undefined)
248
- this.efConstructionSearch = options.efConstructionSearch;
249
- if (options.mL !== undefined)
250
- this.mL = options.mL;
251
- if (options.optimizeRouting !== undefined)
252
- this.optimizeRouting = options.optimizeRouting;
253
- if (options.filterExpansion !== undefined)
254
- 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;
255
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();
256
950
  }
257
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
+ }
258
960
  // Reject non-finite components before touching the graph. NaN in particular poisons
259
961
  // bisectInsert (arr[mid].distance <= NaN is always false → returns 0, pinning the
260
962
  // candidate to rank 1 of every future search). Infinity causes analogous ordering
@@ -331,7 +1033,7 @@ class HierarchicalNavigableSmallWorld {
331
1033
  const storedScale = q ? q.scale : undefined;
332
1034
  let entryPoint = entryPointId && this.safeGetSync(entryPointId, options);
333
1035
  if (entryPoint == null) {
334
- const level = Math.floor(-Math.log(Math.random()) * this.mL);
1036
+ const level = Math.min(Math.floor(-Math.log(this.random()) * this.mL), MAX_LEVEL);
335
1037
  const node = {
336
1038
  vector: storedVector,
337
1039
  scale: storedScale,
@@ -351,7 +1053,7 @@ class HierarchicalNavigableSmallWorld {
351
1053
  return;
352
1054
  }
353
1055
  // Generate random level for this new element
354
- const level = oldNode.level ?? Math.min(Math.floor(-Math.log(Math.random()) * this.mL), MAX_LEVEL);
1056
+ const level = oldNode.level ?? Math.min(Math.floor(-Math.log(this.random()) * this.mL), MAX_LEVEL);
355
1057
  let currentLevel = entryPoint.level;
356
1058
  if (level > currentLevel) {
357
1059
  // if we are at a higher level, make this the new entry point
@@ -500,14 +1202,15 @@ class HierarchicalNavigableSmallWorld {
500
1202
  }
501
1203
  }
502
1204
  // Store the new element
503
- this.indexStore.put(nodeId, {
1205
+ const storedNode = {
504
1206
  vector: storedVector,
505
1207
  scale: storedScale,
506
1208
  invMag,
507
1209
  level,
508
1210
  primaryKey,
509
1211
  ...connections,
510
- }, options);
1212
+ };
1213
+ this.indexStore.put(nodeId, storedNode, options);
511
1214
  }
512
1215
  else {
513
1216
  // removal of this node, but first make sure we have a valid entry point
@@ -818,8 +1521,10 @@ class HierarchicalNavigableSmallWorld {
818
1521
  throw error;
819
1522
  }
820
1523
  }
821
- /** 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. */
822
1525
  resolveNodeCount(options) {
1526
+ if (this.filePrimary)
1527
+ return this.getPlane()?.idHighWater() ?? 0;
823
1528
  if (this.idIncrementer)
824
1529
  return Number(Atomics.load(this.idIncrementer, 0));
825
1530
  try {
@@ -1067,24 +1772,17 @@ class HierarchicalNavigableSmallWorld {
1067
1772
  * This the main entry from Harper's query functionality, where we actually search for an ordered list of nearest
1068
1773
  * neighbors, using the provided sort/order definition object and performing the multi-layer skip-list search.
1069
1774
  * This returns an iterable of the nearest neighbors to the provided target vector, with nearest ordered first.
1070
- * @param target
1071
- * @param value
1072
- * @param descending
1073
- * @param distance
1074
- * @param comparator
1075
- * @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`
1076
1783
  */
1077
- search({ target, value, descending, distance, comparator, ef, filterExpansion, }, context,
1078
- // Predicate-aware traversal (#1241). When provided, only nodes for which `filter(primaryKey)`
1079
- // returns true are admitted to the result list at layer 0; routing is unaffected. Composed by
1080
- // search.ts from companion AND conditions and caller-supplied vector/row filters. Must be
1081
- // synchronous and side-effect free. JS-API only (never from a REST query string).
1082
- filter,
1083
- // offset + limit for a bounded query. A layer-0 search returns at most `ef` candidates, so a
1084
- // query asking for more rows than that used to come back short with no error — capped at 512
1085
- // (AUTO_EF_MAX) however large the limit was. Raising ef to cover the request keeps `limit`
1086
- // meaningful; the caller pays for what it asked for.
1087
- 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;
1088
1786
  let limit; // only set for threshold comparators; 0 is a valid threshold (e.g. dotProduct)
1089
1787
  let limitInclusive = false; // true for `le`, false for `lt`
1090
1788
  switch (comparator) {
@@ -1120,7 +1818,18 @@ class HierarchicalNavigableSmallWorld {
1120
1818
  throw new hdbError_ts_1.ClientError('A target vector must be provided for an HNSW query');
1121
1819
  if (!Array.isArray(target))
1122
1820
  throw new hdbError_ts_1.ClientError('The target vector must be an array');
1123
- 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
1124
1833
  // Resolve search ef: per-query ef wins; else use the schema-pinned value (from either ef option);
1125
1834
  // otherwise auto-scale with the graph size so recall holds as the table grows.
1126
1835
  let effectiveEf = this.efConstructionSearch;
@@ -1163,7 +1872,109 @@ class HierarchicalNavigableSmallWorld {
1163
1872
  filterEvaluations: 0,
1164
1873
  }
1165
1874
  : undefined;
1166
- 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);
1167
1978
  if (!entryPoint)
1168
1979
  return withStats([], filterState);
1169
1980
  let entryPointId = entryPoint.id;
@@ -1176,7 +1987,7 @@ class HierarchicalNavigableSmallWorld {
1176
1987
  // nodes) rather than to ef. See DESIGN.md.
1177
1988
  for (let l = entryPoint.level; l >= 0; l--) {
1178
1989
  // Search for closest neighbors at current level
1179
- 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);
1180
1991
  if (results.length > 0) {
1181
1992
  const neighbor = results[0]; // closest neighbor becomes new entry point
1182
1993
  entryPoint = neighbor.node;
@@ -1185,6 +1996,8 @@ class HierarchicalNavigableSmallWorld {
1185
1996
  }
1186
1997
  if (limit !== undefined)
1187
1998
  results = results.filter((candidate) => limitInclusive ? candidate.distance <= limit : candidate.distance < limit);
1999
+ if (results.length > rerankK)
2000
+ results = results.slice(0, rerankK);
1188
2001
  return withStats(results.map((candidate) => ({
1189
2002
  // we return the result as an entry so we can provide distance as metadata
1190
2003
  key: candidate.node.primaryKey, // return value