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.
@@ -0,0 +1,381 @@
1
+ /*
2
+ * kci_win_compat.h — POSIX → Windows shim for the kci_analyze server.
3
+ * ===================================================================
4
+ * The server (kci_analyze.c) is written against epoll + BSD sockets. This header
5
+ * lets it build and run natively on Windows (mingw-w64), with no WSL and no Docker.
6
+ *
7
+ * What it provides on _WIN32:
8
+ * - Winsock headers + WSAStartup helper (kci_win_net_init)
9
+ * - epoll_* implemented over select() — safe here because the event loop is
10
+ * level-triggered-friendly (it drains reads to EWOULDBLOCK and only arms
11
+ * EPOLLOUT while a write is pending), so EPOLLET is simply ignored.
12
+ * - socket I/O wrappers (recv/send/closesocket) that translate WSA error codes
13
+ * into errno (EAGAIN/EINTR) so the existing errno checks keep working.
14
+ * - small stubs: accept4, fcntl-nonblock, fsync→_commit, SIGPIPE, TCP_QUICKACK.
15
+ *
16
+ * On non-Windows this header is empty; kci_analyze.c includes the real POSIX
17
+ * headers and defines the KCI_SOCK_* macros to plain read/write/close.
18
+ */
19
+ #ifndef KCI_WIN_COMPAT_H
20
+ #define KCI_WIN_COMPAT_H
21
+ #ifdef _WIN32
22
+
23
+ #ifndef FD_SETSIZE
24
+ #define FD_SETSIZE 1024 /* must precede winsock2.h; raises select() capacity */
25
+ #endif
26
+ /* Only the server TU (kci_analyze.c) needs sockets; it defines KCI_WIN_SOCKETS so
27
+ that kci_vec.c / kci_fts.c don't pull in winsock (whose connect() would clash
28
+ with a static function of the same name in kci_vec.c). */
29
+ #ifdef KCI_WIN_SOCKETS
30
+ #include <winsock2.h> /* must come before windows.h */
31
+ #include <ws2tcpip.h>
32
+ #endif
33
+ #ifndef WIN32_LEAN_AND_MEAN
34
+ #define WIN32_LEAN_AND_MEAN /* keep windows.h from pulling old winsock.h */
35
+ #endif
36
+ #include <windows.h>
37
+ #include <io.h> /* _commit, _get_osfhandle, _open/_read/_write/_close */
38
+ #include <fcntl.h>
39
+ #include <malloc.h>
40
+ #include <process.h>
41
+ #include <sys/stat.h>
42
+ #include <sys/types.h>
43
+ #include <stdint.h>
44
+ #include <errno.h>
45
+ #include <signal.h>
46
+ #include <time.h>
47
+
48
+ #ifndef __MINGW32__
49
+ #ifndef _SSIZE_T_DEFINED
50
+ typedef SSIZE_T ssize_t;
51
+ #define _SSIZE_T_DEFINED
52
+ #endif
53
+ #endif
54
+
55
+ /* sysconf(_SC_NPROCESSORS_ONLN) -> Windows logical CPU count */
56
+ #ifndef _SC_NPROCESSORS_ONLN
57
+ #define _SC_NPROCESSORS_ONLN 1
58
+ #endif
59
+ static inline long sysconf(int name) {
60
+ (void)name;
61
+ SYSTEM_INFO si; GetSystemInfo(&si);
62
+ return (long)si.dwNumberOfProcessors;
63
+ }
64
+
65
+ /* posix_memalign -> _aligned_malloc. NOTE: such memory must be released with
66
+ _aligned_free, so the matching free site uses KCI_ALIGNED_FREE (below). */
67
+ static inline int posix_memalign(void **p, size_t align, size_t sz) {
68
+ void *q = _aligned_malloc(sz, align);
69
+ if (!q) return 12 /* ENOMEM */;
70
+ *p = q;
71
+ return 0;
72
+ }
73
+ #define KCI_ALIGNED_FREE(p) _aligned_free(p)
74
+
75
+ /* ---- pthread subset used by the core ----
76
+ *
77
+ * CAVEAT (verified 2026-06): the _MSC_VER branch below is currently unreachable
78
+ * with an unmodified tree. The supported Windows build is mingw-w64 (see
79
+ * build_kci_analyze_win.bat), where __MINGW32__ is defined and real winpthreads
80
+ * is used instead. A straight MSVC `cl` build does not compile anyway, because
81
+ * the core uses GNU C extensions (e.g. __attribute__((packed)) on Slot in
82
+ * kci_analyze.c). This shim is kept as a forward-looking stub so that, if the
83
+ * core is ever made MSVC-clean, threading is already covered — but it has NOT
84
+ * been exercised by a real MSVC compile. Do not assume MSVC support from its
85
+ * presence. */
86
+ #ifdef _MSC_VER
87
+ typedef HANDLE pthread_t;
88
+ typedef CRITICAL_SECTION pthread_mutex_t;
89
+ typedef void pthread_attr_t;
90
+ typedef struct {
91
+ void *(*fn)(void *);
92
+ void *arg;
93
+ } kci_pthread_start_t;
94
+ static unsigned __stdcall kci_pthread_boot(void *opaque) {
95
+ kci_pthread_start_t *st = (kci_pthread_start_t *)opaque;
96
+ void *(*fn)(void *) = st->fn;
97
+ void *arg = st->arg;
98
+ free(st);
99
+ fn(arg);
100
+ return 0;
101
+ }
102
+ static inline int pthread_create(pthread_t *thr, const pthread_attr_t *attr,
103
+ void *(*fn)(void *), void *arg) {
104
+ (void)attr;
105
+ kci_pthread_start_t *st = (kci_pthread_start_t *)malloc(sizeof(*st));
106
+ uintptr_t h;
107
+ if (!st) return ENOMEM;
108
+ st->fn = fn;
109
+ st->arg = arg;
110
+ h = _beginthreadex(NULL, 0, kci_pthread_boot, st, 0, NULL);
111
+ if (!h) {
112
+ free(st);
113
+ return errno ? errno : EAGAIN;
114
+ }
115
+ *thr = (HANDLE)h;
116
+ return 0;
117
+ }
118
+ static inline int pthread_join(pthread_t thr, void **retval) {
119
+ DWORD rc = WaitForSingleObject(thr, INFINITE);
120
+ if (rc != WAIT_OBJECT_0) return EINVAL;
121
+ if (retval) *retval = NULL;
122
+ CloseHandle(thr);
123
+ return 0;
124
+ }
125
+ static inline int pthread_mutex_init(pthread_mutex_t *mu, const void *attr) {
126
+ (void)attr;
127
+ InitializeCriticalSection(mu);
128
+ return 0;
129
+ }
130
+ static inline int pthread_mutex_destroy(pthread_mutex_t *mu) {
131
+ DeleteCriticalSection(mu);
132
+ return 0;
133
+ }
134
+ static inline int pthread_mutex_lock(pthread_mutex_t *mu) {
135
+ EnterCriticalSection(mu);
136
+ return 0;
137
+ }
138
+ static inline int pthread_mutex_unlock(pthread_mutex_t *mu) {
139
+ LeaveCriticalSection(mu);
140
+ return 0;
141
+ }
142
+ #else
143
+ #include <pthread.h>
144
+ #endif
145
+
146
+ /* ---- file-I/O bits POSIX has but Windows spells differently ---- */
147
+ #define fsync(fd) _commit(fd)
148
+ #ifndef O_NONBLOCK
149
+ #define O_NONBLOCK 0x4000 /* sockets only; never reaches a file open() */
150
+ #endif
151
+
152
+ #ifndef CLOCK_REALTIME
153
+ #define CLOCK_REALTIME 0
154
+ #endif
155
+ #ifndef CLOCK_MONOTONIC
156
+ #define CLOCK_MONOTONIC 1
157
+ #endif
158
+ #ifdef _MSC_VER
159
+ static inline int clock_gettime(int clock_id, struct timespec *ts) {
160
+ if (!ts) { errno = EINVAL; return -1; }
161
+ if (clock_id == CLOCK_MONOTONIC) {
162
+ static LARGE_INTEGER freq;
163
+ static int freq_init = 0;
164
+ LARGE_INTEGER ctr;
165
+ if (!freq_init) {
166
+ if (!QueryPerformanceFrequency(&freq)) { errno = EINVAL; return -1; }
167
+ freq_init = 1;
168
+ }
169
+ QueryPerformanceCounter(&ctr);
170
+ ts->tv_sec = (time_t)(ctr.QuadPart / freq.QuadPart);
171
+ ts->tv_nsec = (long)(((ctr.QuadPart % freq.QuadPart) * 1000000000ll) / freq.QuadPart);
172
+ return 0;
173
+ }
174
+ FILETIME ft;
175
+ ULARGE_INTEGER ui;
176
+ GetSystemTimeAsFileTime(&ft);
177
+ ui.LowPart = ft.dwLowDateTime;
178
+ ui.HighPart = ft.dwHighDateTime;
179
+ ui.QuadPart -= 116444736000000000ull; /* FILETIME epoch -> Unix epoch */
180
+ ts->tv_sec = (time_t)(ui.QuadPart / 10000000ull);
181
+ ts->tv_nsec = (long)((ui.QuadPart % 10000000ull) * 100);
182
+ return 0;
183
+ }
184
+ #endif
185
+
186
+ /* ---- minimal mmap() over Windows file mapping ----
187
+ * Covers the read-only MAP_SHARED whole-file mapping the FTS disk mode uses.
188
+ *
189
+ * Signal capability to kci_fts.c: its `#define KCI_FTS_HAVE_MMAP 1` only lives in
190
+ * the POSIX `#elif` branch, so without this the Windows build compiles the
191
+ * `#ifndef KCI_FTS_HAVE_MMAP -> return NULL` stub of kci_fts_open_mmap and FTLOAD
192
+ * MMAP / PACKLOAD MMAP always fail even though the mapping shim below is present. */
193
+ #ifndef KCI_FTS_HAVE_MMAP
194
+ #define KCI_FTS_HAVE_MMAP 1
195
+ #endif
196
+ #define PROT_READ 0x1
197
+ #define PROT_WRITE 0x2
198
+ #define MAP_SHARED 0x01
199
+ #define MAP_PRIVATE 0x02
200
+ #define MAP_FAILED ((void *)-1)
201
+ #define MS_SYNC 4
202
+ static inline void *mmap(void *addr, size_t len, int prot, int flags, int fd, long off) {
203
+ (void)addr; (void)flags;
204
+ HANDLE h = (HANDLE)_get_osfhandle(fd);
205
+ if (h == INVALID_HANDLE_VALUE) return MAP_FAILED;
206
+ DWORD page = (prot & PROT_WRITE) ? PAGE_READWRITE : PAGE_READONLY;
207
+ DWORD acc = (prot & PROT_WRITE) ? FILE_MAP_WRITE : FILE_MAP_READ;
208
+ HANDLE m = CreateFileMappingA(h, NULL, page, 0, 0, NULL);
209
+ if (!m) return MAP_FAILED;
210
+ void *p = MapViewOfFile(m, acc, (DWORD)((uint64_t)off >> 32),
211
+ (DWORD)((uint64_t)off & 0xFFFFFFFFu), len);
212
+ CloseHandle(m); /* the live view keeps the mapping alive */
213
+ return p ? p : MAP_FAILED;
214
+ }
215
+ static inline int munmap(void *addr, size_t len) {
216
+ (void)len;
217
+ return UnmapViewOfFile(addr) ? 0 : -1;
218
+ }
219
+ static inline int msync(void *addr, size_t len, int flags) {
220
+ (void)len; (void)flags;
221
+ return FlushViewOfFile(addr, 0) ? 0 : -1;
222
+ }
223
+
224
+ /* ---- signals / socket options Windows lacks (kept as harmless stubs) ---- */
225
+ #ifndef SIGPIPE
226
+ #define SIGPIPE 13
227
+ #endif
228
+ #ifndef TCP_QUICKACK
229
+ #define TCP_QUICKACK 200 /* Linux-only; setsockopt fails and the caller ignores it */
230
+ #endif
231
+ #ifndef SOCK_NONBLOCK
232
+ #define SOCK_NONBLOCK 0
233
+ #endif
234
+ #ifndef SOCK_CLOEXEC
235
+ #define SOCK_CLOEXEC 0
236
+ #endif
237
+
238
+ #ifdef KCI_WIN_SOCKETS /* ===== sockets + epoll: only the server TU needs these ===== */
239
+
240
+ /* ---- WSA error -> errno, so existing `errno == EAGAIN` checks work ---- */
241
+ static inline int kci_wsa_errno(void) {
242
+ int e = WSAGetLastError();
243
+ if (e == WSAEWOULDBLOCK) return EAGAIN;
244
+ if (e == WSAEINTR) return EINTR;
245
+ return EIO;
246
+ }
247
+
248
+ /* ---- socket I/O wrappers (sockets are not CRT fds on Windows) ---- */
249
+ static inline long kci_sock_read(int fd, void *buf, unsigned long n) {
250
+ int r = recv((SOCKET)fd, (char *)buf, (int)n, 0);
251
+ if (r < 0) errno = kci_wsa_errno();
252
+ return r;
253
+ }
254
+ static inline long kci_sock_write(int fd, const void *buf, unsigned long n) {
255
+ int r = send((SOCKET)fd, (const char *)buf, (int)n, 0);
256
+ if (r < 0) errno = kci_wsa_errno();
257
+ return r;
258
+ }
259
+ static inline int kci_sock_close(int fd) { return closesocket((SOCKET)fd); }
260
+ #define KCI_SOCK_READ(fd, b, n) kci_sock_read((fd), (b), (n))
261
+ #define KCI_SOCK_WRITE(fd, b, n) kci_sock_write((fd), (b), (n))
262
+ #define KCI_SOCK_CLOSE(fd) kci_sock_close(fd)
263
+
264
+ /* ---- set a socket non-blocking (replaces fcntl(F_SETFL,O_NONBLOCK)) ---- */
265
+ static inline int kci_set_nonblock(int fd) {
266
+ u_long m = 1;
267
+ return ioctlsocket((SOCKET)fd, FIONBIO, &m);
268
+ }
269
+
270
+ /* ---- WSAStartup, called once from main ---- */
271
+ static inline void kci_win_net_init(void) {
272
+ WSADATA w;
273
+ WSAStartup(MAKEWORD(2, 2), &w);
274
+ }
275
+
276
+ /* ================= epoll over select() ================= */
277
+ #define EPOLLIN 0x001
278
+ #define EPOLLPRI 0x002
279
+ #define EPOLLOUT 0x004
280
+ #define EPOLLERR 0x008
281
+ #define EPOLLHUP 0x010
282
+ #define EPOLLET 0x80000000u /* ignored: select() is level-triggered (loop drains) */
283
+ #define EPOLL_CTL_ADD 1
284
+ #define EPOLL_CTL_DEL 2
285
+ #define EPOLL_CTL_MOD 3
286
+ #define EPOLL_CLOEXEC 0
287
+
288
+ typedef union { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t;
289
+ struct epoll_event { uint32_t events; epoll_data_t data; };
290
+
291
+ #define KCI_EPOLL_MAX FD_SETSIZE
292
+ typedef struct {
293
+ int used;
294
+ int nfds;
295
+ SOCKET fds[KCI_EPOLL_MAX];
296
+ uint32_t ev [KCI_EPOLL_MAX];
297
+ void *ptr[KCI_EPOLL_MAX];
298
+ } kci_epoll_t;
299
+ static kci_epoll_t kci_epoll_pool[8];
300
+
301
+ static inline int epoll_create1(int flags) {
302
+ (void)flags;
303
+ for (int i = 0; i < 8; i++) {
304
+ if (!kci_epoll_pool[i].used) {
305
+ memset(&kci_epoll_pool[i], 0, sizeof(kci_epoll_t));
306
+ kci_epoll_pool[i].used = 1;
307
+ return i + 1;
308
+ }
309
+ }
310
+ return -1;
311
+ }
312
+ static inline int epoll_create(int n) { (void)n; return epoll_create1(0); }
313
+ static inline int epoll_close(int epfd) {
314
+ if (epfd >= 1 && epfd <= 8) kci_epoll_pool[epfd - 1].used = 0;
315
+ return 0;
316
+ }
317
+
318
+ static inline int epoll_ctl(int epfd, int op, int fd, struct epoll_event *ev) {
319
+ if (epfd < 1 || epfd > 8) { errno = EINVAL; return -1; }
320
+ kci_epoll_t *ep = &kci_epoll_pool[epfd - 1];
321
+ SOCKET s = (SOCKET)fd;
322
+ int idx = -1;
323
+ for (int i = 0; i < ep->nfds; i++) if (ep->fds[i] == s) { idx = i; break; }
324
+ if (op == EPOLL_CTL_DEL) {
325
+ if (idx < 0) return 0;
326
+ ep->fds[idx] = ep->fds[ep->nfds - 1];
327
+ ep->ev [idx] = ep->ev [ep->nfds - 1];
328
+ ep->ptr[idx] = ep->ptr[ep->nfds - 1];
329
+ ep->nfds--;
330
+ return 0;
331
+ }
332
+ if (op == EPOLL_CTL_ADD) {
333
+ if (idx >= 0) return 0;
334
+ if (ep->nfds >= KCI_EPOLL_MAX) { errno = ENOSPC; return -1; }
335
+ idx = ep->nfds++;
336
+ ep->fds[idx] = s;
337
+ }
338
+ ep->ev [idx] = ev ? ev->events : 0;
339
+ ep->ptr[idx] = ev ? ev->data.ptr : NULL;
340
+ return 0;
341
+ }
342
+
343
+ static inline int epoll_wait(int epfd, struct epoll_event *out, int maxev, int timeout_ms) {
344
+ if (epfd < 1 || epfd > 8) { errno = EINVAL; return -1; }
345
+ kci_epoll_t *ep = &kci_epoll_pool[epfd - 1];
346
+ fd_set rd, wr, ex;
347
+ FD_ZERO(&rd); FD_ZERO(&wr); FD_ZERO(&ex);
348
+ for (int i = 0; i < ep->nfds; i++) {
349
+ if (ep->ev[i] & EPOLLIN) FD_SET(ep->fds[i], &rd);
350
+ if (ep->ev[i] & EPOLLOUT) FD_SET(ep->fds[i], &wr);
351
+ FD_SET(ep->fds[i], &ex);
352
+ }
353
+ struct timeval tv, *ptv = NULL;
354
+ if (timeout_ms >= 0) { tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; ptv = &tv; }
355
+ int r = (ep->nfds > 0) ? select(0, &rd, &wr, &ex, ptv)
356
+ : (Sleep(timeout_ms < 0 ? 0 : timeout_ms), 0);
357
+ if (r < 0) { errno = kci_wsa_errno(); return -1; }
358
+ if (r == 0) return 0;
359
+ int n = 0;
360
+ for (int i = 0; i < ep->nfds && n < maxev; i++) {
361
+ uint32_t e = 0;
362
+ if (FD_ISSET(ep->fds[i], &rd)) e |= EPOLLIN;
363
+ if (FD_ISSET(ep->fds[i], &wr)) e |= EPOLLOUT;
364
+ if (FD_ISSET(ep->fds[i], &ex)) e |= EPOLLERR;
365
+ if (e) { out[n].events = e; out[n].data.ptr = ep->ptr[i]; n++; }
366
+ }
367
+ return n;
368
+ }
369
+
370
+ /* accept4(fd, addr, len, flags) — flags ignored; result is set non-blocking */
371
+ static inline int accept4(int fd, struct sockaddr *addr, socklen_t *len, int flags) {
372
+ (void)flags;
373
+ SOCKET c = accept((SOCKET)fd, addr, len);
374
+ if (c == INVALID_SOCKET) { errno = kci_wsa_errno(); return -1; }
375
+ u_long m = 1; ioctlsocket(c, FIONBIO, &m);
376
+ return (int)c;
377
+ }
378
+
379
+ #endif /* KCI_WIN_SOCKETS */
380
+ #endif /* _WIN32 */
381
+ #endif /* KCI_WIN_COMPAT_H */
package/store.js ADDED
@@ -0,0 +1,225 @@
1
+ 'use strict';
2
+ // Store: vectors of your own with string ids, a text and fields each.
3
+ // The folder a Store saves is the one the Python client writes for TextIndex(mode="dense", dense="vectors"):
4
+ // dense.kvec, meta.json, names / texts / fields as .json or, with a key, sealed as .kct. Either client opens the
5
+ // other's folder.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const where = require('./where.js');
9
+
10
+ const METRICS = ['cosine', 'l2', 'ip'];
11
+ const show = (x) => { try { return JSON.stringify(x); } catch (e) { return String(x); } };
12
+ const plain = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
13
+ const one = (x) => typeof x === 'string' || typeof x === 'boolean' || (typeof x === 'number' && Number.isFinite(x));
14
+
15
+ function checkFields(rec, what) {
16
+ if (!plain(rec)) throw new TypeError(`${what}: the fields of one record must be an object such as { genre: 'scifi' }, not ${show(rec)}`);
17
+ for (const [key, x] of Object.entries(rec)) {
18
+ if (!key || key.startsWith('$')) throw new RangeError(`${what}: a field name must not be empty or start with $ (${show(key)})`);
19
+ if (!(x === null || one(x) || (Array.isArray(x) && x.every(one)))) {
20
+ throw new TypeError(`${what}, field ${show(key)}: a value must be a string, a number, true / false, null or an array of those, not ${show(x)}`);
21
+ }
22
+ }
23
+ }
24
+
25
+ module.exports = (KciVec, lib, keyBytes) => class Store {
26
+ #vec = null; #metric; #meta = null;
27
+ #num = new Map(); #name = new Map(); // string id -> number inside, and back
28
+ #row = new Map(); #doc = new Map(); // number inside -> row of the index, and back
29
+ #texts = new Map(); #fields = new Map();
30
+ #next = 0; #rowNext = 0;
31
+
32
+ /** new Store({ metric: 'cosine' | 'l2' | 'ip' }). The length of the vectors is that of the first one added. */
33
+ constructor(opts = {}) {
34
+ const metric = opts.metric === undefined ? 'cosine' : opts.metric;
35
+ if (!METRICS.includes(metric)) throw new RangeError("metric must be 'cosine', 'l2' or 'ip'");
36
+ this.#metric = metric;
37
+ }
38
+
39
+ get size() { return this.#num.size; }
40
+ get dim() { return this.#vec ? this.#vec.dim : 0; }
41
+ get metric() { return this.#metric; }
42
+ ids() { return Array.from(this.#num.keys()); }
43
+ has(id) { return this.#num.has(id); }
44
+ /** { text, fields } of an id, or null. */
45
+ get(id) {
46
+ const d = this.#num.get(id);
47
+ return d === undefined ? null : { text: this.#texts.get(d) ?? '', fields: { ...(this.#fields.get(d) || {}) } };
48
+ }
49
+
50
+ #ready() { if (this.#vec && !this.#vec.isBuilt) this.#vec.build(); }
51
+
52
+ /**
53
+ * Add records: [{ id: 'doc-1', vector: [...], text: '...', fields: { year: 2004 } }, ...]. text and fields may be
54
+ * left out. An id that is already there is refused unless { replace: true } (then the new record stands in its
55
+ * place). Everything is checked first: a call that throws has added nothing. Returns the ids.
56
+ */
57
+ add(records, opts = {}) {
58
+ if (!Array.isArray(records)) throw new TypeError('add: give an array of records such as [{ id, vector, text, fields }]');
59
+ if (!records.length) return [];
60
+ const seen = new Set(), rows = [];
61
+ let dim = this.dim;
62
+ records.forEach((r, i) => {
63
+ const what = `add (record ${i})`;
64
+ if (!plain(r)) throw new TypeError(`${what}: a record must be an object { id, vector, text, fields }`);
65
+ if (typeof r.id !== 'string' || !r.id) throw new TypeError(`${what}: the id must be a string that is not empty, not ${show(r.id)}`);
66
+ if (seen.has(r.id)) throw new RangeError(`${what}: the id ${show(r.id)} is given twice in this call`);
67
+ seen.add(r.id);
68
+ if (this.#num.has(r.id) && !opts.replace) throw new RangeError(`${what}: the id ${show(r.id)} is already in the store ({ replace: true } replaces it)`);
69
+ let v = r.vector;
70
+ if (v instanceof Float32Array) v = Float32Array.from(v);
71
+ else if (Array.isArray(v) || v instanceof Float64Array) v = Float32Array.from(v);
72
+ else throw new TypeError(`${what}: vector must be a Float32Array, a Float64Array or an array of numbers`);
73
+ if (!v.length) throw new RangeError(`${what}: the vector is empty`);
74
+ if (!dim) dim = v.length;
75
+ if (v.length !== dim) throw new RangeError(`${what}: the vector has ${v.length} numbers, the others ${dim}`);
76
+ if (!v.every(Number.isFinite)) throw new RangeError(`${what}: the vector has a NaN or an infinity`);
77
+ if (this.#metric === 'cosine' && !v.some((x) => x !== 0)) throw new RangeError(`${what}: the vector is all zeros: it has no direction to compare by cosine`);
78
+ if (r.text !== undefined && r.text !== null && typeof r.text !== 'string') throw new TypeError(`${what}: text must be a string`);
79
+ if (r.fields !== undefined && r.fields !== null) checkFields(r.fields, what);
80
+ rows.push({ id: r.id, v, text: r.text ?? '', fields: r.fields ? JSON.parse(JSON.stringify(r.fields)) : null });
81
+ });
82
+ if (!this.#vec) this.#vec = new KciVec(dim, { metric: this.#metric, rerank: 200 });
83
+ const old = rows.filter((r) => this.#num.has(r.id));
84
+ if (old.length) { this.#ready(); for (const r of old) this.#vec.delete(this.#row.get(this.#num.get(r.id))); }
85
+ const built = this.#vec.isBuilt;
86
+ for (const r of rows) {
87
+ let d = this.#num.get(r.id);
88
+ if (d === undefined) { d = this.#next++; this.#num.set(r.id, d); this.#name.set(d, r.id); }
89
+ else this.#doc.delete(this.#row.get(d));
90
+ const row = this.#rowNext++;
91
+ if (built) this.#vec.insert(row, r.v); else this.#vec.add(row, r.v);
92
+ this.#row.set(d, row); this.#doc.set(row, d); this.#texts.set(d, r.text);
93
+ if (r.fields && Object.keys(r.fields).length) this.#fields.set(d, r.fields); else this.#fields.delete(d);
94
+ }
95
+ return rows.map((r) => r.id);
96
+ }
97
+
98
+ /** Take a record out. true when it was there. */
99
+ delete(id) {
100
+ const d = this.#num.get(id);
101
+ if (d === undefined) return false;
102
+ this.#ready();
103
+ const row = this.#row.get(d);
104
+ this.#vec.delete(row);
105
+ this.#num.delete(id); this.#name.delete(d); this.#row.delete(d); this.#doc.delete(row); this.#texts.delete(d); this.#fields.delete(d);
106
+ return true;
107
+ }
108
+
109
+ /**
110
+ * The k nearest records to a vector: [{ id, score, text, fields }], best first (cosine and ip: larger = nearer;
111
+ * l2: the squared distance, smaller = nearer). opts.where: a condition on the fields ({ year: { $gte: 2000 } },
112
+ * see where.js); opts.filter: the ids that may be answered (an array or a Set). With both, a record must pass both.
113
+ * A field name that no record has throws.
114
+ */
115
+ search(vector, k = 5, opts = {}) {
116
+ if (typeof k !== 'number' || !Number.isInteger(k) || k < 1) throw new RangeError(`search: k must be a whole number from 1, not ${String(k)}`);
117
+ let rows = null;
118
+ if (opts.filter != null) {
119
+ if (typeof opts.filter === 'string' || typeof opts.filter[Symbol.iterator] !== 'function') throw new TypeError('search: filter must be an array or a Set of ids');
120
+ rows = [];
121
+ for (const id of new Set(opts.filter)) { const d = this.#num.get(id); if (d !== undefined) rows.push(this.#row.get(d)); }
122
+ }
123
+ if (opts.where != null) {
124
+ const by = new Map();
125
+ for (const [d, row] of this.#row) by.set(row, this.#fields.get(d) || {});
126
+ const pass = new Set(where.ids(by, opts.where));
127
+ rows = rows === null ? Array.from(pass) : rows.filter((r) => pass.has(r));
128
+ }
129
+ if (!this.#vec || !this.#num.size) return [];
130
+ const q = vector instanceof Float32Array ? vector : (Array.isArray(vector) || vector instanceof Float64Array) ? Float32Array.from(vector) : null;
131
+ if (!q) throw new TypeError('search: the vector must be a Float32Array, a Float64Array or an array of numbers');
132
+ if (q.length !== this.dim) throw new RangeError(`search: the vector has ${q.length} numbers, those in the store ${this.dim}`);
133
+ if (rows !== null && !rows.length) return [];
134
+ this.#ready();
135
+ const hits = this.#vec.search(q, Math.min(k, this.#num.size), rows === null ? {} : { filter: rows });
136
+ const out = [];
137
+ for (const h of hits) {
138
+ const d = this.#doc.get(Number(h.id));
139
+ if (d !== undefined) out.push({ id: this.#name.get(d), score: h.score, text: this.#texts.get(d) ?? '', fields: { ...(this.#fields.get(d) || {}) } });
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /**
145
+ * Write the store into the folder dir. key (a passphrase): the index, the ids, the texts and the fields are
146
+ * encrypted; without it they are readable. meta.json stays readable either way (settings and counts, no text, no id).
147
+ */
148
+ save(dir, key) {
149
+ if (typeof dir !== 'string' || !dir) throw new TypeError('save: the folder must be a string');
150
+ if (!this.#num.size) throw new Error('save: the store is empty');
151
+ const kb = keyBytes(key);
152
+ this.#ready();
153
+ fs.mkdirSync(dir, { recursive: true });
154
+ this.#vec.save(path.join(dir, 'dense.kvec'), kb);
155
+ const put = (base, obj) => {
156
+ for (const ext of ['.json', '.kct']) fs.rmSync(path.join(dir, base + ext), { force: true }); // never leave an older copy, a plain one least of all
157
+ if (obj === null) return;
158
+ const raw = new Uint8Array(Buffer.from(JSON.stringify(obj), 'utf8'));
159
+ fs.writeFileSync(path.join(dir, base + (kb ? '.kct' : '.json')), kb ? lib.seal(raw, kb) : raw);
160
+ };
161
+ const byD = (m) => Object.fromEntries(Array.from(m.entries()).sort((a, b) => a[0] - b[0]).map(([d, x]) => [String(d), x]));
162
+ put('texts', byD(this.#texts));
163
+ put('fields', this.#fields.size ? byD(this.#fields) : null);
164
+ put('names', byD(this.#name));
165
+ const ds = Array.from(this.#name.keys()).sort((a, b) => a - b);
166
+ const meta = {
167
+ lang: 'ja', w_dense: 0.4, sparse: null, sparse_dim: null, chunk: 0, dense_chunk: 0, overlap: null, dedup: false, phrase: false,
168
+ phrase_depth: 1000, phrase_stop: [], phrase_common: null, ...(this.#meta || {}),
169
+ format: 5, names: true, fields: this.#fields.size > 0, mode: 'dense', blocks: false, sparse_blocks: false, next: this.#next, ids: ds, texts: true,
170
+ encrypted: !!kb, dense: 'vectors', row_next: this.#rowNext, sparse_state: false,
171
+ rows: ds.map((d) => [this.#row.get(d), d, 0, Array.from(this.#texts.get(d) ?? '').length, 'b']).sort((a, b) => a[0] - b[0]),
172
+ };
173
+ fs.writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(meta));
174
+ }
175
+
176
+ /** Open a saved store (also one saved by the Python client with dense="vectors" and string ids). */
177
+ static load(dir, key) {
178
+ if (typeof dir !== 'string' || !dir) throw new TypeError('load: the folder must be a string');
179
+ let meta;
180
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')); } catch (e) {
181
+ throw new Error(`load: ${show(dir)} is not a saved store (meta.json ${e.code === 'ENOENT' ? 'is missing' : 'cannot be read'})`);
182
+ }
183
+ if (!plain(meta) || !Array.isArray(meta.ids) || !Array.isArray(meta.rows)) throw new Error('load: meta.json is damaged');
184
+ if (!(meta.format <= 5)) throw new Error(`load: this folder was written by a newer version (format ${show(meta.format)})`);
185
+ if (meta.dense !== 'vectors' || meta.mode !== 'dense') throw new Error('load: this index was made with a language model or with words (the Python client opens it); Store holds vectors of your own');
186
+ if (meta.ids.length && !meta.names) throw new Error('load: this index has whole-number ids (the Python client opens it); Store keeps string ids');
187
+ const kb = meta.encrypted ? keyBytes(key) : null;
188
+ if (meta.encrypted && !kb) throw new Error('load: this store was saved with a key; give the key');
189
+ const s = new Store();
190
+ s.#vec = KciVec.load(path.join(dir, 'dense.kvec'), kb, { rerank: 200 });
191
+ s.#metric = s.#vec.metric;
192
+ const get = (base, need) => {
193
+ const f = path.join(dir, base + (kb ? '.kct' : '.json'));
194
+ if (!fs.existsSync(f)) { if (need) throw new Error(`load: ${base + (kb ? '.kct' : '.json')} is missing`); return {}; }
195
+ const raw = fs.readFileSync(f);
196
+ let obj;
197
+ try { obj = JSON.parse(Buffer.from(kb ? lib.unseal(new Uint8Array(raw), kb) : raw).toString('utf8')); } catch (e) {
198
+ throw new Error(`load: ${path.basename(f)} cannot be read (${kb ? 'wrong key, or ' : ''}damaged)`);
199
+ }
200
+ if (!plain(obj)) throw new Error(`load: ${path.basename(f)} is damaged`);
201
+ return obj;
202
+ };
203
+ const names = get('names', meta.ids.length > 0), texts = meta.texts ? get('texts', false) : {}, fields = meta.fields ? get('fields', true) : {};
204
+ const live = new Set(meta.ids.map(Number));
205
+ for (const [d0, nm] of Object.entries(names)) {
206
+ const d = Number(d0);
207
+ if (!live.has(d) || typeof nm !== 'string') continue;
208
+ s.#num.set(nm, d); s.#name.set(d, nm); s.#texts.set(d, typeof texts[d0] === 'string' ? texts[d0] : '');
209
+ if (plain(fields[d0])) s.#fields.set(d, fields[d0]);
210
+ }
211
+ for (const r of meta.rows) {
212
+ const row = Number(r[0]), d = Number(r[1]);
213
+ if (s.#name.has(d) && !s.#row.has(d)) { s.#row.set(d, row); s.#doc.set(row, d); }
214
+ }
215
+ for (const d of s.#name.keys()) if (!s.#row.has(d)) throw new Error('load: meta.json is damaged (an id without its vector)');
216
+ s.#next = Number(meta.next) || 0; s.#rowNext = Number(meta.row_next ?? meta.next) || 0;
217
+ for (const d of s.#name.keys()) { s.#next = Math.max(s.#next, d + 1); s.#rowNext = Math.max(s.#rowNext, s.#row.get(d) + 1); }
218
+ const { ids, rows, ...rest } = meta;
219
+ s.#meta = rest;
220
+ return s;
221
+ }
222
+
223
+ /** Free the index now. */
224
+ close() { if (this.#vec) { this.#vec.close(); this.#vec = null; } this.#num.clear(); }
225
+ };