@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/sweep.ts ADDED
@@ -0,0 +1,446 @@
1
+ // Keeping the vectors in step with the text, off the write path.
2
+ //
3
+ // Embedding is slow and usually remote; a write is neither. So nothing here
4
+ // runs when a row changes: a trigger notes the entity (./owed.ts), and the
5
+ // sweep runs on its own schedule and settles what was noted — it deletes the
6
+ // vectors of entities that no longer have text, and re-embeds the ones whose
7
+ // text (or model) changed. What decides "changed" is the content hash stored
8
+ // beside each vector, so an entity queued without its text moving costs a
9
+ // read and no call to the embedder.
10
+ //
11
+ // The sweep is the only asynchronous thing in this package, because an embedder
12
+ // may be a network call. Everything a query touches stays synchronous.
13
+
14
+ import type { Eid } from 'jsr:@yaks/graph@0.2.36'
15
+ import { after, type Clock, system } from '@yaks/fp'
16
+ import {
17
+ and,
18
+ as,
19
+ at,
20
+ col,
21
+ descriptorHolds,
22
+ each,
23
+ eq,
24
+ exists,
25
+ fn,
26
+ from,
27
+ isNull,
28
+ type Join,
29
+ join,
30
+ lit,
31
+ not,
32
+ or,
33
+ select,
34
+ type Statements,
35
+ sub,
36
+ table,
37
+ val,
38
+ } from '@yaks/sql'
39
+ import { type Embedder, hash, Refused } from './embedder.js'
40
+ import { allowed, type Field, present, tablesIn, trimmed } from './fields.js'
41
+ import { TABLE } from './ddl.js'
42
+ import { type Due, due, left, owe, paid, watch } from './owed.js'
43
+ import { fill, filling } from './fill.js'
44
+ import { pack, unit } from './vector.js'
45
+ import { prepare } from './native.js'
46
+ import { absorb } from './held.js'
47
+ import { heal, put as code } from './coded.js'
48
+
49
+ /** How many queued entities one sweep takes by default. */
50
+ export let BATCH = 64
51
+
52
+ /**
53
+ * One entity's embeddable text: its integer owner id, its eid, the text of all
54
+ * its embedded fields joined together, and the hash of the vector already
55
+ * stored for it (null when it has none).
56
+ */
57
+ export type Source = {
58
+ owner: number
59
+ entity: Eid
60
+ text: string
61
+ had: string | null
62
+ }
63
+
64
+ // The pieces joined per entity, in field order: the rows arrive sorted by
65
+ // owner and field. Assembled here rather than with a SQL group_concat because
66
+ // the order matters and SQLite does not guarantee one for an aggregate, and
67
+ // because the pieces may come from several statements (./fields.ts `pieces`).
68
+ let assemble = (
69
+ rows: { owner: number; eid: Eid; had: string | null; t: string }[],
70
+ ): Source[] => {
71
+ let by = new Map<number, Source>()
72
+ for (let r of rows) {
73
+ let s = by.get(r.owner) ??
74
+ { owner: r.owner, entity: r.eid, text: '', had: r.had }
75
+ s.text = s.text ? `${s.text}\n${r.t}` : r.t
76
+ by.set(r.owner, s)
77
+ }
78
+ return [...by.values()]
79
+ }
80
+
81
+ /**
82
+ * Every entity that still exists and has text to embed — or those of `owners`
83
+ * that do — its text assembled and its stored hash beside it. Deleted entities
84
+ * are left out, so an entity stops being a neighbour as soon as it is deleted.
85
+ */
86
+ export let sources = (
87
+ db: Statements,
88
+ wanted: Field[],
89
+ owners?: number[],
90
+ ): Source[] => {
91
+ // The fields a table stands for. Their exclusions stay whole for the
92
+ // descriptor, which names what an entity wears without reading a table; a
93
+ // read of the tables themselves reads only those that stand.
94
+ let fields = present(db, wanted, false)
95
+ let names = tablesIn(db)
96
+ let o = at('o'), e = at('e')
97
+ // Shared exclusions are one property of the owner. Its descriptor answers
98
+ // all of them in one seek, rather than seeking every excluded table for
99
+ // every text field. Partial and older stores keep the physical-table check.
100
+ let excluded = fields[0]?.not ?? []
101
+ let classified = db.archetypes && excluded.length > 0 &&
102
+ fields.every((f) => JSON.stringify(f.not ?? []) == JSON.stringify(excluded))
103
+ let a = at('a')
104
+ let eligibility = classified
105
+ ? or(
106
+ and(
107
+ not(isNull(a('entity'))),
108
+ ...excluded.map((name) =>
109
+ not(
110
+ db.holds?.(a('tables'), name) ??
111
+ descriptorHolds(a('tables'), undefined, name),
112
+ )
113
+ ),
114
+ ),
115
+ and(
116
+ isNull(a('entity')),
117
+ ...allowed(trimmed(fields[0], names), col('entity', 'c')),
118
+ ),
119
+ )
120
+ : undefined
121
+ // One row supplies every field of a component. Resolving a body can seek
122
+ // another table, so read it once and drop blank pieces after it comes back.
123
+ let groups = new Map<string, { field: Field; ord: number }[]>()
124
+ fields.forEach((field, ord) => {
125
+ let key = JSON.stringify([field.comp, field.on, field.not ?? []])
126
+ groups.set(key, [...groups.get(key) ?? [], { field, ord }])
127
+ })
128
+ // A row already resolves its owner's descriptor for shared exclusions.
129
+ // Retain that complete shape for this read alone; it can prove a later
130
+ // component or scope absent without seeking its table. Owners for which no
131
+ // row supplied a descriptor still take the physical-table path.
132
+ let shapes = new Map<number, Set<string>>()
133
+ let rows = [...groups.values()].flatMap((group) => {
134
+ let { field } = group[0]
135
+ let selected = owners?.filter((owner) => {
136
+ let shape = shapes.get(owner)
137
+ return !shape ||
138
+ shape.has(field.comp) && (!field.on || shape.has(field.on))
139
+ })
140
+ if (selected && !selected.length) return []
141
+ let c = at('c'), w = at('w')
142
+ let values = group.map(({ field: f }, i) => {
143
+ let stored = c(f.prop)
144
+ return as(f.text ? f.text(stored) : stored, `t${i}`)
145
+ })
146
+ // Asked about some owners, the read starts from them: one seek of the
147
+ // component and one of the entity each. Left to its statistics, SQLite
148
+ // may scan every entity and test each against the list instead (it did
149
+ // after a bulk load, 79,000 rows a batch), so CROSS JOIN, whose order it
150
+ // keeps, spells the order out.
151
+ let how: Join['how'] = selected ? 'cross' : 'join'
152
+ return db.query(select({
153
+ cols: [
154
+ as(o('id'), 'owner'),
155
+ as(o('eid'), 'eid'),
156
+ as(e('hash'), 'had'),
157
+ ...classified && owners ? [as(a('tables'), 'shape')] : [],
158
+ ...values,
159
+ ],
160
+ from: selected
161
+ ? from(each([...new Set(selected)]), 'w')
162
+ : table(field.comp, 'c'),
163
+ joins: [
164
+ ...selected
165
+ ? [{
166
+ how,
167
+ src: table(field.comp, 'c'),
168
+ on: eq(c('entity'), w('value')),
169
+ }]
170
+ : [],
171
+ { how, src: table('entity', 'o'), on: eq(o('id'), c('entity')) },
172
+ ...field.on
173
+ ? [
174
+ join(
175
+ table(field.on, 'scope'),
176
+ eq(col('entity', 'scope'), c('entity')),
177
+ ),
178
+ ]
179
+ : [],
180
+ ...classified
181
+ ? [{
182
+ how: 'left' as const,
183
+ src: table('archetype', 'a'),
184
+ on: eq(a('entity'), o('archetype')),
185
+ }]
186
+ : [],
187
+ {
188
+ how: 'left',
189
+ src: table(TABLE, 'e'),
190
+ on: eq(e('owner'), c('entity')),
191
+ },
192
+ ],
193
+ where: and(
194
+ ...eligibility
195
+ ? [eligibility]
196
+ : allowed(trimmed(field, names), c('entity')),
197
+ not(exists(select({
198
+ cols: [lit(1)],
199
+ from: table('tombstone', 't'),
200
+ where: eq(col('entity', 't'), c('entity')),
201
+ }))),
202
+ ),
203
+ })).flatMap((r) => {
204
+ if (r.shape != null) {
205
+ let text = String(r.shape)
206
+ let shape = db.named ? db.named(text) : JSON.parse(text)
207
+ if (
208
+ Array.isArray(shape) && shape.every((name) => typeof name == 'string')
209
+ ) {
210
+ shapes.set(Number(r.owner), new Set(shape))
211
+ }
212
+ }
213
+ return group.flatMap(({ ord }, i) => {
214
+ let t = String(r[`t${i}`] ?? '')
215
+ // Match SQLite trim's explicit whitespace list, including preserving
216
+ // non-breaking spaces that are meaningful text under the same rule.
217
+ if (!/[^ \t\n\r\v\f]/.test(t)) return []
218
+ return [{
219
+ owner: Number(r.owner),
220
+ eid: String(r.eid),
221
+ had: r.had == null ? null : String(r.had),
222
+ ord,
223
+ t,
224
+ }]
225
+ })
226
+ })
227
+ })
228
+ return assemble(rows.sort((a, b) => a.owner - b.owner || a.ord - b.ord))
229
+ }
230
+
231
+ /**
232
+ * Store a source's vector, replacing whatever its owner had, and say whether
233
+ * it did. The vector was made from text read before the model was asked, and
234
+ * anything may run while it answers: the identity may be gone by then (the
235
+ * write that made it rolled back, the store was emptied) or its integer id
236
+ * may name another entity (an emptied store planted again). So the row is
237
+ * written only while the owner's id still names the source's entity.
238
+ */
239
+ export let put = (
240
+ db: Statements,
241
+ source: Pick<Source, 'owner' | 'entity' | 'text'>,
242
+ model: string,
243
+ vec: Float32Array,
244
+ ): boolean => {
245
+ let fresh = (k: string) => col(k, 'excluded')
246
+ let stored = unit(vec)
247
+ let wrote = db.query({
248
+ t: 'insert',
249
+ into: TABLE,
250
+ cols: ['owner', 'model', 'hash', 'vec'],
251
+ q: select({
252
+ cols: [
253
+ col('id'),
254
+ val(model),
255
+ val(hash(model, source.text)),
256
+ val(pack(stored)),
257
+ ],
258
+ from: table('entity'),
259
+ where: and(
260
+ eq(col('id'), val(source.owner)),
261
+ eq(col('eid'), val(source.entity)),
262
+ ),
263
+ }),
264
+ upsert: [{
265
+ on: [col('owner')],
266
+ set: {
267
+ model: fresh('model'),
268
+ hash: fresh('hash'),
269
+ vec: fresh('vec'),
270
+ at: fresh('at'),
271
+ },
272
+ }],
273
+ returning: [col('owner')],
274
+ }).length > 0
275
+ if (wrote) code(db, source.owner, stored)
276
+ return wrote
277
+ }
278
+
279
+ // Delete one entity's vector: it has no text to make one from, or its text
280
+ // was refused.
281
+ let drop = (db: Statements, owner: number): void =>
282
+ void db.query({
283
+ t: 'delete',
284
+ from: TABLE,
285
+ where: eq(col('owner'), val(owner)),
286
+ })
287
+
288
+ // Whether any stored vector was made by another model. Asked only once the
289
+ // queue is empty, so a model change queues everything once, not every pass.
290
+ // The smallest and largest model name, each read off the model index: a scan
291
+ // for one that differs would read every vector.
292
+ let moved = (db: Statements, model: string): boolean => {
293
+ let edge = (f: string) =>
294
+ sub(select({ cols: [fn(f, col('model'))], from: table(TABLE) }))
295
+ let [r] = db.query(
296
+ select({ cols: [as(edge('min'), 'lo'), as(edge('max'), 'hi')] }),
297
+ )
298
+ return r.lo != null && (r.lo != model || r.hi != model)
299
+ }
300
+
301
+ /**
302
+ * Owe every text its vector again when a stored one was made by another model,
303
+ * and say whether it did: what a host asks where its model may have changed (a
304
+ * deploy), since a sweep looks only once nothing else is owed.
305
+ */
306
+ export let remodel = (
307
+ db: Statements,
308
+ fields: Field[],
309
+ model: string,
310
+ ): boolean | Promise<boolean> => {
311
+ if (!moved(db, model)) return false
312
+ return after(owe(db, fields), () => true)
313
+ }
314
+
315
+ // The vectors for a batch of texts, asked for together; a text the embedder
316
+ // refused is its `Refused`. The embedder isolates each refusal when it
317
+ // batches requests. Anything else stops the sweep.
318
+ let embedAll = (
319
+ embedder: Embedder,
320
+ texts: string[],
321
+ ): Promise<(Float32Array | Refused)[]> => {
322
+ return Promise.all(texts.map(async (t) => {
323
+ try {
324
+ return await embedder.embed(t)
325
+ } catch (error) {
326
+ if (error instanceof Refused) return error
327
+ throw error
328
+ }
329
+ }))
330
+ }
331
+
332
+ /** What one sweep did. */
333
+ export type Swept = {
334
+ /** how many entities were (re)embedded */
335
+ fresh: number
336
+ /** how many are queued, plus one while reconciliation still has more */
337
+ left: number
338
+ /** the texts the embedder refused: their entities have no vector */
339
+ refused: { entity: Eid; error: Refused }[]
340
+ }
341
+
342
+ /**
343
+ * One pass: make the queue's triggers match the fields (./owed.ts `watch`),
344
+ * then settle the newest `limit` queued entities — embed what changed, delete
345
+ * the vectors of what has no text, and leave the rest as they are. An
346
+ * embedder that cannot be reached stops the pass: what it took stays queued
347
+ * for the next one, and the error reaches the caller rather than being
348
+ * swallowed into a quietly half-embedded corpus.
349
+ */
350
+ export let sweep = async (
351
+ db: Statements,
352
+ fields: Field[],
353
+ embedder: Embedder,
354
+ limit = BATCH,
355
+ queued?: Due[],
356
+ ): Promise<Swept> => {
357
+ let { model } = embedder
358
+ // A host may have just read the first batch to decide whether to start.
359
+ // Trigger changes can queue more text, so only reuse it while they stood.
360
+ let moved = await watch(db, fields)
361
+ if (!moved) await fill(db, present(db, fields))
362
+ let owed = !moved && queued?.length ? queued : due(db, limit)
363
+ if (!owed.length && !filling(db) && await remodel(db, fields, model)) {
364
+ owed = due(db, limit)
365
+ }
366
+ let by = new Map(
367
+ sources(db, fields, owed.map((d) => d.owner)).map((s) => [s.owner, s]),
368
+ )
369
+ let todo = owed.flatMap((d) => {
370
+ let s = by.get(d.owner)
371
+ return s && s.had != hash(model, s.text) ? [{ d, s }] : []
372
+ })
373
+ let got = await embedAll(embedder, todo.map(({ s }) => s.text))
374
+ let refused: Swept['refused'] = []
375
+ let fresh = 0
376
+ await db.atomic(() => {
377
+ let shape = got.find((v) => v instanceof Float32Array)
378
+ if (shape instanceof Float32Array) prepare(db, shape.length)
379
+ todo.forEach(({ d, s }, i) => {
380
+ let v = got[i]
381
+ if (v instanceof Refused) {
382
+ refused.push({ entity: s.entity, error: v })
383
+ drop(db, d.owner)
384
+ } else if (put(db, s, model, v)) fresh++
385
+ paid(db, d)
386
+ })
387
+ // What was queued and has nothing to embed: no text, deleted, or no longer
388
+ // wearing a field. What has text that did not change is settled as it is.
389
+ let taken = new Set(todo.map((t) => t.d))
390
+ for (let d of owed) {
391
+ if (taken.has(d)) continue
392
+ if (!by.has(d.owner)) drop(db, d.owner)
393
+ paid(db, d)
394
+ }
395
+ })
396
+ return { fresh, left: left(db), refused }
397
+ }
398
+
399
+ // A turn for the rest of the thread between batches of codes.
400
+ let pause = (time: Clock) => new Promise<void>((done) => time.after(0, done))
401
+
402
+ /** What one {@link drain} did: how many vectors it made, and the texts the
403
+ * embedder refused. */
404
+ export type Drained = { fresh: number; refused: Swept['refused'] }
405
+
406
+ /**
407
+ * Sweep pass after pass until nothing is owed, folding each pass into the
408
+ * vectors this process holds (./held.ts `absorb`), then code every vector that
409
+ * has no codes (./coded.ts), and stop. A
410
+ * host with nothing standing between requests (a Durable Object sleeps) runs
411
+ * this when a write asks; the service (./service.ts) runs it, then waits. An
412
+ * aborted `signal` stops it after the pass it is in. An embedder that cannot
413
+ * be reached throws, and what it took stays owed.
414
+ */
415
+ export let drain = async (
416
+ db: Statements,
417
+ fields: Field[],
418
+ embedder: Embedder,
419
+ opts: {
420
+ batch?: number
421
+ signal?: AbortSignal
422
+ /** The first batch already read by the host, with its queue generations. */
423
+ queued?: Due[]
424
+ /** The clock used to yield between bounded passes. */
425
+ clock?: Clock
426
+ } = {},
427
+ ): Promise<Drained> => {
428
+ let done: Drained = { fresh: 0, refused: [] }
429
+ let queued = opts.queued
430
+ let time = opts.clock ?? system
431
+ for (;;) {
432
+ let swept = await sweep(db, fields, embedder, opts.batch, queued)
433
+ queued = undefined
434
+ done.fresh += swept.fresh
435
+ done.refused.push(...swept.refused)
436
+ await db.atomic(() => prepare(db))
437
+ absorb(db)
438
+ if (opts.signal?.aborted) return done
439
+ if (!swept.left) {
440
+ while (await heal(db) && !opts.signal?.aborted) await pause(time)
441
+ return done
442
+ }
443
+ await pause(time)
444
+ if (opts.signal?.aborted) return done
445
+ }
446
+ }
package/tools.js ADDED
@@ -0,0 +1,57 @@
1
+ // Check embedding availability and the native scan used for vector search.
2
+ import { checked } from "@yaks/tools/check";
3
+ import { as, col, fn, select, statements, table } from "@yaks/sql";
4
+ import { TABLE } from "./ddl.js";
5
+ import { state } from "./native.js";
6
+ import { embedderOf } from "./options.js";
7
+ // When the newest vector was written, or null where there are none.
8
+ let newest = (db)=>db.query(select({
9
+ cols: [
10
+ as(fn('max', col('at')), 'at')
11
+ ],
12
+ from: table(TABLE)
13
+ }))[0]?.at ?? null;
14
+ /** The implementation behind the tool ./vocab.json declares, over this
15
+ * server's own database connection — which is why this export is a factory. */ export let runs = (host, options = {})=>{
16
+ let db = statements(host.storage);
17
+ return {
18
+ vector_check: async (call)=>{
19
+ let about = 'vector search reads the current canonical vectors';
20
+ let warn = (text)=>checked(call.entity.eid, about, [
21
+ {
22
+ level: 'warn',
23
+ text
24
+ }
25
+ ]);
26
+ // What this server is waiting for, if anything: a sweep that cannot embed
27
+ // is not behind on a build, it has not started at all.
28
+ let { waiting } = await embedderOf(options, host.graph, host.embedders);
29
+ if (waiting) {
30
+ return warn(`nothing is being embedded — ${waiting}. The sweep starts on its ` + `own once the config is there; nothing has to be restarted`);
31
+ }
32
+ let said;
33
+ try {
34
+ said = state(db);
35
+ } catch {
36
+ // No vector table: this server never composed `@yaks/embedding/graph`,
37
+ // so there is no index and no sweep. Not a failure, and not a pass
38
+ // either.
39
+ return warn('this host keeps no vector table, so there are no vectors to search — ' + '@yaks/embedding/graph is what raises one');
40
+ }
41
+ let last = newest(db);
42
+ if (!last) return checked(call.entity.eid, about, []);
43
+ // Where no index serves, a database only this process has open holds its
44
+ // vectors in memory (./held.ts): no search reads them.
45
+ let held = db.ownership == 'exclusive' && (!said.installed || !said.model);
46
+ if (held) return checked(call.entity.eid, about, []);
47
+ if (!said.installed) {
48
+ return warn('sqlite-vector is not installed on this database, so every search ' + 'reads every stored vector — back the file up, then installNative() ' + 'once');
49
+ }
50
+ if (!said.model) {
51
+ return warn("two models' vectors share the table while the sweep re-embeds; " + 'native scans wait for one model, and JavaScript scores each ' + 'matching vector until then');
52
+ }
53
+ return checked(call.entity.eid, about, []);
54
+ }
55
+ };
56
+ };
57
+ //# sourceMappingURL=tools.js.map
package/tools.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sources":["./tools.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAG3E,SAAS,OAAO,iCAAsC;AACtD,SACE,EAAE,EACF,GAAG,EACH,EAAE,EACF,MAAM,EAEN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E;QACnB,OAAO,KACL,sEACE,wEACA;MAEN;MACA,IAAI,CAAC,KAAK,KAAK,EAAE;QACf,OAAO,KACL,oEACE,iEACA;MAEN;MACA,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE;IAC3C;EACF;AACF,EAAC"}
package/tools.ts ADDED
@@ -0,0 +1,88 @@
1
+ // Check embedding availability and the native scan used for vector search.
2
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
3
+ import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
4
+ import { checked } from '@yaks/tools/check'
5
+ import {
6
+ as,
7
+ col,
8
+ fn,
9
+ select,
10
+ type Statements,
11
+ statements,
12
+ table,
13
+ } from '@yaks/sql'
14
+ import { TABLE } from './ddl.js'
15
+ import { state } from './native.js'
16
+ import { embedderOf, type Lent, type Options } from './options.js'
17
+
18
+ export type { Options }
19
+
20
+ // When the newest vector was written, or null where there are none.
21
+ let newest = (db: Statements): string | null =>
22
+ (db.query(select({
23
+ cols: [as(fn('max', col('at')), 'at')],
24
+ from: table(TABLE),
25
+ }))[0]?.at as string | null) ?? null
26
+
27
+ /** The implementation behind the tool ./vocab.json declares, over this
28
+ * server's own database connection — which is why this export is a factory. */
29
+ export let runs = (
30
+ host: {
31
+ storage: { statements?: Statements }
32
+ graph: Pick<Graph, 'get'>
33
+ embedders?: Lent
34
+ },
35
+ options: Options = {},
36
+ ): Runs => {
37
+ let db = statements(host.storage)
38
+ return {
39
+ vector_check: async (call) => {
40
+ let about = 'vector search reads the current canonical vectors'
41
+ let warn = (text: string) =>
42
+ checked(call.entity.eid, about, [{ level: 'warn', text }])
43
+ // What this server is waiting for, if anything: a sweep that cannot embed
44
+ // is not behind on a build, it has not started at all.
45
+ let { waiting } = await embedderOf(options, host.graph, host.embedders)
46
+ if (waiting) {
47
+ return warn(
48
+ `nothing is being embedded — ${waiting}. The sweep starts on its ` +
49
+ `own once the config is there; nothing has to be restarted`,
50
+ )
51
+ }
52
+ let said
53
+ try {
54
+ said = state(db)
55
+ } catch {
56
+ // No vector table: this server never composed `@yaks/embedding/graph`,
57
+ // so there is no index and no sweep. Not a failure, and not a pass
58
+ // either.
59
+ return warn(
60
+ 'this host keeps no vector table, so there are no vectors to search — ' +
61
+ '@yaks/embedding/graph is what raises one',
62
+ )
63
+ }
64
+ let last = newest(db)
65
+ if (!last) return checked(call.entity.eid, about, [])
66
+ // Where no index serves, a database only this process has open holds its
67
+ // vectors in memory (./held.ts): no search reads them.
68
+ let held = db.ownership == 'exclusive' &&
69
+ (!said.installed || !said.model)
70
+ if (held) return checked(call.entity.eid, about, [])
71
+ if (!said.installed) {
72
+ return warn(
73
+ 'sqlite-vector is not installed on this database, so every search ' +
74
+ 'reads every stored vector — back the file up, then installNative() ' +
75
+ 'once',
76
+ )
77
+ }
78
+ if (!said.model) {
79
+ return warn(
80
+ "two models' vectors share the table while the sweep re-embeds; " +
81
+ 'native scans wait for one model, and JavaScript scores each ' +
82
+ 'matching vector until then',
83
+ )
84
+ }
85
+ return checked(call.entity.eid, about, [])
86
+ },
87
+ }
88
+ }
package/vector.js ADDED
@@ -0,0 +1,78 @@
1
+ // The vectors themselves: how one is stored, read back, and compared.
2
+ //
3
+ // A vector is a `Float32Array`. The store holds its raw bytes as a blob, so the
4
+ // dimension is the blob's byte length over four and no column has to carry it —
5
+ // and a vector from a different model, with a different dimension, is refused by
6
+ // arithmetic rather than by bookkeeping.
7
+ //
8
+ // Comparison is cosine similarity: 1 identical, 0 unrelated, negative opposed.
9
+ // For unit-length vectors that is just the dot product, and everything stored
10
+ // here is normalized on the way in, so ranking a corpus is one multiply-add
11
+ // pass per vector.
12
+ /** A vector's raw bytes, for storing it as a blob. */ export let pack = (v)=>new Uint8Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength));
13
+ /**
14
+ * A vector read back from its blob. The copy is deliberate: a `Float32Array`
15
+ * needs a 4-byte-aligned buffer, and bytes handed back by a driver are aligned
16
+ * only by luck.
17
+ */ export let unpack = (bytes)=>new Float32Array(bytes.slice().buffer);
18
+ /**
19
+ * A vector read back from its blob without a copy where it can be: a view of
20
+ * the bytes where they are 4-byte aligned, {@link unpack}'s copy where not.
21
+ * The view shares the bytes, so it is for reading.
22
+ */ export let floats = (bytes)=>bytes.byteOffset % 4 == 0 ? new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4) : unpack(bytes);
23
+ /**
24
+ * The same direction at length 1. A zero vector has no direction, so it comes
25
+ * back unchanged — {@link cosine} answers 0 against it, which is what "unrelated
26
+ * to everything" should read as.
27
+ */ export let unit = (v)=>{
28
+ let sum = 0;
29
+ for (let x of v)sum += x * x;
30
+ let len = Math.sqrt(sum);
31
+ if (!len) return v;
32
+ let out = new Float32Array(v.length);
33
+ for(let i = 0; i < v.length; i++)out[i] = v[i] / len;
34
+ return out;
35
+ };
36
+ /**
37
+ * Cosine similarity, 1 for the same direction and 0 for unrelated. Two vectors
38
+ * of different lengths are from different spaces and score 0 — a model change
39
+ * makes every old vector unrelated rather than subtly wrong.
40
+ */ export let cosine = (a, b)=>{
41
+ if (a.length != b.length) return 0;
42
+ let dot = 0, la = 0, lb = 0;
43
+ for(let i = 0; i < a.length; i++){
44
+ dot += a[i] * b[i];
45
+ la += a[i] * a[i];
46
+ lb += b[i] * b[i];
47
+ }
48
+ let len = Math.sqrt(la) * Math.sqrt(lb);
49
+ return len ? dot / len : 0;
50
+ };
51
+ /**
52
+ * Code `v` into `codes` from `at`: each coordinate over the largest, rounded
53
+ * to one of 255 steps from -127 to 127. Returns the scale that turns the
54
+ * codes' dot product with a query back into cosine times the query's length;
55
+ * 0 for a vector with no direction. The codes alone keep the direction, so
56
+ * their cosine is the vector's, give or take a step.
57
+ */ export let code = (v, codes, at = 0)=>{
58
+ let max = 0, sum = 0, dim = v.length;
59
+ for(let j = 0; j < dim; j++){
60
+ let x = v[j];
61
+ sum += x * x;
62
+ if (x > max) max = x;
63
+ else if (-x > max) max = -x;
64
+ }
65
+ if (!max) {
66
+ codes.fill(0, at, at + dim);
67
+ return 0;
68
+ }
69
+ let k = 127 / max;
70
+ for(let j = 0; j < dim; j++)codes[at + j] = Math.round(v[j] * k);
71
+ return max / 127 / Math.sqrt(sum);
72
+ };
73
+ /** A vector's int8 codes as a blob, the shape a native int8 scan reads. */ export let coded = (v)=>{
74
+ let codes = new Int8Array(v.length);
75
+ code(v, codes);
76
+ return new Uint8Array(codes.buffer);
77
+ };
78
+ //# sourceMappingURL=vector.js.map
package/vector.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vector.js","sources":["./vector.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,gFAAgF;AAChF,gFAAgF;AAChF,iFAAiF;AACjF,yCAAyC;AACzC,EAAE;AACF,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,mBAAmB;AAEnB,oDAAoD,GACpD,OAAO,IAAI,OAAO,CAAC,IACjB,IAAI,WAAW,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,EAAE,UAAU,GAAG,EAAE,UAAU,GAAE;AAE3E;;;;CAIC,GACD,OAAO,IAAI,SAAS,CAAC,QACnB,IAAI,aAAa,MAAM,KAAK,GAAG,MAAM,EAAC;AAExC;;;;CAIC,GACD,OAAO,IAAI,SAAS,CAAC,QACnB,MAAM,UAAU,GAAG,KAAK,IACpB,IAAI,aAAa,MAAM,MAAM,EAAE,MAAM,UAAU,EAAE,MAAM,UAAU,GAAG,KACpE,OAAO,OAAM;AAEnB;;;;CAIC,GACD,OAAO,IAAI,OAAO,CAAC;EACjB,IAAI,MAAM;EACV,KAAK,IAAI,KAAK,EAAG,OAAO,IAAI;EAC5B,IAAI,MAAM,KAAK,IAAI,CAAC;EACpB,IAAI,CAAC,KAAK,OAAO;EACjB,IAAI,MAAM,IAAI,aAAa,EAAE,MAAM;EACnC,IAAK,IAAI,IAAI,GAAG,IAAI,EAAE,MAAM,EAAE,IAAK,GAAG,CAAC,EAAE,G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