@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/service.js ADDED
@@ -0,0 +1,107 @@
1
+ // The work this package keeps doing while a process is up: the `service`
2
+ // export (`@yaks/embedding/service`), a loop that settles what the queue
3
+ // holds (./owed.ts), run by one process per graph (@yaks/cli holds it under a
4
+ // lease). "The server" here means whichever process holds it.
5
+ //
6
+ // It is a loop rather than an effect because the writes it answers are not
7
+ // only this process's. The queue's triggers note every write to embedded text
8
+ // in the same statement as the write, whoever made it — this server, a CLI, a
9
+ // restore — so the loop reads the queue, not the commits it happened to see.
10
+ // While work is left it takes the next batch at once (./sweep.ts `drain`),
11
+ // which is how a backfill drains; when the queue is empty it looks again after
12
+ // `after`, which is how soon a new entry is found by its meaning. An empty
13
+ // look costs a few index reads. A host with nothing standing between requests
14
+ // (a Durable Object sleeps) runs `drain` itself when a write asks, and no loop
15
+ // at all.
16
+ //
17
+ // Embedding is slow and usually remote, and a pass never holds a write open:
18
+ // what it reads and writes are a batch's rows, and the wait between is the
19
+ // model's.
20
+ //
21
+ // Native search scans canonical vectors; no index maintenance holds a write.
22
+ //
23
+ // The config, and the provider and model rows it names, are read on every
24
+ // pass (./options.ts). A server whose key or provider has not arrived starts
25
+ // up, stores no vectors, reports what it is waiting for once, and keeps
26
+ // looking, so the first pass after it appears is the one that embeds and
27
+ // nothing has to be restarted. A pass that fails leaves its work queued for
28
+ // the next look: a machine that cannot reach its model has stale vectors, not
29
+ // a broken graph. What its failure is comes from ./outage.ts, as it does for a
30
+ // yaks.app store's drains: a model out for a while is a line in the log when
31
+ // it starts and when it ends, texts it holds up past OVERDUE report once, and
32
+ // any other failure reports at once to the host's tracker, once while passes
33
+ // keep failing by it, with a line when one answers again.
34
+ import { sleep } from "@yaks/effects";
35
+ import { statements } from "@yaks/sql";
36
+ import { resolved } from "./fields.js";
37
+ import { ready } from "./options.js";
38
+ import { drain } from "./sweep.js";
39
+ import { drained, failed, Overdue } from "./outage.js";
40
+ import { prepare } from "./native.js";
41
+ /** How long an empty queue waits before the loop looks again, by default. */ export let AFTER = 3_000;
42
+ /** Settle the queue for as long as `signal` lets it: one pass when it has
43
+ * already aborted, the way a one-shot command runs a service. */ export let service = async (host, options = {}, signal = AbortSignal.abort())=>{
44
+ let db = statements(host.storage);
45
+ let after = options.after ?? AFTER;
46
+ // Reported once per distinct message: a server waiting for a key says so on
47
+ // the first pass and then goes quiet; `vector_check` keeps the answer.
48
+ let told = new Set();
49
+ let now = options.now ?? Date.now;
50
+ let outage = null;
51
+ let ride = async (made)=>{
52
+ let rode = made(outage, now());
53
+ outage = rode.outage;
54
+ if (rode.log) console.warn('@yaks/embedding —', rode.log);
55
+ if (!rode.report) return;
56
+ // What varies across one outage (the model, how many texts, how many
57
+ // tries, how long they waited) is the occurrence's, not the bug's.
58
+ let context = rode.report instanceof Overdue ? rode.report.context : {};
59
+ let tags = {
60
+ package: '@yaks/embedding',
61
+ step: 'embedding pass',
62
+ ...context
63
+ };
64
+ try {
65
+ if (host.report) await host.report(rode.report, {
66
+ tags
67
+ });
68
+ else console.error('@yaks/embedding pass —', rode.report);
69
+ } catch (error) {
70
+ console.error('@yaks/embedding report —', error);
71
+ }
72
+ };
73
+ for(;;){
74
+ try {
75
+ let is = await ready(host.vocab, options, host.graph, host.embedders);
76
+ if (is.embedder) {
77
+ let text = resolved(is.text, host.derived);
78
+ let done = await drain(db, text, is.embedder, {
79
+ batch: options.batch,
80
+ signal
81
+ });
82
+ // A text the model will not take is the text's, not the pass's: it
83
+ // has no vector, and ranks by its words alone.
84
+ for (let r of done.refused){
85
+ console.warn('@yaks/embedding refused', r.entity, '—', r.error);
86
+ }
87
+ await ride(drained);
88
+ } else {
89
+ if (!told.has(is.waiting)) {
90
+ told.add(is.waiting);
91
+ console.warn('@yaks/embedding —', is.waiting);
92
+ }
93
+ // Native scans still search the vectors already stored.
94
+ prepare(db);
95
+ }
96
+ } catch (error) {
97
+ // A pass the host ended mid-way wrote nothing it had not settled: its
98
+ // work is still queued, and the store it would report into is closing.
99
+ if (signal.aborted) return;
100
+ await ride(failed(error));
101
+ }
102
+ if (signal.aborted) return;
103
+ await sleep(after, signal);
104
+ if (signal.aborted) return;
105
+ }
106
+ };
107
+ //# sourceMappingURL=service.js.map
package/service.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sources":["./service.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,yEAAyE;AACzE,8EAA8E;AAC9E,8DAA8D;AAC9D,EAAE;AACF,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,+EAA+E;AAC/E,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,UAAU;AACV,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,WAAW;AACX,EAAE;AACF,6EAA6E;AAC7E,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,wEAAwE;AACxE,yEAAyE;AACzE,4EAA4E;AAC5E,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,6EA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,KAAK,EAAE,KAAK,SAAS;MACpE,IAAI,GAAG,QAAQ,EAAE;QACf,IAAI,OAAO,SAAS,GAAG,IAAI,EAAE,KAAK,OAAO;QACzC,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM,GAAG,QAAQ,EAAE;UAC5C,OAAO,QAAQ,KAAK;UACpB;QACF;QACA,mEAAmE;QACnE,+CAA+C;QAC/C,KAAK,IAAI,KAAK,KAAK,OAAO,CAAE;UAC1B,QAAQ,IAAI,CAAC,2BAA2B,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK;QAChE;QACA,MAAM,KAAK;MACb,OAAO;QACL,IAAI,CAAC,KAAK,GAAG,CAAC,GAAG,OAAO,GAAI;UAC1B,KAAK,GAAG,CAAC,GAAG,OAAO;UACnB,QAAQ,IAAI,CAAC,qBAAqB,GAAG,OAAO;QAC9C;QACA,wDAAwD;QACxD,QAAQ;MACV;IACF,EAAE,OAAO,OAAO;MACd,sEAAsE;MACtE,uEAAuE;MACvE,IAAI,OAAO,OAAO,EAAE;MACpB,MAAM,KAAK,OAAO;IACpB;IACA,IAAI,OAAO,OAAO,EAAE;IACpB,MAAM,MAAM,OAAO;IACnB,IAAI,OAAO,OAAO,EAAE;EACtB;AACF,EAAC"}
package/service.ts ADDED
@@ -0,0 +1,133 @@
1
+ // The work this package keeps doing while a process is up: the `service`
2
+ // export (`@yaks/embedding/service`), a loop that settles what the queue
3
+ // holds (./owed.ts), run by one process per graph (@yaks/cli holds it under a
4
+ // lease). "The server" here means whichever process holds it.
5
+ //
6
+ // It is a loop rather than an effect because the writes it answers are not
7
+ // only this process's. The queue's triggers note every write to embedded text
8
+ // in the same statement as the write, whoever made it — this server, a CLI, a
9
+ // restore — so the loop reads the queue, not the commits it happened to see.
10
+ // While work is left it takes the next batch at once (./sweep.ts `drain`),
11
+ // which is how a backfill drains; when the queue is empty it looks again after
12
+ // `after`, which is how soon a new entry is found by its meaning. An empty
13
+ // look costs a few index reads. A host with nothing standing between requests
14
+ // (a Durable Object sleeps) runs `drain` itself when a write asks, and no loop
15
+ // at all.
16
+ //
17
+ // Embedding is slow and usually remote, and a pass never holds a write open:
18
+ // what it reads and writes are a batch's rows, and the wait between is the
19
+ // model's.
20
+ //
21
+ // Native search scans canonical vectors; no index maintenance holds a write.
22
+ //
23
+ // The config, and the provider and model rows it names, are read on every
24
+ // pass (./options.ts). A server whose key or provider has not arrived starts
25
+ // up, stores no vectors, reports what it is waiting for once, and keeps
26
+ // looking, so the first pass after it appears is the one that embeds and
27
+ // nothing has to be restarted. A pass that fails leaves its work queued for
28
+ // the next look: a machine that cannot reach its model has stale vectors, not
29
+ // a broken graph. What its failure is comes from ./outage.ts, as it does for a
30
+ // yaks.app store's drains: a model out for a while is a line in the log when
31
+ // it starts and when it ends, texts it holds up past OVERDUE report once, and
32
+ // any other failure reports at once to the host's tracker, once while passes
33
+ // keep failing by it, with a line when one answers again.
34
+
35
+ import { sleep } from '@yaks/effects'
36
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
37
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
38
+ import { type Derived, type Statements, statements } from '@yaks/sql'
39
+ import { resolved } from './fields.js'
40
+ import { type Lent, type Options, ready } from './options.js'
41
+ import { drain } from './sweep.js'
42
+ import { drained, failed, type Outage, Overdue, type Ride } from './outage.js'
43
+ import { prepare } from './native.js'
44
+
45
+ /** How long an empty queue waits before the loop looks again, by default. */
46
+ export let AFTER = 3_000
47
+
48
+ /** What the service reads: the vocabulary, the database, the graph the
49
+ * provider and model rows are read from, and the host's derived columns,
50
+ * through which a body @yaks/blob stores by address is read as its text. */
51
+ export type Host = {
52
+ vocab: Vocab
53
+ storage: { statements?: Statements }
54
+ graph: Pick<Graph, 'get'>
55
+ derived?: Derived
56
+ /** the embedders lent by name (@yaks/host `embedders`) */
57
+ embedders?: Lent
58
+ /** where a failed pass is reported (@yaks/host `report`; default
59
+ * `console.error`) */
60
+ report?: (
61
+ error: unknown,
62
+ context: { tags: Record<string, string> },
63
+ ) => void | Promise<void>
64
+ }
65
+
66
+ /** Settle the queue for as long as `signal` lets it: one pass when it has
67
+ * already aborted, the way a one-shot command runs a service. */
68
+ export let service = async (
69
+ host: Host,
70
+ options: Options = {},
71
+ signal: AbortSignal = AbortSignal.abort(),
72
+ ): Promise<void> => {
73
+ let db = statements(host.storage)
74
+ let after = options.after ?? AFTER
75
+ // Reported once per distinct message: a server waiting for a key says so on
76
+ // the first pass and then goes quiet; `vector_check` keeps the answer.
77
+ let told = new Set<string>()
78
+ let now = options.now ?? Date.now
79
+ let outage: Outage | null = null
80
+ let ride = async (made: Ride) => {
81
+ let rode = made(outage, now())
82
+ outage = rode.outage
83
+ if (rode.log) console.warn('@yaks/embedding —', rode.log)
84
+ if (!rode.report) return
85
+ // What varies across one outage (the model, how many texts, how many
86
+ // tries, how long they waited) is the occurrence's, not the bug's.
87
+ let context = rode.report instanceof Overdue ? rode.report.context : {}
88
+ let tags = {
89
+ package: '@yaks/embedding',
90
+ step: 'embedding pass',
91
+ ...context,
92
+ }
93
+ try {
94
+ if (host.report) await host.report(rode.report, { tags })
95
+ else console.error('@yaks/embedding pass —', rode.report)
96
+ } catch (error) {
97
+ console.error('@yaks/embedding report —', error)
98
+ }
99
+ }
100
+ for (;;) {
101
+ try {
102
+ let is = await ready(host.vocab, options, host.graph, host.embedders)
103
+ if (is.embedder) {
104
+ let text = resolved(is.text, host.derived)
105
+ let done = await drain(db, text, is.embedder, {
106
+ batch: options.batch,
107
+ signal,
108
+ })
109
+ // A text the model will not take is the text's, not the pass's: it
110
+ // has no vector, and ranks by its words alone.
111
+ for (let r of done.refused) {
112
+ console.warn('@yaks/embedding refused', r.entity, '—', r.error)
113
+ }
114
+ await ride(drained)
115
+ } else {
116
+ if (!told.has(is.waiting!)) {
117
+ told.add(is.waiting!)
118
+ console.warn('@yaks/embedding —', is.waiting)
119
+ }
120
+ // Native scans still search the vectors already stored.
121
+ prepare(db)
122
+ }
123
+ } catch (error) {
124
+ // A pass the host ended mid-way wrote nothing it had not settled: its
125
+ // work is still queued, and the store it would report into is closing.
126
+ if (signal.aborted) return
127
+ await ride(failed(error))
128
+ }
129
+ if (signal.aborted) return
130
+ await sleep(after, signal)
131
+ if (signal.aborted) return
132
+ }
133
+ }
package/sleeper.js ADDED
@@ -0,0 +1,107 @@
1
+ // The drain a host with nothing standing between requests runs: a Durable
2
+ // Object, which sleeps. The service (./service.ts) is a loop that looks
3
+ // again; this has no loop. It drains once a write has committed and when its
4
+ // alarm rings, a batch at a time, waiting on the model between batches, so
5
+ // requests interleave and none waits on it. It drains for a slice
6
+ // (`deadline`) and arms the alarm for the rest, so a store that owes a
7
+ // vector for every text it holds catches up behind its own traffic.
8
+ //
9
+ // The embedder asks again through a passing failure of the model's own
10
+ // (./remote.ts `retrying`). A drain that fails even so comes back `retry` ms
11
+ // later, and nothing else starts one meanwhile. A model that did not answer
12
+ // is an outage the drains ride out (./outage.ts), kept by the host, since it
13
+ // outlives the incarnations its retries wake.
14
+ //
15
+ // What the host does is handed in: its clock, its alarm, how it holds work
16
+ // past a request (`waitUntil`), where it keeps the outage and reports. The
17
+ // app stores and the Operator's store on yaks.app run it the same way.
18
+ import { system } from "@yaks/fp";
19
+ import { BATCH, drain } from "./sweep.js";
20
+ import { due, owing, queues } from "./owed.js";
21
+ import { drained, failed, Overdue } from "./outage.js";
22
+ /** How long a drain runs before the alarm takes up the rest. */ export let DEADLINE = 10_000;
23
+ /** How long a failed drain waits. */ export let RETRY = 60_000;
24
+ /** The drains of a host that sleeps between requests. */ export let sleeper = (host)=>{
25
+ let clock = host.clock ?? system;
26
+ let log = host.log ?? ((line, ...detail)=>console.warn(line, ...detail));
27
+ let work = null;
28
+ let again = false;
29
+ let waits = 0;
30
+ let ride = (ride)=>{
31
+ let was = host.outage.get();
32
+ let { outage, report, log: line } = ride(was, clock.now());
33
+ if (outage != was) host.outage.set(outage);
34
+ if (line) log('embedding', line);
35
+ // What varies across one outage (the model, how many texts, how many
36
+ // tries, how long they waited) is the occurrence's, not the bug's.
37
+ if (report) {
38
+ host.report(report, report instanceof Overdue ? report.context : {});
39
+ }
40
+ };
41
+ let owes = ()=>{
42
+ let texts = host.texts();
43
+ return !!texts && owing(texts.statements);
44
+ };
45
+ let run = ()=>{
46
+ let model = host.model();
47
+ let texts = host.texts();
48
+ if (!texts || !model) return;
49
+ if (clock.now() < waits) return;
50
+ if (work) {
51
+ if (owes()) again = true;
52
+ return;
53
+ }
54
+ // Keep the batch that proves work is owed; the drain need not read it
55
+ // again. Queue generations still protect writes made while the model
56
+ // runs.
57
+ let queued = due(texts.statements, BATCH);
58
+ // Nothing owed waits on the model, whether or not it answers.
59
+ if (!queued.length && !owes()) return ride(drained);
60
+ work = (async ()=>{
61
+ do {
62
+ again = false;
63
+ let now = host.texts();
64
+ if (!now) return;
65
+ let deadline = new AbortController();
66
+ let cancel = clock.after(host.deadline ?? DEADLINE, ()=>deadline.abort(new DOMException('timed out', 'TimeoutError')));
67
+ let done = await drain(now.statements, now.fields, model, {
68
+ signal: deadline.signal,
69
+ queued
70
+ }).finally(cancel);
71
+ queued = undefined;
72
+ if (!host.texts()) return;
73
+ // A text the model will not take is the text's, not the host's: it
74
+ // has no vector, and ranks by its words alone.
75
+ for (let r of done.refused){
76
+ log('embed refused', r.entity, r.error.message);
77
+ }
78
+ }while (again)
79
+ ride(drained);
80
+ if (owes()) await host.arm(host.soon?.() ?? clock.now(), 'embedding');
81
+ })().catch(async (error)=>{
82
+ ride(failed(error));
83
+ waits = clock.now() + (host.retry?.(error) ?? RETRY);
84
+ await host.arm(waits, 'embedding retry').catch((e)=>host.report(e, {
85
+ request: 'embedding retry'
86
+ }));
87
+ }).finally(()=>{
88
+ work = null;
89
+ if (again) run();
90
+ });
91
+ host.hold?.(work);
92
+ };
93
+ return {
94
+ wrote: (bundles)=>{
95
+ // Its triggers queued the text in the write's own statement, so this
96
+ // asks only of a write that names what a trigger watches.
97
+ let texts = host.texts();
98
+ if (texts && queues(texts.fields, bundles)) run();
99
+ return bundles;
100
+ },
101
+ run,
102
+ owes,
103
+ retry: ()=>waits > clock.now() ? waits : null,
104
+ work: ()=>work
105
+ };
106
+ };
107
+ //# sourceMappingURL=sleeper.js.map
package/sleeper.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sleeper.js","sources":["./sleeper.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wEAAwE;AACxE,6EAA6E;AAC7E,2EAA2E;AAC3E,kEAAkE;AAClE,uEAAuE;AACvE,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,4EAA4E;AAC5E,6EAA6E;AAC7E,8CAA8C;AAC9C,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,uEAAuE;AAIvE,SAAqB,MAAM,wBAA6B;AAGxD,SAAS,KAAK,EAAE,KAAK,qBAAkC;AACvD,SAAS,GAAG,EAAE,KAAK,EAAE,MAAM,oBAAmB;AAC9C,SAAS,OAAO,EAAE,MAAM,EAAe,OAAO,sBAAgC;AA0C9E,8DAA8D,GAC9D,OAAO,IAAI,WAAW,OAAM;AAE5B,mCAAmC,GACnC,OAAO,IAAI,QAAQ,OAAM;AAEzB,uDAAuD,GACvD,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,QAAQ,KAAK,KAAK,IAAI;EAC1B,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,SAAW,QAAQ,IAAI,CAAC,SAAS,OAAO;EACzE,IAAI,OAA6B;EACjC,IAAI,QAAQ;EACZ,IAAI,QAAQ;EAEZ,IAAI,OAAO,CAAC;IACV,IAAI,MAAM,KAAK,MAAM,CAAC,GAAG;IACzB,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,IAAI,EAAE,GAAG,KAAK,KAAK,MAAM,GAAG;IACvD,IAAI,UAAU,KAAK,KAAK,MAAM,CAAC,GAAG,CAAC;IACnC,IAAI,MAAM,IAAI,aAAa;IAC3B,qEAAqE;IACrE,m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,IAAI,KAAK,CAAC,OAAO;MAChB,KAAK,OAAO;MACZ,QAAQ,MAAM,GAAG,KAAK,CAAC,KAAK,KAAK,GAAG,UAAU,KAAK;MACnD,MAAM,KAAK,GAAG,CAAC,OAAO,mBACnB,KAAK,CAAC,CAAC,IAAM,KAAK,MAAM,CAAC,GAAG;UAAE,SAAS;QAAkB;IAC9D,GAAG,OAAO,CAAC;MACT,OAAO;MACP,IAAI,OAAO;IACb;IACA,KAAK,IAAI,GAAG;EACd;EAEA,OAAO;IACL,OAAO,CAAC;MACN,qEAAqE;MACrE,0DAA0D;MAC1D,IAAI,QAAQ,KAAK,KAAK;MACtB,IAAI,SAAS,OAAO,MAAM,MAAM,EAAE,UAAU;MAC5C,OAAO;IACT;IACA;IACA;IACA,OAAO,IAAM,QAAQ,MAAM,GAAG,KAAK,QAAQ;IAC3C,MAAM,IAAM;EACd;AACF,EAAC"}
package/sleeper.ts ADDED
@@ -0,0 +1,166 @@
1
+ // The drain a host with nothing standing between requests runs: a Durable
2
+ // Object, which sleeps. The service (./service.ts) is a loop that looks
3
+ // again; this has no loop. It drains once a write has committed and when its
4
+ // alarm rings, a batch at a time, waiting on the model between batches, so
5
+ // requests interleave and none waits on it. It drains for a slice
6
+ // (`deadline`) and arms the alarm for the rest, so a store that owes a
7
+ // vector for every text it holds catches up behind its own traffic.
8
+ //
9
+ // The embedder asks again through a passing failure of the model's own
10
+ // (./remote.ts `retrying`). A drain that fails even so comes back `retry` ms
11
+ // later, and nothing else starts one meanwhile. A model that did not answer
12
+ // is an outage the drains ride out (./outage.ts), kept by the host, since it
13
+ // outlives the incarnations its retries wake.
14
+ //
15
+ // What the host does is handed in: its clock, its alarm, how it holds work
16
+ // past a request (`waitUntil`), where it keeps the outage and reports. The
17
+ // app stores and the Operator's store on yaks.app run it the same way.
18
+
19
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
20
+ import type { Statements } from 'jsr:@yaks/sql@0.2.36'
21
+ import { type Clock, system } from '@yaks/fp'
22
+ import type { Embedder } from './embedder.ts'
23
+ import type { Field } from './fields.ts'
24
+ import { BATCH, drain, type Drained } from './sweep.js'
25
+ import { due, owing, queues } from './owed.js'
26
+ import { drained, failed, type Outage, Overdue, type Ride } from './outage.js'
27
+
28
+ /** What a sleeping host lends its drains. */
29
+ export type Sleeping = {
30
+ /** its texts, or null while it can drain nothing: no schema standing yet,
31
+ * or asleep for good */
32
+ texts: () => { statements: Statements; fields: Field[] } | null
33
+ /** the embedder, or null where none is lent */
34
+ model: () => Embedder | null
35
+ /** sets the host's alarm, for the rest of a drain or its retry */
36
+ arm: (at: number, why: string) => Promise<void>
37
+ /** keeps the host up until the work is done (`waitUntil`) */
38
+ hold?: (work: Promise<unknown>) => void
39
+ /** where the outage the drains are riding out is kept */
40
+ outage: { get: () => Outage | null; set: (o: Outage | null) => void }
41
+ /** where a failure goes, with what varies across one outage */
42
+ report: (error: unknown, context: Record<string, unknown>) => void
43
+ /** a line for the log */
44
+ log?: (line: string, ...detail: unknown[]) => void
45
+ clock?: Clock
46
+ /** how long one drain may run, in ms */
47
+ deadline?: number
48
+ /** how long a failed drain waits, in ms, given its error */
49
+ retry?: (error: unknown) => number
50
+ /** when the alarm rings for the rest of a drain */
51
+ soon?: () => number
52
+ }
53
+
54
+ /** A sleeping host's drains. */
55
+ export type Sleeper = {
56
+ /** what a committed write calls: a drain where it queued a text */
57
+ wrote: (bundles: Bundle[]) => Bundle[]
58
+ /** a drain, unless one runs or a failed one waits */
59
+ run: () => void
60
+ /** whether a text is owed its vector: one queued row sought */
61
+ owes: () => boolean
62
+ /** when a failed drain is retried, if one waits */
63
+ retry: () => number | null
64
+ /** the drain in flight */
65
+ work: () => Promise<void> | null
66
+ }
67
+
68
+ /** How long a drain runs before the alarm takes up the rest. */
69
+ export let DEADLINE = 10_000
70
+
71
+ /** How long a failed drain waits. */
72
+ export let RETRY = 60_000
73
+
74
+ /** The drains of a host that sleeps between requests. */
75
+ export let sleeper = (host: Sleeping): Sleeper => {
76
+ let clock = host.clock ?? system
77
+ let log = host.log ?? ((line, ...detail) => console.warn(line, ...detail))
78
+ let work: Promise<void> | null = null
79
+ let again = false
80
+ let waits = 0
81
+
82
+ let ride = (ride: Ride) => {
83
+ let was = host.outage.get()
84
+ let { outage, report, log: line } = ride(was, clock.now())
85
+ if (outage != was) host.outage.set(outage)
86
+ if (line) log('embedding', line)
87
+ // What varies across one outage (the model, how many texts, how many
88
+ // tries, how long they waited) is the occurrence's, not the bug's.
89
+ if (report) {
90
+ host.report(report, report instanceof Overdue ? report.context : {})
91
+ }
92
+ }
93
+
94
+ let owes = () => {
95
+ let texts = host.texts()
96
+ return !!texts && owing(texts.statements)
97
+ }
98
+
99
+ let run = () => {
100
+ let model = host.model()
101
+ let texts = host.texts()
102
+ if (!texts || !model) return
103
+ if (clock.now() < waits) return
104
+ if (work) {
105
+ if (owes()) again = true
106
+ return
107
+ }
108
+ // Keep the batch that proves work is owed; the drain need not read it
109
+ // again. Queue generations still protect writes made while the model
110
+ // runs.
111
+ let queued: ReturnType<typeof due> | undefined = due(
112
+ texts.statements,
113
+ BATCH,
114
+ )
115
+ // Nothing owed waits on the model, whether or not it answers.
116
+ if (!queued.length && !owes()) return ride(drained)
117
+ work = (async () => {
118
+ do {
119
+ again = false
120
+ let now = host.texts()
121
+ if (!now) return
122
+ let deadline = new AbortController()
123
+ let cancel = clock.after(
124
+ host.deadline ?? DEADLINE,
125
+ () => deadline.abort(new DOMException('timed out', 'TimeoutError')),
126
+ )
127
+ let done: Drained = await drain(now.statements, now.fields, model, {
128
+ signal: deadline.signal,
129
+ queued,
130
+ }).finally(cancel)
131
+ queued = undefined
132
+ if (!host.texts()) return
133
+ // A text the model will not take is the text's, not the host's: it
134
+ // has no vector, and ranks by its words alone.
135
+ for (let r of done.refused) {
136
+ log('embed refused', r.entity, r.error.message)
137
+ }
138
+ } while (again)
139
+ ride(drained)
140
+ if (owes()) await host.arm(host.soon?.() ?? clock.now(), 'embedding')
141
+ })().catch(async (error) => {
142
+ ride(failed(error))
143
+ waits = clock.now() + (host.retry?.(error) ?? RETRY)
144
+ await host.arm(waits, 'embedding retry')
145
+ .catch((e) => host.report(e, { request: 'embedding retry' }))
146
+ }).finally(() => {
147
+ work = null
148
+ if (again) run()
149
+ })
150
+ host.hold?.(work)
151
+ }
152
+
153
+ return {
154
+ wrote: (bundles) => {
155
+ // Its triggers queued the text in the write's own statement, so this
156
+ // asks only of a write that names what a trigger watches.
157
+ let texts = host.texts()
158
+ if (texts && queues(texts.fields, bundles)) run()
159
+ return bundles
160
+ },
161
+ run,
162
+ owes,
163
+ retry: () => waits > clock.now() ? waits : null,
164
+ work: () => work,
165
+ }
166
+ }
package/sparse.js ADDED
@@ -0,0 +1,36 @@
1
+ // A selective shared-file search reads only its admitted codes, then the
2
+ // ordinary reader scores the best few from their float vectors. Reading every
3
+ // admitted float instead touched thousands of scattered pages on the box.
4
+ import { among, and, col, eq, exists, lit, not, select, table } from "@yaks/sql";
5
+ import { CODE } from "./ddl.js";
6
+ import { scored } from "./score.js";
7
+ /** The best `limit` admitted codes, when every stored vector has its codes. */ export let sparse = (db, query, within, limit)=>{
8
+ let rows = db.query(select({
9
+ cols: [
10
+ col('owner', 'c'),
11
+ col('code', 'c')
12
+ ],
13
+ from: table(CODE, 'c'),
14
+ where: and(among(col('owner', 'c'), within), not(exists(select({
15
+ cols: [
16
+ lit(1)
17
+ ],
18
+ from: table('tombstone', 't'),
19
+ where: eq(col('entity', 't'), col('owner', 'c'))
20
+ }))))
21
+ }));
22
+ let vectors = function*() {
23
+ for (let row of rows){
24
+ let bytes = row.code;
25
+ yield {
26
+ owner: Number(row.owner),
27
+ vector: new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
28
+ };
29
+ }
30
+ };
31
+ return scored(query, vectors(), {
32
+ limit,
33
+ floor: -1
34
+ }).map((hit)=>hit.owner);
35
+ };
36
+ //# sourceMappingURL=sparse.js.map
package/sparse.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sparse.js","sources":["./sparse.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,0EAA0E;AAC1E,SACE,KAAK,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,MAAM,EACN,GAAG,EACH,GAAG,EAEH,MAAM,EAEN,KAAK,yBACsB;AAC7B,SAAS,IAAI,mBAAkB;AAC/B,SAAS,MAAM,qBAAiC;AAEhD,6EAA6E,GAC7E,OAAO,IAAI,SAAS,CAClB,IACA,OACA,QACA;EAEA,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO;IACzB,MAAM;MAAC,IAAI,SAAS;MAAM,IAAI,QAAQ;KAAK;IAC3C,MAAM,MAAM,MAAM;IAClB,OAAO,IACL,MAAM,IAAI,SAAS,MAAM,SACzB,IAAI,OAAO,OAAO;MAChB,MAAM;QAAC,IAAI;OAAG;MACd,MAAM,MAAM,aAAa;MACzB,OAAO,GAAG,IAAI,UAAU,MAAM,IAAI,SAAS;IAC7C;EAEJ;EACA,IAAI,UAAU;IACZ,KAAK,IAAI,OAAO,KAAM;MACpB,IAAI,QAAQ,IAAI,IAAI;MACpB,MAAM;QACJ,OAAO,OAAO,IAAI,KAAK;QACvB,QAAQ,IAAI,UAAU,MAAM,MAAM,EAAE,MAAM,UAAU,EAAE,MAAM,UAAU;MACxE;IACF;EACF;EACA,OAAO,OAAO,OAAO,WAAW;IAAE;IAAO,OAAO,CAAC;EAAE,GAAG,GAAG,CAAC,CAAC,MAAQ,IAAI,KAAK;AAC9E,EAAC"}
package/sparse.ts ADDED
@@ -0,0 +1,49 @@
1
+ // A selective shared-file search reads only its admitted codes, then the
2
+ // ordinary reader scores the best few from their float vectors. Reading every
3
+ // admitted float instead touched thousands of scattered pages on the box.
4
+ import {
5
+ among,
6
+ and,
7
+ col,
8
+ eq,
9
+ exists,
10
+ lit,
11
+ not,
12
+ type Raw,
13
+ select,
14
+ type Statements,
15
+ table,
16
+ } from '@yaks/sql'
17
+ import { CODE } from './ddl.js'
18
+ import { scored, type Vector } from './score.js'
19
+
20
+ /** The best `limit` admitted codes, when every stored vector has its codes. */
21
+ export let sparse = (
22
+ db: Statements,
23
+ query: Float32Array,
24
+ within: Raw,
25
+ limit: number,
26
+ ): number[] => {
27
+ let rows = db.query(select({
28
+ cols: [col('owner', 'c'), col('code', 'c')],
29
+ from: table(CODE, 'c'),
30
+ where: and(
31
+ among(col('owner', 'c'), within),
32
+ not(exists(select({
33
+ cols: [lit(1)],
34
+ from: table('tombstone', 't'),
35
+ where: eq(col('entity', 't'), col('owner', 'c')),
36
+ }))),
37
+ ),
38
+ }))
39
+ let vectors = function* (): Generator<Vector> {
40
+ for (let row of rows) {
41
+ let bytes = row.code as Uint8Array
42
+ yield {
43
+ owner: Number(row.owner),
44
+ vector: new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength),
45
+ }
46
+ }
47
+ }
48
+ return scored(query, vectors(), { limit, floor: -1 }).map((hit) => hit.owner)
49
+ }