kci-vec 0.0.0-stage → 0.2.31

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yukihiro Kimura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # kci-vec for Node.js (experimental)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vector search inside your Node.js program. No server, no runtime dependencies; the index can be saved to an
4
+ encrypted file. With nothing else given, a search misses no row.
5
+
6
+ ```sh
7
+ npm install kci-vec
8
+ ```
9
+
10
+ | Machine | What the install does |
11
+ |---|---|
12
+ | Windows x64, Linux x64 (glibc 2.28 or later), macOS on Apple silicon (macOS 11 or later) | uses the ready-made binary in the package: no compiler needed |
13
+ | anything else (Intel Mac, ARM Linux, Alpine and other musl Linux, older Linux) | builds the C sources in the package: needs `gcc` or `cc` on the PATH |
14
+
15
+ On x86-64 the CPU must have AVX2 and FMA (otherwise loading says so). Node.js 18 or later. Not tried on an Intel Mac or on ARM Linux.
16
+
17
+ ```js
18
+ const { KciVec } = require('kci-vec');
19
+
20
+ const v = new KciVec(3); // 3 dimensions, cosine
21
+ v.addMany([1, 2, 3], [[1, 0, 0], [0, 1, 0], [0.9, 0.1, 0]]);
22
+ v.build();
23
+
24
+ console.log(v.search([1, 0, 0], 2)); // [ { id: 1, score: 1 }, { id: 3, score: 0.99... } ]
25
+
26
+ v.save('my.kvec', 'a pass phrase'); // encrypted; a wrong key or an altered file is refused at load
27
+ const w = KciVec.load('my.kvec', 'a pass phrase');
28
+ ```
29
+
30
+ `node example.js` runs the whole round: search, narrowing by fields, an encrypted file, opening it again.
31
+
32
+ | Call | What it does |
33
+ |---|---|
34
+ | `new KciVec(dim, { metric, M, efc, rerank, maxNorm, dedup, bigint })` | `metric`: `'cosine'` (default), `'l2'`, `'ip'`. `rerank: 0` keeps no floats (less memory; answers can miss rows). `bigint: true` answers ids as BigInt |
35
+ | `add(id, vec)`, `addMany(ids, rows)` | before `build()`. A vector is a `Float32Array` or an array of numbers; `rows` an array of vectors or one `Float32Array` |
36
+ | `build({ threads })`, `buildAsync({ threads })` | `build` blocks until done; `buildAsync` returns a Promise and leaves the event loop free |
37
+ | `search(query, k, { filter, ef, rerankN, method, threads })` | `[{ id, score }]`, best first. `filter`: the ids that may be answered (array, typed array, Set) |
38
+ | `searchAsync(query, k, { ... })` | the same as a Promise, on a worker thread; several may run at once |
39
+ | `where.ids(fieldsById, condition)` | the ids whose fields pass a condition, to give as `filter` (below) |
40
+ | `insert(id, vec)`, `delete(id)`, `compact()` | change a built index. `delete` returns false when the id is not there (or already deleted); after `add()` on a built index it throws until `build()`, as `search` does |
41
+ | `save(file, key)`, `KciVec.load(file, key, { rerank, bigint })` | `key`: a string or bytes; without it the file is not encrypted |
42
+ | `knnGraph(k, { exact, ef, threads })` | the k nearest other ids of every id, as typed arrays |
43
+ | `count`, `dim`, `metric`, `isBuilt`, `closed`, `close()` | |
44
+
45
+ ## Store: string ids, texts and fields kept with the vectors
46
+
47
+ When the records have names of their own, a text and some fields, `Store` keeps them together and saves them
48
+ together (encrypted with a key). The vectors are yours (an embedding API, a model of your own).
49
+
50
+ ```js
51
+ const { Store } = require('kci-vec');
52
+
53
+ const s = new Store(); // { metric: 'l2' } or 'ip' for vectors whose length matters
54
+ s.add([{ id: 'manual-12', vector: [0.1, 0.9, 0.2], text: 'How to reset the password', fields: { year: 2024, kind: 'manual' } },
55
+ { id: 'memo-3', vector: [0.8, 0.1, 0.3], text: 'Expense reports close at month end', fields: { year: 2025, kind: 'memo' } }]);
56
+ const hits = s.search([0.2, 0.8, 0.1], 5, { where: { year: { $gte: 2024 } } }); // [{ id, score, text, fields }]
57
+ s.save('my_store', 'a passphrase'); // a folder; without the key nothing in it is readable
58
+ const again = Store.load('my_store', 'a passphrase');
59
+ ```
60
+
61
+ | Call | What it does |
62
+ |---|---|
63
+ | `add(records, { replace })` | an id that is already there is refused unless `replace: true`. A call that throws has added nothing |
64
+ | `search(vector, k, { where, filter })` | best first. `where`: a condition on the fields (below); `filter`: the ids that may be answered |
65
+ | `get(id)`, `has(id)`, `delete(id)`, `ids()`, `size`, `dim`, `metric` | |
66
+ | `save(dir, key)`, `Store.load(dir, key)` | the folder is the one the Python client writes for `TextIndex(mode="dense", dense="vectors")` with string ids: either opens the other's |
67
+
68
+ No language model runs in the Node client: texts are kept and returned, not read.
69
+
70
+ Fields beside the vectors (genre, year, owner ...): keep them yourself, ask by a condition.
71
+
72
+ ```js
73
+ const { KciVec, where } = require('kci-vec');
74
+
75
+ const fields = new Map([[1, { genre: 'scifi', year: 2004 }], [2, { genre: 'crime', year: 2011 }], [3, { genre: 'scifi', year: 2019 }]]);
76
+ const hits = v.search([1, 0, 0], 2, { filter: where.ids(fields, { genre: 'scifi', year: { $gte: 2010 } }) });
77
+ ```
78
+
79
+ Comparisons: `$eq` `$ne` `$gt` `$gte` `$lt` `$lte` `$in` `$nin` `$contains` `$exists`; `$and`, `$or`, `$not` combine
80
+ conditions. A field name that no record has throws (a mistyped name would otherwise answer nothing).
81
+
82
+ Limits
83
+
84
+ - Ids are whole numbers from 0. Above 2^53 - 1 give BigInt and make the index with `{ bigint: true }`.
85
+ - `knnGraph`, `compact` and `save` block the event loop while they run; the build and the search have async forms.
86
+ - One index belongs to one JavaScript thread (the main thread or one worker). While `searchAsync` calls are under way the index cannot be changed.
87
+ - A filter is a set of ids, not a function; the fields themselves are not stored in the index or its file.
88
+ - The partitioned lists, the quantized graph and the text layer of the Python client are not here.
89
+ - A file saved here is read by the Python client and the other way round (the same format and keys).
90
+ - Marked experimental: names and defaults may still change.
91
+
92
+ From the source repository (the folder `clients/node`):
93
+
94
+ ```sh
95
+ npm install # fetches node-api-headers (headers for the build) and builds build/kci_vec.node
96
+ node test.js # needs gcc (MinGW-w64 on Windows) or cc for the build; "node build.js" builds again
97
+ node test_store.js
98
+ node test_fuzz.js # random indexes and changes, every answer against the exact one (about a minute)
99
+ ```
100
+
101
+ There the examples read `require('./index.js')`. `npm pack` makes the package (it carries the C sources).
package/build.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+ // Builds build/kci_vec.node with gcc / cc: kci_vec_node.c + kci_vec.c + kci_sparse.c (for the files Store keeps
3
+ // beside the index), nothing else linked.
4
+ // Needs the node-api-headers package (npm install) for node_api.h and, on Windows, the list of Node's exports.
5
+ // The tools run in this folder and get every path relative to it (the name of the folder above does not matter then).
6
+ // CC = the compiler (default gcc, cc on macOS); KCI_VEC_MARCH = the -march value (default x86-64-v3 on x86-64).
7
+ const { execFileSync } = require('child_process');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const hdr = require('node-api-headers');
11
+
12
+ const here = __dirname;
13
+ const src = [path.join(here, '..', '..'), path.join(here, 'src')].find((d) => fs.existsSync(path.join(d, 'kci_vec.c'))); // the repository's own first, then the copy a package carries
14
+ if (!src) throw new Error('kci_vec.c was not found (looked in ./src and ../..)');
15
+ const out = path.join(here, 'build');
16
+ fs.mkdirSync(out, { recursive: true });
17
+ const cc = process.env.CC || (process.platform === 'darwin' ? 'cc' : 'gcc');
18
+ const rel = (p) => path.relative(here, p) || '.';
19
+ const run = (cmd, args) => { console.log(cmd + ' ' + args.join(' ')); execFileSync(cmd, args, { stdio: 'inherit', cwd: here }); };
20
+
21
+ const flags = ['-O3', '-std=gnu11', '-fno-strict-aliasing', '-I' + rel(hdr.include_dir), '-I' + rel(src), '-shared'];
22
+ if (process.arch === 'x64') flags.push('-march=' + (process.env.KCI_VEC_MARCH || 'x86-64-v3'), '-maes', '-mprefer-vector-width=256');
23
+ else if (process.env.KCI_VEC_MARCH) flags.push('-march=' + process.env.KCI_VEC_MARCH);
24
+ const files = ['kci_vec_node.c', rel(path.join(src, 'kci_vec.c')), rel(path.join(src, 'kci_sparse.c'))];
25
+ const target = path.join(out, 'kci_vec.node');
26
+ if (process.platform === 'win32') {
27
+ // MinGW: the import library for Node's own exports is made from the list node-api-headers carries
28
+ const imp = rel(path.join(out, 'libnode_api.a'));
29
+ run('dlltool', ['-d', rel(hdr.def_paths.node_api_def), '-l', imp]);
30
+ run(cc, [...flags, '-fno-ipa-bit-cp', '-static', '-static-libgcc', '-s', '-o', rel(target), ...files, imp]);
31
+ } else if (process.platform === 'darwin') {
32
+ run(cc, [...flags, '-fPIC', '-undefined', 'dynamic_lookup', '-o', rel(target), ...files, '-lpthread', '-lm']);
33
+ } else {
34
+ run(cc, [...flags, '-fPIC', '-o', rel(target), ...files, '-lpthread', '-lm']);
35
+ }
36
+ console.log('built ' + target);
package/example.js ADDED
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ // The whole round in one file: put vectors in, search, narrow by fields, save encrypted, open again.
3
+ // node example.js
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { KciVec, where } = require('./index.js');
8
+
9
+ // Vectors usually come from an embedding model. Here: 4 hand-made ones of 3 dimensions.
10
+ const items = [
11
+ { id: 1, title: 'Dune', vec: [0.9, 0.1, 0.0], fields: { genre: 'scifi', year: 1965 } },
12
+ { id: 2, title: 'Neuromancer', vec: [0.8, 0.2, 0.1], fields: { genre: 'scifi', year: 1984 } },
13
+ { id: 3, title: 'The Big Sleep', vec: [0.1, 0.9, 0.0], fields: { genre: 'crime', year: 1939 } },
14
+ { id: 4, title: 'Gone Girl', vec: [0.2, 0.8, 0.1], fields: { genre: 'crime', year: 2012 } },
15
+ ];
16
+ const title = new Map(items.map((x) => [x.id, x.title]));
17
+ const fields = new Map(items.map((x) => [x.id, x.fields]));
18
+
19
+ const v = new KciVec(3);
20
+ v.addMany(items.map((x) => x.id), items.map((x) => x.vec));
21
+ v.build();
22
+
23
+ const show = (label, hits) => console.log(label + ': ' + hits.map((h) => `${title.get(h.id)} (${h.score.toFixed(3)})`).join(', '));
24
+ const query = [1, 0, 0];
25
+ show('nearest 2', v.search(query, 2));
26
+ show('after 1980 only', v.search(query, 2, { filter: where.ids(fields, { year: { $gte: 1980 } }) }));
27
+ show('crime only', v.search(query, 2, { filter: where.ids(fields, { genre: 'crime' }) }));
28
+
29
+ const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'kci-vec-')), 'books.kvec');
30
+ v.save(file, 'a pass phrase'); // encrypted: without the key the file cannot be opened
31
+ v.close();
32
+ const w = KciVec.load(file, 'a pass phrase');
33
+ w.searchAsync(query, 1).then((hits) => { // the same search on a worker thread
34
+ show('opened again', hits);
35
+ try { KciVec.load(file, 'a wrong key'); } catch (e) { console.log('wrong key: refused'); }
36
+ w.close();
37
+ fs.rmSync(path.dirname(file), { recursive: true, force: true });
38
+ });
package/index.d.ts ADDED
@@ -0,0 +1,83 @@
1
+ export type Id = number | bigint;
2
+ export type Vector = Float32Array | Float64Array | number[];
3
+ export type Ids = Id[] | BigUint64Array | Set<Id> | ArrayLike<number>;
4
+
5
+ export interface KciVecOptions {
6
+ /** 'cosine' (default), 'l2' (squared Euclidean distance) or 'ip' (dot product) */
7
+ metric?: 'cosine' | 'l2' | 'ip';
8
+ M?: number;
9
+ efc?: number;
10
+ /** candidates scored on the floats; 0 keeps no floats (less memory, answers can miss rows). Default 200 */
11
+ rerank?: number;
12
+ /** l2 / ip: the longest vector to expect (0 = taken from the data at the build) */
13
+ maxNorm?: number;
14
+ /** keep identical vectors once */
15
+ dedup?: boolean;
16
+ /** answer ids as BigInt (needed for ids above 2^53 - 1) */
17
+ bigint?: boolean;
18
+ }
19
+ export interface SearchOptions {
20
+ ef?: number;
21
+ rerankN?: number;
22
+ /** only these ids may be answered */
23
+ filter?: Ids;
24
+ /** 'auto' (default): no row is missed while the floats are kept; 'graph': the graph search; 'exact' */
25
+ method?: 'auto' | 'graph' | 'exact';
26
+ threads?: number;
27
+ }
28
+ export interface Hit { id: Id; score: number; }
29
+ export interface KnnGraph { count: number; k: number; ids: BigUint64Array; neighbors: BigUint64Array; scores: Float32Array; }
30
+
31
+ export class KciVec {
32
+ constructor(dim: number, opts?: KciVecOptions);
33
+ readonly count: number;
34
+ readonly dim: number;
35
+ readonly metric: 'cosine' | 'l2' | 'ip';
36
+ readonly isBuilt: boolean;
37
+ readonly closed: boolean;
38
+ add(id: Id, vec: Vector): void;
39
+ addMany(ids: Ids, rows: Vector[] | Float32Array): number;
40
+ build(opts?: { threads?: number }): number;
41
+ buildAsync(opts?: { threads?: number }): Promise<number>;
42
+ search(query: Vector, k?: number, opts?: SearchOptions): Hit[];
43
+ searchAsync(query: Vector, k?: number, opts?: SearchOptions): Promise<Hit[]>;
44
+ insert(id: Id, vec: Vector): void;
45
+ delete(id: Id): boolean;
46
+ compact(): number;
47
+ save(file: string, key?: string | Uint8Array | null): void;
48
+ static load(file: string, key?: string | Uint8Array | null, opts?: { rerank?: number; bigint?: boolean }): KciVec;
49
+ knnGraph(k?: number, opts?: { exact?: boolean; ef?: number; threads?: number }): KnnGraph;
50
+ close(): void;
51
+ }
52
+
53
+ export type FieldValue = string | number | boolean | null | Array<string | number | boolean>;
54
+ export type Fields = Record<string, FieldValue>;
55
+ export type Condition = Record<string, unknown>;
56
+ export namespace where {
57
+ /** the condition as a function of one record */
58
+ function matcher(cond: Condition): (record: Fields | null | undefined) => boolean;
59
+ /** the ids whose fields pass, for search(query, k, { filter }) */
60
+ function ids<T extends Id>(fieldsById: Map<T, Fields> | Record<number, Fields>, cond: Condition): T[];
61
+ }
62
+
63
+ /** vectors of your own with string ids, a text and fields each; saved as a folder the Python client also opens */
64
+ export interface StoreRecord { id: string; vector: Vector; text?: string | null; fields?: Fields | null; }
65
+ export interface StoreHit { id: string; score: number; text: string; fields: Fields; }
66
+ export class Store {
67
+ constructor(opts?: { metric?: 'cosine' | 'l2' | 'ip' });
68
+ readonly size: number;
69
+ readonly dim: number;
70
+ readonly metric: 'cosine' | 'l2' | 'ip';
71
+ ids(): string[];
72
+ has(id: string): boolean;
73
+ get(id: string): { text: string; fields: Fields } | null;
74
+ /** an id that is already there is refused unless replace is true; a call that throws has added nothing */
75
+ add(records: StoreRecord[], opts?: { replace?: boolean }): string[];
76
+ delete(id: string): boolean;
77
+ /** best first. cosine / ip: larger = nearer; l2: the squared distance, smaller = nearer */
78
+ search(vector: Vector, k?: number, opts?: { where?: Condition; filter?: Iterable<string> }): StoreHit[];
79
+ /** key: a passphrase; the index, the ids, the texts and the fields are then encrypted */
80
+ save(dir: string, key?: string | Uint8Array | null): void;
81
+ static load(dir: string, key?: string | Uint8Array | null): Store;
82
+ close(): void;
83
+ }
package/index.js ADDED
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+ // KCI-Vec for Node.js. The addon (kci_vec_node.c) hands the calls to kci_vec.c; the defaults here follow
3
+ // the Python client: with nothing else given a search misses no row (the exact answer) while the floats are kept.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ // A binary that is there but does not load (a ready-made one on a system it was not built for) is passed
8
+ // over and the next place is tried; the error names each place and why.
9
+ function addon() {
10
+ const tried = [];
11
+ for (const p of [process.env.KCI_VEC_NODE,
12
+ path.join(__dirname, 'prebuilds', `${process.platform}-${process.arch}`, 'kci_vec.node'),
13
+ path.join(__dirname, 'build', 'kci_vec.node')]) {
14
+ if (!p) continue;
15
+ if (!fs.existsSync(p)) { tried.push(p + ' (not there)'); continue; }
16
+ try { return require(p); } catch (e) { tried.push(p + ' (' + String(e && e.message).split('\n')[0] + ')'); }
17
+ }
18
+ throw new Error('kci-vec: the native part could not be loaded (run "node build.js" in the package folder; it needs gcc / cc). Looked at: ' + tried.join('; '));
19
+ }
20
+ const lib = addon();
21
+
22
+ const METRICS = ['cosine', 'l2', 'ip'];
23
+ const MAX_U64 = (1n << 64n) - 1n;
24
+ const EXACT_FLOATS = 1e7; // count x dim up to which the exact answer may scan the floats
25
+ const EXACT_ONE_THREAD = 4e7; // up to here the exact answer runs on one thread
26
+ const KNN_EXACT = 2e13; // knnGraph: exact while count x count x dim is at most this
27
+
28
+ function id1(x, what) {
29
+ if (typeof x === 'bigint') {
30
+ if (x < 0n || x > MAX_U64) throw new RangeError(`${what}: id ${x} is outside 0 .. 2^64 - 1`);
31
+ return x;
32
+ }
33
+ if (typeof x === 'number' && Number.isSafeInteger(x) && x >= 0) return BigInt(x);
34
+ throw new TypeError(`${what}: an id must be a whole number (a number up to 2^53 - 1, or a BigInt up to 2^64 - 1), not ${String(x)}`);
35
+ }
36
+ function ids64(ids, what) {
37
+ if (ids instanceof BigUint64Array) return ids;
38
+ if (ids == null || typeof ids[Symbol.iterator] !== 'function' || typeof ids === 'string') throw new TypeError(`${what}: the ids must be an array, a typed array or a Set`);
39
+ const a = Array.isArray(ids) || ArrayBuffer.isView(ids) ? ids : Array.from(ids);
40
+ const out = new BigUint64Array(a.length);
41
+ for (let i = 0; i < a.length; i++) out[i] = id1(a[i], what);
42
+ return out;
43
+ }
44
+ function int1(x, what, lo, hi) {
45
+ if (typeof x !== 'number' || !Number.isInteger(x) || x < lo || x > hi) throw new RangeError(`${what} must be a whole number ${lo} .. ${hi}, not ${String(x)}`);
46
+ return x;
47
+ }
48
+ function row(v, dim, what) {
49
+ let a;
50
+ if (v instanceof Float32Array) a = v;
51
+ else if (Array.isArray(v) || v instanceof Float64Array) a = Float32Array.from(v);
52
+ else throw new TypeError(`${what}: a vector must be a Float32Array, a Float64Array or an array of numbers`);
53
+ if (a.length !== dim) throw new RangeError(`${what}: the vector has ${a.length} numbers, the index has ${dim} dimensions`);
54
+ for (let i = 0; i < dim; i++) if (!Number.isFinite(a[i])) throw new RangeError(`${what}: the vector has a NaN or an infinity (at ${i})`);
55
+ return a;
56
+ }
57
+ function keyBytes(key) {
58
+ if (key == null || key === '' || key.length === 0) return null;
59
+ if (typeof key === 'string') return new Uint8Array(Buffer.from(key, 'utf8'));
60
+ if (key instanceof Uint8Array) return new Uint8Array(key.buffer, key.byteOffset, key.length); // a Buffer too
61
+ throw new TypeError('the key must be a string, a Buffer or a Uint8Array');
62
+ }
63
+ function fileEncrypted(p) { // true / false as the header says, null when it cannot be read (load then says why)
64
+ let fd;
65
+ try {
66
+ fd = fs.openSync(p, 'r');
67
+ const h = Buffer.alloc(12);
68
+ if (fs.readSync(fd, h, 0, 12, 0) < 12 || h.toString('latin1', 0, 4) !== 'KCIV') return null;
69
+ return (h.readUInt32LE(8) & 1) === 1;
70
+ } catch (e) {
71
+ return null;
72
+ } finally {
73
+ if (fd !== undefined) fs.closeSync(fd);
74
+ }
75
+ }
76
+
77
+ class KciVec {
78
+ #h; #big; #rerank; #warnedI8 = false;
79
+
80
+ /** new KciVec(dim, { metric: 'cosine' | 'l2' | 'ip', M: 16, efc: 200, rerank: 200, maxNorm: 0, dedup: false, bigint: false }) */
81
+ constructor(dim, opts = {}) {
82
+ if (dim && dim.__handle !== undefined) { // from load()
83
+ this.#h = dim.__handle; this.#big = !!opts.bigint; this.#rerank = opts.rerank === undefined ? 100 : int1(opts.rerank, 'rerank', 0, 32767);
84
+ return;
85
+ }
86
+ int1(dim, 'dim', 1, 65536);
87
+ const metric = opts.metric === undefined ? 'cosine' : opts.metric;
88
+ if (!METRICS.includes(metric)) throw new RangeError("metric must be 'cosine', 'l2' or 'ip'");
89
+ const M = opts.M === undefined ? 16 : int1(opts.M, 'M', 2, 256);
90
+ const efc = opts.efc === undefined ? 200 : int1(opts.efc, 'efc', 1, 32767);
91
+ this.#rerank = opts.rerank === undefined ? 200 : int1(opts.rerank, 'rerank', 0, 32767);
92
+ const mx = opts.maxNorm === undefined ? 0 : opts.maxNorm;
93
+ if (typeof mx !== 'number' || !(mx >= 0)) throw new RangeError('maxNorm must be 0 or more');
94
+ this.#big = !!opts.bigint;
95
+ this.#h = lib.create(dim, M, efc, METRICS.indexOf(metric), mx, this.#rerank > 0, !!opts.dedup);
96
+ }
97
+
98
+ #info() { const x = lib.info(this.#live()); return { count: x[0], dim: x[1], metric: x[2], built: x[3] !== 0, floats: x[4] === 1, proof: x[5] === 1, ef: x[6], rerank: x[7], unreached: x[8] }; }
99
+ #live() { if (!this.#h) throw new Error('kci_vec: the index is closed'); return this.#h; }
100
+ #id(b) {
101
+ if (this.#big) return b;
102
+ if (b > 9007199254740991n) throw new RangeError(`kci_vec: id ${b} does not fit a number; make the index with { bigint: true }`);
103
+ return Number(b);
104
+ }
105
+
106
+ get count() { return this.#info().count; }
107
+ get dim() { return this.#info().dim; }
108
+ get metric() { return METRICS[this.#info().metric]; }
109
+ get isBuilt() { return this.#info().built; }
110
+ get closed() { return !this.#h; }
111
+
112
+ /** Add one vector (before build). The same id again replaces the earlier one at the build. */
113
+ add(id, vec) {
114
+ const d = this.dim;
115
+ this.#rows(new BigUint64Array([id1(id, 'add')]), row(vec, d, 'add'), false, 'add');
116
+ }
117
+
118
+ /** Add many: ids (array / typed array) and rows (an array of vectors, or one Float32Array of ids.length x dim numbers). */
119
+ addMany(ids, rows) {
120
+ const d = this.dim, u = ids64(ids, 'addMany');
121
+ let x;
122
+ if (rows instanceof Float32Array) {
123
+ x = rows;
124
+ for (let i = 0; i < x.length; i++) if (!Number.isFinite(x[i])) throw new RangeError(`addMany: row ${Math.floor(i / d)} has a NaN or an infinity; nothing was added`);
125
+ } else if (Array.isArray(rows)) {
126
+ x = new Float32Array(rows.length * d);
127
+ for (let i = 0; i < rows.length; i++) x.set(row(rows[i], d, `addMany (row ${i})`), i * d);
128
+ } else throw new TypeError('addMany: rows must be an array of vectors or a Float32Array');
129
+ if (x.length !== u.length * d) throw new RangeError(`addMany: ${u.length} ids but ${x.length / d} rows of ${d} numbers`);
130
+ this.#rows(u, x, false, 'addMany');
131
+ return u.length;
132
+ }
133
+
134
+ #rows(u, x, ins, what) {
135
+ const r = lib.add(this.#live(), u, x, ins);
136
+ if (r >= 0) return;
137
+ if (r <= -2e9) throw new Error(`${what}: the index keeps no floats (rerank: 0); insert needs them`);
138
+ const i = -r - 1, m = this.metric;
139
+ throw new Error(`${what}: row ${i} (id ${u[i]}) was refused` + (m === 'l2' ? ' (l2: longer than maxNorm, or than the vectors at the build?)' : m === 'ip' ? ' (ip: longer than the longest vector at the build?)' : '')
140
+ + (i ? `; the ${i} rows before it were added` : ''));
141
+ }
142
+
143
+ #built(r) {
144
+ if (r[3] > 0) process.emitWarning(`kci_vec: ${r[3]} rows cannot be reached by the graph search after this build (the exact search still finds them)`);
145
+ if (r[1] > 0 && r[2] < 0.97) process.emitWarning(`kci_vec: at the widest search tried (ef ${r[1]}) the index finds ${(100 * r[2]).toFixed(1)} % of the true 10 nearest of its own vectors; a graph search will miss some. A larger M at creation, or ef / rerankN at search, raise it.`);
146
+ return r[0];
147
+ }
148
+ /** Build the graph. Returns the seconds it took. Blocks until done: see buildAsync. threads: 0 = all cores. */
149
+ build(opts = {}) {
150
+ return this.#built(lib.build(this.#live(), opts.threads === undefined ? 0 : int1(opts.threads, 'threads', 0, 1024), this.#rerank));
151
+ }
152
+ /** As build(), on a worker thread: a Promise of the seconds. Until it settles every other call on this index throws. */
153
+ async buildAsync(opts = {}) {
154
+ return this.#built(await lib.buildAsync(this.#live(), opts.threads === undefined ? 0 : int1(opts.threads, 'threads', 0, 1024), this.#rerank));
155
+ }
156
+
157
+ /**
158
+ * The k best as [{ id, score }], best first (score: cosine, squared distance for 'l2', dot product for 'ip').
159
+ * With nothing else given no row is missed while the floats are kept. opts: ef / rerankN (the graph's knobs),
160
+ * filter (ids that may be answered: array, typed array or Set), method 'auto' | 'graph' | 'exact', threads.
161
+ */
162
+ search(query, k = 10, opts = {}) {
163
+ const p = this.#plan(query, k, opts);
164
+ return p ? this.#hits(lib.search(...p), p[3]) : [];
165
+ }
166
+ /** As search(), on a worker thread: a Promise of the hits. Several may run at once; until all have settled the calls that change the index (add, insert, delete, compact, build, close) throw. */
167
+ async searchAsync(query, k = 10, opts = {}) {
168
+ const p = this.#plan(query, k, opts);
169
+ return p ? this.#hits(await lib.searchAsync(...p), p[3]) : [];
170
+ }
171
+
172
+ // the arguments of the addon's search for this question, or null when the answer is [] without asking
173
+ #plan(query, k, opts) {
174
+ const inf = this.#info();
175
+ int1(k, 'k', 0, 16000000);
176
+ const q = row(query, inf.dim, 'search');
177
+ // as the Python client: cosine has no answer for a query with no direction. 'l2' and 'ip' answer it.
178
+ if (inf.metric === 0 && !q.some((x) => x !== 0)) throw new RangeError('search: the query is all zeros: it has no direction for the cosine index');
179
+ const method = opts.method === undefined ? 'auto' : opts.method;
180
+ if (!['auto', 'graph', 'exact'].includes(method)) throw new RangeError("method must be 'auto', 'graph' or 'exact'");
181
+ const ef0 = opts.ef === undefined ? null : int1(opts.ef, 'ef', 1, 32767);
182
+ const rn0 = opts.rerankN === undefined ? null : int1(opts.rerankN, 'rerankN', 0, 32767);
183
+ let f = null;
184
+ if (opts.filter != null) {
185
+ f = ids64(opts.filter, 'filter').slice().sort();
186
+ if (f.length === 0) return null;
187
+ }
188
+ if (k === 0 || inf.count === 0) return null;
189
+ if (!inf.built) throw new Error('kci_vec: the index is not built (call build() after adding; insert() adds to a built index)');
190
+ // as the Python client: an index without the floats (rerank: 0) ranks on its 1-byte rows and can miss
191
+ // rows; said once an index, at its first search.
192
+ if (!inf.floats && !this.#warnedI8) {
193
+ this.#warnedI8 = true;
194
+ process.emitWarning('kci_vec: this index keeps no floats (rerank: 0): a search can miss rows the floats would rank in; give rerank above 0 at creation for the exact answer');
195
+ }
196
+ const cells = inf.count * inf.dim, big = cells > EXACT_ONE_THREAD;
197
+ const small = inf.floats ? (cells <= EXACT_FLOATS || inf.proof) : cells <= EXACT_FLOATS;
198
+ let exact = method === 'exact';
199
+ if (method === 'auto') {
200
+ if (small && !(big && (ef0 !== null || rn0 !== null))) exact = true;
201
+ else if (f && inf.floats && f.length * inf.dim <= EXACT_FLOATS) exact = true; // few ids pass: compare with each of them
202
+ }
203
+ if (exact) {
204
+ const th = opts.threads === undefined ? (big ? 0 : 1) : int1(opts.threads, 'threads', 0, 1024);
205
+ return [this.#h, q, k, 1, 0, 0, th, f];
206
+ }
207
+ const ef = Math.max(k, ef0 !== null ? ef0 : (inf.ef > 0 ? inf.ef : 100));
208
+ let rn = rn0 !== null ? rn0 : (inf.floats ? this.#rerank : 0);
209
+ if (rn0 === null && rn && inf.rerank > rn && ef >= inf.rerank) rn = inf.rerank;
210
+ if (rn) rn = Math.max(rn, k);
211
+ return [this.#h, q, k, 0, ef, rn, 0, f];
212
+ }
213
+ #hits(r, mode) {
214
+ if (r[2] < 0) throw new Error(mode === 1 ? 'kci_vec: this index cannot give the exact answer' : 'kci_vec: the graph search was refused (no graph built, or out of memory)');
215
+ const out = new Array(r[2]);
216
+ for (let i = 0; i < r[2]; i++) out[i] = { id: this.#id(r[0][i]), score: r[1][i] };
217
+ return out;
218
+ }
219
+
220
+ /** Add one vector to a built index (no build needed after it). An id that is there is replaced. */
221
+ insert(id, vec) {
222
+ const inf = this.#info();
223
+ if (!inf.built) throw new Error('insert: the index is not built yet; use add() / addMany() and then build()');
224
+ this.#rows(new BigUint64Array([id1(id, 'insert')]), row(vec, inf.dim, 'insert'), true, 'insert');
225
+ }
226
+ /** Remove an id from the answers. true when it was there. count stays until compact(). */
227
+ // after add() on a built index (before the next build), refused as search() is.
228
+ delete(id) {
229
+ const u = id1(id, 'delete'), inf = this.#info();
230
+ if (!inf.built && inf.count > 0) throw new Error('delete: the index is not built (call build() after adding; insert() adds to a built index); nothing was deleted');
231
+ return lib.del(this.#h, u);
232
+ }
233
+ /** Build again over the ids that are left, giving the room of the deleted ones back. Returns the count. */
234
+ compact() { return lib.compact(this.#live()); }
235
+
236
+ /** Write the index to a file. key (a string or bytes) encrypts it. */
237
+ save(file, key) {
238
+ if (typeof file !== 'string') throw new TypeError('save: the path must be a string');
239
+ if (lib.save(this.#live(), file, keyBytes(key)) !== 0) throw new Error(`save failed: cannot write ${JSON.stringify(file)}`);
240
+ }
241
+ /** Read an index. A wrong key, a damaged or altered file, or a plain file where a key was given: an Error. */
242
+ static load(file, key, opts = {}) {
243
+ if (typeof file !== 'string') throw new TypeError('load: the path must be a string');
244
+ const kb = keyBytes(key);
245
+ if (kb && fileEncrypted(file) === false) throw new Error('load failed: a key was given but the file is not encrypted (it may have been replaced)');
246
+ return new KciVec({ __handle: lib.load(file, kb) }, opts);
247
+ }
248
+
249
+ /**
250
+ * The k nearest other ids of every id (a kNN graph). Returns { count, k, ids, neighbors, scores }: ids is a
251
+ * BigUint64Array of count, neighbors a BigUint64Array and scores a Float32Array of count x k (line i belongs to
252
+ * ids[i]; 2^64 - 1 and -Infinity (l2: Infinity) where an id has fewer than k neighbours).
253
+ * opts.exact: true = no neighbour missed, false = through the graph, default: exact while count x count x dim is
254
+ * at most 2 x 10^13 and the floats are kept. Blocks until done.
255
+ */
256
+ knnGraph(k = 10, opts = {}) {
257
+ const inf = this.#info();
258
+ int1(k, 'k', 1, 16383);
259
+ const ef = opts.ef === undefined ? 0 : int1(opts.ef, 'ef', 1, 32767);
260
+ if (inf.count && !inf.built) throw new Error('kci_vec: the index is not built (call build() after adding)');
261
+ let exact = opts.exact;
262
+ if (exact === undefined || exact === null) exact = inf.floats && inf.count * inf.count * inf.dim <= KNN_EXACT;
263
+ else if (exact && !inf.floats) throw new Error('knnGraph: exact needs the floats (rerank above 0 at creation)');
264
+ const r = lib.knn(this.#h, k, exact ? -1 : ef, opts.threads === undefined ? 0 : int1(opts.threads, 'threads', 0, 1024));
265
+ if (r[3] < 0) throw new Error('knnGraph: this index cannot answer (no graph, or out of memory)');
266
+ const n = r[3];
267
+ return { count: n, k, ids: r[0].subarray(0, n), neighbors: r[1].subarray(0, n * k), scores: r[2].subarray(0, n * k) };
268
+ }
269
+
270
+ /** Free the index now (otherwise when it is collected). Calls after it throw. */
271
+ close() { if (this.#h) { lib.close(this.#h); this.#h = null; } }
272
+ }
273
+
274
+ module.exports = { KciVec, Store: require('./store.js')(KciVec, lib, keyBytes), where: require('./where.js') };
package/install.js ADDED
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+ // npm runs this after installing: nothing to do when a ready-made binary for this machine came with the
3
+ // package (prebuilds/), otherwise build from the C sources (needs gcc / cc).
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ // the ready-made binary is loaded once here: where it does not load (an older or different C library,
7
+ // a CPU it was not built for) the C sources are built instead.
8
+ const pre = path.join(__dirname, 'prebuilds', `${process.platform}-${process.arch}`, 'kci_vec.node');
9
+ if (fs.existsSync(pre)) {
10
+ try { require(pre); process.exit(0); } catch (e) {
11
+ console.error('kci-vec: the ready-made binary does not load here (' + String(e && e.message).split('\n')[0] + '); building from the C sources');
12
+ }
13
+ }
14
+ try {
15
+ require('./build.js');
16
+ } catch (e) {
17
+ console.error('\nkci-vec: could not build the native part: ' + (e && e.message ? e.message.split('\n')[0] : e));
18
+ console.error('kci-vec: it needs a C compiler on the PATH (gcc; on Windows MinGW-w64, on macOS the command line tools).');
19
+ console.error('kci-vec: after installing one, install again (in the source folder: "node build.js")\n');
20
+ process.exit(1);
21
+ }