@harperfast/harper 5.3.0-alpha.1 → 5.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cliOperations.ts +12 -0
- package/bin/restart.ts +66 -6
- package/components/Application.ts +1134 -112
- package/components/DESIGN.md +421 -0
- package/components/OptionsWatcher.ts +368 -102
- package/components/Scope.ts +20 -1
- package/components/componentLoader.ts +43 -4
- package/components/deploymentOperations.ts +4 -1
- package/components/deploymentRecorder.ts +9 -2
- package/components/mcp/DESIGN.md +109 -0
- package/components/mcp/audit.ts +21 -17
- package/components/operations.js +284 -52
- package/components/operationsValidation.js +49 -2
- package/components/packageComponent.ts +25 -1
- package/components/requestRestart.ts +11 -0
- package/config/DESIGN.md +306 -0
- package/config/RootConfigWatcher.ts +191 -37
- package/config/configReadRetry.ts +62 -0
- package/config/configUtils.ts +78 -26
- package/config/parseConfigFile.ts +34 -0
- package/config/readConfigFileSync.ts +44 -0
- package/config/watcherArming.ts +59 -0
- package/config-root.schema.json +4 -0
- package/dataLayer/DESIGN.md +179 -0
- package/dataLayer/harperBridge/ResourceBridge.ts +28 -2
- package/dataLayer/restoreMarker.ts +92 -25
- package/dist/bin/cliOperations.js +13 -0
- package/dist/bin/cliOperations.js.map +1 -1
- package/dist/bin/restart.js +42 -6
- package/dist/bin/restart.js.map +1 -1
- package/dist/components/Application.d.ts +104 -9
- package/dist/components/Application.js +954 -102
- package/dist/components/Application.js.map +1 -1
- package/dist/components/OptionsWatcher.d.ts +4 -1
- package/dist/components/OptionsWatcher.js +378 -104
- package/dist/components/OptionsWatcher.js.map +1 -1
- package/dist/components/Scope.js +15 -1
- package/dist/components/Scope.js.map +1 -1
- package/dist/components/componentLoader.js +35 -3
- package/dist/components/componentLoader.js.map +1 -1
- package/dist/components/deploymentOperations.js +4 -1
- package/dist/components/deploymentOperations.js.map +1 -1
- package/dist/components/deploymentRecorder.d.ts +4 -2
- package/dist/components/deploymentRecorder.js +1 -0
- package/dist/components/deploymentRecorder.js.map +1 -1
- package/dist/components/mcp/audit.d.ts +2 -1
- package/dist/components/mcp/audit.js +21 -17
- package/dist/components/mcp/audit.js.map +1 -1
- package/dist/components/operations.d.ts +28 -0
- package/dist/components/operations.js +263 -54
- package/dist/components/operations.js.map +1 -1
- package/dist/components/operationsValidation.js +48 -2
- package/dist/components/operationsValidation.js.map +1 -1
- package/dist/components/packageComponent.js +24 -0
- package/dist/components/packageComponent.js.map +1 -1
- package/dist/components/requestRestart.d.ts +1 -0
- package/dist/components/requestRestart.js +7 -0
- package/dist/components/requestRestart.js.map +1 -1
- package/dist/config/RootConfigWatcher.d.ts +2 -0
- package/dist/config/RootConfigWatcher.js +189 -35
- package/dist/config/RootConfigWatcher.js.map +1 -1
- package/dist/config/configReadRetry.d.ts +8 -0
- package/dist/config/configReadRetry.js +62 -0
- package/dist/config/configReadRetry.js.map +1 -0
- package/dist/config/configUtils.d.ts +10 -9
- package/dist/config/configUtils.js +63 -27
- package/dist/config/configUtils.js.map +1 -1
- package/dist/config/parseConfigFile.d.ts +4 -0
- package/dist/config/parseConfigFile.js +35 -0
- package/dist/config/parseConfigFile.js.map +1 -0
- package/dist/config/readConfigFileSync.d.ts +1 -0
- package/dist/config/readConfigFileSync.js +47 -0
- package/dist/config/readConfigFileSync.js.map +1 -0
- package/dist/config/watcherArming.d.ts +15 -0
- package/dist/config/watcherArming.js +59 -0
- package/dist/config/watcherArming.js.map +1 -0
- package/dist/dataLayer/harperBridge/ResourceBridge.js +21 -2
- package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
- package/dist/dataLayer/restoreMarker.d.ts +21 -8
- package/dist/dataLayer/restoreMarker.js +94 -27
- package/dist/dataLayer/restoreMarker.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +9 -1
- package/dist/index.js.map +1 -1
- package/dist/json/systemSchema.json +3 -0
- package/dist/resources/DatabaseTransaction.d.ts +25 -0
- package/dist/resources/DatabaseTransaction.js +224 -18
- package/dist/resources/DatabaseTransaction.js.map +1 -1
- package/dist/resources/LMDBTransaction.d.ts +2 -1
- package/dist/resources/LMDBTransaction.js +22 -3
- package/dist/resources/LMDBTransaction.js.map +1 -1
- package/dist/resources/PrimaryRocksDatabase.js +22 -6
- package/dist/resources/PrimaryRocksDatabase.js.map +1 -1
- package/dist/resources/RecordEncoder.d.ts +1 -1
- package/dist/resources/RecordEncoder.js +46 -10
- package/dist/resources/RecordEncoder.js.map +1 -1
- package/dist/resources/Resource.js +97 -13
- package/dist/resources/Resource.js.map +1 -1
- package/dist/resources/ResourceInterface.d.ts +8 -0
- package/dist/resources/RocksIndexStore.js +2 -1
- package/dist/resources/RocksIndexStore.js.map +1 -1
- package/dist/resources/RocksTransactionLogStore.d.ts +10 -0
- package/dist/resources/RocksTransactionLogStore.js +104 -33
- package/dist/resources/RocksTransactionLogStore.js.map +1 -1
- package/dist/resources/Table.d.ts +58 -7
- package/dist/resources/Table.js +1143 -348
- package/dist/resources/Table.js.map +1 -1
- package/dist/resources/analytics/write.d.ts +3 -0
- package/dist/resources/analytics/write.js +49 -16
- package/dist/resources/analytics/write.js.map +1 -1
- package/dist/resources/auditStore.d.ts +170 -0
- package/dist/resources/auditStore.js +457 -11
- package/dist/resources/auditStore.js.map +1 -1
- package/dist/resources/crdt.d.ts +10 -0
- package/dist/resources/crdt.js +22 -0
- package/dist/resources/crdt.js.map +1 -1
- package/dist/resources/dataLoader.js +3 -4
- package/dist/resources/dataLoader.js.map +1 -1
- package/dist/resources/databases.d.ts +16 -13
- package/dist/resources/databases.js +625 -177
- package/dist/resources/databases.js.map +1 -1
- package/dist/resources/derivedIndexRegistry.d.ts +5 -0
- package/dist/resources/derivedIndexRegistry.js +68 -0
- package/dist/resources/derivedIndexRegistry.js.map +1 -0
- package/dist/resources/derivedIndexRuntime.d.ts +215 -0
- package/dist/resources/derivedIndexRuntime.js +2027 -0
- package/dist/resources/derivedIndexRuntime.js.map +1 -0
- package/dist/resources/graphql.js +3 -2
- package/dist/resources/graphql.js.map +1 -1
- package/dist/resources/indexes/HierarchicalNavigableSmallWorld.d.ts +102 -9
- package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js +867 -39
- package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js.map +1 -1
- package/dist/resources/indexes/fullTextDerivedIndex.d.ts +81 -0
- package/dist/resources/indexes/fullTextDerivedIndex.js +1004 -0
- package/dist/resources/indexes/fullTextDerivedIndex.js.map +1 -0
- package/dist/resources/indexes/fullTextNativeBinding.d.ts +78 -0
- package/dist/resources/indexes/fullTextNativeBinding.js +85 -0
- package/dist/resources/indexes/fullTextNativeBinding.js.map +1 -0
- package/dist/resources/indexes/hnswDerivedIndex.d.ts +67 -0
- package/dist/resources/indexes/hnswDerivedIndex.js +464 -0
- package/dist/resources/indexes/hnswDerivedIndex.js.map +1 -0
- package/dist/resources/indexes/hnswPlaneBinding.d.ts +65 -0
- package/dist/resources/indexes/hnswPlaneBinding.js +91 -0
- package/dist/resources/indexes/hnswPlaneBinding.js.map +1 -0
- package/dist/resources/indexes/nativeFullTextDerivedIndexLifecycle.d.ts +24 -0
- package/dist/resources/indexes/nativeFullTextDerivedIndexLifecycle.js +149 -0
- package/dist/resources/indexes/nativeFullTextDerivedIndexLifecycle.js.map +1 -0
- package/dist/resources/nodeIdMapping.d.ts +5 -0
- package/dist/resources/nodeIdMapping.js +49 -0
- package/dist/resources/nodeIdMapping.js.map +1 -1
- package/dist/resources/recordLock.d.ts +47 -4
- package/dist/resources/recordLock.js +138 -7
- package/dist/resources/recordLock.js.map +1 -1
- package/dist/resources/recordLockCoordinator.d.ts +557 -0
- package/dist/resources/recordLockCoordinator.js +2597 -0
- package/dist/resources/recordLockCoordinator.js.map +1 -0
- package/dist/resources/replayLogs.js +5 -0
- package/dist/resources/replayLogs.js.map +1 -1
- package/dist/resources/replicatedApplyFailure.d.ts +16 -0
- package/dist/resources/replicatedApplyFailure.js +63 -0
- package/dist/resources/replicatedApplyFailure.js.map +1 -0
- package/dist/resources/scheduler/scheduler.js +3 -3
- package/dist/resources/scheduler/scheduler.js.map +1 -1
- package/dist/resources/search.d.ts +10 -4
- package/dist/resources/search.js +160 -40
- package/dist/resources/search.js.map +1 -1
- package/dist/resources/tracked.d.ts +5 -1
- package/dist/resources/tracked.js +74 -23
- package/dist/resources/tracked.js.map +1 -1
- package/dist/resources/transactionBroadcast.js +4 -6
- package/dist/resources/transactionBroadcast.js.map +1 -1
- package/dist/security/auth.js +59 -23
- package/dist/security/auth.js.map +1 -1
- package/dist/security/deferredAuthentication.d.ts +11 -0
- package/dist/security/deferredAuthentication.js +25 -3
- package/dist/security/deferredAuthentication.js.map +1 -1
- package/dist/security/jsLoader.js +9 -4
- package/dist/security/jsLoader.js.map +1 -1
- package/dist/server/REST.js +39 -5
- package/dist/server/REST.js.map +1 -1
- package/dist/server/http.d.ts +5 -1
- package/dist/server/http.js +34 -2
- package/dist/server/http.js.map +1 -1
- package/dist/server/mqtt.js +5 -1
- package/dist/server/mqtt.js.map +1 -1
- package/dist/server/serverHelpers/Headers.d.ts +2 -0
- package/dist/server/serverHelpers/Headers.js +6 -0
- package/dist/server/serverHelpers/Headers.js.map +1 -1
- package/dist/server/serverHelpers/NodeAdapterResponse.d.ts +48 -0
- package/dist/server/serverHelpers/NodeAdapterResponse.js +220 -0
- package/dist/server/serverHelpers/NodeAdapterResponse.js.map +1 -0
- package/dist/server/serverHelpers/Request.d.ts +5 -10
- package/dist/server/serverHelpers/Request.js +38 -136
- package/dist/server/serverHelpers/Request.js.map +1 -1
- package/dist/server/serverHelpers/contentTypes.d.ts +2 -0
- package/dist/server/serverHelpers/contentTypes.js +189 -15
- package/dist/server/serverHelpers/contentTypes.js.map +1 -1
- package/dist/server/serverHelpers/serverUtilities.d.ts +3 -3
- package/dist/server/serverHelpers/serverUtilities.js +110 -20
- package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
- package/dist/server/serverHelpers/uwsServer.js +4 -1
- package/dist/server/serverHelpers/uwsServer.js.map +1 -1
- package/dist/server/serverHelpers/webSocketCloseReason.d.ts +2 -0
- package/dist/server/serverHelpers/webSocketCloseReason.js +29 -0
- package/dist/server/serverHelpers/webSocketCloseReason.js.map +1 -0
- package/dist/server/storageReclamation.js +1 -1
- package/dist/server/storageReclamation.js.map +1 -1
- package/dist/server/threads/isolatedApplications.d.ts +47 -0
- package/dist/server/threads/isolatedApplications.js +171 -0
- package/dist/server/threads/isolatedApplications.js.map +1 -0
- package/dist/server/threads/logRotationTransport.d.ts +1 -0
- package/dist/server/threads/logRotationTransport.js +33 -0
- package/dist/server/threads/logRotationTransport.js.map +1 -0
- package/dist/server/threads/manageThreads.d.ts +64 -6
- package/dist/server/threads/manageThreads.js +261 -12
- package/dist/server/threads/manageThreads.js.map +1 -1
- package/dist/server/threads/socketRouter.d.ts +1 -0
- package/dist/server/threads/socketRouter.js +196 -13
- package/dist/server/threads/socketRouter.js.map +1 -1
- package/dist/server/threads/threadServer.js +30 -7
- package/dist/server/threads/threadServer.js.map +1 -1
- package/dist/utility/errors/hdbError.d.ts +24 -0
- package/dist/utility/errors/hdbError.js +58 -1
- package/dist/utility/errors/hdbError.js.map +1 -1
- package/dist/utility/hdbTerms.d.ts +2 -0
- package/dist/utility/hdbTerms.js +2 -0
- package/dist/utility/hdbTerms.js.map +1 -1
- package/dist/utility/logging/harper_logger.js +218 -38
- package/dist/utility/logging/harper_logger.js.map +1 -1
- package/dist/utility/logging/logGenerationCoordinator.d.ts +35 -0
- package/dist/utility/logging/logGenerationCoordinator.js +184 -0
- package/dist/utility/logging/logGenerationCoordinator.js.map +1 -0
- package/dist/utility/logging/logRotation.d.ts +46 -0
- package/dist/utility/logging/logRotation.js +365 -0
- package/dist/utility/logging/logRotation.js.map +1 -0
- package/dist/utility/logging/logRotator.d.ts +1 -1
- package/dist/utility/logging/logRotator.js +172 -92
- package/dist/utility/logging/logRotator.js.map +1 -1
- package/dist/utility/npmUtilities.js +6 -4
- package/dist/utility/npmUtilities.js.map +1 -1
- package/dist/utility/watcherFallback.d.ts +0 -45
- package/dist/utility/watcherFallback.js +1 -125
- package/dist/utility/watcherFallback.js.map +1 -1
- package/dist/validation/configValidator.js +6 -3
- package/dist/validation/configValidator.js.map +1 -1
- package/index.ts +9 -0
- package/json/systemSchema.json +3 -0
- package/npm-shrinkwrap.json +177 -87
- package/package.json +13 -5
- package/resources/DESIGN.md +689 -19
- package/resources/DatabaseTransaction.ts +230 -17
- package/resources/LMDBTransaction.ts +21 -3
- package/resources/PrimaryRocksDatabase.ts +20 -7
- package/resources/RecordEncoder.ts +52 -10
- package/resources/Resource.ts +97 -13
- package/resources/ResourceInterface.ts +8 -0
- package/resources/RocksIndexStore.ts +2 -1
- package/resources/RocksTransactionLogStore.ts +111 -31
- package/resources/Table.ts +1273 -396
- package/resources/analytics/DESIGN.md +38 -0
- package/resources/analytics/write.ts +50 -17
- package/resources/auditStore.ts +460 -11
- package/resources/crdt.ts +22 -0
- package/resources/dataLoader.ts +3 -4
- package/resources/databases.ts +611 -147
- package/resources/derivedIndexRegistry.ts +56 -0
- package/resources/derivedIndexRuntime.ts +2292 -0
- package/resources/graphql.ts +3 -2
- package/resources/indexes/DESIGN.md +833 -0
- package/resources/indexes/HierarchicalNavigableSmallWorld.ts +924 -46
- package/resources/indexes/fullTextDerivedIndex.ts +1165 -0
- package/resources/indexes/fullTextNativeBinding.ts +146 -0
- package/resources/indexes/hnswDerivedIndex.ts +531 -0
- package/resources/indexes/hnswPlaneBinding.ts +174 -0
- package/resources/indexes/nativeFullTextDerivedIndexLifecycle.ts +181 -0
- package/resources/nodeIdMapping.ts +50 -0
- package/resources/record-locks.md +1407 -0
- package/resources/recordLock.ts +173 -7
- package/resources/recordLockCoordinator.ts +3082 -0
- package/resources/replayLogs.ts +5 -0
- package/resources/replicatedApplyFailure.ts +77 -0
- package/resources/scheduler/DESIGN.md +40 -0
- package/resources/scheduler/scheduler.ts +4 -4
- package/resources/search.ts +169 -49
- package/resources/tracked.ts +73 -22
- package/resources/transactionBroadcast.ts +4 -4
- package/security/DESIGN.md +175 -0
- package/security/auth.ts +53 -24
- package/security/deferredAuthentication.ts +24 -2
- package/security/jsLoader.ts +9 -4
- package/server/DESIGN.md +275 -0
- package/server/REST.ts +42 -6
- package/server/http.ts +34 -2
- package/server/mqtt.ts +6 -4
- package/server/serverHelpers/Headers.ts +5 -1
- package/server/serverHelpers/NodeAdapterResponse.ts +221 -0
- package/server/serverHelpers/Request.ts +33 -131
- package/server/serverHelpers/contentTypes.ts +188 -15
- package/server/serverHelpers/serverUtilities.ts +157 -27
- package/server/serverHelpers/uwsServer.ts +4 -1
- package/server/serverHelpers/webSocketCloseReason.ts +25 -0
- package/server/storageReclamation.ts +2 -2
- package/server/threads/isolatedApplications.ts +157 -0
- package/server/threads/logRotationTransport.ts +40 -0
- package/server/threads/manageThreads.js +254 -12
- package/server/threads/socketRouter.ts +217 -11
- package/server/threads/threadServer.js +30 -7
- package/studio/web/assets/{Chat-BnCBegQz.js → Chat-DADFFGe_.js} +1 -1
- package/studio/web/assets/{FloatingChat-CoDW1ySS.js → FloatingChat-D_mI-rZ7.js} +3 -3
- package/studio/web/assets/{apiToken-Bwk5BLXW.js → apiToken-c2NiSDHa.js} +1 -1
- package/studio/web/assets/{applications-DHxGi7JH.js → applications-DktUqh7G.js} +1 -1
- package/studio/web/assets/{cssMode-s0cWI-_M.js → cssMode-Cs_75Xhw.js} +1 -1
- package/studio/web/assets/{editor-DNcRHK54.js → editor-19b-Y1IN.js} +1 -1
- package/studio/web/assets/{html-Bdssedlg.js → html-DiYEQMpB.js} +1 -1
- package/studio/web/assets/{htmlMode-CoDlJ3fw.js → htmlMode-CmR0y7P_.js} +1 -1
- package/studio/web/assets/{index-D6sxmFLR.js → index-Dm0rfkJ7.js} +5 -5
- package/studio/web/assets/{index.lazy-tmU5BS8s.js → index.lazy-7vqt2CC3.js} +1 -1
- package/studio/web/assets/{javascript-B8meVSTH.js → javascript-BWtCFuOt.js} +1 -1
- package/studio/web/assets/{jsonMode-DpIPd35T.js → jsonMode-Buzzbv9y.js} +1 -1
- package/studio/web/assets/{languageServices-C_5FMJzQ.js → languageServices-SqsFWfTM.js} +1 -1
- package/studio/web/assets/{lspLanguageFeatures-BIzNBzPK.js → lspLanguageFeatures-EMV5cmjo.js} +1 -1
- package/studio/web/assets/{notifications-CvZivSbh.js → notifications-CAB-LZWT.js} +1 -1
- package/studio/web/assets/{notifications-CQf18QKb.js → notifications-DRzmSRxM.js} +1 -1
- package/studio/web/assets/{profile-DdOwtntb.js → profile-BNKAl79n.js} +1 -1
- package/studio/web/assets/{regions-n69fwagr.js → regions-CUow_Zw2.js} +1 -1
- package/studio/web/assets/{register-PfWTCXWB.js → register-Dkt3WUMp.js} +2 -2
- package/studio/web/assets/{setComponentFile-Bg6O7X0S.js → setComponentFile-BZRfMD0N.js} +1 -1
- package/studio/web/assets/{setup-CUx_aUDl.js → setup-D_yiEPO2.js} +2 -2
- package/studio/web/assets/{status-D7BVKqX9.js → status-DhHh1Ge-.js} +1 -1
- package/studio/web/assets/{toggleHighContrast-DBSyXzMr.js → toggleHighContrast-D7L1PDtV.js} +1 -1
- package/studio/web/assets/{tsMode-BByKCjBS.js → tsMode-CCwLk1YS.js} +1 -1
- package/studio/web/assets/{typescript-DDLnLpw9.js → typescript-BP1j1mjn.js} +1 -1
- package/studio/web/assets/{useEntityRestURL-31CHGaHk.js → useEntityRestURL-D7bnYxLw.js} +1 -1
- package/studio/web/assets/{workers-pR3jRY9D.js → workers-tOuCNT17.js} +1 -1
- package/studio/web/assets/{xml-2iRnMhQO.js → xml-BSG_3mQT.js} +1 -1
- package/studio/web/assets/{yaml-Bf92gJpd.js → yaml-DxiLprBB.js} +1 -1
- package/studio/web/index.html +1 -1
- package/utility/DESIGN.md +55 -0
- package/utility/errors/hdbError.ts +54 -0
- package/utility/hdbTerms.ts +2 -0
- package/utility/logging/harper_logger.ts +210 -30
- package/utility/logging/logGenerationCoordinator.ts +196 -0
- package/utility/logging/logRotation.ts +367 -0
- package/utility/logging/logRotator.ts +196 -91
- package/utility/npmUtilities.ts +6 -4
- package/utility/watcherFallback.ts +0 -122
- package/validation/configValidator.ts +6 -3
|
@@ -1,12 +1,39 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, rmSync, statSync, unlinkSync } from 'node:fs';
|
|
1
2
|
import { cosineDistance, euclideanDistance, dotProductDistance } from './vector.ts';
|
|
2
|
-
import { FLOAT32_OPTIONS } from 'msgpackr';
|
|
3
|
+
import { FLOAT32_OPTIONS, pack, unpack } from 'msgpackr';
|
|
3
4
|
import { loggerWithTag } from '../../utility/logging/logger.ts';
|
|
4
|
-
import { ClientError } from '../../utility/errors/hdbError.ts';
|
|
5
|
+
import { ClientError, ServerError, DerivedIndexLagError } from '../../utility/errors/hdbError.ts';
|
|
5
6
|
import type { Id } from '../../resources/ResourceInterface.ts';
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_MAX_INDEX_LAG_MILLISECONDS,
|
|
9
|
+
MAX_WAIT_FOR_INDEX_MILLISECONDS,
|
|
10
|
+
type DerivedNativeIndexHost,
|
|
11
|
+
} from './hnswDerivedIndex.ts';
|
|
12
|
+
import { derivedIndexTime, type DerivedIndexReadiness, type DerivedIndexCoverage } from '../derivedIndexRuntime.ts';
|
|
6
13
|
import { SKIP } from '@harperfast/extended-iterable';
|
|
14
|
+
import { RocksDatabase } from '@harperfast/rocksdb-js';
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import {
|
|
17
|
+
getPlaneBinding,
|
|
18
|
+
invalidatePlaneFile as invalidateHnswPlaneFile,
|
|
19
|
+
planeFilePathFor,
|
|
20
|
+
planeStalePathFor,
|
|
21
|
+
PLANE_NO_ID,
|
|
22
|
+
type HnswPlane,
|
|
23
|
+
type PlanePredicate,
|
|
24
|
+
type PlaneSearchHits,
|
|
25
|
+
} from './hnswPlaneBinding.ts';
|
|
7
26
|
|
|
8
27
|
const logger = loggerWithTag('HNSW');
|
|
9
28
|
|
|
29
|
+
/** Element-wise equality of the array-like projections a derived index stores; anything else that failed `===` counts as changed. */
|
|
30
|
+
export function derivedValuesEqual(a: any, b: any): boolean {
|
|
31
|
+
if (a === b) return true;
|
|
32
|
+
if (a == null || b == null || typeof a.length !== 'number' || a.length !== b.length) return false;
|
|
33
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
10
37
|
// int8 scalar quantization of stored graph nodes is ON by default. Each node holds the
|
|
11
38
|
// vector as a compact int8 `bin` plus a per-vector `scale`, roughly a 5x size reduction
|
|
12
39
|
// over float32 and ~10x cheaper to decode (a single typed-array view instead of decoding
|
|
@@ -86,6 +113,10 @@ const ROUTING_EF = 1;
|
|
|
86
113
|
// index's own auto-scaled ceiling so the worst case stays the same order. Schema and per-query ef
|
|
87
114
|
// pins are authoritative cost ceilings; only an automatically scaled index widens from `limit`.
|
|
88
115
|
const LIMIT_EF_MAX = 2 * AUTO_EF_CEILING;
|
|
116
|
+
// Rerank candidates per row a bounded nearest-neighbor query consumes, with a floor: each
|
|
117
|
+
// candidate costs a record load and an exact distance, so the rerank must not scale with ef.
|
|
118
|
+
const RERANK_FACTOR = 4;
|
|
119
|
+
const RERANK_MIN = 32;
|
|
89
120
|
// Auto-scaled construction ef, used only when an index does not explicitly configure efConstruction.
|
|
90
121
|
// At a constant efConstruction, edge quality erodes as the graph grows until true neighbours become
|
|
91
122
|
// unreachable at ANY search ef; the cap bounds per-insert cost. Measurements and policy in
|
|
@@ -105,6 +136,73 @@ function autoScaleEfConstruction(nodeCount: number): number {
|
|
|
105
136
|
// this only has to be short enough that a table growing from empty picks up a larger ef promptly.
|
|
106
137
|
const NODE_COUNT_TTL = 10_000;
|
|
107
138
|
|
|
139
|
+
// Native traversal-plane geometry (DESIGN.md § Native HNSW plane). A file-primary index builds no
|
|
140
|
+
// JS graph, so the plane header carries its only layer-0 maximum. maxNodes is a fixed sparse
|
|
141
|
+
// reservation — pages materialize on write — and ids at or past it are rejected by the crate,
|
|
142
|
+
// which disables the plane.
|
|
143
|
+
const PLANE_LAYER0_CAP = 64;
|
|
144
|
+
const PLANE_LAYER0_CAP_MAX = 1024;
|
|
145
|
+
// The crate's fixed connection count, which nativePlane pins the index to: a layer-0 cap below it
|
|
146
|
+
// could not hold a node's own forward edges.
|
|
147
|
+
const PLANE_M = 16;
|
|
148
|
+
const PLANE_MAX_NODES = 1 << 24;
|
|
149
|
+
// Default inline primary-key bytes per plane slot (msgpack-encoded); 40 fits UUIDs inside the slot
|
|
150
|
+
// padding. `nativePlaneKeyCap` raises it for tables whose keys are longer.
|
|
151
|
+
const PLANE_KEY_CAP = 40;
|
|
152
|
+
const PLANE_KEY_CAP_MAX = 65535;
|
|
153
|
+
// An existing plane file that cannot be opened is normally another worker mid-create (retry);
|
|
154
|
+
// past this age it is a crashed create and is deleted so the audit-backed runtime can rebuild it.
|
|
155
|
+
const PLANE_STALE_CREATE_MS = 60_000;
|
|
156
|
+
// Retry cadence while another worker holds the create; its header lands shortly after exclusive open.
|
|
157
|
+
const PLANE_ATTACH_RETRY_MS = 250;
|
|
158
|
+
// Marks an error thrown by an app-supplied filter during a plane search: the caller re-raises
|
|
159
|
+
// it as an ordinary query failure instead of disabling the (healthy) plane.
|
|
160
|
+
const NOT_A_PLANE_FAILURE = Symbol('notAPlaneFailure');
|
|
161
|
+
|
|
162
|
+
function numericOption(name: string, value: unknown): number | undefined {
|
|
163
|
+
if (value === undefined || value === null) return undefined;
|
|
164
|
+
if ((typeof value !== 'number' && typeof value !== 'string') || (typeof value === 'string' && value.trim() === ''))
|
|
165
|
+
throw new ClientError(`${name} must be a finite number`);
|
|
166
|
+
const numericValue = Number(value);
|
|
167
|
+
if (!Number.isFinite(numericValue)) throw new ClientError(`${name} must be a finite number`);
|
|
168
|
+
return numericValue;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function normalizeOptimizeRoutingDeclaration(value: unknown): unknown {
|
|
172
|
+
if (value === true || value === 'true') return 1;
|
|
173
|
+
if (value === false || value === 'false') return 0;
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function nativePlaneMaxNodes(options: any): number {
|
|
178
|
+
const maxNodes = numericOption('nativePlaneMaxNodes', options?.nativePlaneMaxNodes) ?? PLANE_MAX_NODES;
|
|
179
|
+
if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes >= PLANE_NO_ID) {
|
|
180
|
+
throw new ClientError('nativePlaneMaxNodes must be a positive integer below 2^32-1');
|
|
181
|
+
}
|
|
182
|
+
return maxNodes;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function nativePlaneLayer0Cap(options: any): number {
|
|
186
|
+
const layer0Cap = numericOption('nativePlaneLayer0Cap', options?.nativePlaneLayer0Cap) ?? PLANE_LAYER0_CAP;
|
|
187
|
+
if (!Number.isSafeInteger(layer0Cap) || layer0Cap < PLANE_M || layer0Cap > PLANE_LAYER0_CAP_MAX) {
|
|
188
|
+
throw new ClientError(`nativePlaneLayer0Cap must be an integer between ${PLANE_M} and ${PLANE_LAYER0_CAP_MAX}`);
|
|
189
|
+
}
|
|
190
|
+
return layer0Cap;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function nativePlaneKeyCap(options: any): number {
|
|
194
|
+
const keyCap = numericOption('nativePlaneKeyCap', options?.nativePlaneKeyCap) ?? PLANE_KEY_CAP;
|
|
195
|
+
if (!Number.isSafeInteger(keyCap) || keyCap < 8 || keyCap > PLANE_KEY_CAP_MAX) {
|
|
196
|
+
throw new ClientError('nativePlaneKeyCap must be an integer between 8 and 65535');
|
|
197
|
+
}
|
|
198
|
+
return keyCap;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function nativePlaneDefaultDisabled(): boolean {
|
|
202
|
+
const value = process.env.HNSW_NO_NATIVE_DEFAULT;
|
|
203
|
+
return value != null && value !== '' && value !== '0' && value.toLowerCase() !== 'false';
|
|
204
|
+
}
|
|
205
|
+
|
|
108
206
|
class MinHeap {
|
|
109
207
|
private data: Candidate[] = [];
|
|
110
208
|
get size() {
|
|
@@ -162,6 +260,10 @@ function bisectInsert(arr: Candidate[], distance: number): number {
|
|
|
162
260
|
*/
|
|
163
261
|
const ENTRY_POINT = Symbol.for('entryPoint');
|
|
164
262
|
const KEY_PREFIX = Symbol.for('key');
|
|
263
|
+
/** A Map key for a primary key: composite keys by their encoding, since arrays compare by reference. */
|
|
264
|
+
function pendingMappingKey(primaryKey: Id): Id {
|
|
265
|
+
return Array.isArray(primaryKey) ? `\0${pack(primaryKey).toString('latin1')}` : primaryKey;
|
|
266
|
+
}
|
|
165
267
|
const MAX_LEVEL = 10; // should give good high-level skip list performance up to trillions of nodes
|
|
166
268
|
// Visit budget for the post-delete connectivity probe (repairSeveredNeighbors, #1712). Severed
|
|
167
269
|
// islands are small (bounded by the deleted node's neighborhood), so a probe that visits this many
|
|
@@ -191,11 +293,146 @@ type Node = {
|
|
|
191
293
|
*/
|
|
192
294
|
export class HierarchicalNavigableSmallWorld {
|
|
193
295
|
static useObjectStore = true;
|
|
296
|
+
static numericOptions = new Set([
|
|
297
|
+
'M',
|
|
298
|
+
'efConstruction',
|
|
299
|
+
'efConstructionSearch',
|
|
300
|
+
'mL',
|
|
301
|
+
'optimizeRouting',
|
|
302
|
+
'filterExpansion',
|
|
303
|
+
'nativePlaneMaxNodes',
|
|
304
|
+
'nativePlaneKeyCap',
|
|
305
|
+
'nativePlaneLayer0Cap',
|
|
306
|
+
'maxLagMilliseconds',
|
|
307
|
+
]);
|
|
308
|
+
static truthyStructuralOptions = new Set(['nativePlane']);
|
|
309
|
+
static normalizeOptionValue(name: string, value: unknown): unknown {
|
|
310
|
+
if (name !== 'optimizeRouting') return value;
|
|
311
|
+
if (value === true) return 1;
|
|
312
|
+
if (value === false) return 0;
|
|
313
|
+
if (
|
|
314
|
+
typeof value === 'string' &&
|
|
315
|
+
(value === 'true' || value === 'false' || (value.trim() !== '' && Number(value) === 0))
|
|
316
|
+
)
|
|
317
|
+
// Legacy strings are truthy at runtime; keep them structurally distinct from false/0 so #1357 rebuilds.
|
|
318
|
+
return `legacy:${value}`;
|
|
319
|
+
return value;
|
|
320
|
+
}
|
|
321
|
+
static normalizeDeclarationOptions(options: any, persistedOptions?: any): void {
|
|
322
|
+
for (const name of HierarchicalNavigableSmallWorld.numericOptions) {
|
|
323
|
+
if (options[name] === undefined) continue;
|
|
324
|
+
if (persistedOptions && Object.hasOwn(persistedOptions, name) && Object.is(options[name], persistedOptions[name]))
|
|
325
|
+
continue;
|
|
326
|
+
if (
|
|
327
|
+
name === 'optimizeRouting' &&
|
|
328
|
+
typeof persistedOptions?.[name] === 'string' &&
|
|
329
|
+
options[name] !== false &&
|
|
330
|
+
options[name] !== 'false'
|
|
331
|
+
) {
|
|
332
|
+
try {
|
|
333
|
+
const declared = numericOption(name, normalizeOptimizeRoutingDeclaration(options[name]));
|
|
334
|
+
const persisted = numericOption(name, normalizeOptimizeRoutingDeclaration(persistedOptions[name]));
|
|
335
|
+
if (Object.is(declared, persisted)) {
|
|
336
|
+
options[name] = persistedOptions[name];
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
} catch {}
|
|
340
|
+
}
|
|
341
|
+
if (options[name] === null) {
|
|
342
|
+
delete options[name];
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const value = name === 'optimizeRouting' ? normalizeOptimizeRoutingDeclaration(options[name]) : options[name];
|
|
346
|
+
options[name] = numericOption(name, value);
|
|
347
|
+
}
|
|
348
|
+
if (Object.hasOwn(options, 'nativePlaneMaxNodes')) nativePlaneMaxNodes(options);
|
|
349
|
+
if (Object.hasOwn(options, 'nativePlaneKeyCap')) nativePlaneKeyCap(options);
|
|
350
|
+
if (Object.hasOwn(options, 'nativePlaneLayer0Cap')) nativePlaneLayer0Cap(options);
|
|
351
|
+
}
|
|
352
|
+
static normalizeNativePlaneDeclaration(value: unknown): boolean | undefined {
|
|
353
|
+
if (value === undefined || value === null) return undefined;
|
|
354
|
+
if (value === true || value === 'true') return true;
|
|
355
|
+
if (value === false || value === 'false') return false;
|
|
356
|
+
throw new ClientError('nativePlane must be true or false');
|
|
357
|
+
}
|
|
358
|
+
static validateNativePlaneOptions(rootStore: unknown, options: any) {
|
|
359
|
+
if (!(rootStore instanceof RocksDatabase)) {
|
|
360
|
+
throw new ClientError(
|
|
361
|
+
'nativePlane requires the RocksDB storage engine; set nativePlane: false to use the JS index'
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
const nativeM = numericOption('M', options?.M);
|
|
365
|
+
const nativeEfConstruction = numericOption('efConstruction', options?.efConstruction);
|
|
366
|
+
const nativeML = numericOption('mL', options?.mL);
|
|
367
|
+
const nativeOptimizeRouting = numericOption(
|
|
368
|
+
'optimizeRouting',
|
|
369
|
+
normalizeOptimizeRoutingDeclaration(options?.optimizeRouting)
|
|
370
|
+
);
|
|
371
|
+
if (
|
|
372
|
+
options?.M === null ||
|
|
373
|
+
options?.efConstruction === null ||
|
|
374
|
+
options?.mL === null ||
|
|
375
|
+
options?.optimizeRouting === null ||
|
|
376
|
+
(nativeM !== undefined && nativeM !== PLANE_M) ||
|
|
377
|
+
(nativeEfConstruction !== undefined && nativeEfConstruction !== 200) ||
|
|
378
|
+
(nativeML !== undefined && nativeML !== 1 / Math.log(PLANE_M)) ||
|
|
379
|
+
(nativeOptimizeRouting !== undefined && nativeOptimizeRouting !== 0.5)
|
|
380
|
+
) {
|
|
381
|
+
throw new ClientError(
|
|
382
|
+
'nativePlane requires M=16, efConstruction=200, mL=1/ln(16), and optimizeRouting=0.5; set nativePlane: false to use the JS index'
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
const maxNodes = nativePlaneMaxNodes(options);
|
|
386
|
+
const keyCap = nativePlaneKeyCap(options);
|
|
387
|
+
const layer0Cap = nativePlaneLayer0Cap(options);
|
|
388
|
+
if (options?.quantization === 'none' || options?.distance === 'euclidean' || options?.distance === 'dotProduct') {
|
|
389
|
+
throw new ClientError(
|
|
390
|
+
'nativePlane requires an int8-quantized cosine HNSW index; set nativePlane: false to use the JS index'
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
return { nativeM, nativeEfConstruction, nativeML, nativeOptimizeRouting, maxNodes, keyCap, layer0Cap };
|
|
394
|
+
}
|
|
395
|
+
static canRunNativePlane(rootStore: unknown, options: any, warnForMissingBinding = true): boolean {
|
|
396
|
+
nativePlaneMaxNodes(options);
|
|
397
|
+
nativePlaneKeyCap(options);
|
|
398
|
+
nativePlaneLayer0Cap(options);
|
|
399
|
+
if (!(rootStore instanceof RocksDatabase) || getPlaneBinding(warnForMissingBinding) == null) return false;
|
|
400
|
+
if (
|
|
401
|
+
options?.M === null ||
|
|
402
|
+
options?.efConstruction === null ||
|
|
403
|
+
options?.mL === null ||
|
|
404
|
+
options?.optimizeRouting === null
|
|
405
|
+
)
|
|
406
|
+
return false;
|
|
407
|
+
const configuredM = numericOption('M', options?.M);
|
|
408
|
+
const configuredEfConstruction = numericOption('efConstruction', options?.efConstruction);
|
|
409
|
+
const configuredML = numericOption('mL', options?.mL);
|
|
410
|
+
const configuredOptimizeRouting = numericOption(
|
|
411
|
+
'optimizeRouting',
|
|
412
|
+
normalizeOptimizeRoutingDeclaration(options?.optimizeRouting)
|
|
413
|
+
);
|
|
414
|
+
const baseEligible =
|
|
415
|
+
options?.quantization !== 'none' &&
|
|
416
|
+
options?.distance !== 'euclidean' &&
|
|
417
|
+
options?.distance !== 'dotProduct' &&
|
|
418
|
+
(configuredM === undefined || configuredM === PLANE_M) &&
|
|
419
|
+
(configuredEfConstruction === undefined || configuredEfConstruction === 200) &&
|
|
420
|
+
(configuredML === undefined || configuredML === 1 / Math.log(PLANE_M)) &&
|
|
421
|
+
(configuredOptimizeRouting === undefined || configuredOptimizeRouting === 0.5);
|
|
422
|
+
if (!baseEligible) return false;
|
|
423
|
+
return true;
|
|
424
|
+
}
|
|
425
|
+
static canDefaultToNativePlane(rootStore: unknown, options: any): boolean {
|
|
426
|
+
return (
|
|
427
|
+
!nativePlaneDefaultDisabled() && HierarchicalNavigableSmallWorld.canRunNativePlane(rootStore, options, false)
|
|
428
|
+
);
|
|
429
|
+
}
|
|
194
430
|
// Index options that only affect search, not the stored graph — changing them must not trigger a
|
|
195
431
|
// reindex (databases.ts persists the new value but skips rebuilding). efConstructionSearch is the
|
|
196
432
|
// search-time candidate-list size; the build uses efConstruction/M/distance, which are structural.
|
|
197
|
-
// filterExpansion is the visit-budget multiplier for predicate-aware (filtered) traversal
|
|
198
|
-
|
|
433
|
+
// filterExpansion is the visit-budget multiplier for predicate-aware (filtered) traversal;
|
|
434
|
+
// maxLagMilliseconds controls delivery admission rather than the graph itself.
|
|
435
|
+
static searchOnlyOptions = ['efConstructionSearch', 'filterExpansion', 'maxLagMilliseconds'];
|
|
199
436
|
// Signals to search.ts that this index accepts a per-record predicate in search() and applies it
|
|
200
437
|
// during traversal (predicate-aware / ACORN-style filtering), so companion conditions and RBAC can
|
|
201
438
|
// be pushed down instead of post-filtering an under-filled candidate set (#1241).
|
|
@@ -235,6 +472,34 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
235
472
|
private convertedNodes = new WeakMap<object, any>();
|
|
236
473
|
private nodeCount = 0;
|
|
237
474
|
private nodeCountAt = 0;
|
|
475
|
+
// Native file-primary index. The RocksDB index store holds identity mappings and replay cursors;
|
|
476
|
+
// graph nodes and adjacency exist only in this file.
|
|
477
|
+
// undefined = not yet attached (may retry), null = unavailable or disabled for this process.
|
|
478
|
+
private plane: HnswPlane | null | undefined;
|
|
479
|
+
private planeEligible = false;
|
|
480
|
+
private planeRetryAt = 0;
|
|
481
|
+
private planeDisabledLogged = false;
|
|
482
|
+
private filePrimary = false;
|
|
483
|
+
private nativePlaneMaxNodes = PLANE_MAX_NODES;
|
|
484
|
+
private nativePlaneKeyCap = PLANE_KEY_CAP;
|
|
485
|
+
private nativePlaneLayer0Cap = PLANE_LAYER0_CAP;
|
|
486
|
+
// Installed by attachDerivedIndexes on every worker: shared readiness of the index and the way
|
|
487
|
+
// to ask its owner for a rebuild. Only the owning worker's runtime ever destroys native state.
|
|
488
|
+
private derivedHost?: DerivedNativeIndexHost;
|
|
489
|
+
// keyed by pendingMappingKey(pk): a composite key's arrays never compare equal by reference
|
|
490
|
+
private pendingDerivedMappings = new Map<
|
|
491
|
+
Id,
|
|
492
|
+
{
|
|
493
|
+
primaryKey: Id;
|
|
494
|
+
id?: number;
|
|
495
|
+
previousId?: number;
|
|
496
|
+
signature?: string;
|
|
497
|
+
version?: number;
|
|
498
|
+
pending?: boolean;
|
|
499
|
+
cleared?: boolean;
|
|
500
|
+
}
|
|
501
|
+
>();
|
|
502
|
+
postCommit?: true;
|
|
238
503
|
constructor(indexStore: any, options: any) {
|
|
239
504
|
this.indexStore = indexStore;
|
|
240
505
|
if (indexStore) {
|
|
@@ -242,10 +507,16 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
242
507
|
// (we would actually like to use float16 if it were available)
|
|
243
508
|
this.indexStore.encoder.useFloat32 = FLOAT32_OPTIONS.ALWAYS;
|
|
244
509
|
}
|
|
510
|
+
const configuredM = options?.M;
|
|
511
|
+
const configuredEfConstruction = options?.efConstruction;
|
|
512
|
+
const configuredEfConstructionSearch = options?.efConstructionSearch;
|
|
513
|
+
const configuredML = options?.mL;
|
|
514
|
+
const configuredOptimizeRouting = options?.optimizeRouting;
|
|
515
|
+
const configuredFilterExpansion = options?.filterExpansion;
|
|
245
516
|
this.int8 = options?.quantization !== 'none';
|
|
246
517
|
// Respect an explicitly-configured ef (efConstruction seeds the search ef too); otherwise auto-scale both.
|
|
247
|
-
this.efSearchConfigured =
|
|
248
|
-
this.efConstructionConfigured =
|
|
518
|
+
this.efSearchConfigured = configuredEfConstructionSearch !== undefined || configuredEfConstruction !== undefined;
|
|
519
|
+
this.efConstructionConfigured = configuredEfConstruction !== undefined;
|
|
249
520
|
this.distance =
|
|
250
521
|
options?.distance === 'euclidean'
|
|
251
522
|
? euclideanDistance
|
|
@@ -254,19 +525,497 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
254
525
|
: cosineDistance;
|
|
255
526
|
if (options) {
|
|
256
527
|
// allow all the HNSW parameters to be configured/tuned
|
|
257
|
-
if (
|
|
258
|
-
this.M =
|
|
528
|
+
if (configuredM !== undefined) {
|
|
529
|
+
this.M = configuredM;
|
|
259
530
|
this.mL = 1 / Math.log(this.M); // recalculate
|
|
260
531
|
}
|
|
261
|
-
if (
|
|
262
|
-
this.efConstruction = this.efConstructionSearch =
|
|
263
|
-
if (
|
|
264
|
-
if (
|
|
265
|
-
if (
|
|
266
|
-
if (
|
|
532
|
+
if (configuredEfConstruction !== undefined)
|
|
533
|
+
this.efConstruction = this.efConstructionSearch = configuredEfConstruction;
|
|
534
|
+
if (configuredEfConstructionSearch !== undefined) this.efConstructionSearch = configuredEfConstructionSearch;
|
|
535
|
+
if (configuredML !== undefined) this.mL = configuredML;
|
|
536
|
+
if (configuredOptimizeRouting !== undefined) this.optimizeRouting = configuredOptimizeRouting;
|
|
537
|
+
if (configuredFilterExpansion !== undefined) this.filterExpansion = configuredFilterExpansion;
|
|
538
|
+
}
|
|
539
|
+
if (options?.nativePlane) {
|
|
540
|
+
const { nativeM, nativeEfConstruction, nativeML, nativeOptimizeRouting, maxNodes, keyCap, layer0Cap } =
|
|
541
|
+
HierarchicalNavigableSmallWorld.validateNativePlaneOptions(indexStore?.rootStore, options);
|
|
542
|
+
if (nativeM !== undefined) this.M = nativeM;
|
|
543
|
+
if (nativeML !== undefined) this.mL = nativeML;
|
|
544
|
+
if (nativeOptimizeRouting !== undefined) this.optimizeRouting = nativeOptimizeRouting;
|
|
545
|
+
this.efConstruction = nativeEfConstruction ?? 200;
|
|
546
|
+
this.nativePlaneMaxNodes = maxNodes;
|
|
547
|
+
this.nativePlaneKeyCap = keyCap;
|
|
548
|
+
this.nativePlaneLayer0Cap = layer0Cap;
|
|
549
|
+
// The plane stores int8 bins and computes asymmetric cosine only, so the flag is a
|
|
550
|
+
// no-op for float (quantization: "none") and non-cosine indexes.
|
|
551
|
+
this.planeEligible = this.int8 && this.distance === cosineDistance;
|
|
552
|
+
if (!this.planeEligible) {
|
|
553
|
+
throw new ClientError(
|
|
554
|
+
'nativePlane requires an int8-quantized cosine HNSW index; set nativePlane: false to use the JS index'
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
this.filePrimary = true;
|
|
558
|
+
this.postCommit = true;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Remove derived native state after the option is disabled. */
|
|
563
|
+
cleanupDisabledPlane(): void {
|
|
564
|
+
if (this.planeEligible) return;
|
|
565
|
+
const filePath = this.planeFilePath();
|
|
566
|
+
if (!filePath) return;
|
|
567
|
+
try {
|
|
568
|
+
if (existsSync(filePath)) this.invalidatePlaneFile(filePath, this.plane);
|
|
569
|
+
unlinkSync(filePath);
|
|
570
|
+
logger.info?.('deleted the HNSW plane file of an index no longer using nativePlane');
|
|
571
|
+
} catch (error: any) {
|
|
572
|
+
if (error?.code !== 'ENOENT') {
|
|
573
|
+
// A later re-enable must not adopt a file that missed mutations while disabled.
|
|
574
|
+
logger.warn?.('could not delete the HNSW plane file; marking it stale', error);
|
|
575
|
+
this.invalidatePlaneFile(filePath);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Absolute path of this index's plane file, or undefined when the store exposes no path. */
|
|
581
|
+
planeFilePath(): string | undefined {
|
|
582
|
+
const storePath = this.indexStore?.path;
|
|
583
|
+
const storeName = this.indexStore?.name;
|
|
584
|
+
if (typeof storePath !== 'string' || typeof storeName !== 'string') return undefined;
|
|
585
|
+
return planeFilePathFor(storePath, storeName);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Open or lazily create the native file. An exclusive create resolves multi-worker races; the
|
|
590
|
+
* derived-index runtime owns population, replay, and publication.
|
|
591
|
+
*/
|
|
592
|
+
private getPlane(dims?: number, dimsFromVector = false): HnswPlane | null {
|
|
593
|
+
if (this.plane !== undefined) return this.plane;
|
|
594
|
+
if (!this.planeEligible) return (this.plane = null);
|
|
595
|
+
const now = Date.now();
|
|
596
|
+
if (now < this.planeRetryAt) return null;
|
|
597
|
+
const Plane = getPlaneBinding();
|
|
598
|
+
if (!Plane) return (this.plane = null); // the loader warned once already
|
|
599
|
+
if (!('keyCap' in Plane.prototype)) {
|
|
600
|
+
if (!this.planeDisabledLogged) {
|
|
601
|
+
this.planeDisabledLogged = true;
|
|
602
|
+
logger.error?.('the installed @harperfast/hnsw predates 0.3.0; the native HNSW index needs 0.3.0 or later');
|
|
603
|
+
}
|
|
604
|
+
return (this.plane = null);
|
|
605
|
+
}
|
|
606
|
+
const filePath = this.planeFilePath();
|
|
607
|
+
if (!filePath) {
|
|
608
|
+
this.disablePlane(new Error('the index store exposes no path to place the plane file next to'));
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
try {
|
|
612
|
+
// a tombstone marks a plane a previous unlink could not remove (Windows EBUSY while
|
|
613
|
+
// mapped): the file is stale and must never be opened over a fresh graph
|
|
614
|
+
const stalePath = planeStalePathFor(filePath);
|
|
615
|
+
if (existsSync(stalePath)) {
|
|
616
|
+
try {
|
|
617
|
+
// force: either artifact may already be gone (the documented rollback deletes the
|
|
618
|
+
// plane file by hand), and an ENOENT here disables the plane on every later attach
|
|
619
|
+
rmSync(filePath, { force: true });
|
|
620
|
+
rmSync(stalePath, { force: true });
|
|
621
|
+
} catch {
|
|
622
|
+
this.planeRetryAt = now + NODE_COUNT_TTL;
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (existsSync(filePath)) {
|
|
627
|
+
try {
|
|
628
|
+
// Crash recovery is per-slot inside the crate. The clean flag is advisory;
|
|
629
|
+
// another worker may still be constructing this shared file.
|
|
630
|
+
const opened = Plane.open(filePath);
|
|
631
|
+
// A header that disagrees with the declaration is a different graph, not a
|
|
632
|
+
// repairable file, and only the owner may destroy it: invalidating through this
|
|
633
|
+
// handle would write a path-based tombstone that could name a replacement the
|
|
634
|
+
// owner had already created.
|
|
635
|
+
const geometryMismatch =
|
|
636
|
+
opened.keyCap !== this.nativePlaneKeyCap
|
|
637
|
+
? `keyCap ${opened.keyCap} differs from the configured ${this.nativePlaneKeyCap}`
|
|
638
|
+
: opened.layer0Cap !== this.nativePlaneLayer0Cap
|
|
639
|
+
? `layer0Cap ${opened.layer0Cap} differs from the configured ${this.nativePlaneLayer0Cap}`
|
|
640
|
+
: undefined;
|
|
641
|
+
if (geometryMismatch) {
|
|
642
|
+
this.disablePlane(new Error(`plane ${geometryMismatch}`));
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
return (this.plane = opened);
|
|
646
|
+
} catch (openError) {
|
|
647
|
+
if (now - statSync(filePath).mtimeMs <= PLANE_STALE_CREATE_MS) {
|
|
648
|
+
// another worker is between its exclusive create and the header write
|
|
649
|
+
this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
|
|
650
|
+
return null;
|
|
651
|
+
}
|
|
652
|
+
logger.warn?.('deleting an unopenable HNSW plane file left by an interrupted create', openError);
|
|
653
|
+
unlinkSync(filePath);
|
|
654
|
+
if (this.filePrimary) {
|
|
655
|
+
// The surviving mappings still name node ids from the file just removed.
|
|
656
|
+
// Creating a fresh plane here would resolve them against an empty graph;
|
|
657
|
+
// only reconstruction, which clears the mappings first, is safe.
|
|
658
|
+
this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (!dims) return null; // open-only call and no file: nothing to attach yet
|
|
664
|
+
// A search target must not pin an empty index's dimensionality: creation is deferred to
|
|
665
|
+
// the first committed vector or to the rebuild scan. Return before the exclusive create
|
|
666
|
+
// rather than creating and unlinking — a concurrent insert that saw the empty file would
|
|
667
|
+
// read it as another worker's in-progress create and 503 for PLANE_STALE_CREATE_MS.
|
|
668
|
+
if (!dimsFromVector) return null;
|
|
669
|
+
let fd: number;
|
|
670
|
+
try {
|
|
671
|
+
fd = openSync(filePath, 'wx');
|
|
672
|
+
} catch {
|
|
673
|
+
// another worker won the create race; its header lands within moments
|
|
674
|
+
this.planeRetryAt = now + PLANE_ATTACH_RETRY_MS;
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
closeSync(fd);
|
|
678
|
+
try {
|
|
679
|
+
return (this.plane = Plane.create(
|
|
680
|
+
filePath,
|
|
681
|
+
dims,
|
|
682
|
+
this.nativePlaneLayer0Cap,
|
|
683
|
+
this.nativePlaneMaxNodes,
|
|
684
|
+
this.nativePlaneKeyCap
|
|
685
|
+
));
|
|
686
|
+
} catch (createError) {
|
|
687
|
+
// Never leave a partial file that a later process could trust as current.
|
|
688
|
+
try {
|
|
689
|
+
unlinkSync(filePath);
|
|
690
|
+
} catch {
|
|
691
|
+
// the disable below already forces the JS path for this process
|
|
692
|
+
}
|
|
693
|
+
this.disablePlane(createError);
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
696
|
+
} catch (error) {
|
|
697
|
+
this.planeRetryAt = now + NODE_COUNT_TTL;
|
|
698
|
+
logger.warn?.('could not attach the HNSW plane file; will retry', error);
|
|
699
|
+
return null;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** True only while the owning runtime publishes the index as ready, on whichever worker owns it. */
|
|
704
|
+
private planeSearchReady(plane: HnswPlane): boolean {
|
|
705
|
+
if (plane.invalidated()) {
|
|
706
|
+
this.plane = undefined;
|
|
707
|
+
return false;
|
|
708
|
+
}
|
|
709
|
+
return this.derivedReadiness() === 'ready';
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
private derivedReadiness(): DerivedIndexReadiness['state'] {
|
|
713
|
+
return this.derivedHost?.readiness().state ?? 'unknown';
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* Detach this process from the plane after a failure and ask the index's owner for a rebuild.
|
|
718
|
+
* Only the owner destroys native state (`resetDerivedStorage` under its epoch), so a failure
|
|
719
|
+
* observed here after a peer has already replaced the file cannot take out the replacement.
|
|
720
|
+
*/
|
|
721
|
+
private disablePlane(error: unknown): void {
|
|
722
|
+
this.plane = undefined;
|
|
723
|
+
this.planeRetryAt = Date.now() + PLANE_ATTACH_RETRY_MS;
|
|
724
|
+
if (!this.planeDisabledLogged) {
|
|
725
|
+
this.planeDisabledLogged = true;
|
|
726
|
+
logger.error?.('the HNSW native index failed; requesting a rebuild from its owner', error);
|
|
727
|
+
}
|
|
728
|
+
this.derivedHost?.requestRebuild();
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Delete the derived plane state before an audit-backed reconstruction. Path invalidation
|
|
733
|
+
* makes peers stop using an old mapping even when unlink leaves their mmap inode alive.
|
|
734
|
+
*/
|
|
735
|
+
resetDerivedStorage(): void {
|
|
736
|
+
this.pendingDerivedMappings.clear();
|
|
737
|
+
const attached = this.plane;
|
|
738
|
+
this.plane = undefined;
|
|
739
|
+
this.planeRetryAt = 0;
|
|
740
|
+
const filePath = this.planeFilePath();
|
|
741
|
+
if (!filePath) return;
|
|
742
|
+
if (this.filePrimary && existsSync(filePath)) this.invalidatePlaneFile(filePath, attached);
|
|
743
|
+
try {
|
|
744
|
+
unlinkSync(filePath);
|
|
745
|
+
} catch (error: any) {
|
|
746
|
+
if (error?.code !== 'ENOENT') {
|
|
747
|
+
// a stale file that cannot be deleted (e.g. Windows EBUSY while mapped) must not
|
|
748
|
+
// be reopened as if current — mark it so no process ever adopts it
|
|
749
|
+
this.plane = null;
|
|
750
|
+
logger.warn?.('could not delete the HNSW plane file; marking it stale', error);
|
|
751
|
+
this.invalidatePlaneFile(filePath, attached);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** True while any primary-key mapping survives, which is the only proof this index holds nodes. */
|
|
757
|
+
private hasNodeMappings(): boolean {
|
|
758
|
+
for (const { value } of this.indexStore.getRange({})) {
|
|
759
|
+
if (value && typeof value === 'object' && typeof value.id === 'number') return true;
|
|
760
|
+
}
|
|
761
|
+
return false;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** Make an undeletable plane unadoptable before this process releases it. */
|
|
765
|
+
private invalidatePlaneFile(filePath: string, attached?: HnswPlane | null): void {
|
|
766
|
+
try {
|
|
767
|
+
invalidateHnswPlaneFile(filePath, attached);
|
|
768
|
+
} catch (error) {
|
|
769
|
+
logger.warn?.('could not invalidate the stale HNSW plane file', error);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Native search over the plane: one NAPI crossing, traversal on the libuv pool, every hit
|
|
775
|
+
* carrying its primary key out of the slot. The predicate adapter runs on this thread's event
|
|
776
|
+
* loop (batched over a ThreadsafeFunction), so this promise must never be awaited by code the
|
|
777
|
+
* predicate itself blocks on; the normal request path awaits it safely.
|
|
778
|
+
*/
|
|
779
|
+
private searchPlane(
|
|
780
|
+
plane: HnswPlane,
|
|
781
|
+
target: number[],
|
|
782
|
+
k: number,
|
|
783
|
+
ef: number,
|
|
784
|
+
filter: ((primaryKey: Id) => boolean) | undefined,
|
|
785
|
+
filterState: FilterState | undefined
|
|
786
|
+
): Promise<any[]> {
|
|
787
|
+
const query = Float32Array.from(target);
|
|
788
|
+
let resultPromise: Promise<PlaneSearchHits>;
|
|
789
|
+
let predicateError: unknown;
|
|
790
|
+
let planeError: unknown;
|
|
791
|
+
if (filter && filterState) {
|
|
792
|
+
const predicate: PlanePredicate = (ids, keys, keyEnds) => {
|
|
793
|
+
const verdicts = new Uint8Array(ids.length);
|
|
794
|
+
if (predicateError !== undefined || planeError !== undefined) return verdicts;
|
|
795
|
+
for (let i = 0; i < ids.length; i++) {
|
|
796
|
+
const start = i === 0 ? 0 : keyEnds[i - 1];
|
|
797
|
+
const end = keyEnds[i];
|
|
798
|
+
if (end === start) continue;
|
|
799
|
+
let primaryKey: Id;
|
|
800
|
+
try {
|
|
801
|
+
primaryKey = unpack(keys.subarray(start, end));
|
|
802
|
+
} catch (error) {
|
|
803
|
+
planeError = error;
|
|
804
|
+
break;
|
|
805
|
+
}
|
|
806
|
+
try {
|
|
807
|
+
if (this.admit(filter, filterState, primaryKey)) verdicts[i] = 1;
|
|
808
|
+
} catch (error) {
|
|
809
|
+
predicateError = error;
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
return verdicts;
|
|
814
|
+
};
|
|
815
|
+
resultPromise = plane.searchWithPredicate(query, k, ef, predicate, undefined, filterState.maxVisits);
|
|
816
|
+
} else {
|
|
817
|
+
resultPromise = plane.search(query, k, ef);
|
|
818
|
+
}
|
|
819
|
+
return resultPromise.then((hits) => {
|
|
820
|
+
if (planeError !== undefined) throw planeError;
|
|
821
|
+
if (predicateError !== undefined) {
|
|
822
|
+
// the plane itself is healthy; mark the failure as the application's so the caller
|
|
823
|
+
// re-raises it rather than disabling the plane and retrying
|
|
824
|
+
try {
|
|
825
|
+
(predicateError as any)[NOT_A_PLANE_FAILURE] = true;
|
|
826
|
+
} catch {
|
|
827
|
+
// a frozen/primitive throw still propagates, it just also disables the plane
|
|
828
|
+
}
|
|
829
|
+
throw predicateError;
|
|
830
|
+
}
|
|
831
|
+
const entries: any[] = [];
|
|
832
|
+
const { distances, keys, keyEnds } = hits;
|
|
833
|
+
// a key appears twice only after a crash (see applyDerivedValue); keep the nearer hit
|
|
834
|
+
const seen = new Set<string>();
|
|
835
|
+
for (let i = 0; i < keyEnds.length; i++) {
|
|
836
|
+
const start = i === 0 ? 0 : keyEnds[i - 1];
|
|
837
|
+
const end = keyEnds[i];
|
|
838
|
+
if (end === start) continue;
|
|
839
|
+
const encoded = keys.toString('latin1', start, end);
|
|
840
|
+
if (seen.has(encoded)) continue;
|
|
841
|
+
seen.add(encoded);
|
|
842
|
+
entries.push({ key: unpack(keys.subarray(start, end)), distance: distances[i] });
|
|
843
|
+
}
|
|
844
|
+
// nodesVisited stays 0 here: layer-0 visits happen inside the native traversal
|
|
845
|
+
// (filterEvaluations is still counted by the predicate adapter)
|
|
846
|
+
return withStats(entries, filterState);
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
attachDerivedHost(host: DerivedNativeIndexHost): void {
|
|
851
|
+
this.derivedHost = host;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
private queryCoverage(maxLagMilliseconds: number) {
|
|
855
|
+
const coverage = this.derivedHost?.coverage(maxLagMilliseconds);
|
|
856
|
+
if (!coverage || coverage.state === 'unknown') {
|
|
857
|
+
const age = coverage?.lagUpperBoundMilliseconds;
|
|
858
|
+
throw new DerivedIndexLagError(
|
|
859
|
+
`Cannot certify native HNSW index coverage within ${maxLagMilliseconds} ms` +
|
|
860
|
+
(age === undefined ? '; freshness is unknown' : `; last certified ${Math.ceil(age)} ms ago`) +
|
|
861
|
+
'; retry this query'
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
return coverage;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* The commit path only validates: a malformed vector is the client's 400 here rather than an
|
|
869
|
+
* unindexable record later. The shared derived-index runtime reads the committed log; nothing
|
|
870
|
+
* is staged on the transaction.
|
|
871
|
+
*/
|
|
872
|
+
prepareCommitted(primaryKey: Id, vector: number[], existingVector: number[]): void {
|
|
873
|
+
// O(dims) on every write to the table, so skip it when the projection did not change — an
|
|
874
|
+
// unchanged vector was validated when it was first written.
|
|
875
|
+
if (derivedValuesEqual(vector, existingVector)) return;
|
|
876
|
+
this.validateVector(primaryKey, vector);
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** The runtime's projection guard: what fails here is delivered as unindexable, not applied. */
|
|
880
|
+
assertDerivedValue(vector: unknown, label: string): void {
|
|
881
|
+
this.assertPlaneVector(vector as number[], label);
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
private validateVector(primaryKey: Id, vector?: number[]): void {
|
|
885
|
+
if (!vector) return;
|
|
886
|
+
this.assertPlaneVector(vector, `Vector for attribute "${String(primaryKey)}"`);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Everything reaching the plane — a committed record's projection or a query target — has to
|
|
891
|
+
* convert to the f32 it stores, and to a representable magnitude. What fails here would instead
|
|
892
|
+
* throw out of `Float32Array.from` or out of the crate, as an error neither the search path nor
|
|
893
|
+
* reconstruction can attribute to the record: a query would unlink a healthy file, and a record
|
|
894
|
+
* would abort every rebuild attempt at the same entry.
|
|
895
|
+
*/
|
|
896
|
+
private assertPlaneVector(vector: number[], label: string): void {
|
|
897
|
+
// A positive integer length, not merely a numeric one: a negative or fractional length skips
|
|
898
|
+
// the component loop and the emptiness check, and reaches Plane.create with it.
|
|
899
|
+
const length = (vector as any)?.length;
|
|
900
|
+
if (!Number.isInteger(length) || length < 1) {
|
|
901
|
+
throw new ClientError(`${label} must be an array of at least one number.`);
|
|
902
|
+
}
|
|
903
|
+
let sumOfSquares = 0;
|
|
904
|
+
for (let i = 0; i < vector.length; i++) {
|
|
905
|
+
const component = vector[i];
|
|
906
|
+
// The type check precedes Math.fround, which throws a TypeError on the BigInt a msgpackr
|
|
907
|
+
// or cbor-x decode produces for a large int64.
|
|
908
|
+
if (typeof component !== 'number' || !Number.isFinite(Math.fround(component))) {
|
|
909
|
+
throw new ClientError(
|
|
910
|
+
`${label} has a component at index ${i} that is not a finite 32-bit float: ${String(component)}.`
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
const asFloat32 = Math.fround(component);
|
|
914
|
+
sumOfSquares += asFloat32 * asFloat32;
|
|
915
|
+
}
|
|
916
|
+
// Components can each be f32-finite while their squares are not, which stores invMag 0 and
|
|
917
|
+
// makes every distance involving that node NaN.
|
|
918
|
+
if (!Number.isFinite(Math.fround(sumOfSquares))) {
|
|
919
|
+
throw new ClientError(`${label} has a magnitude too large to represent in 32-bit floats.`);
|
|
920
|
+
}
|
|
921
|
+
// The plane's dimensionality is fixed at create time by the first committed vector.
|
|
922
|
+
const dims = this.plane?.dims;
|
|
923
|
+
if (dims !== undefined && vector.length !== dims) {
|
|
924
|
+
throw new ClientError(`${label} has ${vector.length} components, but this index stores ${dims}.`);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
applyDerivedValue(primaryKey: Id, vector: number[], version?: number): void {
|
|
929
|
+
this.validateVector(primaryKey, vector);
|
|
930
|
+
const safeKey = typeof primaryKey === 'number' ? [KEY_PREFIX, primaryKey] : primaryKey;
|
|
931
|
+
const pendingKey = pendingMappingKey(primaryKey);
|
|
932
|
+
const pendingMapping = this.pendingDerivedMappings.get(pendingKey);
|
|
933
|
+
const storedMapping = pendingMapping ?? this.indexStore.getSync(safeKey);
|
|
934
|
+
const oldNodeId = typeof storedMapping === 'number' ? storedMapping : storedMapping?.id;
|
|
935
|
+
// Neither a plane removal nor an insert is durable before the barrier, so a pending
|
|
936
|
+
// mapping keeps naming the last published node (previousId) for replay to remove.
|
|
937
|
+
const displacedNodeId: number | undefined = storedMapping?.previousId;
|
|
938
|
+
const durableNodeId = storedMapping?.pending ? displacedNodeId : oldNodeId;
|
|
939
|
+
if (storedMapping?.version != null && version != null && storedMapping.version > version) return;
|
|
940
|
+
const nativeVector = vector ? Float32Array.from(vector) : undefined;
|
|
941
|
+
const signature = nativeVector
|
|
942
|
+
? createHash('sha256')
|
|
943
|
+
.update(Buffer.from(nativeVector.buffer, nativeVector.byteOffset, nativeVector.byteLength))
|
|
944
|
+
.digest('base64url')
|
|
945
|
+
: undefined;
|
|
946
|
+
if (
|
|
947
|
+
oldNodeId != null &&
|
|
948
|
+
signature &&
|
|
949
|
+
storedMapping.signature === signature &&
|
|
950
|
+
!pendingMapping &&
|
|
951
|
+
!storedMapping.pending
|
|
952
|
+
) {
|
|
953
|
+
this.indexStore.putSync(safeKey, { id: oldNodeId, signature, version });
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
let plane = vector ? this.getPlane(vector.length, true) : this.getPlane();
|
|
957
|
+
if (plane?.invalidated()) {
|
|
958
|
+
this.plane = undefined;
|
|
959
|
+
plane = vector ? this.getPlane(vector.length, true) : this.getPlane();
|
|
960
|
+
}
|
|
961
|
+
// The pre-commit check above ran before this worker had a plane to compare against, so it
|
|
962
|
+
// cannot have caught a mismatch. Reject before the removal below, or the record loses its
|
|
963
|
+
// old node on the way to failing.
|
|
964
|
+
if (vector && plane && vector.length !== plane.dims) {
|
|
965
|
+
throw new ClientError(
|
|
966
|
+
`Vector for attribute "${String(primaryKey)}" has ${vector.length} components, but this index stores ${plane.dims}.`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
// in process a pending mapping's removals already happened and their ids may be reused
|
|
970
|
+
const removeDisplaced = displacedNodeId != null && !pendingMapping && displacedNodeId !== oldNodeId;
|
|
971
|
+
const removeOld = oldNodeId != null && !(pendingMapping && storedMapping.cleared);
|
|
972
|
+
if (removeDisplaced) plane?.remove(displacedNodeId);
|
|
973
|
+
if (removeOld) plane?.remove(oldNodeId);
|
|
974
|
+
if (!vector) {
|
|
975
|
+
const cleared = { id: oldNodeId, previousId: durableNodeId, version, pending: true, cleared: true };
|
|
976
|
+
if (oldNodeId != null || durableNodeId != null) this.indexStore.putSync(safeKey, cleared);
|
|
977
|
+
else this.indexStore.removeSync(safeKey);
|
|
978
|
+
this.pendingDerivedMappings.set(pendingKey, { ...cleared, primaryKey });
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (!plane) throw new ServerError('The native HNSW module is unavailable for a file-primary index', 503);
|
|
982
|
+
const nodeId = plane.insert(nativeVector!, pack(primaryKey));
|
|
983
|
+
const mapping = { id: nodeId, previousId: durableNodeId, signature, version, pending: true };
|
|
984
|
+
this.indexStore.putSync(safeKey, mapping);
|
|
985
|
+
this.pendingDerivedMappings.set(pendingKey, { ...mapping, primaryKey });
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
async flushDerived(watermark?: number): Promise<void> {
|
|
989
|
+
const plane = this.getPlane();
|
|
990
|
+
if (!plane) {
|
|
991
|
+
if (!getPlaneBinding()) throw new ServerError('The native HNSW module is unavailable', 503);
|
|
992
|
+
return this.publishDerivedMappings();
|
|
993
|
+
}
|
|
994
|
+
await plane.flushAsync(watermark);
|
|
995
|
+
this.publishDerivedMappings();
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
private publishDerivedMappings(): void {
|
|
999
|
+
for (const { primaryKey, ...mapping } of this.pendingDerivedMappings.values()) {
|
|
1000
|
+
const safeKey = typeof primaryKey === 'number' ? [KEY_PREFIX, primaryKey] : primaryKey;
|
|
1001
|
+
if (mapping.cleared || mapping.id === undefined) {
|
|
1002
|
+
this.indexStore.removeSync(safeKey);
|
|
1003
|
+
} else {
|
|
1004
|
+
const published = { id: mapping.id, signature: mapping.signature, version: mapping.version };
|
|
1005
|
+
this.indexStore.putSync(safeKey, published);
|
|
1006
|
+
}
|
|
267
1007
|
}
|
|
1008
|
+
this.pendingDerivedMappings.clear();
|
|
268
1009
|
}
|
|
1010
|
+
|
|
269
1011
|
index(primaryKey: Id, vector: number[], existingVector?: number[], options: any = {}) {
|
|
1012
|
+
if (this.filePrimary) {
|
|
1013
|
+
if (options.transaction) return this.prepareCommitted(primaryKey, vector, existingVector);
|
|
1014
|
+
// runIndexing invokes custom indexes without a transaction. The shared runtime owns the
|
|
1015
|
+
// primary-record rebuild and the log replay; populating here would duplicate native
|
|
1016
|
+
// construction and race the owner's generation reset.
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
270
1019
|
// Reject non-finite components before touching the graph. NaN in particular poisons
|
|
271
1020
|
// bisectInsert (arr[mid].distance <= NaN is always false → returns 0, pinning the
|
|
272
1021
|
// candidate to rank 1 of every future search). Infinity causes analogous ordering
|
|
@@ -508,18 +1257,15 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
508
1257
|
}
|
|
509
1258
|
|
|
510
1259
|
// Store the new element
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
},
|
|
521
|
-
options
|
|
522
|
-
);
|
|
1260
|
+
const storedNode = {
|
|
1261
|
+
vector: storedVector,
|
|
1262
|
+
scale: storedScale,
|
|
1263
|
+
invMag,
|
|
1264
|
+
level,
|
|
1265
|
+
primaryKey,
|
|
1266
|
+
...connections,
|
|
1267
|
+
};
|
|
1268
|
+
this.indexStore.put(nodeId, storedNode, options);
|
|
523
1269
|
} else {
|
|
524
1270
|
// removal of this node, but first make sure we have a valid entry point
|
|
525
1271
|
if (entryPointId === nodeId) {
|
|
@@ -815,8 +1561,9 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
815
1561
|
}
|
|
816
1562
|
}
|
|
817
1563
|
|
|
818
|
-
/** O(1) node count
|
|
1564
|
+
/** O(1) node count: the plane's id high-water, the shared id counter, or one reverse seek. */
|
|
819
1565
|
private resolveNodeCount(options?: any): number {
|
|
1566
|
+
if (this.filePrimary) return this.getPlane()?.idHighWater() ?? 0;
|
|
820
1567
|
if (this.idIncrementer) return Number(Atomics.load(this.idIncrementer, 0));
|
|
821
1568
|
try {
|
|
822
1569
|
for (const key of this.indexStore.getKeys({
|
|
@@ -1057,12 +1804,14 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1057
1804
|
* This the main entry from Harper's query functionality, where we actually search for an ordered list of nearest
|
|
1058
1805
|
* neighbors, using the provided sort/order definition object and performing the multi-layer skip-list search.
|
|
1059
1806
|
* This returns an iterable of the nearest neighbors to the provided target vector, with nearest ordered first.
|
|
1060
|
-
*
|
|
1061
|
-
*
|
|
1062
|
-
*
|
|
1063
|
-
*
|
|
1064
|
-
* @param comparator
|
|
1065
|
-
*
|
|
1807
|
+
*
|
|
1808
|
+
* This is also the contract an index implemented outside this repo has to satisfy, so everything
|
|
1809
|
+
* optional is named: a future capability (a paging cursor, a deadline, a recall target) is a new
|
|
1810
|
+
* field on `options` rather than a positional argument that breaks every existing implementation.
|
|
1811
|
+
* @param searchCondition the vector query: `target`, `comparator`, and the optional `value`,
|
|
1812
|
+
* `descending`, `distance`, `ef` and `filterExpansion` tuning knobs
|
|
1813
|
+
* @param context the query context; its `transaction` is the nested RocksDB transaction reads use
|
|
1814
|
+
* @param options optional, named: `filter` (predicate-aware traversal) and `minResults`
|
|
1066
1815
|
*/
|
|
1067
1816
|
search(
|
|
1068
1817
|
{
|
|
@@ -1073,6 +1822,8 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1073
1822
|
comparator,
|
|
1074
1823
|
ef,
|
|
1075
1824
|
filterExpansion,
|
|
1825
|
+
maxIndexLagMilliseconds = DEFAULT_MAX_INDEX_LAG_MILLISECONDS,
|
|
1826
|
+
waitForIndexMilliseconds = 0,
|
|
1076
1827
|
}: {
|
|
1077
1828
|
target: number[];
|
|
1078
1829
|
value: number;
|
|
@@ -1081,19 +1832,27 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1081
1832
|
comparator: string;
|
|
1082
1833
|
ef?: number;
|
|
1083
1834
|
filterExpansion?: number;
|
|
1835
|
+
maxIndexLagMilliseconds?: number;
|
|
1836
|
+
waitForIndexMilliseconds?: number;
|
|
1084
1837
|
},
|
|
1085
1838
|
context: any,
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1839
|
+
{
|
|
1840
|
+
filter,
|
|
1841
|
+
minResults,
|
|
1842
|
+
}: {
|
|
1843
|
+
// Predicate-aware traversal (#1241). When provided, only nodes for which `filter(primaryKey)`
|
|
1844
|
+
// returns true are admitted to the result list at layer 0; routing is unaffected. Composed by
|
|
1845
|
+
// search.ts from companion AND conditions and caller-supplied vector/row filters. Must be
|
|
1846
|
+
// synchronous and side-effect free. JS-API only (never from a REST query string).
|
|
1847
|
+
filter?: (primaryKey: Id) => boolean;
|
|
1848
|
+
// offset + limit for a bounded query. A layer-0 search returns at most `ef` candidates, so a
|
|
1849
|
+
// query asking for more rows than that used to come back short with no error — capped at 512
|
|
1850
|
+
// (AUTO_EF_MAX) however large the limit was. Raising ef to cover the request keeps `limit`
|
|
1851
|
+
// meaningful; the caller pays for what it asked for.
|
|
1852
|
+
minResults?: number;
|
|
1853
|
+
} = {}
|
|
1096
1854
|
) {
|
|
1855
|
+
const waiting = this.filePrimary && waitForIndexMilliseconds > 0;
|
|
1097
1856
|
let limit: number | undefined; // only set for threshold comparators; 0 is a valid threshold (e.g. dotProduct)
|
|
1098
1857
|
let limitInclusive = false; // true for `le`, false for `lt`
|
|
1099
1858
|
switch (comparator) {
|
|
@@ -1120,8 +1879,25 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1120
1879
|
else distanceFunction = this.distance;
|
|
1121
1880
|
if (!target) throw new ClientError('A target vector must be provided for an HNSW query');
|
|
1122
1881
|
if (!Array.isArray(target)) throw new ClientError('The target vector must be an array');
|
|
1882
|
+
if (
|
|
1883
|
+
this.filePrimary &&
|
|
1884
|
+
(typeof maxIndexLagMilliseconds !== 'number' ||
|
|
1885
|
+
!Number.isFinite(maxIndexLagMilliseconds) ||
|
|
1886
|
+
maxIndexLagMilliseconds < 0)
|
|
1887
|
+
)
|
|
1888
|
+
throw new ClientError('maxIndexLagMilliseconds must be a finite nonnegative number');
|
|
1889
|
+
if (
|
|
1890
|
+
this.filePrimary &&
|
|
1891
|
+
(typeof waitForIndexMilliseconds !== 'number' ||
|
|
1892
|
+
!Number.isFinite(waitForIndexMilliseconds) ||
|
|
1893
|
+
waitForIndexMilliseconds < 0 ||
|
|
1894
|
+
waitForIndexMilliseconds > MAX_WAIT_FOR_INDEX_MILLISECONDS)
|
|
1895
|
+
)
|
|
1896
|
+
throw new ClientError(
|
|
1897
|
+
`waitForIndexMilliseconds must be a finite number between 0 and ${MAX_WAIT_FOR_INDEX_MILLISECONDS}`
|
|
1898
|
+
);
|
|
1123
1899
|
|
|
1124
|
-
const
|
|
1900
|
+
const txnOptions = context.transaction; // should have a nested RocksDB transaction
|
|
1125
1901
|
// Resolve search ef: per-query ef wins; else use the schema-pinned value (from either ef option);
|
|
1126
1902
|
// otherwise auto-scale with the graph size so recall holds as the table grows.
|
|
1127
1903
|
let effectiveEf = this.efConstructionSearch;
|
|
@@ -1163,7 +1939,108 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1163
1939
|
filterEvaluations: 0,
|
|
1164
1940
|
}
|
|
1165
1941
|
: undefined;
|
|
1166
|
-
|
|
1942
|
+
const rerankK =
|
|
1943
|
+
comparator === 'sort' && minResults !== undefined
|
|
1944
|
+
? Math.min(effectiveEf, Math.max(RERANK_MIN, minResults * RERANK_FACTOR))
|
|
1945
|
+
: effectiveEf;
|
|
1946
|
+
if (this.filePrimary && distanceFunction !== this.distance) {
|
|
1947
|
+
throw new ClientError('A nativePlane index only supports its configured cosine distance');
|
|
1948
|
+
}
|
|
1949
|
+
const searchNative = (certified?: DerivedIndexCoverage) => {
|
|
1950
|
+
if (this.filePrimary && this.derivedReadiness() !== 'ready') {
|
|
1951
|
+
throw new ServerError(
|
|
1952
|
+
`The native HNSW index is ${this.derivedReadiness() === 'unavailable' ? 'unavailable' : 'rebuilding'}`,
|
|
1953
|
+
503
|
|
1954
|
+
);
|
|
1955
|
+
}
|
|
1956
|
+
// The plane traverses the index's own metric (cosine — the eligibility requirement), so a
|
|
1957
|
+
// query overriding `distance` has to take the JS path: rescoreResults only corrects the
|
|
1958
|
+
// reported distances of whatever candidates came back, not which candidates the beam kept.
|
|
1959
|
+
if (this.planeEligible && distanceFunction === this.distance) {
|
|
1960
|
+
const plane = this.getPlane(target.length, false);
|
|
1961
|
+
// A file-primary index has no JS path to fall through to, so a target the plane cannot
|
|
1962
|
+
// accept has to fail as the client error it is. Otherwise it throws out of
|
|
1963
|
+
// Float32Array.from or the traversal, is read as plane corruption, and unlinks a healthy
|
|
1964
|
+
// file — one malformed query costing a full reconstruction.
|
|
1965
|
+
if (this.filePrimary && plane) this.assertPlaneVector(target, 'Search target');
|
|
1966
|
+
// a non-file-primary query whose dimensionality differs from the graph's takes the JS
|
|
1967
|
+
// path, which tolerates the mismatch, rather than disabling the healthy plane
|
|
1968
|
+
if (plane && plane.dims === target.length && this.planeSearchReady(plane)) {
|
|
1969
|
+
const coverage = certified ?? (this.filePrimary ? this.queryCoverage(maxIndexLagMilliseconds) : undefined);
|
|
1970
|
+
try {
|
|
1971
|
+
const searched = this.searchPlane(plane, target, rerankK, effectiveEf, filter, filterState)
|
|
1972
|
+
.catch((error) => {
|
|
1973
|
+
if (error?.[NOT_A_PLANE_FAILURE]) throw error;
|
|
1974
|
+
// There is no JS graph behind a file-primary index: it stays unavailable until
|
|
1975
|
+
// its audit-backed rebuild succeeds.
|
|
1976
|
+
this.disablePlane(error);
|
|
1977
|
+
throw new ServerError('The native HNSW index is rebuilding', 503);
|
|
1978
|
+
})
|
|
1979
|
+
.then((entries) => {
|
|
1980
|
+
if (coverage) Object.defineProperty(entries, 'indexCoverage', { value: coverage });
|
|
1981
|
+
return entries;
|
|
1982
|
+
});
|
|
1983
|
+
if (coverage) Object.defineProperty(searched, 'indexCoverage', { value: coverage });
|
|
1984
|
+
return searched;
|
|
1985
|
+
} catch (error) {
|
|
1986
|
+
// Handle a throw raised before the asynchronous native search returns its promise.
|
|
1987
|
+
this.disablePlane(error);
|
|
1988
|
+
throw new ServerError('The native HNSW index is rebuilding', 503);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
if (this.filePrimary) {
|
|
1993
|
+
const state = this.derivedReadiness();
|
|
1994
|
+
if (state === 'unavailable') throw new ServerError('The native HNSW index is unavailable', 503);
|
|
1995
|
+
const planePath = this.planeFilePath();
|
|
1996
|
+
if (state !== 'ready' || (planePath && existsSync(planePath))) {
|
|
1997
|
+
throw new ServerError('The native HNSW index is rebuilding', 503);
|
|
1998
|
+
}
|
|
1999
|
+
// The absence of a file is not proof of an empty index — it is also the state just after
|
|
2000
|
+
// any process removes an unopenable one. Only the surviving node mappings prove it.
|
|
2001
|
+
if (this.hasNodeMappings()) {
|
|
2002
|
+
// A table taking no further writes never drains, so a query is the only thing left
|
|
2003
|
+
// that can notice the graph is gone and ask for it back.
|
|
2004
|
+
logger.error?.(`${this.indexStore.name} lost its native file while its node mappings survive`);
|
|
2005
|
+
this.derivedHost?.requestRebuild();
|
|
2006
|
+
throw new ServerError('The native HNSW index is rebuilding', 503);
|
|
2007
|
+
}
|
|
2008
|
+
const entries = withStats([], filterState);
|
|
2009
|
+
Object.defineProperty(entries, 'indexCoverage', {
|
|
2010
|
+
value: certified ?? this.queryCoverage(maxIndexLagMilliseconds),
|
|
2011
|
+
});
|
|
2012
|
+
return entries;
|
|
2013
|
+
}
|
|
2014
|
+
};
|
|
2015
|
+
if (waiting) {
|
|
2016
|
+
context.signal?.throwIfAborted();
|
|
2017
|
+
const host = this.derivedHost;
|
|
2018
|
+
const state = host?.readiness().state;
|
|
2019
|
+
if (state !== 'ready') {
|
|
2020
|
+
throw new ServerError(
|
|
2021
|
+
`The native HNSW index is ${state === 'unavailable' ? 'unavailable' : 'rebuilding'}`,
|
|
2022
|
+
503
|
|
2023
|
+
);
|
|
2024
|
+
}
|
|
2025
|
+
const searched = Promise.resolve(context.indexSearchStart).then(async () => {
|
|
2026
|
+
context.signal?.throwIfAborted();
|
|
2027
|
+
if (minResults === 0) return [];
|
|
2028
|
+
const started = derivedIndexTime(this.indexStore.rootStore);
|
|
2029
|
+
if (host.coverage(0)?.state !== 'current')
|
|
2030
|
+
await host.waitForCoverage(started, waitForIndexMilliseconds, context.signal);
|
|
2031
|
+
context.signal?.throwIfAborted();
|
|
2032
|
+
return searchNative({
|
|
2033
|
+
state: 'current',
|
|
2034
|
+
maxLagMilliseconds: maxIndexLagMilliseconds,
|
|
2035
|
+
lagUpperBoundMilliseconds: 0,
|
|
2036
|
+
});
|
|
2037
|
+
});
|
|
2038
|
+
searched.catch(() => {});
|
|
2039
|
+
return searched;
|
|
2040
|
+
}
|
|
2041
|
+
const native = searchNative();
|
|
2042
|
+
if (native) return native;
|
|
2043
|
+
let entryPoint = this.getEntryPoint(txnOptions);
|
|
1167
2044
|
if (!entryPoint) return withStats([], filterState);
|
|
1168
2045
|
let entryPointId = entryPoint.id;
|
|
1169
2046
|
let results: Candidate[] = [];
|
|
@@ -1181,7 +2058,7 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1181
2058
|
entryPoint,
|
|
1182
2059
|
l === 0 ? effectiveEf : ROUTING_EF,
|
|
1183
2060
|
l,
|
|
1184
|
-
|
|
2061
|
+
txnOptions,
|
|
1185
2062
|
distanceFunction,
|
|
1186
2063
|
l === 0 ? filter : undefined,
|
|
1187
2064
|
l === 0 ? filterState : undefined
|
|
@@ -1197,6 +2074,7 @@ export class HierarchicalNavigableSmallWorld {
|
|
|
1197
2074
|
results = results.filter((candidate) =>
|
|
1198
2075
|
limitInclusive ? candidate.distance <= limit : candidate.distance < limit
|
|
1199
2076
|
);
|
|
2077
|
+
if (results.length > rerankK) results = results.slice(0, rerankK);
|
|
1200
2078
|
return withStats(
|
|
1201
2079
|
results.map((candidate) => ({
|
|
1202
2080
|
// we return the result as an entry so we can provide distance as metadata
|