cursedbelt-server 4.66.0 → 4.68.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.
- package/dist/server/clientIssues/d1.d.ts +93 -0
- package/dist/server/clientIssues/d1.js +149 -0
- package/dist/server/d1/fakeD1.d.ts +5 -0
- package/dist/server/d1/fakeD1.js +9 -6
- package/dist/server/d1/index.d.ts +1 -0
- package/dist/server/d1/index.js +1 -0
- package/dist/server/d1/plans.d.ts +70 -0
- package/dist/server/d1/plans.js +127 -0
- package/dist/server/meaning/meaning.d.ts +7 -0
- package/dist/server/meaning/meaning.js +7 -0
- package/package.json +8 -2
- package/src/server/clientIssues/d1.spec.ts +139 -0
- package/src/server/clientIssues/d1.ts +221 -0
- package/src/server/d1/fakeD1.ts +9 -6
- package/src/server/d1/index.ts +11 -0
- package/src/server/d1/plans.spec.ts +129 -0
- package/src/server/d1/plans.ts +148 -0
- package/src/server/d1/sameShape.spec.ts +40 -0
- package/src/server/meaning/meaning.spec.ts +8 -0
- package/src/server/meaning/meaning.ts +7 -0
- package/src/server/telemetryIsWorkerSafe.spec.ts +12 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
|
|
3
|
+
* the fixture's.
|
|
4
|
+
*
|
|
5
|
+
* Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
|
|
6
|
+
* per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
|
|
7
|
+
* about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
|
|
8
|
+
* deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
|
|
9
|
+
* 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
|
|
10
|
+
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
|
+
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
|
+
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { D1LikeDatabase } from './types.js';
|
|
22
|
+
|
|
23
|
+
/** One row of `EXPLAIN QUERY PLAN`. */
|
|
24
|
+
export interface PlanRow {
|
|
25
|
+
id: number;
|
|
26
|
+
parent: number;
|
|
27
|
+
detail: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The columns a search keyed by alone still reads the table whole: one value matches most rows.
|
|
32
|
+
* An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
|
|
33
|
+
*/
|
|
34
|
+
export const LOW_CARDINALITY_COLUMNS: readonly string[] = ['state', 'status', 'deleted_at', 'owner_id'];
|
|
35
|
+
|
|
36
|
+
export interface PlanCheckOptions {
|
|
37
|
+
/** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
|
|
38
|
+
lowCardinality?: readonly string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
42
|
+
const lowCardinalityRule = (columns: readonly string[]): RegExp | null =>
|
|
43
|
+
columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
|
|
44
|
+
|
|
45
|
+
/** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
|
|
46
|
+
function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null): boolean {
|
|
47
|
+
const bareScan =
|
|
48
|
+
/^SCAN (?!CONSTANT ROW)/.test(detail) &&
|
|
49
|
+
!detail.includes(' VIRTUAL TABLE ') &&
|
|
50
|
+
!derived.has(detail.split(' ')[1] ?? '') &&
|
|
51
|
+
!/ USING (?:COVERING )?INDEX /.test(detail);
|
|
52
|
+
return bareScan || (low?.test(detail) ?? false);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
|
|
56
|
+
const derivedOf = (plan: readonly PlanRow[]): Set<string> =>
|
|
57
|
+
new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
|
|
58
|
+
|
|
59
|
+
/** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
|
|
60
|
+
export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
|
|
61
|
+
const byId = new Map(plan.map((r) => [r.id, r]));
|
|
62
|
+
// The nearest subquery around a step decides: an uncorrelated one inside a correlated one is computed once.
|
|
63
|
+
const correlated = (row: PlanRow): boolean => {
|
|
64
|
+
// Newer SQLite runs `EXISTS (…)` as a semi-join, a loop inside the outer one: `SEARCH s EXISTS USING …`.
|
|
65
|
+
if (/^SEARCH \S+ EXISTS /.test(row.detail)) return true;
|
|
66
|
+
for (let p = byId.get(row.parent); p; p = byId.get(p.parent)) {
|
|
67
|
+
if (/SUBQUERY|^CORRELATED/.test(p.detail)) return p.detail.startsWith('CORRELATED');
|
|
68
|
+
}
|
|
69
|
+
return false;
|
|
70
|
+
};
|
|
71
|
+
return plan.filter(correlated);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
|
|
76
|
+
* that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
|
|
77
|
+
*/
|
|
78
|
+
export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
|
|
79
|
+
const derived = derivedOf(plan);
|
|
80
|
+
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
81
|
+
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
|
|
86
|
+
* TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
|
|
87
|
+
* an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
|
|
88
|
+
*/
|
|
89
|
+
export function wholeTablePages(plan: readonly PlanRow[], opts: PlanCheckOptions = {}): string[] {
|
|
90
|
+
const outer = plan.filter((r) => r.parent === 0);
|
|
91
|
+
if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY')) return [];
|
|
92
|
+
const derived = derivedOf(plan);
|
|
93
|
+
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
94
|
+
return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
|
|
99
|
+
* after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
|
|
100
|
+
*/
|
|
101
|
+
export async function preparedBy(db: { prepare(sql: string): unknown }, run: () => Promise<unknown>): Promise<string[]> {
|
|
102
|
+
const seen = new Set<string>();
|
|
103
|
+
// Put back exactly what was there: an own property as it was, a prototype method by removing the shadow.
|
|
104
|
+
const own = Object.hasOwn(db, 'prepare');
|
|
105
|
+
const original = db.prepare;
|
|
106
|
+
const real = original.bind(db);
|
|
107
|
+
db.prepare = (sql: string) => {
|
|
108
|
+
seen.add(sql);
|
|
109
|
+
return real(sql);
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
await run();
|
|
113
|
+
} finally {
|
|
114
|
+
if (own) db.prepare = original;
|
|
115
|
+
else delete (db as { prepare?: unknown }).prepare;
|
|
116
|
+
}
|
|
117
|
+
return [...seen];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
|
|
121
|
+
export async function planOf(db: D1LikeDatabase, sql: string): Promise<PlanRow[]> {
|
|
122
|
+
return (await db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all<PlanRow>()).results;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
|
|
127
|
+
* — one line each, naming the step and the statement. `[]` is the pass.
|
|
128
|
+
*
|
|
129
|
+
* Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
|
|
130
|
+
* UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
|
|
131
|
+
* of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
|
|
132
|
+
*/
|
|
133
|
+
export async function planOffenders(
|
|
134
|
+
db: D1LikeDatabase,
|
|
135
|
+
statements: readonly string[],
|
|
136
|
+
opts: PlanCheckOptions & { writes?: boolean } = {},
|
|
137
|
+
): Promise<string[]> {
|
|
138
|
+
const offenders: string[] = [];
|
|
139
|
+
for (const sql of statements) {
|
|
140
|
+
const write = /^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql);
|
|
141
|
+
if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql)) continue;
|
|
142
|
+
const plan = await planOf(db, sql);
|
|
143
|
+
const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
144
|
+
for (const step of perRowReads(plan, { ...opts, perEvent: write })) offenders.push(`${step} ← ${where}`);
|
|
145
|
+
if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, opts)) offenders.push(`page: ${step} ← ${where}`);
|
|
146
|
+
}
|
|
147
|
+
return offenders;
|
|
148
|
+
}
|
|
@@ -300,6 +300,46 @@ describe('local and D1 drivers return identical shapes', () => {
|
|
|
300
300
|
expect(local).toEqual([3, 1]);
|
|
301
301
|
});
|
|
302
302
|
|
|
303
|
+
// 🔴 D1 counts the rows a TRIGGER writes in `meta.changes`; SQLite's own `changes()` does not.
|
|
304
|
+
// Measured 2026-11-10 on family-stage's D1: this exact trigger (two log rows per insert) made a
|
|
305
|
+
// 3-row INSERT report 9 and an `INSERT … RETURNING` of 2 report 6. These are absolute numbers,
|
|
306
|
+
// not a comparison of the two drivers — both drivers once agreed on 3 and 2.
|
|
307
|
+
const TRIGGERED = `CREATE TABLE tlog (id INTEGER PRIMARY KEY, v TEXT);
|
|
308
|
+
CREATE TRIGGER t_log AFTER INSERT ON t BEGIN
|
|
309
|
+
INSERT INTO tlog (v) VALUES (new.text_col);
|
|
310
|
+
INSERT INTO tlog (v) VALUES (new.text_col);
|
|
311
|
+
END;`;
|
|
312
|
+
|
|
313
|
+
test('run() counts the rows a trigger wrote, as D1 does — 9 for a 3-row insert, on both', async () => {
|
|
314
|
+
p.seed(TRIGGERED);
|
|
315
|
+
const { local, remote } = await both(p, async (db) => {
|
|
316
|
+
const res = await db.prepare("INSERT INTO t (text_col) VALUES ('a'), ('b'), ('c')").run();
|
|
317
|
+
return { changes: res.meta.changes, last_row_id: res.meta.last_row_id };
|
|
318
|
+
});
|
|
319
|
+
expect(local).toEqual({ changes: 9, last_row_id: 3 });
|
|
320
|
+
expect(remote).toEqual({ changes: 9, last_row_id: 3 });
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
test('all() of an INSERT … RETURNING counts its trigger rows too — 6 for 2, on both', async () => {
|
|
324
|
+
p.seed(TRIGGERED);
|
|
325
|
+
const { local, remote } = await both(p, async (db) => {
|
|
326
|
+
const res = await db.prepare("INSERT INTO t (text_col) VALUES ('d'), ('e') RETURNING id").all<{ id: number }>();
|
|
327
|
+
return { ids: res.results.map((r) => r.id), changes: res.meta.changes };
|
|
328
|
+
});
|
|
329
|
+
expect(local).toEqual({ ids: [1, 2], changes: 6 });
|
|
330
|
+
expect(remote).toEqual({ ids: [1, 2], changes: 6 });
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
test('a batch member counts its trigger rows, on both', async () => {
|
|
334
|
+
p.seed(TRIGGERED);
|
|
335
|
+
const { local, remote } = await both(p, async (db) => {
|
|
336
|
+
const res = await db.batch([db.prepare("INSERT INTO t (text_col) VALUES ('a')"), db.prepare("UPDATE t SET text_col = 'z'")]);
|
|
337
|
+
return res.map((r) => r.meta.changes);
|
|
338
|
+
});
|
|
339
|
+
expect(local).toEqual([3, 1]);
|
|
340
|
+
expect(remote).toEqual([3, 1]);
|
|
341
|
+
});
|
|
342
|
+
|
|
303
343
|
test('batch() reports last_row_id for an insert, on both', async () => {
|
|
304
344
|
const { local, remote } = await both(p, async (db) => {
|
|
305
345
|
const res = await db.batch([
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
d1MeaningStore,
|
|
10
10
|
EMBED_DIMS,
|
|
11
11
|
EMBED_MODEL,
|
|
12
|
+
FACE_DIMS,
|
|
12
13
|
fuse,
|
|
13
14
|
MEANING_CACHE_DAYS,
|
|
14
15
|
MEANING_D1_DDL,
|
|
@@ -17,6 +18,7 @@ import {
|
|
|
17
18
|
meaningCacheKey,
|
|
18
19
|
RERANK_MODEL,
|
|
19
20
|
rerankOrder,
|
|
21
|
+
REGION_DIMS,
|
|
20
22
|
rerankScores,
|
|
21
23
|
whyFound,
|
|
22
24
|
} from './meaning.js';
|
|
@@ -97,6 +99,12 @@ function d1() {
|
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
describe('the shared pieces', () => {
|
|
102
|
+
// photos' Mac writes these widths and family's door refuses any other length (forge task 4828):
|
|
103
|
+
// a change here is a model change, and both apps' stored vectors go with it.
|
|
104
|
+
it("the image engines' widths are ArcFace's 512 and the region embedder's 1536", () => {
|
|
105
|
+
expect([FACE_DIMS, REGION_DIMS]).toEqual([512, 1536]);
|
|
106
|
+
});
|
|
107
|
+
|
|
100
108
|
it('fuse: an id both lists found leads, a tie keeps first-seen order', () => {
|
|
101
109
|
expect(fuse([['a', 'b', 'c'], ['c', 'd']])).toEqual(['c', 'a', 'b', 'd']);
|
|
102
110
|
expect(fuse([['x'], ['y']])).toEqual(['x', 'y']);
|
|
@@ -23,6 +23,13 @@
|
|
|
23
23
|
/** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
|
|
24
24
|
export const EMBED_MODEL = '@cf/baai/bge-m3';
|
|
25
25
|
export const EMBED_DIMS = 1024;
|
|
26
|
+
/**
|
|
27
|
+
* The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
|
|
28
|
+
* they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
|
|
29
|
+
*/
|
|
30
|
+
export const FACE_DIMS = 512;
|
|
31
|
+
/** The image region embedder: 1536 floats, sent as float16. */
|
|
32
|
+
export const REGION_DIMS = 1536;
|
|
26
33
|
/** The cross-encoder that reads the query beside each candidate's document. */
|
|
27
34
|
export const RERANK_MODEL = '@cf/baai/bge-reranker-base';
|
|
28
35
|
/**
|
|
@@ -139,6 +139,18 @@ describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096
|
|
|
139
139
|
});
|
|
140
140
|
});
|
|
141
141
|
|
|
142
|
+
describe('🔴 cursedbelt-server/client-issues/d1 — a Worker mounts it (forge task 4500)', () => {
|
|
143
|
+
test('reaches no `bun:` module at runtime, and its export map points at the real module', () => {
|
|
144
|
+
const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'clientIssues', 'd1.ts'));
|
|
145
|
+
expect(bunImports).toEqual([]);
|
|
146
|
+
expect(files.some((f) => f.endsWith('clientIssues/d1.ts'))).toBe(true);
|
|
147
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as {
|
|
148
|
+
exports: Record<string, { import?: string }>;
|
|
149
|
+
};
|
|
150
|
+
expect(pkg.exports['./client-issues/d1']?.import).toBe('./dist/server/clientIssues/d1.js');
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
142
154
|
/**
|
|
143
155
|
* The three D1 halves `apps/family`'s Worker port needs (task 393). Each sits beside a sync
|
|
144
156
|
* store that is `bun:sqlite` by construction, so the walk also proves the split held: the
|