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/kci_vec_node.c ADDED
@@ -0,0 +1,378 @@
1
+ /* Node.js addon for kci_vec.c (Node-API, plain C, nothing else linked). The policy (ids, defaults, the
2
+ * exact answer when nothing is given) is in index.js; this file only hands the calls over. Every function takes the
3
+ * handle first. One searcher per handle, made at the first search and dropped when the index changes.
4
+ * Build: node build.js (gcc / cc and the node-api-headers package). */
5
+ #define NAPI_VERSION 8
6
+ #include <node_api.h>
7
+ #include <stdlib.h>
8
+ #include <string.h>
9
+ #include "kci_vec.h"
10
+ #include "kci_sparse.h" /* kci_seal / kci_unseal, for the files Store keeps beside the index */
11
+
12
+ #define KN_POOL 16
13
+ typedef struct { KciVec *v; KciVecSearcher *s; int busy; /* busy: an async build holds the index */
14
+ int readers; KciVecSearcher *pool[KN_POOL]; int npool; /* async searches under way; their searchers, kept for the next */
15
+ int warm; } Kn; /* bit 1 / 2: a graph / an exact search has run since the index last changed */
16
+ typedef struct { const uint64_t *ids; size_t n; } KnIds; /* a filter: sorted ids */
17
+
18
+ static napi_value kn_throw(napi_env env, const char *msg){ napi_throw_error(env, NULL, msg); return NULL; }
19
+ #define ARGS(N) size_t argc=(N); napi_value a[(N)]; if(napi_get_cb_info(env,info,&argc,a,NULL,NULL)!=napi_ok || argc<(N)) return kn_throw(env,"kci_vec: too few arguments")
20
+
21
+ static Kn *kn_h(napi_env env, napi_value x){
22
+ void *p=NULL;
23
+ if(napi_get_value_external(env,x,&p)!=napi_ok || !p){ kn_throw(env,"kci_vec: not an index"); return NULL; }
24
+ Kn *h=p;
25
+ if(!h->v){ kn_throw(env,"kci_vec: the index is closed"); return NULL; }
26
+ if(h->busy){ kn_throw(env,"kci_vec: the index is being built (await buildAsync first)"); return NULL; }
27
+ return h;
28
+ }
29
+ /* for the calls that change the index: not while an async search reads it */
30
+ static Kn *kn_w(napi_env env, napi_value x){
31
+ Kn *h=kn_h(env,x);
32
+ if(h && h->readers){ kn_throw(env,"kci_vec: the index is being searched (await the searchAsync calls first)"); return NULL; }
33
+ return h;
34
+ }
35
+ static void kn_drop_s(Kn *h){
36
+ h->warm=0;
37
+ if(h->s){ kci_vec_searcher_free(h->s); h->s=NULL; }
38
+ while(h->npool>0) kci_vec_searcher_free(h->pool[--h->npool]);
39
+ }
40
+ static void kn_final(napi_env env, void *data, void *hint){
41
+ (void)env; (void)hint; Kn *h=data;
42
+ if(h->busy) return; /* cannot happen: the async work holds a reference */
43
+ kn_drop_s(h); if(h->v) kci_vec_free(h->v); free(h);
44
+ }
45
+ static napi_value kn_wrap(napi_env env, KciVec *v){
46
+ Kn *h=calloc(1,sizeof(Kn)); if(!h){ kci_vec_free(v); return kn_throw(env,"kci_vec: out of memory"); }
47
+ h->v=v; napi_value r;
48
+ if(napi_create_external(env,h,kn_final,NULL,&r)!=napi_ok){ kci_vec_free(v); free(h); return kn_throw(env,"kci_vec: cannot make the handle"); }
49
+ return r;
50
+ }
51
+ static int kn_i32(napi_env env, napi_value x, int32_t *o){ return napi_get_value_int32(env,x,o)==napi_ok; }
52
+ static int kn_f32a(napi_env env, napi_value x, const float **p, size_t *n){
53
+ napi_typedarray_type t; void *d=NULL;
54
+ if(napi_get_typedarray_info(env,x,&t,n,&d,NULL,NULL)!=napi_ok || t!=napi_float32_array) return 0;
55
+ *p=d; return 1;
56
+ }
57
+ static int kn_u64a(napi_env env, napi_value x, const uint64_t **p, size_t *n){
58
+ napi_typedarray_type t; void *d=NULL;
59
+ if(napi_get_typedarray_info(env,x,&t,n,&d,NULL,NULL)!=napi_ok || t!=napi_biguint64_array) return 0;
60
+ *p=d; return 1;
61
+ }
62
+ static int kn_null(napi_env env, napi_value x){ napi_valuetype t; return napi_typeof(env,x,&t)!=napi_ok || t==napi_null || t==napi_undefined; }
63
+ static char *kn_str(napi_env env, napi_value x){
64
+ size_t n=0; if(napi_get_value_string_utf8(env,x,NULL,0,&n)!=napi_ok) return NULL;
65
+ char *s=malloc(n+1); if(!s) return NULL;
66
+ if(napi_get_value_string_utf8(env,x,s,n+1,&n)!=napi_ok){ free(s); return NULL; }
67
+ return s;
68
+ }
69
+ /* A path for kci_vec.c. On Windows it opens files with fopen, which reads the name in the system's code page, not
70
+ * UTF-8: the code page's bytes go in; a name the code page cannot write goes by its short (8.3) name; NULL when
71
+ * neither works. */
72
+ #ifdef _WIN32
73
+ #include <windows.h>
74
+ static char *kn_acp(const wchar_t *w){
75
+ UINT cp=GetACP(); BOOL bad=FALSE, *pb=(cp==CP_UTF8)?NULL:&bad; DWORD fl=(cp==CP_UTF8)?0:WC_NO_BEST_FIT_CHARS;
76
+ int n=WideCharToMultiByte(cp,fl,w,-1,NULL,0,NULL,pb); if(n<=0 || bad) return NULL;
77
+ char *s=malloc((size_t)n); if(!s) return NULL;
78
+ if(WideCharToMultiByte(cp,fl,w,-1,s,n,NULL,pb)<=0 || bad){ free(s); return NULL; }
79
+ return s;
80
+ }
81
+ static char *kn_path(napi_env env, napi_value x){
82
+ size_t n=0; if(napi_get_value_string_utf16(env,x,NULL,0,&n)!=napi_ok) return NULL;
83
+ wchar_t *w=malloc((n+1)*sizeof(wchar_t)); if(!w) return NULL;
84
+ if(napi_get_value_string_utf16(env,x,(char16_t*)w,n+1,&n)!=napi_ok){ free(w); return NULL; }
85
+ char *s=kn_acp(w); if(s){ free(w); return s; }
86
+ wchar_t *full=malloc(32768*sizeof(wchar_t)), *sh=malloc(32768*sizeof(wchar_t));
87
+ if(full && sh){
88
+ DWORD fn=GetFullPathNameW(w,32768,full,NULL);
89
+ if(fn>0 && fn<32768){
90
+ DWORD k=GetShortPathNameW(full,sh,32768); /* the file itself, when it exists */
91
+ if(k>0 && k<32768) s=kn_acp(sh);
92
+ if(!s){ /* its folder by the short name + the file's own name */
93
+ wchar_t *cut=wcsrchr(full,(wchar_t)92); /* 92: the backslash */
94
+ if(cut){
95
+ *cut=0; k=GetShortPathNameW(full,sh,32768);
96
+ if(k>0 && k+wcslen(cut+1)+2<32768){ sh[k]=(wchar_t)92; wcscpy(sh+k+1,cut+1); s=kn_acp(sh); }
97
+ }
98
+ }
99
+ }
100
+ }
101
+ free(full); free(sh); free(w); return s;
102
+ }
103
+ #define KN_BAD_PATH "kci_vec: this Windows cannot hand the path to the library (characters outside the system's code page, and no short name): use a path in plain letters"
104
+ #else
105
+ #define kn_path kn_str
106
+ #define KN_BAD_PATH "kci_vec: bad path"
107
+ #endif
108
+ static napi_value kn_num(napi_env env, double d){ napi_value r; napi_create_double(env,d,&r); return r; }
109
+ static int kn_idf(uint64_t id, void *ctx){ /* KciVecFilter: only reads, any thread */
110
+ const KnIds *f=ctx; size_t lo=0, hi=f->n;
111
+ while(lo<hi){ size_t m=lo+(hi-lo)/2; if(f->ids[m]<id) lo=m+1; else hi=m; }
112
+ return lo<f->n && f->ids[lo]==id;
113
+ }
114
+
115
+ /* create(dim, M, efc, metric 0 cosine / 1 l2 / 2 ip, maxNorm, keepFloat, dedup) */
116
+ static napi_value kn_create(napi_env env, napi_callback_info info){
117
+ ARGS(7); int32_t dim,M,efc,metric; double mx; bool kf,dd;
118
+ if(!kn_i32(env,a[0],&dim) || !kn_i32(env,a[1],&M) || !kn_i32(env,a[2],&efc) || !kn_i32(env,a[3],&metric)
119
+ || napi_get_value_double(env,a[4],&mx)!=napi_ok || napi_get_value_bool(env,a[5],&kf)!=napi_ok
120
+ || napi_get_value_bool(env,a[6],&dd)!=napi_ok) return kn_throw(env,"kci_vec: bad arguments");
121
+ KciVec *v = metric==1 ? kci_vec_new_l2(dim,M,efc,(float)mx) : metric==2 ? kci_vec_new_ip(dim,M,efc,(float)mx) : kci_vec_new(dim,M,efc);
122
+ if(!v) return kn_throw(env,"kci_vec: cannot make the index (dim must be above 0; l2 / ip: maxNorm 0 or more)");
123
+ if(kf) kci_vec_keep_float(v,1);
124
+ if(dd && kci_vec_set_dedup(v,1)!=0){ kci_vec_free(v); return kn_throw(env,"kci_vec: dedup is not available"); }
125
+ return kn_wrap(env,v);
126
+ }
127
+ static napi_value kn_close(napi_env env, napi_callback_info info){
128
+ ARGS(1); void *p=NULL; if(napi_get_value_external(env,a[0],&p)!=napi_ok || !p) return kn_throw(env,"kci_vec: not an index");
129
+ Kn *h=p; if(h->busy) return kn_throw(env,"kci_vec: the index is being built (await buildAsync first)");
130
+ if(h->readers) return kn_throw(env,"kci_vec: the index is being searched (await the searchAsync calls first)");
131
+ kn_drop_s(h); if(h->v){ kci_vec_free(h->v); h->v=NULL; }
132
+ return NULL;
133
+ }
134
+ /* info(h) -> [count, dim, metric, built, floats, by proof, default ef, default rerank, unreached] */
135
+ static napi_value kn_info(napi_env env, napi_callback_info info){
136
+ ARGS(1); Kn *h=kn_h(env,a[0]); if(!h) return NULL;
137
+ double x[9]={ kci_vec_count(h->v), kci_vec_dim(h->v), kci_vec_metric(h->v), kci_vec_is_built(h->v), kci_vec_has_floats(h->v),
138
+ kci_vec_exact_by_proof(h->v), kci_vec_default_ef(h->v), kci_vec_default_rerank(h->v), kci_vec_unreached(h->v) };
139
+ napi_value r; napi_create_array_with_length(env,9,&r);
140
+ for(uint32_t i=0;i<9;i++) napi_set_element(env,r,i,kn_num(env,x[i]));
141
+ return r;
142
+ }
143
+ /* add(h, ids BigUint64Array, rows Float32Array, insert) -> rows taken; -(i+1): row i was refused (-(i+1) - 2e9: no floats) */
144
+ static napi_value kn_add(napi_env env, napi_callback_info info){
145
+ ARGS(4); Kn *h=kn_w(env,a[0]); if(!h) return NULL;
146
+ const uint64_t *ids; const float *x; size_t n, m; bool ins;
147
+ if(!kn_u64a(env,a[1],&ids,&n) || !kn_f32a(env,a[2],&x,&m) || napi_get_value_bool(env,a[3],&ins)!=napi_ok) return kn_throw(env,"kci_vec: bad arguments");
148
+ size_t dim=(size_t)kci_vec_dim(h->v);
149
+ if(m!=n*dim) return kn_throw(env,"kci_vec: the rows do not hold ids x dim numbers");
150
+ kn_drop_s(h); /* the searcher's scratch is sized for the index as it was */
151
+ if(!ins) kci_vec_reserve(h->v,(uint32_t)(kci_vec_count(h->v)+n+1));
152
+ for(size_t i=0;i<n;i++){
153
+ int64_t r = ins ? kci_vec_insert(h->v,ids[i],x+i*dim) : kci_vec_add(h->v,ids[i],x+i*dim);
154
+ if(r<0) return kn_num(env, -(double)(i+1) - (r==-2 ? 2e9 : 0));
155
+ }
156
+ return kn_num(env,(double)n);
157
+ }
158
+
159
+ /* build + what the Python client does after it: the search width this data needs when the exact answer is not the
160
+ * default (or the index is large), and the short rows for the exact answer where they pay. */
161
+ typedef struct { Kn *h; int threads, rerank, rc, ef; double secs; float rec; napi_deferred def; napi_async_work work; napi_ref ref; } KnB;
162
+ static void kn_build_all(KnB *b){
163
+ KciVec *v=b->h->v; b->ef=0; b->rec=-1.0f; b->secs=0;
164
+ kn_drop_s(b->h);
165
+ b->rc=kci_vec_build(v,b->threads,&b->secs); if(b->rc) return;
166
+ double cells=(double)kci_vec_count(v)*(double)kci_vec_dim(v);
167
+ int fl=kci_vec_has_floats(v)==1, proof=kci_vec_exact_by_proof(v)==1;
168
+ int small = fl ? (cells<=1e7 || proof) : cells<=1e7;
169
+ if(!small || cells>4e7){ float r=-1.0f; int e=kci_vec_calibrate(v,10,b->rerank,0.98f,128,b->threads,&r); if(e>0){ b->ef=e; b->rec=r; } }
170
+ if(kci_vec_dim(v)>=32 && small && proof){ float sh=0; (void)kci_vec_exact_short_if(v,0,b->threads,0.8f,&sh); }
171
+ }
172
+ static napi_value kn_build_res(napi_env env, const KnB *b){ /* [seconds, calibrated ef or 0, its recall or -1, unreached] */
173
+ napi_value r; napi_create_array_with_length(env,4,&r);
174
+ napi_set_element(env,r,0,kn_num(env,b->secs)); napi_set_element(env,r,1,kn_num(env,b->ef));
175
+ napi_set_element(env,r,2,kn_num(env,b->rec)); napi_set_element(env,r,3,kn_num(env,kci_vec_unreached(b->h->v)));
176
+ return r;
177
+ }
178
+ static napi_value kn_build(napi_env env, napi_callback_info info){
179
+ ARGS(3); Kn *h=kn_w(env,a[0]); if(!h) return NULL;
180
+ KnB b; memset(&b,0,sizeof b); b.h=h;
181
+ if(!kn_i32(env,a[1],&b.threads) || !kn_i32(env,a[2],&b.rerank)) return kn_throw(env,"kci_vec: bad arguments");
182
+ kn_build_all(&b);
183
+ if(b.rc) return kn_throw(env,"kci_vec: build failed (no vectors, or out of memory)");
184
+ return kn_build_res(env,&b);
185
+ }
186
+ static void kn_build_exec(napi_env env, void *data){ (void)env; kn_build_all(data); }
187
+ static void kn_build_done(napi_env env, napi_status st, void *data){
188
+ KnB *b=data; b->h->busy=0;
189
+ if(st!=napi_ok || b->rc){
190
+ napi_value msg, err; napi_create_string_utf8(env,"kci_vec: build failed (no vectors, or out of memory)",NAPI_AUTO_LENGTH,&msg);
191
+ napi_create_error(env,NULL,msg,&err); napi_reject_deferred(env,b->def,err);
192
+ } else napi_resolve_deferred(env,b->def,kn_build_res(env,b));
193
+ napi_delete_reference(env,b->ref); napi_delete_async_work(env,b->work); free(b);
194
+ }
195
+ static napi_value kn_build_async(napi_env env, napi_callback_info info){
196
+ ARGS(3); Kn *h=kn_w(env,a[0]); if(!h) return NULL;
197
+ KnB *b=calloc(1,sizeof(KnB)); if(!b) return kn_throw(env,"kci_vec: out of memory");
198
+ b->h=h; napi_value pr, name;
199
+ if(!kn_i32(env,a[1],&b->threads) || !kn_i32(env,a[2],&b->rerank)){ free(b); return kn_throw(env,"kci_vec: bad arguments"); }
200
+ napi_create_string_utf8(env,"kci_vec.build",NAPI_AUTO_LENGTH,&name);
201
+ if(napi_create_promise(env,&b->def,&pr)!=napi_ok || napi_create_reference(env,a[0],1,&b->ref)!=napi_ok
202
+ || napi_create_async_work(env,NULL,name,kn_build_exec,kn_build_done,b,&b->work)!=napi_ok){ free(b); return kn_throw(env,"kci_vec: cannot start the build"); }
203
+ h->busy=1;
204
+ if(napi_queue_async_work(env,b->work)!=napi_ok){ h->busy=0; napi_delete_reference(env,b->ref); napi_delete_async_work(env,b->work); free(b); return kn_throw(env,"kci_vec: cannot start the build"); }
205
+ return pr;
206
+ }
207
+
208
+ /* search(h, q Float32Array, k, mode 0 graph / 1 exact, ef, rerankN, threads, filter ids or null) -> [ids, scores, n]; n < 0: refused */
209
+ static napi_value kn_search(napi_env env, napi_callback_info info){
210
+ ARGS(8); Kn *h=kn_h(env,a[0]); if(!h) return NULL;
211
+ const float *q; size_t qn; int32_t k,mode,ef,rn,th; KnIds f={NULL,0}; int filt=!kn_null(env,a[7]);
212
+ if(!kn_f32a(env,a[1],&q,&qn) || !kn_i32(env,a[2],&k) || !kn_i32(env,a[3],&mode) || !kn_i32(env,a[4],&ef) || !kn_i32(env,a[5],&rn)
213
+ || !kn_i32(env,a[6],&th) || (filt && !kn_u64a(env,a[7],&f.ids,&f.n))) return kn_throw(env,"kci_vec: bad arguments");
214
+ if(qn!=(size_t)kci_vec_dim(h->v)) return kn_throw(env,"kci_vec: the query does not hold dim numbers");
215
+ if(k<1 || k>16000000) return kn_throw(env,"kci_vec: k must be 1 .. 16,000,000");
216
+ napi_value bi, bs, ids, sc, r; void *pi=NULL, *ps=NULL;
217
+ if(napi_create_arraybuffer(env,(size_t)k*8,&pi,&bi)!=napi_ok || napi_create_arraybuffer(env,(size_t)k*4,&ps,&bs)!=napi_ok)
218
+ return kn_throw(env,"kci_vec: out of memory");
219
+ int n;
220
+ if(mode==1) n = filt ? kci_vec_search_exact_filtered(h->v,q,k,th,kn_idf,&f,pi,ps) : kci_vec_search_exact(h->v,q,k,th,pi,ps);
221
+ else {
222
+ if(!h->s) h->s=kci_vec_searcher_new(h->v);
223
+ if(!h->s) return kn_throw(env,"kci_vec: cannot make the searcher (out of memory)");
224
+ n = filt ? kci_vec_search_filtered(h->s,q,k,ef,rn,kn_idf,&f,pi,ps)
225
+ : rn>0 ? kci_vec_search_rerank(h->s,q,k,ef,rn,pi,ps) : kci_vec_search_r(h->s,q,k,ef,pi,ps);
226
+ }
227
+ if(n>=0) h->warm |= mode==1 ? 2 : 1;
228
+ napi_create_typedarray(env,napi_biguint64_array,(size_t)k,bi,0,&ids); napi_create_typedarray(env,napi_float32_array,(size_t)k,bs,0,&sc);
229
+ napi_create_array_with_length(env,3,&r);
230
+ napi_set_element(env,r,0,ids); napi_set_element(env,r,1,sc); napi_set_element(env,r,2,kn_num(env,n));
231
+ return r;
232
+ }
233
+ /* searchAsync(same arguments as search) -> a Promise of [ids, scores, n]. The search runs on a worker thread with a
234
+ * searcher of its own (taken from the pool here, given back when done), on copies of the query and the filter.
235
+ * Several may run at once; the calls that change the index are refused until all have settled. */
236
+ typedef struct { Kn *h; KciVecSearcher *s; float *q; KnIds f; int filt, k, mode, ef, rn, th, n; uint64_t *oi; float *os;
237
+ napi_deferred def; napi_async_work work; napi_ref ref; } KnS;
238
+ static void kn_s_free(KnS *w){ free(w->q); free((void*)w->f.ids); free(w->oi); free(w->os); free(w); }
239
+ static void kn_s_exec(napi_env env, void *data){
240
+ (void)env; KnS *w=data; KciVec *v=w->h->v;
241
+ if(w->mode==1) w->n = w->filt ? kci_vec_search_exact_filtered(v,w->q,w->k,w->th,kn_idf,&w->f,w->oi,w->os) : kci_vec_search_exact(v,w->q,w->k,w->th,w->oi,w->os);
242
+ else {
243
+ if(!w->s) w->s=kci_vec_searcher_new(v);
244
+ if(!w->s){ w->n=-2; return; }
245
+ w->n = w->filt ? kci_vec_search_filtered(w->s,w->q,w->k,w->ef,w->rn,kn_idf,&w->f,w->oi,w->os)
246
+ : w->rn>0 ? kci_vec_search_rerank(w->s,w->q,w->k,w->ef,w->rn,w->oi,w->os) : kci_vec_search_r(w->s,w->q,w->k,w->ef,w->oi,w->os);
247
+ }
248
+ }
249
+ static void kn_s_done(napi_env env, napi_status st, void *data){
250
+ KnS *w=data; Kn *h=w->h; h->readers--;
251
+ if(w->s){ if(h->npool<KN_POOL) h->pool[h->npool++]=w->s; else kci_vec_searcher_free(w->s); }
252
+ int n = st==napi_ok ? w->n : -3; size_t m = n>0 ? (size_t)n : 0;
253
+ napi_value bi, bs, ids, sc, r; void *pi=NULL, *ps=NULL;
254
+ if(napi_create_arraybuffer(env,m*8,&pi,&bi)!=napi_ok || napi_create_arraybuffer(env,m*4,&ps,&bs)!=napi_ok){
255
+ napi_value msg, err; napi_create_string_utf8(env,"kci_vec: out of memory",NAPI_AUTO_LENGTH,&msg);
256
+ napi_create_error(env,NULL,msg,&err); napi_reject_deferred(env,w->def,err);
257
+ } else {
258
+ if(m){ memcpy(pi,w->oi,m*8); memcpy(ps,w->os,m*4); }
259
+ napi_create_typedarray(env,napi_biguint64_array,m,bi,0,&ids); napi_create_typedarray(env,napi_float32_array,m,bs,0,&sc);
260
+ napi_create_array_with_length(env,3,&r);
261
+ napi_set_element(env,r,0,ids); napi_set_element(env,r,1,sc); napi_set_element(env,r,2,kn_num(env,n));
262
+ napi_resolve_deferred(env,w->def,r);
263
+ }
264
+ napi_delete_reference(env,w->ref); napi_delete_async_work(env,w->work); kn_s_free(w);
265
+ }
266
+ static napi_value kn_search_async(napi_env env, napi_callback_info info){
267
+ ARGS(8); Kn *h=kn_h(env,a[0]); if(!h) return NULL;
268
+ const float *q; size_t qn; const uint64_t *fi=NULL; size_t fn=0; int32_t k,mode,ef,rn,th; int filt=!kn_null(env,a[7]);
269
+ if(!kn_f32a(env,a[1],&q,&qn) || !kn_i32(env,a[2],&k) || !kn_i32(env,a[3],&mode) || !kn_i32(env,a[4],&ef) || !kn_i32(env,a[5],&rn)
270
+ || !kn_i32(env,a[6],&th) || (filt && !kn_u64a(env,a[7],&fi,&fn))) return kn_throw(env,"kci_vec: bad arguments");
271
+ if(qn!=(size_t)kci_vec_dim(h->v)) return kn_throw(env,"kci_vec: the query does not hold dim numbers");
272
+ if(k<1 || k>16000000) return kn_throw(env,"kci_vec: k must be 1 .. 16,000,000");
273
+ KnS *w=calloc(1,sizeof(KnS)); if(!w) return kn_throw(env,"kci_vec: out of memory");
274
+ w->h=h; w->k=k; w->mode=mode; w->ef=ef; w->rn=rn; w->th=th; w->filt=filt; w->f.n=fn;
275
+ w->q=malloc(qn*4); w->oi=malloc((size_t)k*8); w->os=malloc((size_t)k*4);
276
+ uint64_t *fc = filt ? malloc((fn?fn:1)*8) : NULL; w->f.ids=fc;
277
+ if(!w->q || !w->oi || !w->os || (filt && !fc)){ kn_s_free(w); return kn_throw(env,"kci_vec: out of memory"); }
278
+ memcpy(w->q,q,qn*4); if(filt && fn) memcpy(fc,fi,fn*8);
279
+ if(!(h->warm & (mode==1 ? 2 : 1))){
280
+ uint64_t wi; float ws; int wn;
281
+ if(mode==1) wn=kci_vec_search_exact(h->v,w->q,1,1,&wi,&ws);
282
+ else { if(!h->s) h->s=kci_vec_searcher_new(h->v); wn = h->s ? kci_vec_search_r(h->s,w->q,1,ef,&wi,&ws) : -1; }
283
+ if(wn>=0) h->warm |= mode==1 ? 2 : 1;
284
+ }
285
+ napi_value pr, name; napi_create_string_utf8(env,"kci_vec.search",NAPI_AUTO_LENGTH,&name);
286
+ if(napi_create_promise(env,&w->def,&pr)!=napi_ok || napi_create_reference(env,a[0],1,&w->ref)!=napi_ok
287
+ || napi_create_async_work(env,NULL,name,kn_s_exec,kn_s_done,w,&w->work)!=napi_ok){ kn_s_free(w); return kn_throw(env,"kci_vec: cannot start the search"); }
288
+ if(mode!=1 && h->npool>0) w->s=h->pool[--h->npool];
289
+ h->readers++;
290
+ if(napi_queue_async_work(env,w->work)!=napi_ok){
291
+ h->readers--; if(w->s) h->pool[h->npool++]=w->s;
292
+ napi_delete_reference(env,w->ref); napi_delete_async_work(env,w->work); kn_s_free(w); return kn_throw(env,"kci_vec: cannot start the search");
293
+ }
294
+ return pr;
295
+ }
296
+ /* del(h, id BigInt) -> true when the id was there */
297
+ static napi_value kn_del(napi_env env, napi_callback_info info){
298
+ ARGS(2); Kn *h=kn_w(env,a[0]); if(!h) return NULL;
299
+ uint64_t id; bool ok;
300
+ if(napi_get_value_bigint_uint64(env,a[1],&id,&ok)!=napi_ok || !ok) return kn_throw(env,"kci_vec: bad id");
301
+ napi_value r; napi_get_boolean(env, kci_vec_delete(h->v,id)==0, &r); return r;
302
+ }
303
+ static napi_value kn_compact(napi_env env, napi_callback_info info){
304
+ ARGS(1); Kn *h=kn_w(env,a[0]); if(!h) return NULL;
305
+ kn_drop_s(h); return kn_num(env,kci_vec_compact(h->v));
306
+ }
307
+ /* save(h, path, key Uint8Array or null) -> 0 or not; load(path, key or null) -> handle */
308
+ static int kn_key(napi_env env, napi_value x, const uint8_t **key, size_t *n){
309
+ *key=NULL; *n=0; if(kn_null(env,x)) return 1;
310
+ napi_typedarray_type t; void *d=NULL;
311
+ if(napi_get_typedarray_info(env,x,&t,n,&d,NULL,NULL)!=napi_ok || t!=napi_uint8_array) return 0;
312
+ *key=d; if(!*n) *key=NULL; return 1;
313
+ }
314
+ static napi_value kn_save(napi_env env, napi_callback_info info){
315
+ ARGS(3); Kn *h=kn_h(env,a[0]); if(!h) return NULL;
316
+ const uint8_t *key; size_t kl; if(!kn_key(env,a[2],&key,&kl)) return kn_throw(env,"kci_vec: bad key");
317
+ char *p=kn_path(env,a[1]); if(!p) return kn_throw(env,KN_BAD_PATH);
318
+ int rc=kci_vec_save(h->v,p,key,(int)kl); free(p);
319
+ return kn_num(env,rc);
320
+ }
321
+ static napi_value kn_load(napi_env env, napi_callback_info info){
322
+ ARGS(2); const uint8_t *key; size_t kl; if(!kn_key(env,a[1],&key,&kl)) return kn_throw(env,"kci_vec: bad key");
323
+ char *p=kn_path(env,a[0]); if(!p) return kn_throw(env,KN_BAD_PATH);
324
+ KciVec *v=kci_vec_load(p,key,(int)kl); free(p);
325
+ if(!v) return kn_throw(env,"kci_vec: load failed (wrong key, damaged file, or file missing)");
326
+ return kn_wrap(env,v);
327
+ }
328
+ /* knn(h, k, ef (-1 exact, 0 default), threads) -> [own ids, neighbour ids, scores, lines]; lines < 0: refused */
329
+ static napi_value kn_knn(napi_env env, napi_callback_info info){
330
+ ARGS(4); Kn *h=kn_h(env,a[0]); if(!h) return NULL;
331
+ int32_t k,ef,th; if(!kn_i32(env,a[1],&k) || !kn_i32(env,a[2],&ef) || !kn_i32(env,a[3],&th)) return kn_throw(env,"kci_vec: bad arguments");
332
+ if(k<1 || k>16383) return kn_throw(env,"kci_vec: k must be 1 .. 16383");
333
+ size_t n=kci_vec_count(h->v); if(!n) n=1;
334
+ napi_value b0,b1,b2,t0,t1,t2,r; void *p0=NULL,*p1=NULL,*p2=NULL;
335
+ if(napi_create_arraybuffer(env,n*8,&p0,&b0)!=napi_ok || napi_create_arraybuffer(env,n*(size_t)k*8,&p1,&b1)!=napi_ok
336
+ || napi_create_arraybuffer(env,n*(size_t)k*4,&p2,&b2)!=napi_ok) return kn_throw(env,"kci_vec: out of memory");
337
+ int64_t got=kci_vec_knn_graph(h->v,k,ef,th,p0,p1,p2);
338
+ napi_create_typedarray(env,napi_biguint64_array,n,b0,0,&t0); napi_create_typedarray(env,napi_biguint64_array,n*(size_t)k,b1,0,&t1);
339
+ napi_create_typedarray(env,napi_float32_array,n*(size_t)k,b2,0,&t2);
340
+ napi_create_array_with_length(env,4,&r);
341
+ napi_set_element(env,r,0,t0); napi_set_element(env,r,1,t1); napi_set_element(env,r,2,t2); napi_set_element(env,r,3,kn_num(env,(double)got));
342
+ return r;
343
+ }
344
+
345
+ /* seal(bytes, key) -> bytes 40 longer; unseal(bytes, key) -> the bytes back, or throws (wrong key, changed or cut
346
+ * data). The sealing the Python client uses for the files beside the index, so that either reads the other's folder. */
347
+ static napi_value kn_seal2(napi_env env, napi_callback_info info, int open){
348
+ ARGS(2); napi_typedarray_type t; size_t n=0,kl=0; void *d=NULL,*k=NULL;
349
+ if(napi_get_typedarray_info(env,a[0],&t,&n,&d,NULL,NULL)!=napi_ok || t!=napi_uint8_array) return kn_throw(env,"kci_vec: seal: the data must be a Uint8Array");
350
+ if(napi_get_typedarray_info(env,a[1],&t,&kl,&k,NULL,NULL)!=napi_ok || t!=napi_uint8_array || !kl) return kn_throw(env,"kci_vec: seal: the key must be a Uint8Array that is not empty");
351
+ if(open && n<40) return kn_throw(env,"kci_vec: unseal failed (wrong key, or the data was changed or cut off)");
352
+ size_t on = open ? n-40 : n+40; void *o=NULL; napi_value b,r;
353
+ if(napi_create_arraybuffer(env,on ? on : 1,&o,&b)!=napi_ok) return kn_throw(env,"kci_vec: out of memory");
354
+ int64_t got = open ? kci_unseal(d,n,k,(int)kl,o) : kci_seal(d,n,k,(int)kl,o);
355
+ if(got!=(int64_t)on) return kn_throw(env, open ? "kci_vec: unseal failed (wrong key, or the data was changed or cut off)" : "kci_vec: seal failed");
356
+ napi_create_typedarray(env,napi_uint8_array,on,b,0,&r); return r;
357
+ }
358
+ static napi_value kn_seal(napi_env env, napi_callback_info info){ return kn_seal2(env,info,0); }
359
+ static napi_value kn_unseal(napi_env env, napi_callback_info info){ return kn_seal2(env,info,1); }
360
+
361
+ NAPI_MODULE_INIT(){
362
+ /* built for AVX2 + FMA (the default of build.js, and the ready-made binaries): a CPU without them is told so here */
363
+ #if defined(__x86_64__) && defined(__AVX2__) && defined(__GNUC__)
364
+ __builtin_cpu_init();
365
+ if(!__builtin_cpu_supports("avx2") || !__builtin_cpu_supports("fma")){
366
+ napi_throw_error(env,NULL,"kci_vec: this binary needs a CPU with AVX2 and FMA"); return NULL;
367
+ }
368
+ #endif
369
+ static const struct { const char *name; napi_callback fn; } f[] = {
370
+ {"create",kn_create},{"close",kn_close},{"info",kn_info},{"add",kn_add},{"build",kn_build},{"buildAsync",kn_build_async},
371
+ {"search",kn_search},{"searchAsync",kn_search_async},{"del",kn_del},{"compact",kn_compact},{"save",kn_save},{"load",kn_load},{"knn",kn_knn},
372
+ {"seal",kn_seal},{"unseal",kn_unseal} };
373
+ for(size_t i=0;i<sizeof f/sizeof f[0];i++){
374
+ napi_value fn; if(napi_create_function(env,f[i].name,NAPI_AUTO_LENGTH,f[i].fn,NULL,&fn)!=napi_ok) return NULL;
375
+ napi_set_named_property(env,exports,f[i].name,fn);
376
+ }
377
+ return exports;
378
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "kci-vec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.31",
4
+ "description": "Embedded vector search for Node.js: exact answers by default, encrypted files",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/KimYuki3/kci-vec-src.git",
11
+ "directory": "clients/node"
12
+ },
13
+ "homepage": "https://github.com/KimYuki3/kci-vec-src/tree/main/clients/node#readme",
14
+ "keywords": [
15
+ "vector-search",
16
+ "nearest-neighbor",
17
+ "hnsw",
18
+ "embeddings",
19
+ "encryption",
20
+ "embedded"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "scripts": {
26
+ "install": "node install.js",
27
+ "build": "node build.js",
28
+ "test": "node test.js && node test_store.js",
29
+ "prepack": "node pack-src.js"
30
+ },
31
+ "files": [
32
+ "index.js",
33
+ "where.js",
34
+ "store.js",
35
+ "index.d.ts",
36
+ "build.js",
37
+ "install.js",
38
+ "example.js",
39
+ "kci_vec_node.c",
40
+ "src/",
41
+ "prebuilds/",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "dependencies": {
46
+ "node-api-headers": "^1.5.0"
47
+ }
48
+ }
Binary file
Binary file