@yaks/embedding 0.0.0-stage → 0.2.36

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.
Files changed (132) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +549 -2
  3. package/_dist/compile.d.ts +34 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/ddl.d.ts +31 -0
  6. package/_dist/ddl.d.ts.map +1 -0
  7. package/_dist/embedder.d.ts +55 -0
  8. package/_dist/embedder.d.ts.map +1 -0
  9. package/_dist/fields.d.ts +70 -0
  10. package/_dist/fields.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +63 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/held.d.ts +16 -0
  14. package/_dist/held.d.ts.map +1 -0
  15. package/_dist/image.d.ts +20 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +105 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/native.d.ts +20 -0
  20. package/_dist/native.d.ts.map +1 -0
  21. package/_dist/near.d.ts +35 -0
  22. package/_dist/near.d.ts.map +1 -0
  23. package/_dist/neighbours.d.ts +29 -0
  24. package/_dist/neighbours.d.ts.map +1 -0
  25. package/_dist/options.d.ts +37 -0
  26. package/_dist/options.d.ts.map +1 -0
  27. package/_dist/outage.d.ts +64 -0
  28. package/_dist/outage.d.ts.map +1 -0
  29. package/_dist/owed.d.ts +79 -0
  30. package/_dist/owed.d.ts.map +1 -0
  31. package/_dist/remote.d.ts +116 -0
  32. package/_dist/remote.d.ts.map +1 -0
  33. package/_dist/score.d.ts +10 -0
  34. package/_dist/score.d.ts.map +1 -0
  35. package/_dist/search.d.ts +24 -0
  36. package/_dist/search.d.ts.map +1 -0
  37. package/_dist/service.d.ts +23 -0
  38. package/_dist/service.d.ts.map +1 -0
  39. package/_dist/sleeper.d.ts +37 -0
  40. package/_dist/sleeper.d.ts.map +1 -0
  41. package/_dist/sweep.d.ts +71 -0
  42. package/_dist/sweep.d.ts.map +1 -0
  43. package/_dist/tools.d.ts +14 -0
  44. package/_dist/tools.d.ts.map +1 -0
  45. package/_dist/vector.d.ts +30 -0
  46. package/_dist/vector.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +6 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/coded.js +98 -0
  50. package/coded.js.map +1 -0
  51. package/coded.ts +85 -0
  52. package/compile.js +145 -0
  53. package/compile.js.map +1 -0
  54. package/compile.ts +206 -0
  55. package/ddl.js +476 -0
  56. package/ddl.js.map +1 -0
  57. package/ddl.ts +346 -0
  58. package/deno.json +1 -0
  59. package/embedder.js +85 -0
  60. package/embedder.js.map +1 -0
  61. package/embedder.ts +113 -0
  62. package/fields.js +178 -0
  63. package/fields.js.map +1 -0
  64. package/fields.ts +259 -0
  65. package/fill.js +177 -0
  66. package/fill.js.map +1 -0
  67. package/fill.ts +144 -0
  68. package/graph.js +113 -0
  69. package/graph.js.map +1 -0
  70. package/graph.ts +167 -0
  71. package/held.js +680 -0
  72. package/held.js.map +1 -0
  73. package/held.ts +726 -0
  74. package/image.js +202 -0
  75. package/image.js.map +1 -0
  76. package/image.ts +185 -0
  77. package/mod.js +105 -0
  78. package/mod.js.map +1 -0
  79. package/mod.ts +113 -0
  80. package/native.js +236 -0
  81. package/native.js.map +1 -0
  82. package/native.ts +288 -0
  83. package/near.js +123 -0
  84. package/near.js.map +1 -0
  85. package/near.ts +192 -0
  86. package/neighbours.js +223 -0
  87. package/neighbours.js.map +1 -0
  88. package/neighbours.ts +303 -0
  89. package/options.js +187 -0
  90. package/options.js.map +1 -0
  91. package/options.ts +269 -0
  92. package/outage.js +128 -0
  93. package/outage.js.map +1 -0
  94. package/outage.ts +132 -0
  95. package/owed.js +287 -0
  96. package/owed.js.map +1 -0
  97. package/owed.ts +346 -0
  98. package/package.json +45 -4
  99. package/remote.js +264 -0
  100. package/remote.js.map +1 -0
  101. package/remote.ts +391 -0
  102. package/score.js +46 -0
  103. package/score.js.map +1 -0
  104. package/score.ts +60 -0
  105. package/search.js +65 -0
  106. package/search.js.map +1 -0
  107. package/search.ts +118 -0
  108. package/service.js +107 -0
  109. package/service.js.map +1 -0
  110. package/service.ts +133 -0
  111. package/sleeper.js +107 -0
  112. package/sleeper.js.map +1 -0
  113. package/sleeper.ts +166 -0
  114. package/sparse.js +36 -0
  115. package/sparse.js.map +1 -0
  116. package/sparse.ts +49 -0
  117. package/sweep.js +374 -0
  118. package/sweep.js.map +1 -0
  119. package/sweep.ts +446 -0
  120. package/tools.js +57 -0
  121. package/tools.js.map +1 -0
  122. package/tools.ts +88 -0
  123. package/vector.js +78 -0
  124. package/vector.js.map +1 -0
  125. package/vector.ts +96 -0
  126. package/visibility.js +83 -0
  127. package/visibility.js.map +1 -0
  128. package/visibility.ts +111 -0
  129. package/vocab.js +22 -0
  130. package/vocab.js.map +1 -0
  131. package/vocab.json +19 -0
  132. package/vocab.ts +22 -0
package/held.ts ADDED
@@ -0,0 +1,726 @@
1
+ // The vectors held in this process's memory, so a search compares without
2
+ // reading them all: one copy per statement capability, loaded the first time a
3
+ // search asks for it, or before where a process answers many (./graph.ts
4
+ // `preload`, which a read worker runs). A database only this process has open
5
+ // (a Durable Object's, or one in memory; @yaks/sql `Statements.ownership` says
6
+ // which) keeps its copy current by a dirty set; shared storage, by a journal.
7
+ //
8
+ // The copy is int8. Each vector is held as one signed byte per coordinate, its
9
+ // coordinates over its own largest in 127 steps, and one float that scales
10
+ // them back. A search scans every code, keeps the best {@link RESCORE} the
11
+ // graph lets stand, reads those few vectors' float rows, and ranks them by
12
+ // their exact cosine. Scaling each vector by its own largest coordinate is the
13
+ // calibration that suits an embedding model's unit vectors: Qwen3-Embedding's
14
+ // largest coordinate is ~3.8 times its root mean square, and no one dimension
15
+ // holds it, so one step is ~1/33 of a typical coordinate and the scan's error
16
+ // is far below the gap between a neighbour and the hundredth candidate. It
17
+ // needs no ranges drawn from the data, so a vector codes the same whenever and
18
+ // wherever it is coded, and a copy kept current write by write codes exactly
19
+ // what one loaded afresh would.
20
+ //
21
+ // The table stays the truth, and the copy is the table as of one build. An
22
+ // exclusive store's copy is kept current by triggers on the table, which note
23
+ // every vector written or deleted, by anyone, in the same statement as the
24
+ // write (./ddl.ts, the dirty set), and a search codes what the set names from
25
+ // its rows beside the copy. After each sweep pass, the process that ran it
26
+ // folds the set into its copy and clears it ({@link absorb}), numbering a new
27
+ // build; a copy that sees a build it did not make loads again. So no write can
28
+ // leave a copy behind: a write another driver made, a migration, a rollback
29
+ // are all in the set or in the build number.
30
+ //
31
+ // Shared storage is a file on a box that other processes write too, and its
32
+ // copy loads from the codes kept beside the floats (./coded.ts), a fifth of
33
+ // their bytes, once every vector has them under one model. Triggers journal
34
+ // every vector written, whoever writes it (./ddl.ts `JOURNAL`), and a search
35
+ // first folds in what the journal names past the last change its copy read,
36
+ // coding those vectors from their floats. A copy further behind than
37
+ // {@link FOLLOW} changes, or behind what the sweep trimmed, loads again. So
38
+ // once a copy is held, a search reads only the few vectors it rescores: the
39
+ // native scan it replaces read every code, 7 s of them from disk when the
40
+ // box's page cache had let the file go.
41
+ //
42
+ // Memory is the limit. A vector costs its width in bytes and ~40 bytes beside
43
+ // it (1 KB at 1024 dimensions), and every object in a Worker's isolate shares
44
+ // its 128 MB, so all copies together stay within {@link HELD}: the least
45
+ // recently searched is dropped to make room, and a store whose vectors alone
46
+ // would pass it is not held at all and is read row by row. Today's largest
47
+ // store (24k vectors) holds 25 MB; ten times that would not fit. Shared
48
+ // storage is never in a Worker, so its copies share {@link SHARED} instead: the
49
+ // box's 314k vectors at 384 dimensions hold 133 MB.
50
+
51
+ import {
52
+ among,
53
+ and,
54
+ as,
55
+ at,
56
+ col,
57
+ each,
58
+ eq,
59
+ exists,
60
+ fn,
61
+ from,
62
+ gt,
63
+ join,
64
+ lit,
65
+ not,
66
+ op,
67
+ type Raw,
68
+ select,
69
+ type Statements,
70
+ table,
71
+ tally,
72
+ val,
73
+ } from '@yaks/sql'
74
+ import { BUILD, CODE, DIRTY, JOURNAL, TABLE } from './ddl.js'
75
+ import { admitted, current, few, only } from './native.js'
76
+ import { complete } from './coded.js'
77
+ import type { Near } from './near.ts'
78
+ import { code, cosine, floats } from './vector.js'
79
+
80
+ /** How many bytes of vectors this process holds across every copy: 48 MB of
81
+ * a Worker isolate's 128 MB, which every object in it shares. */
82
+ export let HELD = 48 * 2 ** 20
83
+
84
+ /** How many bytes of shared storage's vectors this process holds across every
85
+ * copy: a box's process, which has the memory a Worker's isolate does not. */
86
+ export let SHARED = 512 * 2 ** 20
87
+
88
+ /** How many changes a copy of shared storage reads on through before it loads
89
+ * again instead, and how many the sweep keeps when it trims the journal. */
90
+ export let FOLLOW = 4096
91
+
92
+ /** How many of the scan's best a search reads from their rows and ranks by
93
+ * their exact cosine (more where it asks for more neighbours). */
94
+ export let RESCORE = 100
95
+
96
+ // Rows read to a statement while a copy loads.
97
+ let PAGE = 2048
98
+
99
+ // The bytes one vector costs held: its codes, its owner, its scale, and its
100
+ // entry in the owner index.
101
+ let cost = (dim: number) => dim + 4 + 4 + 32
102
+
103
+ /** One database's vectors under one model, as of one build. */
104
+ export type Held = {
105
+ model: string
106
+ dim: number
107
+ /** a copy of shared storage, current through the journal */
108
+ shared: boolean
109
+ /** the build this copy is current at, or for shared storage the last change
110
+ * it read; -1 once dropped */
111
+ n: number
112
+ size: number
113
+ ids: Int32Array
114
+ /** each vector's step over its length: a query's dot product with its
115
+ * codes, times this, is the cosine times the query's length */
116
+ scales: Float32Array
117
+ codes: Int8Array
118
+ slot: Map<number, number>
119
+ }
120
+
121
+ // The first `size` coded vectors' scores against `query`: each one's codes'
122
+ // dot product, term after term, times its scale. Four vectors share a pass
123
+ // over the query, which V8 runs nearly twice as fast as one at a time, and
124
+ // each one's sum is still its own terms in order, so a vector scores the same
125
+ // to the last bit however many are scored beside it.
126
+ let scores = (
127
+ query: Float32Array,
128
+ codes: Int8Array,
129
+ scales: Float32Array,
130
+ size: number,
131
+ ): Float64Array => {
132
+ let out = new Float64Array(size)
133
+ let dim = query.length, i = 0
134
+ for (; i + 4 <= size; i += 4) {
135
+ let a = 0, b = 0, c = 0, d = 0
136
+ let p = i * dim, q = p + dim, r = q + dim, s = r + dim
137
+ for (let j = 0; j < dim; j++) {
138
+ let x = query[j]
139
+ a += x * codes[p + j]
140
+ b += x * codes[q + j]
141
+ c += x * codes[r + j]
142
+ d += x * codes[s + j]
143
+ }
144
+ out[i] = scales[i] * a
145
+ out[i + 1] = scales[i + 1] * b
146
+ out[i + 2] = scales[i + 2] * c
147
+ out[i + 3] = scales[i + 3] * d
148
+ }
149
+ for (; i < size; i++) {
150
+ let a = 0, p = i * dim
151
+ for (let j = 0; j < dim; j++) a += query[j] * codes[p + j]
152
+ out[i] = scales[i] * a
153
+ }
154
+ return out
155
+ }
156
+
157
+ // Each driver's copy, gone with the driver. The copies are also listed, least
158
+ // recently searched first, to share one budget; the list holds them weakly, so
159
+ // an object the runtime let go of takes its copy with it.
160
+ let copies = new WeakMap<Statements, Held>()
161
+ let lru = new Set<WeakRef<Held>>()
162
+ let refs = new WeakMap<Held, WeakRef<Held>>()
163
+ // The drivers whose vectors would not fit.
164
+ let over = new WeakSet<Statements>()
165
+
166
+ let bytes = (h: Held) => h.ids.length * cost(h.dim)
167
+
168
+ let touch = (h: Held) => {
169
+ let r = refs.get(h) ?? new WeakRef(h)
170
+ refs.set(h, r)
171
+ lru.delete(r)
172
+ lru.add(r)
173
+ }
174
+
175
+ let listed = (): Held[] =>
176
+ [...lru].flatMap((r) => {
177
+ let h = r.deref()
178
+ if (!h) lru.delete(r)
179
+ return h ? [h] : []
180
+ })
181
+
182
+ let drop = (h: Held) => {
183
+ let r = refs.get(h)
184
+ if (r) lru.delete(r)
185
+ Object.assign(h, {
186
+ n: -1,
187
+ size: 0,
188
+ ids: new Int32Array(0),
189
+ scales: new Float32Array(0),
190
+ codes: new Int8Array(0),
191
+ slot: new Map(),
192
+ })
193
+ }
194
+
195
+ // Room for `need` more bytes, dropping the least recently searched copies of
196
+ // its kind other than `mine`; false when `need` could not fit even then.
197
+ let room = (need: number, mine: Held) => {
198
+ let held = listed().filter((h) => h.shared == mine.shared)
199
+ let budget = mine.shared ? SHARED : HELD
200
+ let used = 0
201
+ for (let h of held) used += bytes(h)
202
+ for (let h of held) {
203
+ if (used + need <= budget) break
204
+ if (h == mine) continue
205
+ used -= bytes(h)
206
+ drop(h)
207
+ }
208
+ return used + need <= budget
209
+ }
210
+
211
+ // Room for `cap` vectors, keeping the ones held.
212
+ let grow = (h: Held, cap: number): boolean => {
213
+ if (!room((cap - h.ids.length) * cost(h.dim), h)) return false
214
+ let ids = new Int32Array(cap), scales = new Float32Array(cap)
215
+ let codes = new Int8Array(cap * h.dim)
216
+ ids.set(h.ids.subarray(0, h.size))
217
+ scales.set(h.scales.subarray(0, h.size))
218
+ codes.set(h.codes.subarray(0, h.size * h.dim))
219
+ Object.assign(h, { ids, scales, codes })
220
+ return true
221
+ }
222
+
223
+ // Forget `owner`'s vector: the last slot moves into its place.
224
+ let lose = (h: Held, owner: number) => {
225
+ let i = h.slot.get(owner)
226
+ if (i == null) return
227
+ let last = --h.size
228
+ h.slot.delete(owner)
229
+ if (i == last) return
230
+ let moved = h.ids[last]
231
+ h.ids[i] = moved
232
+ h.scales[i] = h.scales[last]
233
+ h.codes.copyWithin(i * h.dim, last * h.dim, (last + 1) * h.dim)
234
+ h.slot.set(moved, i)
235
+ }
236
+
237
+ // The slot `owner`'s vector is held in, the one it had or a new one; null
238
+ // when there is no room for it.
239
+ let slot = (h: Held, owner: number): number | null => {
240
+ let i = h.slot.get(owner)
241
+ if (i != null) return i
242
+ if (h.size == h.ids.length && !grow(h, h.size + (h.size >> 3) + 64)) {
243
+ return null
244
+ }
245
+ i = h.size++
246
+ h.slot.set(owner, i)
247
+ h.ids[i] = owner
248
+ return i
249
+ }
250
+
251
+ // Hold `owner`'s vector, coded from its floats; false when there is no room
252
+ // for it.
253
+ let keep = (h: Held, owner: number, bytes: Uint8Array): boolean => {
254
+ if (!h.dim) h.dim = bytes.byteLength / 4
255
+ // A vector of another width is from another space; the model name says
256
+ // which, so this is a row nothing should have written, and it is not held.
257
+ if (bytes.byteLength != h.dim * 4) {
258
+ lose(h, owner)
259
+ return true
260
+ }
261
+ let i = slot(h, owner)
262
+ if (i == null) return false
263
+ h.scales[i] = code(floats(bytes), h.codes, i * h.dim)
264
+ return true
265
+ }
266
+
267
+ // Hold `owner`'s vector as the codes stored for it (./coded.ts), scaled by
268
+ // their own length: their cosine is the vector's, give or take a step.
269
+ let kept = (h: Held, owner: number, bytes: Uint8Array): boolean => {
270
+ if (bytes.byteLength != h.dim) {
271
+ lose(h, owner)
272
+ return true
273
+ }
274
+ let i = slot(h, owner)
275
+ if (i == null) return false
276
+ let codes = new Int8Array(bytes.buffer, bytes.byteOffset, h.dim)
277
+ h.codes.set(codes, i * h.dim)
278
+ let sum = 0
279
+ for (let x of codes) sum += x * x
280
+ h.scales[i] = sum ? 1 / Math.sqrt(sum) : 0
281
+ return true
282
+ }
283
+
284
+ // What the dirty set names, as each entity's vector stands now: its bytes
285
+ // under `model`, or null where it has none (deleted, or another model's).
286
+ let d = at('d'), e = at('e')
287
+ let dirty = (db: Statements, model: string): Map<number, Uint8Array | null> =>
288
+ new Map(
289
+ db.query(select({
290
+ cols: [
291
+ d('owner'),
292
+ as(e('model'), 'model'),
293
+ as(e('vec'), 'vec'),
294
+ ],
295
+ from: table(DIRTY, 'd'),
296
+ joins: [{
297
+ how: 'left',
298
+ src: table(TABLE, 'e'),
299
+ on: eq(e('owner'), d('owner')),
300
+ }],
301
+ })).map((r) => [
302
+ Number(r.owner),
303
+ r.model == model ? r.vec as Uint8Array : null,
304
+ ]),
305
+ )
306
+
307
+ // Where this process alone owns the database, the set is the copies' alone:
308
+ // cleared, with a new
309
+ // build numbered so every other copy of it loads again.
310
+ let owned = (db: Statements) => db.ownership == 'exclusive'
311
+ let advance = (db: Statements): void => {
312
+ db.query({ t: 'update', table: BUILD, set: { n: op('+', col('n'), lit(1)) } })
313
+ db.query({ t: 'delete', from: DIRTY })
314
+ }
315
+ let clear = (db: Statements): number => {
316
+ advance(db)
317
+ return current(db).n
318
+ }
319
+
320
+ // Every vector under `model`, a page at a time, into a copy made to their
321
+ // count; null where they will not fit.
322
+ let load = (db: Statements, model: string): Held | null => {
323
+ let was = copies.get(db)
324
+ if (was) drop(was)
325
+ let h: Held = {
326
+ model,
327
+ dim: 0,
328
+ shared: false,
329
+ n: current(db).n,
330
+ size: 0,
331
+ ids: new Int32Array(0),
332
+ scales: new Float32Array(0),
333
+ codes: new Int8Array(0),
334
+ slot: new Map(),
335
+ }
336
+ touch(h)
337
+ copies.set(db, h)
338
+ let [first] = db.query(select({
339
+ cols: [as(fn('length', col('vec')), 'bytes')],
340
+ from: table(TABLE),
341
+ where: eq(col('model'), val(model)),
342
+ limit: lit(1),
343
+ }))
344
+ h.dim = Number(first?.bytes ?? 0) / 4
345
+ if (!grow(h, tally(db, TABLE, eq(col('model'), val(model))))) {
346
+ drop(h)
347
+ copies.delete(db)
348
+ over.add(db)
349
+ return null
350
+ }
351
+ for (let after = 0;;) {
352
+ let rows = db.query(select({
353
+ cols: [col('owner'), col('vec')],
354
+ from: table(TABLE),
355
+ where: and(gt(col('owner'), val(after)), eq(col('model'), val(model))),
356
+ order: [col('owner')],
357
+ limit: lit(PAGE),
358
+ }))
359
+ for (let r of rows) {
360
+ if (!keep(h, Number(r.owner), r.vec as Uint8Array)) return refuse(db, h)
361
+ }
362
+ if (rows.length < PAGE) break
363
+ after = Number(rows[rows.length - 1].owner)
364
+ }
365
+ // The copy is the table now, so what the set named is in it.
366
+ if (owned(db) && dirty(db, model).size) h.n = clear(db)
367
+ return h
368
+ }
369
+
370
+ // A copy that will not fit: dropped, and `db` never held again.
371
+ let refuse = (db: Statements, h: Held): null => {
372
+ drop(h)
373
+ copies.delete(db)
374
+ over.add(db)
375
+ return null
376
+ }
377
+
378
+ // Whether this database journals its vectors, asked again once its schema
379
+ // changes: a file a process of an older schema opened has no journal yet.
380
+ let journals = new WeakMap<Statements, { version: number; has: boolean }>()
381
+ let journaled = (db: Statements): boolean => {
382
+ let version = db.revision('schema')
383
+ let had = journals.get(db)
384
+ if (had?.version == version) return had.has
385
+ let has = !!db.query(select({
386
+ cols: [col('name')],
387
+ from: table('sqlite_master'),
388
+ where: eq(col('name'), val(JOURNAL)),
389
+ }))[0]
390
+ journals.set(db, { version, has })
391
+ return has
392
+ }
393
+
394
+ // The last change the journal holds, 0 before the first.
395
+ let newest = (db: Statements): number =>
396
+ Number(
397
+ db.query(select({
398
+ cols: [as(fn('max', col('seq')), 'n')],
399
+ from: table(JOURNAL),
400
+ }))[0]?.n ?? 0,
401
+ )
402
+
403
+ // Shared storage's vectors under `model`, from their codes: the journal's
404
+ // newest change read first, so whatever is written while the pages are read
405
+ // is a change past it, which the next search folds in. Null where some vector
406
+ // has no codes yet or there are two models' vectors, which the native scan
407
+ // answers until the sweep has coded them.
408
+ let loadCodes = (db: Statements, model: string): Held | null => {
409
+ if (!complete(db) || only(db) != model) return null
410
+ let was = copies.get(db)
411
+ if (was) drop(was)
412
+ let h: Held = {
413
+ model,
414
+ dim: 0,
415
+ shared: true,
416
+ n: newest(db),
417
+ size: 0,
418
+ ids: new Int32Array(0),
419
+ scales: new Float32Array(0),
420
+ codes: new Int8Array(0),
421
+ slot: new Map(),
422
+ }
423
+ touch(h)
424
+ copies.set(db, h)
425
+ let [first] = db.query(select({
426
+ cols: [as(fn('length', col('code')), 'bytes')],
427
+ from: table(CODE),
428
+ limit: lit(1),
429
+ }))
430
+ h.dim = Number(first?.bytes ?? 0)
431
+ if (!grow(h, tally(db, CODE))) return refuse(db, h)
432
+ for (let after = 0;;) {
433
+ let rows = db.query(select({
434
+ cols: [col('owner'), col('code')],
435
+ from: table(CODE),
436
+ where: gt(col('owner'), val(after)),
437
+ order: [col('owner')],
438
+ limit: lit(PAGE),
439
+ }))
440
+ for (let r of rows) {
441
+ if (!kept(h, Number(r.owner), r.code as Uint8Array)) return refuse(db, h)
442
+ }
443
+ if (rows.length < PAGE) break
444
+ after = Number(rows[rows.length - 1].owner)
445
+ }
446
+ return h
447
+ }
448
+
449
+ // A copy of shared storage brought to the journal's newest change: each owner
450
+ // it names as its vector stands now, coded from its floats, or forgotten where
451
+ // it has none under the copy's model. Null where the copy has to load again:
452
+ // more changes than FOLLOW, or a first one past the next number, which says
453
+ // the sweep trimmed changes this copy had not read.
454
+ let follow = (db: Statements, h: Held): Held | null => {
455
+ let rows = db.query(select({
456
+ cols: [col('seq'), col('owner')],
457
+ from: table(JOURNAL),
458
+ where: gt(col('seq'), val(h.n)),
459
+ order: [col('seq')],
460
+ limit: lit(FOLLOW + 1),
461
+ }))
462
+ if (!rows.length) return h
463
+ if (rows.length > FOLLOW || Number(rows[0].seq) != h.n + 1) return null
464
+ let owners = [...new Set(rows.map((r) => Number(r.owner)))]
465
+ let now = new Map(
466
+ db.query(select({
467
+ cols: [col('owner'), col('model'), col('vec')],
468
+ from: table(TABLE),
469
+ where: among(col('owner'), owners.map((o) => val(o))),
470
+ })).map((r) => [Number(r.owner), r]),
471
+ )
472
+ for (let owner of owners) {
473
+ let r = now.get(owner)
474
+ if (r?.model != h.model) lose(h, owner)
475
+ else if (!keep(h, owner, r.vec as Uint8Array)) return refuse(db, h)
476
+ }
477
+ h.n = Number(rows[rows.length - 1].seq)
478
+ return h
479
+ }
480
+
481
+ // This process's copy of shared storage's vectors under `model`, brought up
482
+ // to date, or loaded where it has none, it is another model's, or it fell
483
+ // too far behind.
484
+ let followed = (db: Statements, model: string): Held | null => {
485
+ if (!journaled(db)) return null
486
+ let had = copies.get(db)
487
+ let h = had?.model == model ? follow(db, had) : null
488
+ if (over.has(db)) return null
489
+ return h ?? loadCodes(db, model)
490
+ }
491
+
492
+ /**
493
+ * This process's copy of `db`'s vectors under `model`, loaded if it has none
494
+ * or its copy is from an older build, and brought up to date; null where the
495
+ * vectors are not held: more than {@link HELD} of them ({@link SHARED} on
496
+ * shared storage), or a shared file whose codes or journal are not there yet.
497
+ */
498
+ export let hold = (db: Statements, model: string): Held | null => {
499
+ if (over.has(db)) return null
500
+ let h: Held | null
501
+ if (db.ownership == 'shared') h = followed(db, model)
502
+ else {
503
+ let had = copies.get(db)
504
+ h = had && had.model == model && had.n == current(db).n
505
+ ? had
506
+ : load(db, model)
507
+ }
508
+ if (!h) return null
509
+ touch(h)
510
+ return h
511
+ }
512
+
513
+ /**
514
+ * Fold what the dirty set names into this process's copy and clear the set:
515
+ * what a sweep pass wrote, from the process that wrote it (./sweep.ts
516
+ * `drain`). On shared storage, where each process's copy reads the journal
517
+ * itself, trim the journal to its newest {@link FOLLOW} changes instead.
518
+ */
519
+ export let absorb = (db: Statements): void => {
520
+ if (db.ownership == 'shared') return trim(db)
521
+ if (!owned(db)) return
522
+ let h = copies.get(db)
523
+ // Until a search holds a copy, there are no codes to refresh. Settle the
524
+ // dirty owners and invalidate any other copy without reading their vectors
525
+ // or the build number nobody here needs.
526
+ if (!h) {
527
+ if (tally(db, DIRTY)) advance(db)
528
+ return
529
+ }
530
+ let now = current(db).n
531
+ let set = dirty(db, h.model)
532
+ if (!set.size) return
533
+ if (h.n == now) {
534
+ for (let [owner, vec] of set) {
535
+ if (!vec) lose(h, owner)
536
+ else if (!keep(h, owner, vec)) {
537
+ drop(h)
538
+ copies.delete(db)
539
+ over.add(db)
540
+ break
541
+ }
542
+ }
543
+ }
544
+ let n = clear(db)
545
+ if (h.n == now) h.n = n
546
+ }
547
+
548
+ // The journal past its newest FOLLOW changes deleted: a copy further behind
549
+ // than that loads again.
550
+ let trim = (db: Statements): void => {
551
+ if (!journaled(db)) return
552
+ let cut = newest(db) - FOLLOW
553
+ if (cut <= 0) return
554
+ db.query({ t: 'delete', from: JOURNAL, where: not(gt(col('seq'), val(cut))) })
555
+ }
556
+
557
+ // The `m` best of the scored, best first: the highest score, and for equal
558
+ // ones the lower owner id, as the scan breaks a tie.
559
+ let top = (owners: Int32Array, sims: Float64Array, m: number): number[] => {
560
+ let worse = (a: number, b: number) =>
561
+ sims[a] < sims[b] || (sims[a] == sims[b] && owners[a] > owners[b])
562
+ let heap: number[] = []
563
+ let sift = (i: number) => {
564
+ for (;;) {
565
+ let c = 2 * i + 1
566
+ if (c >= heap.length) return
567
+ if (c + 1 < heap.length && worse(heap[c + 1], heap[c])) c++
568
+ if (!worse(heap[c], heap[i])) return
569
+ ;[heap[c], heap[i]] = [heap[i], heap[c]]
570
+ i = c
571
+ }
572
+ }
573
+ for (let k = 0; k < owners.length; k++) {
574
+ if (heap.length < m) {
575
+ heap.push(k)
576
+ for (let i = heap.length - 1; i;) {
577
+ let p = (i - 1) >> 1
578
+ if (!worse(heap[i], heap[p])) break
579
+ ;[heap[i], heap[p]] = [heap[p], heap[i]]
580
+ i = p
581
+ }
582
+ } else if (worse(heap[0], k)) {
583
+ heap[0] = k
584
+ sift(0)
585
+ }
586
+ }
587
+ return heap.sort((a, b) => worse(a, b) ? 1 : worse(b, a) ? -1 : 0)
588
+ }
589
+
590
+ // Which of `owners` stand as neighbours, with their eids and their vectors as
591
+ // stored: an entity that is not buried, whose vector is still in `model`'s
592
+ // space, and one the screen admits. Driven by the list, so each candidate
593
+ // costs one read of its entity, its vector and its tombstone.
594
+ let o = at('o'), j = at('j')
595
+ let standing = (
596
+ db: Statements,
597
+ model: string,
598
+ owners: number[],
599
+ within?: Raw,
600
+ ) =>
601
+ new Map(
602
+ db.query(select({
603
+ cols: [
604
+ as(o('id'), 'owner'),
605
+ as(o('eid'), 'eid'),
606
+ as(e('model'), 'model'),
607
+ as(e('vec'), 'vec'),
608
+ ],
609
+ from: from(each(owners), 'j'),
610
+ joins: [
611
+ join(table('entity', 'o'), eq(o('id'), j('value'))),
612
+ join(table(TABLE, 'e'), eq(e('owner'), o('id'))),
613
+ ],
614
+ where: and(
615
+ not(exists(select({
616
+ cols: [lit(1)],
617
+ from: table('tombstone', 't'),
618
+ where: eq(col('entity', 't'), o('id')),
619
+ }))),
620
+ ...(within ? [admitted(within, o('id'))] : []),
621
+ ),
622
+ })).flatMap((r) =>
623
+ r.model == model
624
+ ? [[Number(r.owner), { eid: String(r.eid), vec: r.vec as Uint8Array }]]
625
+ : []
626
+ ),
627
+ )
628
+
629
+ /**
630
+ * The `limit` nearest to `query` in a copy, most similar first: every held
631
+ * vector's codes scanned, what the dirty set names coded from its rows, the
632
+ * best tested against the graph a few at a time until {@link RESCORE} of
633
+ * them stand (reaching further while too few do), and those ranked by the
634
+ * exact cosine of their stored vectors.
635
+ */
636
+ export let ranked = (
637
+ db: Statements,
638
+ h: Held,
639
+ query: Float32Array,
640
+ opts: { limit: number; floor: number; without?: number; within?: Raw },
641
+ ): Near[] => {
642
+ // A shared copy folded its changes in as it was held.
643
+ let fresh = h.shared
644
+ ? new Map<number, Uint8Array | null>()
645
+ : dirty(db, h.model)
646
+ let all = query.length == h.dim
647
+ ? scores(query, h.codes, h.scales, h.size)
648
+ : new Float64Array(h.size)
649
+ let owners = new Int32Array(h.size + fresh.size)
650
+ let sims = new Float64Array(h.size + fresh.size)
651
+ let count = 0
652
+ let score = (owner: number, sim: number) => {
653
+ if (owner == opts.without) return
654
+ owners[count] = owner
655
+ sims[count++] = sim
656
+ }
657
+ for (let i = 0; i < h.size; i++) {
658
+ if (!fresh.has(h.ids[i])) score(h.ids[i], all[i])
659
+ }
660
+ let one = new Int8Array(h.dim), scale = new Float32Array(1)
661
+ for (let [owner, vec] of fresh) {
662
+ if (vec?.byteLength != h.dim * 4 || query.length != h.dim) continue
663
+ scale[0] = code(floats(vec), one)
664
+ score(owner, scores(query, one, scale, 1)[0])
665
+ }
666
+ owners = owners.subarray(0, count)
667
+ sims = sims.subarray(0, count)
668
+ // The ranking narrowed to what a screen admits, less what was tested.
669
+ let narrow = (admits: Set<number>, tested = new Set<number>()) => {
670
+ let rest = [...owners.keys()].filter((k) =>
671
+ !tested.has(k) && admits.has(owners[k])
672
+ )
673
+ ;[owners, sims] = [
674
+ Int32Array.from(rest, (k) => owners[k]),
675
+ Float64Array.from(rest, (k) => sims[k]),
676
+ ]
677
+ }
678
+ let want = Math.max(RESCORE, opts.limit)
679
+ let found: Near[] = []
680
+ let within = opts.within
681
+ // A screen that admits few is read whole first, and the ranking is only
682
+ // what it admits: asked of each candidate instead, it reads every row the
683
+ // candidate's test touches. A person's 7,228 earlier words among 316k
684
+ // vectors read whole in 87 ms, and asked of the 1,600 nearest took 0.6 s
685
+ // with the pages in memory and 7.9 s with them on disk.
686
+ let admits = within && few(db, within, owners.length)
687
+ if (admits) {
688
+ narrow(admits)
689
+ within = undefined
690
+ }
691
+ for (let seen = 0, reach = want; found.length < want;) {
692
+ let best = top(owners, sims, Math.min(reach, owners.length))
693
+ if (best.length == seen) break
694
+ let batch = best.slice(seen)
695
+ let rows = standing(db, h.model, batch.map((k) => owners[k]), within)
696
+ for (let k of batch) {
697
+ let row = rows.get(owners[k])
698
+ if (!row || found.length == want) continue
699
+ let similarity = cosine(query, floats(row.vec))
700
+ found.push({ entity: row.eid, owner: owners[k], similarity })
701
+ }
702
+ seen = best.length
703
+ reach *= 4
704
+ // A broad screen that admits few of the nearest costs a walk through most
705
+ // of the ranking. Once the rate so far says the walk would test more than
706
+ // half of it, the screen is read whole, and the rest of the ranking is
707
+ // what it admits, all of it below everything already tested.
708
+ let rate = Math.max(found.length, 1) / seen
709
+ if (within && found.length < want && want / rate > owners.length / 2) {
710
+ narrow(
711
+ new Set(
712
+ db.query(select({ cols: [col('id', 's')], from: from(within, 's') }))
713
+ .map((r) => Number(r.id)),
714
+ ),
715
+ new Set(best),
716
+ )
717
+ within = undefined
718
+ seen = 0
719
+ reach = want - found.length
720
+ }
721
+ }
722
+ return found
723
+ .filter((n) => n.similarity >= opts.floor)
724
+ .sort((a, b) => b.similarity - a.similarity || a.owner - b.owner)
725
+ .slice(0, opts.limit)
726
+ }