@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/owed.js ADDED
@@ -0,0 +1,287 @@
1
+ // What is owed a look: the queue of entities whose text may have moved since
2
+ // their vector was made, filled by triggers and drained by the sweep.
3
+ //
4
+ // A corpus of transcripts is too big to reconcile whole on every pass — reading
5
+ // and hashing every text to find the few that changed costs minutes, where the
6
+ // changes themselves are a handful of rows. So the database says what moved.
7
+ // A trigger on each embedded component notes the entity a write touched, in
8
+ // the same statement as the write, whichever process made it: this server, a
9
+ // CLI, a restore. The sweep reads the queue newest first, looks at those
10
+ // entities only, and settles each one.
11
+ //
12
+ // A queued entity carries a count, bumped by every write that queues it
13
+ // again. The sweep settles an entity only while the count is the one it read,
14
+ // so a write that lands while a model is answering keeps its entity queued
15
+ // for the next pass instead of being settled by a pass that never saw it.
16
+ //
17
+ // The triggers are made from the fields, so they change when the fields do.
18
+ // {@link watch} makes the database's triggers match the fields. A trigger that
19
+ // was missing or said something else cannot have noted what happened to its
20
+ // table, so the entities in that table are queued — a new field's component,
21
+ // one a field left — and nothing else: a component whose trigger stood saw
22
+ // every write. A new database, or a vector table dropped and made again,
23
+ // moves the triggers on the vectors and the tombstones, and queues everything.
24
+ import { and, as, col, count, desc, eq, exists, lit, not, op, render, select, table, val } from "@yaks/sql";
25
+ import { after } from "@yaks/fp";
26
+ import { present } from "./fields.js";
27
+ import { filled, filling, queue, schedule } from "./fill.js";
28
+ import { OWED, TABLE } from "./ddl.js";
29
+ let one = (e)=>queue({
30
+ rows: [
31
+ [
32
+ e,
33
+ lit(1)
34
+ ]
35
+ ]
36
+ });
37
+ // Whether `table` has a row for this entity: a component table keys it by
38
+ // `entity`, a vector table (./ddl.ts) by `owner`.
39
+ let wears = (name, e)=>exists(select({
40
+ cols: [
41
+ lit(1)
42
+ ],
43
+ from: table(name),
44
+ where: eq(col(name == TABLE || name == OWED ? 'owner' : 'entity', name), e)
45
+ }));
46
+ let NEW = col('entity', 'new');
47
+ let OLD = col('entity', 'old');
48
+ let GONE = col('owner', 'old');
49
+ let trigger = (name, event, on, e, when, of)=>({
50
+ t: 'create trigger',
51
+ name: `${OWED}_${name}`,
52
+ timing: 'after',
53
+ event,
54
+ of,
55
+ on,
56
+ when,
57
+ body: [
58
+ one(e)
59
+ ]
60
+ });
61
+ /**
62
+ * The triggers that keep the queue: for each component a field lives on, its
63
+ * rows arriving, changing and leaving; for text an entity is found by through
64
+ * another component (`on`), that component arriving and leaving too, and the
65
+ * text counting only while it does; exclusions arriving and leaving; an entity
66
+ * with a vector being deleted or restored; and a vector deleted by anything
67
+ * but the sweep, which is owed back.
68
+ */ export let triggers = (fields)=>{
69
+ let groups = new Map();
70
+ for (let f of fields){
71
+ let key = f.on ? `${f.comp}_${f.on}` : f.comp;
72
+ groups.set(key, [
73
+ ...groups.get(key) ?? [],
74
+ f
75
+ ]);
76
+ }
77
+ return [
78
+ ...[
79
+ ...groups
80
+ ].flatMap(([key, [f, ...rest]])=>{
81
+ let props = [
82
+ f,
83
+ ...rest
84
+ ].map((g)=>g.prop);
85
+ let scoped = (e)=>f.on ? wears(f.on, e) : undefined;
86
+ return [
87
+ trigger(`${key}_insert`, 'insert', f.comp, NEW, scoped(NEW)),
88
+ trigger(`${key}_update`, 'update', f.comp, NEW, scoped(NEW), props),
89
+ trigger(`${key}_delete`, 'delete', f.comp, OLD, scoped(OLD)),
90
+ ...f.on ? [
91
+ trigger(`${key}_join`, 'insert', f.on, NEW, wears(f.comp, NEW)),
92
+ trigger(`${key}_leave`, 'delete', f.on, OLD)
93
+ ] : []
94
+ ];
95
+ }),
96
+ ...[
97
+ ...new Set(fields.flatMap((f)=>f.not ?? []))
98
+ ].flatMap((name)=>[
99
+ trigger(`exclude:${name}_insert`, 'insert', name, NEW, wears(TABLE, NEW)),
100
+ // One per group the exclusion hides, so each reads only its own tables
101
+ // and stays as it was made when another field's table is made later.
102
+ ...[
103
+ ...groups
104
+ ].filter(([, g])=>g.some((f)=>f.not?.includes(name))).map(([key, [f]])=>trigger(`exclude:${name}_${key}_delete`, 'delete', name, OLD, and(wears(f.comp, OLD), ...f.on ? [
105
+ wears(f.on, OLD)
106
+ ] : [])))
107
+ ]),
108
+ ...fields.length ? [
109
+ trigger('tombstone_insert', 'insert', 'tombstone', NEW, wears(TABLE, NEW)),
110
+ trigger('tombstone_delete', 'delete', 'tombstone', OLD),
111
+ trigger('vector_delete', 'delete', TABLE, GONE, not(wears(OWED, GONE)))
112
+ ] : []
113
+ ];
114
+ };
115
+ let watching = new WeakMap();
116
+ /**
117
+ * Whether writing these bundles can have queued an entity: whether one names
118
+ * a component a trigger watches ({@link triggers}), or deletes or restores
119
+ * its entity. A host that drains the queue after a write asks the queue only
120
+ * then.
121
+ *
122
+ * ```ts
123
+ * import { queues } from '@yaks/embedding'
124
+ *
125
+ * let fields = [{ comp: 'doc', prop: 'body' }]
126
+ * queues(fields, [{ entity: { eid: 'a' }, doc: { body: 'hi' } }]) // true
127
+ * queues(fields, [{ entity: { eid: 'a' }, $delete: true }]) // true
128
+ * queues(fields, [{ entity: { eid: 'a' }, place: { x: 1 } }]) // false
129
+ * ```
130
+ */ export let queues = (fields, bundles)=>{
131
+ let tables = watching.get(fields);
132
+ if (!tables) {
133
+ watching.set(fields, tables = new Set(triggers(fields).map((t)=>t.on)));
134
+ }
135
+ return bundles.some((b)=>tables.has('tombstone') && b.$delete === true || Object.keys(b).some((name)=>tables.has(name)));
136
+ };
137
+ // A trigger's definition from its name onward. SQLite keeps the statement it
138
+ // was given, so this is what two definitions compare by.
139
+ let body = (sql, name)=>sql.slice(sql.indexOf(`"${name}"`)).trim();
140
+ let watched = new WeakMap();
141
+ // The triggers that are about every vector, not one component's rows.
142
+ let EVERY = new Set([
143
+ TABLE,
144
+ 'tombstone'
145
+ ]);
146
+ /**
147
+ * What {@link watch} does about the triggers a database holds, given the
148
+ * ones the fields want. A trigger that stands as wanted owes nothing: it saw
149
+ * every write to its table. One made, dropped or changed missed or misread
150
+ * its table's writes, so the entities in that table are owed a look, and no
151
+ * others.
152
+ *
153
+ * ```ts
154
+ * import { equal } from '@yaks/testing'
155
+ * import { render } from '@yaks/sql'
156
+ * let book = { comp: 'book', prop: 'title' }
157
+ * let want = triggers([book])
158
+ * let held = want.map((t) => ({ name: t.name, on: t.on, sql: render(t).sql }))
159
+ * equal(moves(held, want).owed, new Set())
160
+ * let more = triggers([book, { comp: 'review', prop: 'prose' }])
161
+ * equal(moves(held, more).owed, new Set(['review']))
162
+ * equal(moves([], want).owed, true)
163
+ * ```
164
+ */ export let moves = (have, want, write = (s)=>render(s))=>{
165
+ let wanted = new Map(want.map((t)=>[
166
+ t.name,
167
+ t
168
+ ]));
169
+ let drop = [];
170
+ let owed = new Set();
171
+ let touched = (on)=>{
172
+ if (owed === true) return;
173
+ if (EVERY.has(on)) owed = true;
174
+ else owed.add(on);
175
+ };
176
+ for (let r of have){
177
+ let now = wanted.get(r.name);
178
+ if (now && body(r.sql, r.name) == body(write(now).sql, r.name)) {
179
+ wanted.delete(r.name);
180
+ continue;
181
+ }
182
+ drop.push(r.name);
183
+ touched(r.on);
184
+ }
185
+ for (let t of wanted.values())touched(t.on);
186
+ return {
187
+ drop,
188
+ make: [
189
+ ...wanted.values()
190
+ ],
191
+ owed
192
+ };
193
+ };
194
+ /**
195
+ * Make the database's queue triggers the ones {@link triggers} says, and
196
+ * queue the entities whose writes a missing or changed trigger may have
197
+ * missed ({@link moves}). Returns whether it changed anything. A second call
198
+ * with the same fields and schema reads and writes nothing.
199
+ */ export let watch = (db, wanted)=>{
200
+ let version = db.revision('schema');
201
+ let fields = present(db, wanted);
202
+ let definitions = triggers(fields);
203
+ let key = JSON.stringify(definitions);
204
+ let kept = watched.get(db);
205
+ if (kept?.version == version && kept.fields == key) return false;
206
+ return after(db.atomic(()=>{
207
+ // Entry can wait for another host, whose transaction may change the schema.
208
+ fields = present(db, wanted);
209
+ definitions = triggers(fields);
210
+ key = JSON.stringify(definitions);
211
+ let have = db.query(select({
212
+ cols: [
213
+ col('name'),
214
+ as(col('tbl_name'), 'on'),
215
+ col('sql')
216
+ ],
217
+ from: table('sqlite_master'),
218
+ where: and(eq(col('type'), val('trigger')), op('glob', col('name'), val(`${OWED}_*`)))
219
+ })).map((r)=>({
220
+ name: String(r.name),
221
+ on: db.tableName?.(String(r.on)) ?? String(r.on),
222
+ sql: String(r.sql)
223
+ }));
224
+ let { drop, make, owed } = moves(have, definitions, db.render);
225
+ if (!drop.length && !make.length) return false;
226
+ for (let name of drop){
227
+ db.query({
228
+ t: 'drop',
229
+ kind: 'trigger',
230
+ name,
231
+ ifExists: true
232
+ });
233
+ }
234
+ for (let t of make)db.query(t);
235
+ if (owed === true) scheduled(db, fields);
236
+ else if (owed.size) scheduled(db, fields, owed);
237
+ return true;
238
+ }), (changed)=>{
239
+ watched.set(db, {
240
+ version: db.revision('schema'),
241
+ fields: key
242
+ });
243
+ return changed;
244
+ });
245
+ };
246
+ /** Schedule every entity wearing a field or holding a vector — or, given
247
+ * `tables`, their owners only. Queue a bounded first window now; the sweep
248
+ * resumes the durable cursors for the rest. */ export let owe = (db, wanted, tables)=>{
249
+ let fields = present(db, wanted);
250
+ return db.atomic(()=>scheduled(db, fields, tables));
251
+ };
252
+ // {@link owe} inside a unit the caller already holds.
253
+ let scheduled = (db, fields, tables)=>{
254
+ schedule(db, tables ?? [
255
+ ...fields.map((f)=>f.comp),
256
+ TABLE
257
+ ]);
258
+ filled(db, fields);
259
+ };
260
+ /** The newest `limit` queued entities, newest first: what was just said is
261
+ * what someone is about to look for. */ export let due = (db, limit)=>db.query(select({
262
+ cols: [
263
+ col('owner'),
264
+ col('n')
265
+ ],
266
+ from: table(OWED),
267
+ order: [
268
+ desc(col('owner'))
269
+ ],
270
+ limit: val(limit)
271
+ })).map((r)=>({
272
+ owner: Number(r.owner),
273
+ n: Number(r.n)
274
+ }));
275
+ /** Settle a queued entity, unless a write queued it again since it was read. */ export let paid = (db, d)=>void db.query({
276
+ t: 'delete',
277
+ from: OWED,
278
+ where: and(eq(col('owner'), val(d.owner)), eq(col('n'), val(d.n)))
279
+ });
280
+ /** How many entities are queued, plus one while reconciliation has more. */ export let left = (db)=>Number(db.query(select({
281
+ cols: [
282
+ as(count(), 'n')
283
+ ],
284
+ from: table(OWED)
285
+ }))[0].n) + Number(filling(db));
286
+ /** Whether queued owners or a reconciliation cursor still need a sweep. */ export let owing = (db)=>due(db, 1).length > 0 || filling(db);
287
+ //# sourceMappingURL=owed.js.map
package/owed.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owed.js","sources":["./owed.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,sEAAsE;AACtE,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,4EAA4E;AAC5E,6EAA6E;AAC7E,yEAAyE;AACzE,uCAAuC;AACvC,EAAE;AACF,wEAAwE;AACxE,8EAA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,yEAAyE;AACzE,+EAA+E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AAE,CAAC,GAAE;AAE5D,8EAA8E,GAC9E,OAAO,IAAI,OAAO,CAAC,IAAgB,IACjC,KAAK,GAAG,KAAK,CAAC;IACZ,GAAG;IACH,MAAM;IACN,OAAO,IAAI,GAAG,IAAI,UAAU,IAAI,EAAE,KAAK,IAAI,GAAG,IAAI,MAAM,IAAI,EAAE,CAAC;EACjE,GAAE;AAEJ,0EAA0E,GAC1E,OAAO,IAAI,OAAO,CAAC,KACjB,OACE,GAAG,KAAK,CAAC,OAAO;IAAE,MAAM;MAAC,GAAG,SAAS;KAAK;IAAE,MAAM,MAAM;EAAM,GAAG,CAAC,EAAE,CAAC,CAAC,IAExE,OAAO,QAAQ,KAAI;AAErB,yEAAyE,GACzE,OAAO,IAAI,QAAQ,CAAC,KAClB,IAAI,IAAI,GAAG,MAAM,GAAG,KAAK,QAAQ,IAAG"}
package/owed.ts ADDED
@@ -0,0 +1,346 @@
1
+ // What is owed a look: the queue of entities whose text may have moved since
2
+ // their vector was made, filled by triggers and drained by the sweep.
3
+ //
4
+ // A corpus of transcripts is too big to reconcile whole on every pass — reading
5
+ // and hashing every text to find the few that changed costs minutes, where the
6
+ // changes themselves are a handful of rows. So the database says what moved.
7
+ // A trigger on each embedded component notes the entity a write touched, in
8
+ // the same statement as the write, whichever process made it: this server, a
9
+ // CLI, a restore. The sweep reads the queue newest first, looks at those
10
+ // entities only, and settles each one.
11
+ //
12
+ // A queued entity carries a count, bumped by every write that queues it
13
+ // again. The sweep settles an entity only while the count is the one it read,
14
+ // so a write that lands while a model is answering keeps its entity queued
15
+ // for the next pass instead of being settled by a pass that never saw it.
16
+ //
17
+ // The triggers are made from the fields, so they change when the fields do.
18
+ // {@link watch} makes the database's triggers match the fields. A trigger that
19
+ // was missing or said something else cannot have noted what happened to its
20
+ // table, so the entities in that table are queued — a new field's component,
21
+ // one a field left — and nothing else: a component whose trigger stood saw
22
+ // every write. A new database, or a vector table dropped and made again,
23
+ // moves the triggers on the vectors and the tombstones, and queues everything.
24
+
25
+ import {
26
+ and,
27
+ as,
28
+ col,
29
+ count,
30
+ type CreateTrigger,
31
+ desc,
32
+ eq,
33
+ exists,
34
+ type Expr,
35
+ type Insert,
36
+ lit,
37
+ not,
38
+ op,
39
+ render,
40
+ select,
41
+ table,
42
+ val,
43
+ } from '@yaks/sql'
44
+ import type { Statements } from '@yaks/sql'
45
+ import { after } from '@yaks/fp'
46
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
47
+ import { type Field, present } from './fields.js'
48
+ import { filled, filling, queue, schedule } from './fill.js'
49
+ import { OWED, TABLE } from './ddl.js'
50
+
51
+ let one = (e: Expr): Insert => queue({ rows: [[e, lit(1)]] })
52
+
53
+ // Whether `table` has a row for this entity: a component table keys it by
54
+ // `entity`, a vector table (./ddl.ts) by `owner`.
55
+ let wears = (name: string, e: Expr): Expr =>
56
+ exists(select({
57
+ cols: [lit(1)],
58
+ from: table(name),
59
+ where: eq(col(name == TABLE || name == OWED ? 'owner' : 'entity', name), e),
60
+ }))
61
+
62
+ let NEW = col('entity', 'new')
63
+ let OLD = col('entity', 'old')
64
+ let GONE = col('owner', 'old')
65
+
66
+ let trigger = (
67
+ name: string,
68
+ event: CreateTrigger['event'],
69
+ on: string,
70
+ e: Expr,
71
+ when?: Expr,
72
+ of?: string[],
73
+ ): CreateTrigger => ({
74
+ t: 'create trigger',
75
+ name: `${OWED}_${name}`,
76
+ timing: 'after',
77
+ event,
78
+ of,
79
+ on,
80
+ when,
81
+ body: [one(e)],
82
+ })
83
+
84
+ /**
85
+ * The triggers that keep the queue: for each component a field lives on, its
86
+ * rows arriving, changing and leaving; for text an entity is found by through
87
+ * another component (`on`), that component arriving and leaving too, and the
88
+ * text counting only while it does; exclusions arriving and leaving; an entity
89
+ * with a vector being deleted or restored; and a vector deleted by anything
90
+ * but the sweep, which is owed back.
91
+ */
92
+ export let triggers = (fields: Field[]): CreateTrigger[] => {
93
+ let groups = new Map<string, Field[]>()
94
+ for (let f of fields) {
95
+ let key = f.on ? `${f.comp}_${f.on}` : f.comp
96
+ groups.set(key, [...groups.get(key) ?? [], f])
97
+ }
98
+ return [
99
+ ...[...groups].flatMap(([key, [f, ...rest]]) => {
100
+ let props = [f, ...rest].map((g) => g.prop)
101
+ let scoped = (e: Expr) => f.on ? wears(f.on, e) : undefined
102
+ return [
103
+ trigger(`${key}_insert`, 'insert', f.comp, NEW, scoped(NEW)),
104
+ trigger(`${key}_update`, 'update', f.comp, NEW, scoped(NEW), props),
105
+ trigger(`${key}_delete`, 'delete', f.comp, OLD, scoped(OLD)),
106
+ ...f.on
107
+ ? [
108
+ trigger(`${key}_join`, 'insert', f.on, NEW, wears(f.comp, NEW)),
109
+ trigger(`${key}_leave`, 'delete', f.on, OLD),
110
+ ]
111
+ : [],
112
+ ]
113
+ }),
114
+ ...[...new Set(fields.flatMap((f) => f.not ?? []))].flatMap((name) => [
115
+ trigger(`exclude:${name}_insert`, 'insert', name, NEW, wears(TABLE, NEW)),
116
+ // One per group the exclusion hides, so each reads only its own tables
117
+ // and stays as it was made when another field's table is made later.
118
+ ...[...groups].filter(([, g]) => g.some((f) => f.not?.includes(name)))
119
+ .map(([key, [f]]) =>
120
+ trigger(
121
+ `exclude:${name}_${key}_delete`,
122
+ 'delete',
123
+ name,
124
+ OLD,
125
+ and(wears(f.comp, OLD), ...f.on ? [wears(f.on, OLD)] : []),
126
+ )
127
+ ),
128
+ ]),
129
+ ...fields.length
130
+ ? [
131
+ trigger(
132
+ 'tombstone_insert',
133
+ 'insert',
134
+ 'tombstone',
135
+ NEW,
136
+ wears(TABLE, NEW),
137
+ ),
138
+ trigger('tombstone_delete', 'delete', 'tombstone', OLD),
139
+ trigger('vector_delete', 'delete', TABLE, GONE, not(wears(OWED, GONE))),
140
+ ]
141
+ : [],
142
+ ]
143
+ }
144
+
145
+ let watching = new WeakMap<Field[], Set<string>>()
146
+
147
+ /**
148
+ * Whether writing these bundles can have queued an entity: whether one names
149
+ * a component a trigger watches ({@link triggers}), or deletes or restores
150
+ * its entity. A host that drains the queue after a write asks the queue only
151
+ * then.
152
+ *
153
+ * ```ts
154
+ * import { queues } from '@yaks/embedding'
155
+ *
156
+ * let fields = [{ comp: 'doc', prop: 'body' }]
157
+ * queues(fields, [{ entity: { eid: 'a' }, doc: { body: 'hi' } }]) // true
158
+ * queues(fields, [{ entity: { eid: 'a' }, $delete: true }]) // true
159
+ * queues(fields, [{ entity: { eid: 'a' }, place: { x: 1 } }]) // false
160
+ * ```
161
+ */
162
+ export let queues = (fields: Field[], bundles: Bundle[]): boolean => {
163
+ let tables = watching.get(fields)
164
+ if (!tables) {
165
+ watching.set(fields, tables = new Set(triggers(fields).map((t) => t.on)))
166
+ }
167
+ return bundles.some((b) =>
168
+ (tables.has('tombstone') && b.$delete === true) ||
169
+ Object.keys(b).some((name) => tables.has(name))
170
+ )
171
+ }
172
+
173
+ // A trigger's definition from its name onward. SQLite keeps the statement it
174
+ // was given, so this is what two definitions compare by.
175
+ let body = (sql: string, name: string): string =>
176
+ sql.slice(sql.indexOf(`"${name}"`)).trim()
177
+
178
+ let watched = new WeakMap<Statements, { version: number; fields: string }>()
179
+
180
+ /** A queue trigger as the database holds it: its name, the table it is on,
181
+ * and the statement it was made by. */
182
+ export type Standing = { name: string; on: string; sql: string }
183
+
184
+ /** What making the database's triggers the wanted ones takes. */
185
+ export type Moves = {
186
+ /** the held triggers to drop: gone from the fields, or said otherwise */
187
+ drop: string[]
188
+ /** the wanted triggers to make */
189
+ make: CreateTrigger[]
190
+ /** whose wearers are owed a look: the tables a moved trigger is on, or
191
+ * everyone (`true`) when one on the vectors or the tombstones moved */
192
+ owed: Set<string> | true
193
+ }
194
+
195
+ // The triggers that are about every vector, not one component's rows.
196
+ let EVERY = new Set([TABLE, 'tombstone'])
197
+
198
+ /**
199
+ * What {@link watch} does about the triggers a database holds, given the
200
+ * ones the fields want. A trigger that stands as wanted owes nothing: it saw
201
+ * every write to its table. One made, dropped or changed missed or misread
202
+ * its table's writes, so the entities in that table are owed a look, and no
203
+ * others.
204
+ *
205
+ * ```ts
206
+ * import { equal } from '@yaks/testing'
207
+ * import { render } from '@yaks/sql'
208
+ * let book = { comp: 'book', prop: 'title' }
209
+ * let want = triggers([book])
210
+ * let held = want.map((t) => ({ name: t.name, on: t.on, sql: render(t).sql }))
211
+ * equal(moves(held, want).owed, new Set())
212
+ * let more = triggers([book, { comp: 'review', prop: 'prose' }])
213
+ * equal(moves(held, more).owed, new Set(['review']))
214
+ * equal(moves([], want).owed, true)
215
+ * ```
216
+ */
217
+ export let moves = (
218
+ have: Standing[],
219
+ want: CreateTrigger[],
220
+ write: (s: CreateTrigger) => { sql: string } = (s) => render(s),
221
+ ): Moves => {
222
+ let wanted = new Map(want.map((t) => [t.name, t]))
223
+ let drop: string[] = []
224
+ let owed: Set<string> | true = new Set()
225
+ let touched = (on: string) => {
226
+ if (owed === true) return
227
+ if (EVERY.has(on)) owed = true
228
+ else owed.add(on)
229
+ }
230
+ for (let r of have) {
231
+ let now = wanted.get(r.name)
232
+ if (now && body(r.sql, r.name) == body(write(now).sql, r.name)) {
233
+ wanted.delete(r.name)
234
+ continue
235
+ }
236
+ drop.push(r.name)
237
+ touched(r.on)
238
+ }
239
+ for (let t of wanted.values()) touched(t.on)
240
+ return { drop, make: [...wanted.values()], owed }
241
+ }
242
+
243
+ /**
244
+ * Make the database's queue triggers the ones {@link triggers} says, and
245
+ * queue the entities whose writes a missing or changed trigger may have
246
+ * missed ({@link moves}). Returns whether it changed anything. A second call
247
+ * with the same fields and schema reads and writes nothing.
248
+ */
249
+ export let watch = (
250
+ db: Statements,
251
+ wanted: Field[],
252
+ ): boolean | Promise<boolean> => {
253
+ let version = db.revision('schema')
254
+ let fields = present(db, wanted)
255
+ let definitions = triggers(fields)
256
+ let key = JSON.stringify(definitions)
257
+ let kept = watched.get(db)
258
+ if (kept?.version == version && kept.fields == key) return false
259
+ return after(
260
+ db.atomic(() => {
261
+ // Entry can wait for another host, whose transaction may change the schema.
262
+ fields = present(db, wanted)
263
+ definitions = triggers(fields)
264
+ key = JSON.stringify(definitions)
265
+ let have = db.query(
266
+ select({
267
+ cols: [col('name'), as(col('tbl_name'), 'on'), col('sql')],
268
+ from: table('sqlite_master'),
269
+ where: and(
270
+ eq(col('type'), val('trigger')),
271
+ op('glob', col('name'), val(`${OWED}_*`)),
272
+ ),
273
+ }),
274
+ ).map((r) => ({
275
+ name: String(r.name),
276
+ on: db.tableName?.(String(r.on)) ?? String(r.on),
277
+ sql: String(r.sql),
278
+ }))
279
+ let { drop, make, owed } = moves(have, definitions, db.render)
280
+ if (!drop.length && !make.length) return false
281
+ for (let name of drop) {
282
+ db.query({ t: 'drop', kind: 'trigger', name, ifExists: true })
283
+ }
284
+ for (let t of make) db.query(t)
285
+ if (owed === true) scheduled(db, fields)
286
+ else if (owed.size) scheduled(db, fields, owed)
287
+ return true
288
+ }),
289
+ (changed) => {
290
+ watched.set(db, { version: db.revision('schema'), fields: key })
291
+ return changed
292
+ },
293
+ )
294
+ }
295
+
296
+ /** Schedule every entity wearing a field or holding a vector — or, given
297
+ * `tables`, their owners only. Queue a bounded first window now; the sweep
298
+ * resumes the durable cursors for the rest. */
299
+ export let owe = (
300
+ db: Statements,
301
+ wanted: Field[],
302
+ tables?: Set<string>,
303
+ ): void | Promise<void> => {
304
+ let fields = present(db, wanted)
305
+ return db.atomic(() => scheduled(db, fields, tables))
306
+ }
307
+
308
+ // {@link owe} inside a unit the caller already holds.
309
+ let scheduled = (db: Statements, fields: Field[], tables?: Set<string>) => {
310
+ schedule(db, tables ?? [...fields.map((f) => f.comp), TABLE])
311
+ filled(db, fields)
312
+ }
313
+
314
+ /** One queued entity, and the count it was read at. */
315
+ export type Due = { owner: number; n: number }
316
+
317
+ /** The newest `limit` queued entities, newest first: what was just said is
318
+ * what someone is about to look for. */
319
+ export let due = (db: Statements, limit: number): Due[] =>
320
+ db.query(
321
+ select({
322
+ cols: [col('owner'), col('n')],
323
+ from: table(OWED),
324
+ order: [desc(col('owner'))],
325
+ limit: val(limit),
326
+ }),
327
+ ).map((r) => ({ owner: Number(r.owner), n: Number(r.n) }))
328
+
329
+ /** Settle a queued entity, unless a write queued it again since it was read. */
330
+ export let paid = (db: Statements, d: Due): void =>
331
+ void db.query({
332
+ t: 'delete',
333
+ from: OWED,
334
+ where: and(eq(col('owner'), val(d.owner)), eq(col('n'), val(d.n))),
335
+ })
336
+
337
+ /** How many entities are queued, plus one while reconciliation has more. */
338
+ export let left = (db: Statements): number =>
339
+ Number(
340
+ db.query(select({ cols: [as(count(), 'n')], from: table(OWED) }))[0].n,
341
+ ) +
342
+ Number(filling(db))
343
+
344
+ /** Whether queued owners or a reconciliation cursor still need a sweep. */
345
+ export let owing = (db: Statements): boolean =>
346
+ due(db, 1).length > 0 || filling(db)