@harperfast/hnsw 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @harperfast/hnsw
2
+
3
+ Persistent, incrementally-maintained, concurrently-searchable HNSW vector index for Node.js —
4
+ a native (Rust) traversal engine over a memory-mapped fixed-slot graph file.
5
+
6
+ Most HNSW libraries for Node either keep the graph in JS objects (slow per-visit cost, GC
7
+ pressure) or wrap an in-memory C++ index with no durable incremental persistence. This one is
8
+ built around a different contract:
9
+
10
+ - **The file is the index.** One memory-mapped file per index: fixed-size node slots
11
+ (int8-quantized vector + neighbor ids, page-grouped so slots never straddle page
12
+ boundaries), an in-file upper-layer region, an id freelist, and a durability watermark.
13
+ Reopen is instant — no rebuild, no sidecars.
14
+ - **Search never touches the JS event loop.** Queries run on the libuv thread pool with one
15
+ N-API crossing each; traversal is zero-copy against the mapping with SIMD (AVX2) int8
16
+ asymmetric-cosine distance.
17
+ - **Reads and writes are genuinely concurrent.** Per-slot seqlocks, no global locks on the
18
+ search path. Measured on one Linux box at 1M × 768-d (ef 512): **6,300+ QPS aggregate
19
+ across 8 search threads while a writer sustains ~1,100 inserts/s**, p50 ≈ 1 ms.
20
+ - **Incremental by design.** Insert, update in place, delete with neighbor repair; deleted
21
+ ids are reused via the freelist, so churn never inflates the graph. Reverse-edge overflow
22
+ uses coverage-aware pruning (a bounded RobustPrune) — measured recall\@10 of 0.999 at 1M
23
+ (768-d int8, ef 512) on a calibrated Gaussian-mixture corpus.
24
+ - **Filtering built in.** Allow-bitset filtering (zero callbacks), or a JS predicate
25
+ evaluated in pipelined batches over a threadsafe function while traversal keeps expanding —
26
+ a busy event loop costs speculative overshoot, never search-thread stalls.
27
+ - **Two integration modes.** Standalone (the library allocates ids and maintains the graph:
28
+ `insert`/`remove`/`search`), or mirroring (`writeNodeRaw`/`clearNode`: a host application
29
+ that already maintains an HNSW graph mirrors it in and gets the native search path —
30
+ this is how [Harper](https://github.com/HarperFast/harper) integrates it).
31
+
32
+ Durability is deliberately relaxed: the file is msync'd on a cadence with a transaction
33
+ watermark, and the intended recovery model is "replay indexing from the watermark" against
34
+ the host's authoritative record store. Approximate indexes don't need per-commit fsyncs;
35
+ they need cheap, bounded catch-up. See [DESIGN.md](DESIGN.md) for the format, the
36
+ concurrency model, measured baselines, and the reasoning behind every trade.
37
+
38
+ ## Install & build
39
+
40
+ ```bash
41
+ npm install @harperfast/hnsw
42
+ ```
43
+
44
+ Prebuilds are not published yet: building requires a [Rust toolchain](https://rustup.rs)
45
+ (`npm run build`, or automatically on install when cargo is available). Linux x86_64 is the
46
+ performance target (AVX2); macOS works (scalar fallback); Windows is untested.
47
+
48
+ ## Usage
49
+
50
+ ```js
51
+ const { Plane } = require('@harperfast/hnsw');
52
+
53
+ const plane = Plane.create('/data/vectors.hnsw', 768, 128, 10_000_000);
54
+ const id = plane.insert(myFloat32Vector);
55
+ const hits = await plane.search(queryVector, 10, 512); // [{ id, distance }, ...]
56
+
57
+ // filtered: allow-bitset over node ids
58
+ const allowed = new Uint8Array(Math.ceil(plane.idHighWater() / 8));
59
+ // ... set bits ...
60
+ const filtered = await plane.search(queryVector, 10, 512, allowed);
61
+
62
+ // or a JS predicate, batched off the event loop
63
+ const predicated = await plane.searchWithPredicate(queryVector, 10, 512, (ids) =>
64
+ Uint8Array.from(ids, (id) => (isVisible(id) ? 1 : 0))
65
+ );
66
+ ```
67
+
68
+ Full API in [index.d.ts](index.d.ts).
69
+
70
+ ## Benchmarks
71
+
72
+ `cargo run --release --bin bench -- 1000000 768 100 512 /tmp/bench.hnsw 128 8` builds a 1M ×
73
+ 768-d graph on a calibrated Gaussian-mixture corpus, reports p50/p95/p99, per-visit cost,
74
+ brute-force recall\@10, and a concurrent-throughput pass. Numbers from the design work
75
+ (Linux, single box): p50 0.75 ms, 0.33 µs/visit, recall\@10 0.999 — ~9× the wall-clock and
76
+ ~13× the per-visit cost of a well-optimized pure-JS implementation of the same graph at
77
+ equal recall.
78
+
79
+ ## Status
80
+
81
+ Extracted from the Harper vector-index engine; the format (v2) and API are young and may
82
+ change with a major version + reindex. Roadmap: prebuilds, binary-quantized slot format
83
+ (~4× smaller traversal plane), Matryoshka dimension truncation, mremap growth, index
84
+ slicing with native top-k merge.
85
+
86
+ ## License
87
+
88
+ Apache-2.0
package/build.mjs ADDED
@@ -0,0 +1,46 @@
1
+ // Builds the NAPI module in place (`npm run build`). With --if-needed (the npm install hook),
2
+ // a missing Rust toolchain or a failed build is a warning and exit 0 — consumers treat the
3
+ // module as optional and fall back to their own path when the artifact is absent.
4
+ import { execSync } from 'node:child_process';
5
+ import { createRequire } from 'node:module';
6
+ import { copyFileSync, existsSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ const crateRoot = dirname(fileURLToPath(import.meta.url));
11
+ const ifNeeded = process.argv.includes('--if-needed');
12
+ const artifact = join(crateRoot, 'hnsw-plane.node');
13
+ const prebuilt = join(crateRoot, 'prebuilds', `${process.platform}-${process.arch}`, 'hnsw-plane.node');
14
+
15
+ // a prebuild satisfies --if-needed only if it actually LOADS on this system (a newer-glibc
16
+ // artifact exists but throws at require; fall through to a local build in that case)
17
+ function loads(path) {
18
+ if (!existsSync(path)) return false;
19
+ try {
20
+ createRequire(import.meta.url)(path);
21
+ return true;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ if (ifNeeded && (loads(artifact) || loads(prebuilt))) {
27
+ process.exit(0);
28
+ }
29
+ try {
30
+ // build the lib alone: the bench bin cannot link against unresolved node-api symbols
31
+ execSync('cargo build --release --features napi --lib', { cwd: crateRoot, stdio: 'inherit' });
32
+ } catch (error) {
33
+ if (ifNeeded) {
34
+ console.warn('@harperfast/hnsw: no Rust toolchain or build failed; native module unavailable until `npm run build` succeeds');
35
+ process.exit(0);
36
+ }
37
+ throw error;
38
+ }
39
+ const cdylib =
40
+ process.platform === 'win32'
41
+ ? 'hnsw_plane.dll'
42
+ : process.platform === 'darwin'
43
+ ? 'libhnsw_plane.dylib'
44
+ : 'libhnsw_plane.so';
45
+ copyFileSync(join(crateRoot, 'target', 'release', cdylib), artifact);
46
+ console.log('built hnsw-plane.node');
package/build.rs ADDED
@@ -0,0 +1,6 @@
1
+ fn main() {
2
+ // napi_build wires the node-api link args for the cdylib; only needed for the napi feature
3
+ if std::env::var("CARGO_FEATURE_NAPI").is_ok() {
4
+ napi_build::setup();
5
+ }
6
+ }
package/index.d.ts ADDED
@@ -0,0 +1,104 @@
1
+ export interface SearchHit {
2
+ id: number;
3
+ distance: number;
4
+ }
5
+
6
+ /**
7
+ * A persistent HNSW graph over a memory-mapped fixed-slot file. One file per index; searches
8
+ * run on the libuv thread pool (one N-API crossing per query) and never block the JS event
9
+ * loop. Vectors are int8-quantized with asymmetric (float query × int8 stored) cosine
10
+ * distance. See DESIGN.md for the file format, concurrency model, and durability contract.
11
+ */
12
+ export declare class Plane {
13
+ /** Create a new plane file. `maxNodes` is a sparse reservation — pages materialize on write. */
14
+ static create(path: string, dims: number, layer0Cap: number, maxNodes: number): Plane;
15
+ /** Open an existing plane file (format-version mismatch throws: rebuild the index). */
16
+ static open(path: string): Plane;
17
+
18
+ /**
19
+ * Insert a vector; returns the allocated node id (freed ids are reused). Throws on a
20
+ * dimension mismatch or when the plane is full (maxNodes reached).
21
+ */
22
+ insert(vector: Float32Array): number;
23
+ /** Delete a node; its id returns to the freelist. Pairs with insert(). */
24
+ remove(id: number): void;
25
+
26
+ /**
27
+ * Async k-NN search. `filter` is an allow-bitset over node ids (bit i of byte i>>3);
28
+ * filtered searches are visit-bounded by ef * filterExpansion (default 24).
29
+ */
30
+ search(vector: Float32Array, k: number, ef: number, filter?: Uint8Array, filterExpansion?: number): Promise<Array<SearchHit>>;
31
+ /**
32
+ * Async k-NN search with a JS predicate, evaluated in batches over a threadsafe function
33
+ * while traversal keeps expanding (the search thread never blocks on the event loop).
34
+ * The predicate returns one 0/1 byte per id. Do not await it from code the predicate
35
+ * itself blocks on.
36
+ */
37
+ searchWithPredicate(
38
+ vector: Float32Array,
39
+ k: number,
40
+ ef: number,
41
+ predicate: (ids: Array<number>) => Uint8Array,
42
+ filterExpansion?: number,
43
+ visitBudget?: number
44
+ ): Promise<Array<SearchHit>>;
45
+ /** Synchronous search (benchmarks/tests; blocks the calling thread). */
46
+ searchSync(vector: Float32Array, k: number, ef: number): Array<SearchHit>;
47
+
48
+ /**
49
+ * Mirror a host-maintained node into the plane (dual-write mode): full node state per
50
+ * call, HOST-allocated id (the plane allocator is bypassed), int8 vector bin plus
51
+ * quantization scale and cached 1/|v|, layer-0 neighbor ids, and per-upper-level
52
+ * neighbor id arrays (level 1 first). An existing upper entry is rewritten in place.
53
+ */
54
+ writeNodeRaw(
55
+ id: number,
56
+ level: number,
57
+ vector: Buffer,
58
+ scale: number,
59
+ invMag: number,
60
+ neighbors: Uint32Array,
61
+ upper?: Array<Uint32Array> | null
62
+ ): void;
63
+ /** Mark a node deleted without touching the plane freelist (dual-write mode). */
64
+ clearNode(id: number): void;
65
+ /**
66
+ * Builder-scan variant of writeNodeRaw: writes only when the slot has never been touched,
67
+ * so a backfill scan of an older snapshot can never overwrite newer live-mirrored state.
68
+ * Returns true when the scan's state was written.
69
+ */
70
+ writeNodeRawIfAbsent(
71
+ id: number,
72
+ level: number,
73
+ vector: Buffer,
74
+ scale: number,
75
+ invMag: number,
76
+ neighbors: Uint32Array,
77
+ upper?: Array<Uint32Array> | null
78
+ ): boolean;
79
+ /**
80
+ * Advisory: whether the file recorded a durability barrier (flush) as its last state when
81
+ * opened. Crash recovery does not depend on it — a per-slot lock abandoned by a dead
82
+ * writer is taken over lazily at that slot by whoever waits past the takeover window.
83
+ */
84
+ openedClean(): boolean;
85
+ /** Set the graph entry point (dual-write mode mirrors the host's entry updates). */
86
+ setEntryPoint(id: number, level: number): void;
87
+ getEntryPoint(): Array<number>;
88
+
89
+ /** Lifetime id high-water (allocated ids, including freed ones awaiting reuse). */
90
+ idHighWater(): number;
91
+ getWatermark(): number;
92
+ setWatermark(txn: number): void;
93
+ /**
94
+ * Durability barrier: flush all data, then advance the watermark (omitted = leave the
95
+ * stored watermark untouched), then flush the header alone — a crash between the two
96
+ * flushes leaves an old watermark over durable data, never a new watermark over missing
97
+ * data. Crash recovery is per-slot: a lock abandoned by a dead handle is detected via a
98
+ * kernel-owned registration (immune to pid reuse) and taken over, with the slot marked
99
+ * deleted until rewritten.
100
+ */
101
+ flush(watermark?: number): void;
102
+ /** flush() on the libuv thread pool — a whole-map msync can stall its calling thread. */
103
+ flushAsync(watermark?: number): Promise<void>;
104
+ }
package/index.js ADDED
@@ -0,0 +1,57 @@
1
+ // Loads the native module: a bundled prebuild for this platform when present, else a
2
+ // locally built artifact (`npm run build`, requires a Rust toolchain). Linux prebuilds are
3
+ // glibc builds; musl systems build locally.
4
+ 'use strict';
5
+ const { existsSync } = require('node:fs');
6
+ const { join } = require('node:path');
7
+
8
+ const candidates = [
9
+ join(__dirname, 'prebuilds', `${process.platform}-${process.arch}`, 'hnsw-plane.node'),
10
+ join(__dirname, 'hnsw-plane.node'),
11
+ ];
12
+ // pick the first candidate that actually LOADS (a prebuilt binary can exist but fail to
13
+ // link, e.g. built against a newer glibc than this system's — fall through to a local build)
14
+ let native0;
15
+ const failures = [];
16
+ for (const candidate of candidates) {
17
+ if (!existsSync(candidate)) continue;
18
+ try {
19
+ native0 = require(candidate);
20
+ break;
21
+ } catch (error) {
22
+ failures.push(`${candidate}: ${error.message}`);
23
+ }
24
+ }
25
+ if (!native0) {
26
+ throw new Error(
27
+ `@harperfast/hnsw could not load a native binary for ${process.platform}-${process.arch}. ` +
28
+ 'Build one with `npm run build` in ' +
29
+ __dirname +
30
+ ' (requires a Rust toolchain: https://rustup.rs).' +
31
+ (failures.length ? ` Load failures: ${failures.join('; ')}` : '')
32
+ );
33
+ }
34
+ const native = native0;
35
+
36
+ // A predicate that throws would surface through the ThreadsafeFunction as a fatal exception
37
+ // (aborting the process); wrap it so a throw denies the batch and rejects the search instead.
38
+ const nativeSearchWithPredicate = native.Plane.prototype.searchWithPredicate;
39
+ native.Plane.prototype.searchWithPredicate = function (vector, k, ef, predicate, ...rest) {
40
+ let predicateError;
41
+ const guarded = (ids) => {
42
+ if (predicateError !== undefined) return new Uint8Array(ids.length);
43
+ try {
44
+ const verdicts = predicate(ids);
45
+ return verdicts instanceof Uint8Array ? verdicts : Uint8Array.from(verdicts ?? []);
46
+ } catch (error) {
47
+ predicateError = error;
48
+ return new Uint8Array(ids.length);
49
+ }
50
+ };
51
+ return nativeSearchWithPredicate.call(this, vector, k, ef, guarded, ...rest).then((hits) => {
52
+ if (predicateError !== undefined) throw predicateError;
53
+ return hits;
54
+ });
55
+ };
56
+
57
+ module.exports = native;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@harperfast/hnsw",
3
+ "version": "0.1.0",
4
+ "description": "Persistent, incrementally-maintained, concurrently-searchable native HNSW for Node.js: a memory-mapped fixed-slot graph file with off-event-loop search, seqlock concurrency, int8 asymmetric distance, and bitset/predicate filtering.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/HarperFast/hnsw.git"
9
+ },
10
+ "main": "index.js",
11
+ "types": "index.d.ts",
12
+ "files": [
13
+ "index.js",
14
+ "index.d.ts",
15
+ "prebuilds",
16
+ "hnsw-plane.node",
17
+ "src",
18
+ "build.rs",
19
+ "build.mjs",
20
+ "Cargo.toml",
21
+ "Cargo.lock",
22
+ "README.md",
23
+ "DESIGN.md"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "scripts": {
29
+ "build": "node build.mjs",
30
+ "install": "node build.mjs --if-needed",
31
+ "test": "cargo test --release && node build.mjs && node smoke.mjs"
32
+ },
33
+ "keywords": [
34
+ "hnsw",
35
+ "ann",
36
+ "vector",
37
+ "nearest-neighbor",
38
+ "similarity-search",
39
+ "embedding",
40
+ "mmap",
41
+ "napi",
42
+ "rust"
43
+ ]
44
+ }