@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/fields.js ADDED
@@ -0,0 +1,178 @@
1
+ // Which text is embedded. Semantic search here is not tied to one "document"
2
+ // component: a vocabulary declares components, some of their properties hold
3
+ // prose, and a vector can be made from any of them. This module is that choice
4
+ // — a `Field` is one `comp.prop` pair, `fields()` reads them off a vocabulary,
5
+ // and a `Pick` narrows that default when an application wants only some of
6
+ // them.
7
+ //
8
+ // The difference from a search index: an entity gets one vector, not one per
9
+ // component. A vector is a point in a space of meanings, and an entity is one
10
+ // thing — so all of its text fields are read and joined into a single string,
11
+ // in vocabulary order, before being embedded. That is also why this rule lives
12
+ // here rather than in a package shared with the full-text one: the two read the
13
+ // vocabulary the same way and then do different things with it, and neither
14
+ // should have to depend on the other in order to search.
15
+ import { and, ARMS, as, col, cut, eq, exists, fn, from, join, lit, ne, not, oneOf, select, table, union, unionAll, val } from "@yaks/sql";
16
+ /** Fields read through a host's derived columns (@yaks/sql `Derived`), so a
17
+ * content-addressed body is embedded as its prose, never as its hash. */ export let resolved = (fields, derived = {})=>fields.map((f)=>{
18
+ let text = derived[`${f.comp}.${f.prop}`]?.text;
19
+ return text ? {
20
+ ...f,
21
+ text
22
+ } : f;
23
+ });
24
+ /**
25
+ * The default choice: every stored text property. A computed property has no
26
+ * row to read, and a number, a stamp or a reference is not prose.
27
+ */ export let textual = (c)=>!c.computed && c.category == 'scalar' && c.scalar == 'text';
28
+ /**
29
+ * The text a bare word searches: the stored text properties the vocabulary
30
+ * marks `search: true`. What a plugin embeds when its config names no `text`,
31
+ * beside the text a component's `search` list says its entities are found by
32
+ * (a transcript entry's `content.body`), so a vector is made of what people
33
+ * and agents said, never of tool arguments or command lines, which are text
34
+ * too.
35
+ */ export let searched = (c)=>textual(c) && c.search;
36
+ /** The embedded fields of a vocabulary, by component then declaration order,
37
+ * then the text each component's `search` list names — the same text a bare
38
+ * word finds (@yaks/fts), so what is found by its words is found by its
39
+ * meaning too. `pick` narrows the properties; a list is the vocabulary's own
40
+ * statement about its component and is always taken. */ export let fields = (vocab, pick = textual)=>{
41
+ let exclusions = unembedded(vocab);
42
+ let excluded = ()=>exclusions.not ? {
43
+ not: [
44
+ ...exclusions.not
45
+ ]
46
+ } : {};
47
+ return [
48
+ ...vocab.all.flatMap((comp)=>vocab.props(comp).map((prop)=>vocab.prop(comp, prop)).filter(pick).map((c)=>({
49
+ comp,
50
+ prop: c.prop,
51
+ ...excluded()
52
+ }))),
53
+ ...vocab.all.flatMap((on)=>(vocab.comp(on)?.search ?? []).map((name)=>{
54
+ let [comp, prop] = name.split('.');
55
+ return {
56
+ comp,
57
+ prop,
58
+ on,
59
+ ...excluded()
60
+ };
61
+ }))
62
+ ];
63
+ };
64
+ /** What keeps an entity from being embedded: the components the vocabulary
65
+ * marks `embed: false`, or `found: false` (found by no search, so no vector
66
+ * is made of it either), as the `not` of a field (none, no key). */ export let unembedded = (vocab)=>{
67
+ let not = vocab.all.filter((comp)=>{
68
+ let c = vocab.comp(comp);
69
+ return c?.embed === false || c?.found === false;
70
+ });
71
+ return not.length ? {
72
+ not
73
+ } : {};
74
+ };
75
+ // The tables a store holds, per schema revision.
76
+ let held = new WeakMap();
77
+ /** The tables a store holds: a store makes a component's table the first
78
+ * time a write names it (@yaks/sqlite), and until then no entity wears it. */ export let tablesIn = (db)=>{
79
+ let at = db.revision('schema');
80
+ let k = held.get(db);
81
+ if (k?.at !== at) {
82
+ let names = new Set(db.query({
83
+ t: 'pragma',
84
+ name: 'table_list'
85
+ }).filter((r)=>r.type == 'table').map((r)=>db.tableName?.(String(r.name)) ?? String(r.name)));
86
+ held.set(db, k = {
87
+ at,
88
+ names
89
+ });
90
+ }
91
+ return k.names;
92
+ };
93
+ /** `f`, excluding only the components among `names`: one no table stands
94
+ * for excludes no entity. */ export let trimmed = (f, names)=>(f.not ?? []).every((n)=>names.has(n)) ? f : {
95
+ ...f,
96
+ not: f.not.filter((n)=>names.has(n))
97
+ };
98
+ /** The fields whose text a store holds a table for, each excluding only the
99
+ * components it holds a table for (`trim`, by default): there is no text to
100
+ * read or watch in a table nothing has written, and nothing to be excluded
101
+ * by. */ export let present = (db, fields, trim = true)=>{
102
+ let names = tablesIn(db);
103
+ let stands = (f)=>names.has(f.comp) && (!f.on || names.has(f.on));
104
+ let kept = fields.every(stands) ? fields : fields.filter(stands);
105
+ if (!trim || kept.every((f)=>trimmed(f, names) == f)) return kept;
106
+ return kept.map((f)=>trimmed(f, names));
107
+ };
108
+ // SQLite's trim() strips spaces only, so the whitespace that makes a text
109
+ // "empty" has to be listed. One rule, written once: a field's text counts when
110
+ // it holds something other than these characters.
111
+ let WS = ' \t\n\r\v\f';
112
+ // The condition that leaves out entities wearing a component marked
113
+ // `embed: false` or `found: false`.
114
+ export let allowed = (f, owner = col('entity', 'c'))=>(f.not ?? []).map((comp)=>not(exists(select({
115
+ cols: [
116
+ lit(1)
117
+ ],
118
+ from: table(comp, 'x'),
119
+ where: eq(col('entity', 'x'), owner)
120
+ }))));
121
+ // The join that scopes a field to the entities wearing `on`.
122
+ let scope = (f)=>f.on ? [
123
+ join(table(f.on, 'o'), eq(col('entity', 'o'), col('entity', 'c')))
124
+ ] : [];
125
+ /**
126
+ * Every embeddable piece of text in the graph, as one row per (entity, field):
127
+ * the owner's integer id, the field's position in the join order, and the text.
128
+ * Blank fields are dropped here, so an entity appears in these results exactly
129
+ * when it has something to embed. `owners` narrows them to those entities,
130
+ * which is how the sweep reads only what it owes. One compound statement per
131
+ * `arms` fields, since an engine bounds the terms one may carry (@yaks/sql
132
+ * `ARMS`: a Durable Object's SQLite takes five); none for a vocabulary with no
133
+ * text properties at all. A caller that checks the owner after joining it can
134
+ * supply `eligible` to replace the component-table checks in each piece.
135
+ */ export let pieces = (fields, owners, arms = ARMS, eligible = allowed)=>cut(fields.map((f, i)=>[
136
+ f,
137
+ i
138
+ ]), arms).filter((group)=>group.length).map((group)=>unionAll(...group.map(([f, i])=>{
139
+ let stored = col(f.prop, 'c');
140
+ let text = f.text ? f.text(stored) : stored;
141
+ let some = ne(fn('trim', fn('coalesce', text, lit('')), val(WS)), lit(''));
142
+ return select({
143
+ cols: [
144
+ as(col('entity', 'c'), 'owner'),
145
+ as(lit(i), 'ord'),
146
+ as(text, 't')
147
+ ],
148
+ from: table(f.comp, 'c'),
149
+ joins: scope(f),
150
+ where: and(some, ...eligible(f), ...owners ? [
151
+ oneOf(col('entity', 'c'), owners)
152
+ ] : [])
153
+ });
154
+ })));
155
+ /**
156
+ * Every entity that wears an embedded field, text or no text: what is owed a
157
+ * look when the fields themselves change. It reads no text, so it costs an
158
+ * index scan per field rather than the corpus. `owners` drives those seeks
159
+ * from a smaller set of candidates. One statement per `arms` fields, as
160
+ * {@link pieces}.
161
+ */ export let wearers = (fields, arms = ARMS, owners)=>cut(fields, arms).filter((group)=>group.length).map((group)=>union(...group.map((f)=>select({
162
+ cols: [
163
+ as(col('entity', 'c'), 'owner')
164
+ ],
165
+ from: owners ? from(owners, 'o') : table(f.comp, 'c'),
166
+ joins: [
167
+ ...owners ? [
168
+ {
169
+ how: 'cross',
170
+ src: table(f.comp, 'c'),
171
+ on: eq(col('entity', 'c'), col('owner', 'o'))
172
+ }
173
+ ] : [],
174
+ ...scope(f)
175
+ ],
176
+ where: and(...allowed(f))
177
+ }))));
178
+ //# sourceMappingURL=fields.js.map
package/fields.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fields.js","sources":["./fields.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,2EAA2E;AAC3E,QAAQ;AACR,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,gFAAgF;AAChF,4EAA4E;AAC5E,yDAAyD;AAEzD,SACE,GAAG,EACH,IAAI,EACJ,EAAE,EACF,GAAG,EACH,GAAG,EAEH,EAAE,EACF,MAAM,EAEN,EAAE,EACF,IAAI,EACJ,IAAI,EACJ,GAAG,EACH,EAAE,EACF,GAAG,EACH,KAAK,EAEL,MAAM,EAEN,KAAK,EACL,KAAK,EACL,QAAQ,EACR,GAAG,yBACwB;AAkB7B;uEACuE,GACvE,OAAO,IAAI,WAAW,CAAC,QAAiB,UAAmB,CAAC,CAAC,GAC3D,OAAO,GAAG,CAAC,CAAC;IACV,IAAI,OAAO,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE;IAC3C,OAAO,OAAO;MAAE,GAAG,CAAC;MAAE;IAAK,IAAI;EACjC,GAAE;AAQJ;;;CAGC,GACD,OAAO,IAAI,UAAgB,CAAC,IAC1B,CAAC,EAAE,QAAQ,IAAI,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,IAAI,OAAM;AAE7D;;;;;;;CAOC,GACD,OAAO,IAAI,WAAiB,CAAC,IAAM,QAAQ,MAAM,EAAE,MAAM,CAAA;AAEzD;;;;sDAIsD,GACtD,OAAO,IAAI,SAAS,CAAC,OAAc,OAAa,OAAO;EACrD,IAAI,aAAa,WAAW;EAC5B,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1C;WAAE,GACA,EAAE;aACH,MAAM;SACV;QACD,OAAO,OAAO,QAAQ;MACxB,MAEH"}
package/fields.ts ADDED
@@ -0,0 +1,259 @@
1
+ // Which text is embedded. Semantic search here is not tied to one "document"
2
+ // component: a vocabulary declares components, some of their properties hold
3
+ // prose, and a vector can be made from any of them. This module is that choice
4
+ // — a `Field` is one `comp.prop` pair, `fields()` reads them off a vocabulary,
5
+ // and a `Pick` narrows that default when an application wants only some of
6
+ // them.
7
+ //
8
+ // The difference from a search index: an entity gets one vector, not one per
9
+ // component. A vector is a point in a space of meanings, and an entity is one
10
+ // thing — so all of its text fields are read and joined into a single string,
11
+ // in vocabulary order, before being embedded. That is also why this rule lives
12
+ // here rather than in a package shared with the full-text one: the two read the
13
+ // vocabulary the same way and then do different things with it, and neither
14
+ // should have to depend on the other in order to search.
15
+
16
+ import {
17
+ and,
18
+ ARMS,
19
+ as,
20
+ col,
21
+ cut,
22
+ type Derived,
23
+ eq,
24
+ exists,
25
+ type Expr,
26
+ fn,
27
+ from,
28
+ join,
29
+ lit,
30
+ ne,
31
+ not,
32
+ oneOf,
33
+ type Query,
34
+ select,
35
+ type Statements,
36
+ table,
37
+ union,
38
+ unionAll,
39
+ val,
40
+ } from '@yaks/sql'
41
+ import type { Prop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
42
+
43
+ /** A `comp.prop` pair naming one embedded text property; for text an entity
44
+ * is found by through another of its components, that component (`on`: an
45
+ * `entry` is found by `content.body`); and — for a property that does not hold
46
+ * its own text, like a @yaks/blob body holding an address — the expression that
47
+ * reads the text a stored value stands for. */
48
+ export type Field = {
49
+ comp: string
50
+ prop: string
51
+ on?: string
52
+ /** components whose wearers are never embedded (vocabulary `embed: false`,
53
+ * or `found: false`, which no search finds) */
54
+ not?: string[]
55
+ text?: (stored: Expr) => Expr
56
+ }
57
+
58
+ /** Fields read through a host's derived columns (@yaks/sql `Derived`), so a
59
+ * content-addressed body is embedded as its prose, never as its hash. */
60
+ export let resolved = (fields: Field[], derived: Derived = {}): Field[] =>
61
+ fields.map((f) => {
62
+ let text = derived[`${f.comp}.${f.prop}`]?.text
63
+ return text ? { ...f, text } : f
64
+ })
65
+
66
+ /**
67
+ * Decides whether a property is embedded. An application passes its own to
68
+ * embed less than everything textual — say, the blurb but not the title.
69
+ */
70
+ export type Pick = (prop: Prop) => boolean
71
+
72
+ /**
73
+ * The default choice: every stored text property. A computed property has no
74
+ * row to read, and a number, a stamp or a reference is not prose.
75
+ */
76
+ export let textual: Pick = (c) =>
77
+ !c.computed && c.category == 'scalar' && c.scalar == 'text'
78
+
79
+ /**
80
+ * The text a bare word searches: the stored text properties the vocabulary
81
+ * marks `search: true`. What a plugin embeds when its config names no `text`,
82
+ * beside the text a component's `search` list says its entities are found by
83
+ * (a transcript entry's `content.body`), so a vector is made of what people
84
+ * and agents said, never of tool arguments or command lines, which are text
85
+ * too.
86
+ */
87
+ export let searched: Pick = (c) => textual(c) && c.search
88
+
89
+ /** The embedded fields of a vocabulary, by component then declaration order,
90
+ * then the text each component's `search` list names — the same text a bare
91
+ * word finds (@yaks/fts), so what is found by its words is found by its
92
+ * meaning too. `pick` narrows the properties; a list is the vocabulary's own
93
+ * statement about its component and is always taken. */
94
+ export let fields = (vocab: Vocab, pick: Pick = textual): Field[] => {
95
+ let exclusions = unembedded(vocab)
96
+ let excluded = () => exclusions.not ? { not: [...exclusions.not] } : {}
97
+ return [
98
+ ...vocab.all.flatMap((comp) =>
99
+ vocab.props(comp)
100
+ .map((prop) => vocab.prop(comp, prop)!)
101
+ .filter(pick)
102
+ .map((c) => ({ comp, prop: c.prop, ...excluded() }))
103
+ ),
104
+ ...vocab.all.flatMap((on) =>
105
+ (vocab.comp(on)?.search ?? []).map((name) => {
106
+ let [comp, prop] = name.split('.')
107
+ return { comp, prop, on, ...excluded() }
108
+ })
109
+ ),
110
+ ]
111
+ }
112
+
113
+ /** What keeps an entity from being embedded: the components the vocabulary
114
+ * marks `embed: false`, or `found: false` (found by no search, so no vector
115
+ * is made of it either), as the `not` of a field (none, no key). */
116
+ export let unembedded = (vocab: Vocab): { not?: string[] } => {
117
+ let not = vocab.all.filter((comp) => {
118
+ let c = vocab.comp(comp)
119
+ return c?.embed === false || c?.found === false
120
+ })
121
+ return not.length ? { not } : {}
122
+ }
123
+
124
+ // The tables a store holds, per schema revision.
125
+ let held = new WeakMap<Statements, { at: number; names: Set<string> }>()
126
+
127
+ /** The tables a store holds: a store makes a component's table the first
128
+ * time a write names it (@yaks/sqlite), and until then no entity wears it. */
129
+ export let tablesIn = (db: Statements): Set<string> => {
130
+ let at = db.revision('schema')
131
+ let k = held.get(db)
132
+ if (k?.at !== at) {
133
+ let names = new Set(
134
+ db.query({ t: 'pragma', name: 'table_list' })
135
+ .filter((r) => r.type == 'table').map((r) =>
136
+ db.tableName?.(String(r.name)) ?? String(r.name)
137
+ ),
138
+ )
139
+ held.set(db, k = { at, names })
140
+ }
141
+ return k.names
142
+ }
143
+
144
+ /** `f`, excluding only the components among `names`: one no table stands
145
+ * for excludes no entity. */
146
+ export let trimmed = (f: Field, names: Set<string>): Field =>
147
+ (f.not ?? []).every((n) => names.has(n))
148
+ ? f
149
+ : { ...f, not: f.not!.filter((n) => names.has(n)) }
150
+
151
+ /** The fields whose text a store holds a table for, each excluding only the
152
+ * components it holds a table for (`trim`, by default): there is no text to
153
+ * read or watch in a table nothing has written, and nothing to be excluded
154
+ * by. */
155
+ export let present = (
156
+ db: Statements,
157
+ fields: Field[],
158
+ trim = true,
159
+ ): Field[] => {
160
+ let names = tablesIn(db)
161
+ let stands = (f: Field) => names.has(f.comp) && (!f.on || names.has(f.on))
162
+ let kept = fields.every(stands) ? fields : fields.filter(stands)
163
+ if (!trim || kept.every((f) => trimmed(f, names) == f)) return kept
164
+ return kept.map((f) => trimmed(f, names))
165
+ }
166
+
167
+ // SQLite's trim() strips spaces only, so the whitespace that makes a text
168
+ // "empty" has to be listed. One rule, written once: a field's text counts when
169
+ // it holds something other than these characters.
170
+ let WS = ' \t\n\r\v\f'
171
+
172
+ // The condition that leaves out entities wearing a component marked
173
+ // `embed: false` or `found: false`.
174
+ export let allowed = (f: Field, owner: Expr = col('entity', 'c')): Expr[] =>
175
+ (f.not ?? []).map((comp) =>
176
+ not(exists(select({
177
+ cols: [lit(1)],
178
+ from: table(comp, 'x'),
179
+ where: eq(col('entity', 'x'), owner),
180
+ })))
181
+ )
182
+
183
+ // The join that scopes a field to the entities wearing `on`.
184
+ let scope = (f: Field) =>
185
+ f.on
186
+ ? [join(table(f.on, 'o'), eq(col('entity', 'o'), col('entity', 'c')))]
187
+ : []
188
+
189
+ /**
190
+ * Every embeddable piece of text in the graph, as one row per (entity, field):
191
+ * the owner's integer id, the field's position in the join order, and the text.
192
+ * Blank fields are dropped here, so an entity appears in these results exactly
193
+ * when it has something to embed. `owners` narrows them to those entities,
194
+ * which is how the sweep reads only what it owes. One compound statement per
195
+ * `arms` fields, since an engine bounds the terms one may carry (@yaks/sql
196
+ * `ARMS`: a Durable Object's SQLite takes five); none for a vocabulary with no
197
+ * text properties at all. A caller that checks the owner after joining it can
198
+ * supply `eligible` to replace the component-table checks in each piece.
199
+ */
200
+ export let pieces = (
201
+ fields: Field[],
202
+ owners?: number[],
203
+ arms = ARMS,
204
+ eligible: (field: Field) => Expr[] = allowed,
205
+ ): Query[] =>
206
+ cut(fields.map((f, i) => [f, i] as const), arms)
207
+ .filter((group) => group.length)
208
+ .map((group) =>
209
+ unionAll(...group.map(([f, i]) => {
210
+ let stored = col(f.prop, 'c')
211
+ let text = f.text ? f.text(stored) : stored
212
+ let some = ne(
213
+ fn('trim', fn('coalesce', text, lit('')), val(WS)),
214
+ lit(''),
215
+ )
216
+ return select({
217
+ cols: [
218
+ as(col('entity', 'c'), 'owner'),
219
+ as(lit(i), 'ord'),
220
+ as(text, 't'),
221
+ ],
222
+ from: table(f.comp, 'c'),
223
+ joins: scope(f),
224
+ where: and(
225
+ some,
226
+ ...eligible(f),
227
+ ...owners ? [oneOf(col('entity', 'c'), owners)] : [],
228
+ ),
229
+ })
230
+ }))
231
+ )
232
+
233
+ /**
234
+ * Every entity that wears an embedded field, text or no text: what is owed a
235
+ * look when the fields themselves change. It reads no text, so it costs an
236
+ * index scan per field rather than the corpus. `owners` drives those seeks
237
+ * from a smaller set of candidates. One statement per `arms` fields, as
238
+ * {@link pieces}.
239
+ */
240
+ export let wearers = (fields: Field[], arms = ARMS, owners?: Query): Query[] =>
241
+ cut(fields, arms).filter((group) => group.length).map((group) =>
242
+ union(...group.map((f) =>
243
+ select({
244
+ cols: [as(col('entity', 'c'), 'owner')],
245
+ from: owners ? from(owners, 'o') : table(f.comp, 'c'),
246
+ joins: [
247
+ ...owners
248
+ ? [{
249
+ how: 'cross' as const,
250
+ src: table(f.comp, 'c'),
251
+ on: eq(col('entity', 'c'), col('owner', 'o')),
252
+ }]
253
+ : [],
254
+ ...scope(f),
255
+ ],
256
+ where: and(...allowed(f)),
257
+ })
258
+ ))
259
+ )
package/fill.js ADDED
@@ -0,0 +1,177 @@
1
+ // Reconciliation is a queue too: a schema or model change can owe the whole
2
+ // corpus. Persist source-table cursors so each pass seeks a bounded window,
3
+ // and a restart resumes it without one enormous INSERT SELECT.
4
+ import { and, as, col, each, eq, fn, from, gt, le, lit, op, select, table, val } from "@yaks/sql";
5
+ import { FILL, OWED, TABLE } from "./ddl.js";
6
+ import { tablesIn, wearers } from "./fields.js";
7
+ /** Queue owners, retaining the generation a concurrent write advances. */ export let queue = (rows)=>({
8
+ t: 'insert',
9
+ into: OWED,
10
+ cols: [
11
+ 'owner',
12
+ 'n'
13
+ ],
14
+ ...rows,
15
+ upsert: [
16
+ {
17
+ on: [
18
+ col('owner')
19
+ ],
20
+ set: {
21
+ n: op('+', col('n'), lit(1))
22
+ }
23
+ }
24
+ ]
25
+ });
26
+ let key = (name)=>name == TABLE ? 'owner' : 'entity';
27
+ /** Schedule source tables through their current high key. New writes are
28
+ * already covered by the installed triggers. Rescheduling restarts a table,
29
+ * so another fields change cannot skip owners the earlier fields excluded. */ export let schedule = (db, names)=>{
30
+ for (let name of new Set(names)){
31
+ let [r] = db.query(select({
32
+ cols: [
33
+ as(fn('max', col(key(name))), 'last')
34
+ ],
35
+ from: table(name)
36
+ }));
37
+ if (r.last == null) continue;
38
+ db.query({
39
+ t: 'insert',
40
+ into: FILL,
41
+ cols: [
42
+ 'name',
43
+ 'after',
44
+ 'last'
45
+ ],
46
+ rows: [
47
+ [
48
+ val(name),
49
+ lit(0),
50
+ val(Number(r.last))
51
+ ]
52
+ ],
53
+ upsert: [
54
+ {
55
+ on: [
56
+ col('name')
57
+ ],
58
+ set: {
59
+ after: lit(0),
60
+ last: col('last', 'excluded')
61
+ }
62
+ }
63
+ ]
64
+ });
65
+ }
66
+ };
67
+ /** Whether reconciliation still has source rows to visit: looked at once
68
+ * while its table's rows stand. */ let looked = new WeakMap();
69
+ export let filling = (db)=>{
70
+ let at = db.revision('data', FILL);
71
+ let held = looked.get(db);
72
+ if (held?.at !== at) {
73
+ let rows = db.query(select({
74
+ cols: [
75
+ lit(1)
76
+ ],
77
+ from: table(FILL),
78
+ limit: lit(1)
79
+ }));
80
+ looked.set(db, held = {
81
+ at,
82
+ filling: rows.length > 0
83
+ });
84
+ }
85
+ return held.filling;
86
+ };
87
+ /** Queue at most `limit` candidate rows, including rows without eligible
88
+ * text. Applying the keyset window before eligibility also bounds a long
89
+ * excluded tail. Advancing the cursor and queueing its owners commit together. */ export let fill = (db, fields, limit = 256)=>{
90
+ if (!filling(db)) return;
91
+ return db.atomic(()=>filled(db, fields, limit));
92
+ };
93
+ /** {@link fill} inside a unit the caller already holds. */ export let filled = (db, fields, limit = 256)=>{
94
+ let names = tablesIn(db);
95
+ while(limit > 0){
96
+ let [job] = db.query(select({
97
+ cols: [
98
+ col('name'),
99
+ col('after'),
100
+ col('last')
101
+ ],
102
+ from: table(FILL),
103
+ order: [
104
+ col('name')
105
+ ],
106
+ limit: lit(1)
107
+ }));
108
+ if (!job) return;
109
+ let name = String(job.name);
110
+ let where = eq(col('name'), val(name));
111
+ let rows = names.has(name) ? db.query(select({
112
+ cols: [
113
+ as(col(key(name)), 'owner')
114
+ ],
115
+ from: table(name),
116
+ where: and(gt(col(key(name)), val(Number(job.after))), le(col(key(name)), val(Number(job.last)))),
117
+ order: [
118
+ col(key(name))
119
+ ],
120
+ limit: val(limit)
121
+ })) : [];
122
+ let owners = rows.map((r)=>Number(r.owner));
123
+ if (owners.length) {
124
+ let candidates = select({
125
+ cols: [
126
+ as(col('value'), 'owner')
127
+ ],
128
+ from: from(each(owners), 'ids')
129
+ });
130
+ let vectors = select({
131
+ cols: [
132
+ col('owner', 'v')
133
+ ],
134
+ from: from(candidates, 'o'),
135
+ joins: [
136
+ {
137
+ how: 'cross',
138
+ src: table(TABLE, 'v'),
139
+ on: eq(col('owner', 'v'), col('owner', 'o'))
140
+ }
141
+ ]
142
+ });
143
+ for (let q of [
144
+ ...wearers(fields, db.arms, candidates),
145
+ vectors
146
+ ]){
147
+ db.query(queue({
148
+ q: select({
149
+ cols: [
150
+ col('owner'),
151
+ lit(1)
152
+ ],
153
+ from: from(q, 'w')
154
+ })
155
+ }));
156
+ }
157
+ }
158
+ if (rows.length < limit || owners.at(-1) == Number(job.last)) {
159
+ db.query({
160
+ t: 'delete',
161
+ from: FILL,
162
+ where
163
+ });
164
+ } else {
165
+ db.query({
166
+ t: 'update',
167
+ table: FILL,
168
+ set: {
169
+ after: val(owners.at(-1))
170
+ },
171
+ where
172
+ });
173
+ }
174
+ limit -= rows.length;
175
+ }
176
+ };
177
+ //# sourceMappingURL=fill.js.map
package/fill.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fill.js","sources":["./fill.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,+DAA+D;AAC/D,SACE,GAAG,EACH,EAAE,EACF,GAAG,EACH,IAAI,EACJ,EAAE,EACF,EAAE,EACF,IAAI,EACJ,EAAE,EAEF,EAAE,EACF,GAAG,EACH,EAAE,EACF,M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