cursedbelt-server 4.64.1 → 4.65.0

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.
@@ -0,0 +1,218 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { describe, expect, it } from 'bun:test';
3
+ import { createFakeD1Binding } from '../d1/fakeD1.js';
4
+ import {
5
+ bandFor,
6
+ cosineTopK,
7
+ createLexicalIndex,
8
+ createMeaningSearch,
9
+ d1MeaningStore,
10
+ EMBED_DIMS,
11
+ EMBED_MODEL,
12
+ fuse,
13
+ MEANING_CACHE_DAYS,
14
+ MEANING_D1_DDL,
15
+ type MeaningAi,
16
+ type MeaningPlace,
17
+ meaningCacheKey,
18
+ RERANK_MODEL,
19
+ rerankOrder,
20
+ rerankScores,
21
+ whyFound,
22
+ } from './meaning.js';
23
+
24
+ const place = (id: string, title: string, about: string, subject: string[], extra: Partial<MeaningPlace> = {}): MeaningPlace => ({
25
+ id,
26
+ href: `/${id}`,
27
+ title,
28
+ crumbs: ['Apps & web', title],
29
+ about,
30
+ facets: { subject, measure: [], breakdown: [] },
31
+ kind: 'page',
32
+ ...extra,
33
+ });
34
+
35
+ const PLACES: MeaningPlace[] = [
36
+ place('cloudflare', 'Cloudflare', 'What the Cloudflare account costs this month, by product: Workers, R2 storage, D1 reads.', ['cloudflare', 'r2', 'd1'], {
37
+ facets: { subject: ['cloudflare'], measure: ['cost', 'price'], breakdown: ['per product'] },
38
+ }),
39
+ place('mac', 'This Mac', 'The MacBook memory pressure, swap, and the processes using the most of it.', ['mac', 'memory']),
40
+ place('usage', 'App usage', 'Each app broken down by its AI neurons, Worker requests and database calls.', ['apps', 'usage']),
41
+ place('backup', 'Backup', 'Which drives hold a copy of every tenant, and when each was last read back.', ['backup', 'drives']),
42
+ ];
43
+
44
+ /**
45
+ * A deterministic embedder: a word's vector is a fixed pseudo-random direction, a text's the sum of
46
+ * its words' plus a SYNONYM table's — so "ram" lands near "memory" the way a real model's would, and
47
+ * every call is counted.
48
+ */
49
+ function fakeAi(options: { rerank?: 'ok' | 'throw' | 'hang' } = {}) {
50
+ const SYNONYM: Record<string, string> = { ram: 'memory', price: 'cost', bill: 'cost', laptop: 'macbook' };
51
+ const dir = (word: string) => {
52
+ let h = 2166136261;
53
+ for (const c of word) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
54
+ return Array.from({ length: EMBED_DIMS }, (_, i) => Math.sin(h * (i + 1)));
55
+ };
56
+ const vec = (text: string) => {
57
+ const out = new Array<number>(EMBED_DIMS).fill(0);
58
+ for (const raw of text.toLowerCase().match(/[a-z0-9]+/g) ?? []) {
59
+ const w = SYNONYM[raw] ?? raw;
60
+ dir(w).forEach((x, i) => {
61
+ out[i] = (out[i] ?? 0) + x;
62
+ });
63
+ }
64
+ return out;
65
+ };
66
+ const calls = { embedTexts: 0, rerank: 0 };
67
+ const ai: MeaningAi = {
68
+ async run(model, input) {
69
+ if (model === EMBED_MODEL) {
70
+ const texts = (input as { text: string[] }).text;
71
+ calls.embedTexts += texts.length;
72
+ return { data: texts.map(vec) };
73
+ }
74
+ if (model === RERANK_MODEL) {
75
+ calls.rerank++;
76
+ if (options.rerank === 'throw') throw new Error('rerank down');
77
+ if (options.rerank === 'hang') return new Promise(() => undefined);
78
+ const { query, contexts } = input as { query: string; contexts: { text: string }[] };
79
+ const q = new Set((query.toLowerCase().match(/[a-z0-9]+/g) ?? []).map((w) => SYNONYM[w] ?? w));
80
+ return {
81
+ response: contexts.map((c, id) => {
82
+ const hits = (c.text.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((w) => q.has(SYNONYM[w] ?? w)).length;
83
+ return { id, score: hits === 0 ? 4e-5 : Math.min(0.9, 0.05 * hits) };
84
+ }),
85
+ };
86
+ }
87
+ throw new Error(`no model ${model}`);
88
+ },
89
+ };
90
+ return { ai, calls };
91
+ }
92
+
93
+ function d1() {
94
+ const sqlite = new Database(':memory:');
95
+ sqlite.exec(MEANING_D1_DDL);
96
+ return { sqlite, store: d1MeaningStore(createFakeD1Binding(sqlite)) };
97
+ }
98
+
99
+ describe('the shared pieces', () => {
100
+ it('fuse: an id both lists found leads, a tie keeps first-seen order', () => {
101
+ expect(fuse([['a', 'b', 'c'], ['c', 'd']])).toEqual(['c', 'a', 'b', 'd']);
102
+ expect(fuse([['x'], ['y']])).toEqual(['x', 'y']);
103
+ });
104
+
105
+ it('rerankOrder: the head is reordered, a near-miss is set apart, the tail keeps its place', () => {
106
+ // Blended, not replaced: b, second by the lists and first by the score, overtakes a.
107
+ const { order, nearMisses } = rerankOrder(['a', 'b', 'c', 'e', 'd'], ['a', 'b', 'c', 'e'], [0.001, 0.9, 0.5, 1e-5]);
108
+ expect(order).toEqual(['b', 'a', 'c', 'd']);
109
+ expect(nearMisses).toEqual(['e']);
110
+ });
111
+
112
+ it('rerankScores: one score per text, an out-of-range or non-numeric row ignored', () => {
113
+ expect(rerankScores({ response: [{ id: 1, score: 0.5 }, { id: 9, score: 1 }, { id: 0, score: 'x' }] }, 2)).toEqual([0, 0.5]);
114
+ expect(() => rerankScores({}, 1)).toThrow('answered no scores');
115
+ });
116
+
117
+ it('BM25 matches an exact short name the embedder would blur', () => {
118
+ const hits = createLexicalIndex(PLACES).search('R2');
119
+ expect(hits[0]?.id).toBe('cloudflare');
120
+ expect(createLexicalIndex(PLACES).search('the of')).toEqual([]);
121
+ });
122
+
123
+ it('cosineTopK ranks the nearest first', () => {
124
+ const v = new Map([
125
+ ['near', Float32Array.from([1, 0])],
126
+ ['far', Float32Array.from([0, 1])],
127
+ ]);
128
+ expect(cosineTopK([0.9, 0.1], v).map((r) => r.id)).toEqual(['near', 'far']);
129
+ });
130
+
131
+ it('whyFound marks the query words in the snippet, and says "by meaning" when none matched', () => {
132
+ const mac = PLACES[1] as MeaningPlace;
133
+ const hit = whyFound('mac memory', mac, 'strong');
134
+ expect(hit.why).toEqual({ words: ['mac', 'memory'], byMeaning: false });
135
+ expect(hit.snippet.marks.map(([s, e]) => mac.about.slice(s, e))).toEqual(['memory']);
136
+ expect(whyFound('ram', mac, 'likely').why).toEqual({ words: [], byMeaning: true });
137
+ // A plural finds its singular, both ways.
138
+ expect(whyFound('app', PLACES[2] as MeaningPlace, 'likely').why.words).toEqual(['app']);
139
+ });
140
+
141
+ it('bands come from the reranker score', () => {
142
+ expect([bandFor(0.5), bandFor(0.01), bandFor(1e-4)]).toEqual(['strong', 'likely', 'loose']);
143
+ });
144
+ });
145
+
146
+ describe('createMeaningSearch over D1', () => {
147
+ it('finds by words and by meaning, says why, and drops a near-miss', async () => {
148
+ const { ai } = fakeAi();
149
+ const engine = createMeaningSearch({ places: PLACES, store: d1().store, ai });
150
+ const cost = await engine.search('cloudflare cost');
151
+ expect(cost.hits[0]?.id).toBe('cloudflare');
152
+ expect(cost.hits[0]?.why.words).toEqual(['cloudflare', 'cost']);
153
+ expect(cost.reranked).toBe(true);
154
+ // "ram" is in no document: the embedder finds the Mac, the reranker keeps it, the why says meaning.
155
+ const ram = await engine.search('RAM');
156
+ expect(ram.hits[0]?.id).toBe('mac');
157
+ expect(ram.hits[0]?.why.byMeaning).toBe(true);
158
+ expect(ram.hits.map((h) => h.id)).not.toContain('backup');
159
+ });
160
+
161
+ it('embeds each document once — a second engine reads the stored vectors', async () => {
162
+ const { store } = d1();
163
+ const first = fakeAi();
164
+ await createMeaningSearch({ places: PLACES, store, ai: first.ai }).search('backup');
165
+ expect(first.calls.embedTexts).toBe(PLACES.length + 1);
166
+ const second = fakeAi();
167
+ await createMeaningSearch({ places: PLACES, store, ai: second.ai }).search('drives');
168
+ expect(second.calls.embedTexts).toBe(1); // the query alone
169
+ });
170
+
171
+ it('a changed document is re-embedded alone, and changes the version — a fresh answer, not a stale one', async () => {
172
+ const { store } = d1();
173
+ const a = createMeaningSearch({ places: PLACES, store, ai: fakeAi().ai });
174
+ const before = await a.search('backup');
175
+ const changed = PLACES.map((p) => (p.id === 'backup' ? { ...p, about: `${p.about} Also the spare drive.` } : p));
176
+ const { ai, calls } = fakeAi();
177
+ const b = createMeaningSearch({ places: changed, store, ai });
178
+ const after = await b.search('backup');
179
+ expect(calls.embedTexts).toBe(2); // the changed document and the query
180
+ expect(after.version).not.toBe(before.version);
181
+ expect(after.cached).toBe(false);
182
+ });
183
+
184
+ it('a repeat search answers from the cache without asking a model, and the timer expires it', async () => {
185
+ let clock = 1_000_000;
186
+ const { sqlite, store } = d1();
187
+ const { ai, calls } = fakeAi();
188
+ const engine = createMeaningSearch({ places: PLACES, store, ai, now: () => clock });
189
+ const first = await engine.search('Mac memory');
190
+ const embedded = calls.embedTexts;
191
+ const again = await engine.search('mac memory');
192
+ expect(again.cached).toBe(true);
193
+ expect(again.hits).toEqual(first.hits);
194
+ expect(calls.embedTexts).toBe(embedded);
195
+ expect(calls.rerank).toBe(1);
196
+ clock += (MEANING_CACHE_DAYS + 1) * 86_400_000;
197
+ expect(await engine.expire()).toBe(1);
198
+ expect(sqlite.query('SELECT count(*) AS n FROM meaning_answers').get()).toEqual({ n: 0 });
199
+ expect((await engine.search('mac memory')).cached).toBe(false);
200
+ });
201
+
202
+ it('a reranker that fails or hangs leaves the fused order — shown, never cached', async () => {
203
+ for (const rerank of ['throw', 'hang'] as const) {
204
+ const { store } = d1();
205
+ const errors: unknown[] = [];
206
+ const engine = createMeaningSearch({ places: PLACES, store, ai: fakeAi({ rerank }).ai, rerankTimeoutMs: 20, onRerankError: (e) => errors.push(e) });
207
+ const answer = await engine.search('cloudflare cost');
208
+ expect(answer.reranked).toBe(false);
209
+ expect(answer.hits[0]?.id).toBe('cloudflare');
210
+ expect(errors).toHaveLength(1);
211
+ expect(await store.readAnswer(meaningCacheKey('cloudflare cost', answer.version), 0)).toBeNull();
212
+ }
213
+ });
214
+
215
+ it('refuses two places with one id', () => {
216
+ expect(() => createMeaningSearch({ places: [PLACES[0] as MeaningPlace, PLACES[0] as MeaningPlace], store: d1().store, ai: fakeAi().ai })).toThrow('share an id');
217
+ });
218
+ });